forked from shader-slang/slang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslang-check-overload.cpp
2987 lines (2708 loc) · 107 KB
/
slang-check-overload.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// slang-check-overload.cpp
#include "slang-ast-base.h"
#include "slang-ast-print.h"
#include "slang-check-impl.h"
#include "slang-lookup.h"
// This file implements semantic checking logic related
// to resolving overloading call operations, by checking
// the applicability and relative priority of various candidates.
namespace Slang
{
bool isFreeFormTypePackParam(SemanticsVisitor* visitor, Type* type, ParamDecl* paramDecl)
{
if (auto declRef = isDeclRefTypeOf<GenericTypePackParamDecl>(type))
{
return visitor->GetOuterGeneric(declRef.getDecl()) ==
visitor->GetOuterGeneric(paramDecl->parentDecl);
}
return false;
}
SemanticsVisitor::ParamCounts SemanticsVisitor::CountParameters(
FilteredMemberRefList<ParamDecl> params)
{
ParamCounts counts = {0, 0};
for (auto param : params)
{
Index allowedArgCountToAdd = 1;
auto paramType = getParamType(m_astBuilder, param);
if (isTypePack(paramType))
{
if (auto typePack = as<ConcreteTypePack>(paramType))
{
counts.required += typePack->getTypeCount();
allowedArgCountToAdd = typePack->getTypeCount();
}
else if (isFreeFormTypePackParam(this, paramType, param.getDecl()))
{
counts.allowed = -1;
}
else
{
counts.required++;
counts.allowed++;
}
}
else if (!param.getDecl()->initExpr)
{
// No initializer means no default value
//
// TODO(tfoley): The logic here is currently broken in two ways:
//
// 1. We are assuming that once one parameter has a default, then all do.
// This can/should be validated earlier, so that we can assume it here.
//
// 2. We are not handling the possibility of multiple declarations for
// a single function, where we'd need to merge default parameters across
// all the declarations.
counts.required++;
}
if (counts.allowed >= 0)
counts.allowed += allowedArgCountToAdd;
}
return counts;
}
SemanticsVisitor::ParamCounts SemanticsVisitor::CountParameters(DeclRef<GenericDecl> genericRef)
{
ParamCounts counts = {0, 0};
for (auto m : genericRef.getDecl()->members)
{
if (auto typeParam = as<GenericTypeParamDecl>(m))
{
if (counts.allowed >= 0)
counts.allowed++;
if (!typeParam->initType.Ptr())
{
counts.required++;
}
}
else if (auto valParam = as<GenericValueParamDecl>(m))
{
if (counts.allowed >= 0)
counts.allowed++;
if (!valParam->initExpr)
{
counts.required++;
}
}
else if (as<GenericTypePackParamDecl>(m))
{
counts.allowed = -1;
}
}
return counts;
}
bool SemanticsVisitor::TryCheckOverloadCandidateClassNewMatchUp(
OverloadResolveContext& context,
OverloadCandidate const& candidate)
{
// Check that a constructor call to a class type must be in a `new` expr, and a `new` expr
// is only used to construct a class.
bool isClassType = false;
bool isNewExpr = false;
if (auto ctorDeclRef = candidate.item.declRef.as<ConstructorDecl>())
{
if (auto resultType = as<DeclRefType>(candidate.resultType))
{
if (resultType->getDeclRef().as<ClassDecl>())
{
isClassType = true;
}
}
}
if (as<NewExpr>(context.originalExpr))
{
isNewExpr = true;
}
if (isNewExpr && !isClassType)
{
getSink()->diagnose(context.originalExpr, Diagnostics::newCanOnlyBeUsedToInitializeAClass);
return false;
}
if (!isNewExpr && isClassType && context.originalExpr)
{
getSink()->diagnose(context.originalExpr, Diagnostics::classCanOnlyBeInitializedWithNew);
return false;
}
return true;
}
bool SemanticsVisitor::TryCheckOverloadCandidateArity(
OverloadResolveContext& context,
OverloadCandidate const& candidate)
{
Count argCount = context.getArgCount();
ParamCounts paramCounts = {0, 0};
switch (candidate.flavor)
{
case OverloadCandidate::Flavor::Func:
paramCounts =
CountParameters(getParameters(m_astBuilder, candidate.item.declRef.as<CallableDecl>()));
break;
case OverloadCandidate::Flavor::Generic:
paramCounts = CountParameters(candidate.item.declRef.as<GenericDecl>());
// A generic can be applied to any number of arguments less
// than or equal to the number of explicitly declared parameters.
// When a program provides fewer arguments than their are parameters,
// the rest will be inferred.
//
paramCounts.required = 0;
break;
case OverloadCandidate::Flavor::Expr:
{
auto paramCount = candidate.funcType->getParamCount();
paramCounts.allowed = paramCount;
paramCounts.required = paramCount;
}
break;
default:
SLANG_UNEXPECTED("unknown flavor of overload candidate");
break;
}
if (argCount >= paramCounts.required &&
(paramCounts.allowed == -1 || argCount <= paramCounts.allowed))
return true;
// Emit an error message if we are checking this call for real
if (context.mode != OverloadResolveContext::Mode::JustTrying)
{
if (argCount < paramCounts.required)
{
getSink()->diagnose(
context.loc,
Diagnostics::notEnoughArguments,
argCount,
paramCounts.required);
}
else
{
SLANG_ASSERT(argCount > paramCounts.allowed);
getSink()->diagnose(
context.loc,
Diagnostics::tooManyArguments,
argCount,
paramCounts.allowed);
}
}
return false;
}
bool SemanticsVisitor::TryCheckOverloadCandidateFixity(
OverloadResolveContext& context,
OverloadCandidate const& candidate)
{
auto expr = context.originalExpr;
auto decl = candidate.item.declRef.getDecl();
if (const auto prefixExpr = as<PrefixExpr>(expr))
{
if (decl->hasModifier<PrefixModifier>())
return true;
if (context.mode != OverloadResolveContext::Mode::JustTrying)
{
getSink()->diagnose(context.loc, Diagnostics::expectedPrefixOperator);
getSink()->diagnose(decl, Diagnostics::seeDefinitionOf, decl->getName());
}
return false;
}
else if (const auto postfixExpr = as<PostfixExpr>(expr))
{
if (decl->hasModifier<PostfixModifier>())
return true;
if (context.mode != OverloadResolveContext::Mode::JustTrying)
{
getSink()->diagnose(context.loc, Diagnostics::expectedPostfixOperator);
getSink()->diagnose(decl, Diagnostics::seeDefinitionOf, decl->getName());
}
return false;
}
else
{
return true;
}
}
bool SemanticsVisitor::TryCheckOverloadCandidateVisibility(
OverloadResolveContext& context,
OverloadCandidate const& candidate)
{
// Always succeeds when we are trying out constructors.
if (context.mode == OverloadResolveContext::Mode::JustTrying)
{
if (as<ConstructorDecl>(candidate.item.declRef))
return true;
}
if (!context.sourceScope)
return true;
if (!candidate.item.declRef)
return true;
if (!isDeclVisibleFromScope(candidate.item.declRef, context.sourceScope))
{
if (context.mode == OverloadResolveContext::Mode::ForReal)
{
getSink()->diagnose(context.loc, Diagnostics::declIsNotVisible, candidate.item.declRef);
}
return false;
}
return true;
}
bool SemanticsVisitor::TryCheckGenericOverloadCandidateTypes(
OverloadResolveContext& context,
OverloadCandidate& candidate)
{
auto genericDeclRef = candidate.item.declRef.as<GenericDecl>();
// Only allow constructing a PartialGenericAppExpr when referencing a callable decl.
// Other types of generic decls must be fully specified.
bool allowPartialGenericApp = false;
if (as<CallableDecl>(genericDeclRef.getDecl()->inner))
{
allowPartialGenericApp = true;
}
// The basic idea here is that we need to check that the
// arguments to a generic application (e.g., `F<A1, A2, ...>`)
// have the right "type," which in this context means
// checking that:
//
// * The argument for any generic type parameter is a (proper) type.
//
// * The argument for any generic value parameter is a
// specialization-time constant value of the appropriate type.
//
// Some additional checks are *not* handled at this point:
//
// * We don't check that a type argument actually conforms to
// the constraints on the parameter.
//
// Along the way we will build up a `GenericSubstitution`
// to represent the arguments that have been coerced to
// appropriate forms.
//
List<Val*> checkedArgs;
// Rather than bail out as soon as we hit a problem,
// we are going to process *all* of the parameters of the
// generic and place suitable arguments into the `checkedArgs`
// array. This is important so that we don't cause crashes
// in cases where the arguments fail this step of checking,
// but we decide to proceed with subsequent steps (e.g.,
// because the candidate we are trying here is the *only*
// candidate).
//
bool success = true;
auto maybeReportGeneralError = [&]()
{
if (context.mode != OverloadResolveContext::Mode::JustTrying)
{
getSink()->diagnose(
context.loc,
Diagnostics::cannotSpecializeGeneric,
candidate.item.declRef);
}
};
List<QualType> paramTypes;
for (auto memberRef : getMembers(m_astBuilder, genericDeclRef))
{
if (auto typeParamRef = memberRef.as<GenericTypeParamDecl>())
{
paramTypes.add(DeclRefType::create(m_astBuilder, typeParamRef));
}
else if (auto valParamRef = memberRef.as<GenericValueParamDecl>())
{
paramTypes.add(getType(m_astBuilder, valParamRef));
}
else if (auto typePackParam = memberRef.as<GenericTypePackParamDecl>())
{
paramTypes.add(DeclRefType::create(m_astBuilder, typePackParam));
}
}
ShortList<OverloadResolveContext::MatchedArg> matchedArgs;
if (!context.matchArgumentsToParams(this, paramTypes, false, matchedArgs))
{
maybeReportGeneralError();
return false;
}
Index aa = 0;
for (auto memberRef : getMembers(m_astBuilder, genericDeclRef))
{
if (auto typeParamRef = memberRef.as<GenericTypeParamDecl>())
{
if (aa >= matchedArgs.getCount())
{
if (allowPartialGenericApp)
{
// If we have run out of arguments, and the referenced decl
// allows partially applied specialization (i.e. a callable
// decl) then we don't apply any more checks at this step.
// We will instead attempt to *infer* an argument at this
// position at a later stage.
//
candidate.flags |= OverloadCandidate::Flag::IsPartiallyAppliedGeneric;
break;
}
else
{
// Otherwise, the generic decl had better provide a default value
// or this reference is ill-formed.
auto substType = typeParamRef.substitute(
m_astBuilder,
typeParamRef.getDecl()->initType.type);
if (!substType)
{
maybeReportGeneralError();
return false;
}
checkedArgs.add(substType);
continue;
}
}
// We have a type parameter, and we expect to find
// a type argument.
//
TypeExp typeArg;
// Per the earlier check, we have at least one
// argument left, so we will grab
// it and try to coerce it to a proper type. The
// manner in which we handle the coercion depends
// on whether we are "just trying" the candidate
// (so a failure would rule out the candidate, but
// shouldn't be reported to the user), or are doing
// the checking "for real" in which case any errors
// we run into need to be reported.
//
auto arg = matchedArgs[aa++];
if (context.mode == OverloadResolveContext::Mode::JustTrying)
{
typeArg = tryCoerceToProperType(TypeExp(arg.argExpr));
}
else
{
arg.argExpr = ExpectATypeRepr(arg.argExpr);
typeArg = CoerceToProperType(TypeExp(arg.argExpr));
}
// If we failed to get a valid type (either because
// there was no matching argument, or because the
// "just trying" coercion failed), then we create
// an error type to stand in for the argument
//
if (!typeArg.type)
{
typeArg.type = m_astBuilder->getErrorType();
success = false;
}
checkedArgs.add(typeArg.type);
}
else if (auto valParamRef = memberRef.as<GenericValueParamDecl>())
{
if (aa >= matchedArgs.getCount())
{
if (allowPartialGenericApp)
{
// If we have run out of arguments and the decl allows
// partial specialization, then we don't apply any more
// checks at this step. We will instead attempt to
// *infer* an argument at this position at a later
// stage.
//
candidate.flags |= OverloadCandidate::Flag::IsPartiallyAppliedGeneric;
break;
}
else
{
// Otherwise, the generic decl had better provide a default value
// or this reference is ill-formed.
ensureDecl(valParamRef, DeclCheckState::DefinitionChecked);
ConstantFoldingCircularityInfo newCircularityInfo(
valParamRef.getDecl(),
nullptr);
auto defaultVal = tryConstantFoldExpr(
valParamRef.substitute(m_astBuilder, valParamRef.getDecl()->initExpr),
ConstantFoldingKind::CompileTime,
&newCircularityInfo);
if (!defaultVal)
{
maybeReportGeneralError();
return false;
}
checkedArgs.add(defaultVal);
continue;
}
}
// The case for a generic value parameter is similar to that
// for a generic type parameter.
//
Expr* arg = nullptr;
// If we have an argument then we need to coerce it
// to the type of the parameter (and fail if the
// coercion is not possible)
//
arg = matchedArgs[aa++].argExpr;
if (context.mode == OverloadResolveContext::Mode::JustTrying)
{
ConversionCost cost = kConversionCost_None;
if (!canCoerce(getType(m_astBuilder, valParamRef), arg->type, arg, &cost))
{
success = false;
}
candidate.conversionCostSum += cost;
}
else
{
arg = coerce(CoercionSite::Argument, getType(m_astBuilder, valParamRef), arg);
}
// If we have an argument to work with, then we will
// try to extract its speicalization-time constant value.
//
Val* val = nullptr;
if (arg)
{
val = ExtractGenericArgInteger(
arg,
getType(m_astBuilder, valParamRef),
context.mode == OverloadResolveContext::Mode::JustTrying ? nullptr : getSink());
}
// If any of the above checking steps fail and we don't
// have a value to work with here, we will instead
// use an "error" value to stand in for the argument.
//
if (!val)
{
val = m_astBuilder->getOrCreate<ErrorIntVal>(m_astBuilder->getIntType());
}
checkedArgs.add(val);
}
else if (auto typePackParam = memberRef.as<GenericTypePackParamDecl>())
{
Val* val = nullptr;
if (aa >= matchedArgs.getCount())
{
if (allowPartialGenericApp)
{
// If we have run out of arguments and the decl allows
// partial specialization, then we don't apply any more
// checks at this step. We will instead attempt to
// *infer* an argument at this position at a later
// stage.
//
candidate.flags |= OverloadCandidate::Flag::IsPartiallyAppliedGeneric;
break;
}
else
{
// Otherwise, we will just create an empty pack.
val = m_astBuilder->getTypePack(ArrayView<Type*>());
}
}
else
{
auto matchedArg = matchedArgs[aa++];
if (auto packExpr = as<PackExpr>(matchedArg.argExpr))
{
// We are providing a concrete pack of types as arguments to a type pack
// parameter. We need to create a `TypePack` type to serve as the argument.
ShortList<Type*> coercedProperTypes;
// Coerce all types in the pack to proper types.
for (Index i = 0; i < packExpr->args.getCount(); i++)
{
TypeExp typeArg;
auto elementTypeExpr = packExpr->args[i];
if (context.mode == OverloadResolveContext::Mode::JustTrying)
{
typeArg = tryCoerceToProperType(TypeExp(elementTypeExpr));
if (!typeArg.type)
{
typeArg.type = m_astBuilder->getErrorType();
success = false;
}
}
else
{
elementTypeExpr = ExpectATypeRepr(elementTypeExpr);
typeArg = CoerceToProperType(TypeExp(elementTypeExpr));
}
// If we failed to get a valid type (either because
// there was no matching argument, or because the
// "just trying" coercion failed), then we create
// an error type to stand in for the argument
//
if (!typeArg.type)
{
typeArg.type = m_astBuilder->getErrorType();
success = false;
}
coercedProperTypes.add(typeArg.type);
}
val = m_astBuilder->getTypePack(coercedProperTypes.getArrayView().arrayView);
}
else if (auto expandExpr = as<ExpandExpr>(matchedArg.argExpr))
{
auto argType = expandExpr->type.type;
if (auto typeType = as<TypeType>(argType))
argType = typeType->getType();
val = argType;
}
else if (auto typeType = as<TypeType>(matchedArg.argType))
{
if (isAbstractTypePack(typeType->getType()))
{
val = typeType->getType();
}
}
}
if (val == nullptr)
{
maybeReportGeneralError();
return false;
}
checkedArgs.add(val);
}
else
{
continue;
}
}
auto genSubst = m_astBuilder->getGenericAppDeclRef(genericDeclRef, checkedArgs.getArrayView());
candidate.subst = SubstitutionSet(genSubst);
// Once we are done processing the parameters of the generic,
// we will have build up a usable `checkedArgs` array and
// can return to the caller a report of whether we
// were successful or not.
//
return success;
}
static QualType getParamQualType(ASTBuilder* astBuilder, DeclRef<ParamDecl> param)
{
auto paramType = getType(astBuilder, param);
bool isLVal = false;
switch (getParameterDirection(param.getDecl()))
{
case kParameterDirection_InOut:
case kParameterDirection_Out:
case kParameterDirection_Ref:
isLVal = true;
break;
}
return QualType(paramType, isLVal);
}
static QualType getParamQualType(Type* paramType)
{
if (auto paramDirType = as<ParamDirectionType>(paramType))
{
if (as<OutTypeBase>(paramDirType) || as<RefType>(paramDirType))
return QualType(paramDirType->getValueType(), true);
}
return paramType;
}
bool SemanticsVisitor::TryCheckOverloadCandidateTypes(
OverloadResolveContext& context,
OverloadCandidate& candidate)
{
Index argCount = context.getArgCount();
List<QualType> paramTypes;
switch (candidate.flavor)
{
case OverloadCandidate::Flavor::Func:
for (auto param : getParameters(m_astBuilder, candidate.item.declRef.as<CallableDecl>()))
{
paramTypes.add(getParamQualType(m_astBuilder, param));
}
break;
case OverloadCandidate::Flavor::Expr:
{
auto funcType = candidate.funcType;
Count paramCount = funcType->getParamCount();
for (Index i = 0; i < paramCount; ++i)
{
auto paramType = getParamQualType(funcType->getParamType(i));
paramTypes.add(paramType);
}
}
break;
case OverloadCandidate::Flavor::Generic:
{
return TryCheckGenericOverloadCandidateTypes(context, candidate);
}
default:
SLANG_UNEXPECTED("unknown flavor of overload candidate");
break;
}
Index paramIndex = 0;
Index argIndex = 0;
struct Arg
{
Expr* argExpr;
Type* type;
};
auto readArg = [&]() -> Arg
{
if (argIndex >= argCount)
return {nullptr, nullptr};
auto arg = context.getArg(argIndex);
Arg result = {arg, context.getArgType(argIndex)};
argIndex++;
return result;
};
auto coerceArgToParam = [&](Arg arg, QualType paramType) -> Arg
{
auto argType = QualType(arg.type, paramType.isLeftValue);
if (!paramType)
return {nullptr, nullptr};
if (!argType)
return {nullptr, nullptr};
if (context.mode == OverloadResolveContext::Mode::JustTrying)
{
ConversionCost cost = kConversionCost_None;
if (context.disallowNestedConversions)
{
// We need an exact match in this case.
if (!paramType->equals(argType))
return {nullptr, nullptr};
}
else if (!canCoerce(paramType, argType, arg.argExpr, &cost))
{
return {nullptr, nullptr};
}
candidate.conversionCostSum += cost;
}
else
{
arg.argExpr = coerce(CoercionSite::Argument, paramType, arg.argExpr);
}
return arg;
};
ShortList<Expr*> resultArgs;
while (paramIndex < paramTypes.getCount())
{
auto paramType = paramTypes[paramIndex];
if (auto paramTypePack = as<ConcreteTypePack>(paramType))
{
ShortList<Expr*> innerArgs;
for (Index i = 0; i < paramTypePack->getTypeCount(); i++)
{
auto arg = readArg();
auto coercedArg = coerceArgToParam(
arg,
QualType(paramTypePack->getElementType(i), paramType.isLeftValue));
if (!coercedArg.type)
{
return false;
}
if (context.mode == OverloadResolveContext::Mode::ForReal)
innerArgs.add(coercedArg.argExpr);
}
if (context.mode == OverloadResolveContext::Mode::ForReal)
{
auto packArg = m_astBuilder->create<PackExpr>();
for (auto aa : innerArgs)
packArg->args.add(aa);
packArg->type = paramType;
resultArgs.add(packArg);
}
// Always add a flat cost for using an argument pack,
// so that we prefer non-pack overloads when possible.
candidate.conversionCostSum += kConversionCost_ParameterPack;
}
else
{
auto arg = readArg();
if (!arg.type)
{
// If we run out of arguments, we can exit the loop now.
// Note that in this type we don't need to worry about
// default arguments, because we already checked that
// the number of arguments was correct in `TryCheckOverloadCandidateArity`.
break;
}
auto coercedArg = coerceArgToParam(arg, paramType);
if (!coercedArg.type)
{
return false;
}
if (context.mode == OverloadResolveContext::Mode::ForReal)
resultArgs.add(coercedArg.argExpr);
}
paramIndex++;
}
if (context.mode == OverloadResolveContext::Mode::ForReal)
{
context.argCount = resultArgs.getCount();
if (context.args)
{
context.args->setCount(context.argCount);
for (Index i = 0; i < context.argCount; i++)
(*context.args)[i] = resultArgs[i];
}
}
return true;
}
bool isEffectivelyMutating(CallableDecl* decl)
{
if (decl->hasModifier<MutatingAttribute>())
return true;
if (decl->hasModifier<RefAttribute>())
return true;
if (decl->hasModifier<NonmutatingAttribute>())
return false;
if (as<SetterDecl>(decl))
return true;
return false;
}
ParamDecl* SemanticsVisitor::isReferenceIntoFunctionInputParameter(Expr* inExpr)
{
auto expr = inExpr;
for (;;)
{
if (auto declRefExpr = as<DeclRefExpr>(expr))
{
auto declRef = declRefExpr->declRef;
if (auto paramDeclRef = declRef.as<ParamDecl>())
{
if (paramDeclRef.as<ModernParamDecl>())
{
// functions declared in our "modern" style (using
// the `func` keyword) never have mutable `in`
// parameters.
//
return nullptr;
}
if (paramDeclRef.getDecl()->findModifier<OutModifier>() ||
paramDeclRef.getDecl()->findModifier<RefModifier>())
{
// Function parameters marked with `out`, `inout`,
// `in out` or `ref` are all mutable in a way where
// the result of mutations will be visible to the
// caller.
//
return nullptr;
}
// At this point we have an l-value decl-ref to a
// function parameter that is (implicitly or
// explicitly) declared `in`.
//
return paramDeclRef.getDecl();
}
}
else if (auto memberExpr = as<MemberExpr>(expr))
{
expr = memberExpr->baseExpression;
continue;
}
else if (auto indexExpr = as<IndexExpr>(expr))
{
expr = indexExpr->baseExpression;
continue;
}
return nullptr;
}
}
bool SemanticsVisitor::TryCheckOverloadCandidateDirections(
OverloadResolveContext& context,
OverloadCandidate const& candidate)
{
if (candidate.flavor != OverloadCandidate::Flavor::Func)
return true;
auto funcDeclRef = candidate.item.declRef.as<CallableDecl>();
SLANG_ASSERT(funcDeclRef);
// Note: This operation was originally introduced as
// a place to add checking around l-value-ness of arguments
// and parameters, but currently that checking is being
// done in other places.
//
// For now we will only use this step to check the
// mutability of the `this` parameter where necessary.
//
if (!isEffectivelyStatic(funcDeclRef.getDecl()))
{
if (isEffectivelyMutating(funcDeclRef.getDecl()))
{
if (context.baseExpr && !context.baseExpr->type.isLeftValue)
{
if (context.mode == OverloadResolveContext::Mode::ForReal)
{
getSink()->diagnose(
context.loc,
Diagnostics::mutatingMethodOnImmutableValue,
funcDeclRef.getName());
maybeDiagnoseThisNotLValue(context.baseExpr);
}
return false;
}
// The parameters of functions declared using traditional/legacy
// syntax are currently exposed as mutable locals within the body
// of the relevant function. As such, it is legal to call `[mutating]`
// methods on such a function parameter. However, doing so is typically
// indicative of an error on the programmer's part.
//
// We will detect such cases here and issue a diagnostic that explains
// the situation.
//
if (context.baseExpr && context.mode == OverloadResolveContext::Mode::ForReal)
{
if (auto paramDecl = isReferenceIntoFunctionInputParameter(context.baseExpr))
{
const bool isNonCopyable = isNonCopyableType(paramDecl->getType());
const auto& diagnotic =
isNonCopyable ? Diagnostics::mutatingMethodOnFunctionInputParameterError
: Diagnostics::mutatingMethodOnFunctionInputParameterWarning;
getSink()->diagnose(
context.loc,
diagnotic,
funcDeclRef.getName(),
paramDecl->getName());
}
}
}
}
return true;
}
bool SemanticsVisitor::TryCheckOverloadCandidateConstraints(
OverloadResolveContext& context,
OverloadCandidate& candidate)
{
// We only need this step for generics, so always succeed on
// everything else.
if (candidate.flavor != OverloadCandidate::Flavor::Generic)
return true;
// It is possible that the overload candidate was only partially
// applied (the number of arguments was not equal to the number
// of explicit parameters). In that case, we want to defer
// final checking of things like constraints until later, in
// case a subsequent pass of overload resolution (like applying
// an overloaded generic function to arguments) will give us
// the missing information to enable inference.
//
if (candidate.flags & OverloadCandidate::Flag::IsPartiallyAppliedGeneric)
return true;
auto genericDeclRef = candidate.item.declRef.as<GenericDecl>();
SLANG_ASSERT(genericDeclRef); // otherwise we wouldn't be a generic candidate...
// We should have the existing arguments to the generic
// handy, so that we can construct a substitution list.
auto substArgs = tryGetGenericArguments(candidate.subst, genericDeclRef.getDecl());
SLANG_ASSERT(substArgs.getCount());
List<Val*> newArgs;
for (auto arg : substArgs)
newArgs.add(arg);
for (auto constraintDecl :
genericDeclRef.getDecl()->getMembersOfType<GenericTypeConstraintDecl>())
{
DeclRef<GenericTypeConstraintDecl> constraintDeclRef =
m_astBuilder
->getGenericAppDeclRef(genericDeclRef, newArgs.getArrayView(), constraintDecl)
.as<GenericTypeConstraintDecl>();
auto sub = getSub(m_astBuilder, constraintDeclRef);
auto sup = getSup(m_astBuilder, constraintDeclRef);
auto subTypeWitness = tryGetSubtypeWitness(sub, sup);
if (subTypeWitness)
{
newArgs.add(subTypeWitness);
}
else
{
if (context.mode != OverloadResolveContext::Mode::JustTrying)
{
subTypeWitness = isSubtype(sub, sup, IsSubTypeOptions::None);
getSink()->diagnose(
context.loc,
Diagnostics::typeArgumentDoesNotConformToInterface,
sub,
sup);
}
return false;
}
}
candidate.subst =
SubstitutionSet(m_astBuilder->getGenericAppDeclRef(genericDeclRef, newArgs.getArrayView()));
// Done checking all the constraints, hooray.
return true;
}
void SemanticsVisitor::TryCheckOverloadCandidate(
OverloadResolveContext& context,
OverloadCandidate& candidate)
{
if (!TryCheckOverloadCandidateArity(context, candidate))
return;
candidate.status = OverloadCandidate::Status::ArityChecked;
if (!TryCheckOverloadCandidateFixity(context, candidate))
return;