-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
CSGen.cpp
5199 lines (4326 loc) · 198 KB
/
CSGen.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
//===--- CSGen.cpp - Constraint Generator ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements constraint generation for the type checker.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckConcurrency.h"
#include "TypeCheckDecl.h"
#include "TypeCheckMacros.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include <utility>
using namespace swift;
using namespace swift::constraints;
static bool isArithmeticOperatorDecl(ValueDecl *vd) {
return vd && vd->getBaseIdentifier().isArithmeticOperator();
}
static bool mergeRepresentativeEquivalenceClasses(ConstraintSystem &CS,
TypeVariableType* tyvar1,
TypeVariableType* tyvar2) {
if (tyvar1 && tyvar2) {
auto rep1 = CS.getRepresentative(tyvar1);
auto rep2 = CS.getRepresentative(tyvar2);
if (rep1 != rep2) {
auto fixedType2 = CS.getFixedType(rep2);
// If the there exists fixed type associated with the second
// type variable, and we simply merge two types together it would
// mean that portion of the constraint graph previously associated
// with that (second) variable is going to be disconnected from its
// new equivalence class, which is going to lead to incorrect solutions,
// so we need to make sure to re-bind fixed to the new representative.
if (fixedType2) {
CS.addConstraint(ConstraintKind::Bind, fixedType2, rep1,
rep1->getImpl().getLocator());
}
CS.mergeEquivalenceClasses(rep1, rep2, /*updateWorkList*/ false);
return true;
}
}
return false;
}
namespace {
/// Internal struct for tracking information about types within a series
/// of "linked" expressions. (Such as a chain of binary operator invocations.)
struct LinkedTypeInfo {
bool hasLiteral = false;
llvm::SmallSet<TypeBase*, 16> collectedTypes;
llvm::SmallVector<BinaryExpr *, 4> binaryExprs;
};
/// Walks an expression sub-tree, and collects information about expressions
/// whose types are mutually dependent upon one another.
class LinkedExprCollector : public ASTWalker {
llvm::SmallVectorImpl<Expr*> &LinkedExprs;
public:
LinkedExprCollector(llvm::SmallVectorImpl<Expr *> &linkedExprs)
: LinkedExprs(linkedExprs) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (isa<ClosureExpr>(expr))
return Action::SkipNode(expr);
// Store top-level binary exprs for further analysis.
if (isa<BinaryExpr>(expr) ||
// Literal exprs are contextually typed, so store them off as well.
isa<LiteralExpr>(expr) ||
// We'd like to look at the elements of arrays and dictionaries.
isa<ArrayExpr>(expr) ||
isa<DictionaryExpr>(expr) ||
// assignment expression can involve anonymous closure parameters
// as source and destination, so it's beneficial for diagnostics if
// we look at the assignment.
isa<AssignExpr>(expr)) {
LinkedExprs.push_back(expr);
return Action::SkipNode(expr);
}
return Action::Continue(expr);
}
/// Ignore statements.
PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
return Action::SkipNode(stmt);
}
/// Ignore declarations.
PreWalkAction walkToDeclPre(Decl *decl) override {
return Action::SkipNode();
}
/// Ignore patterns.
PreWalkResult<Pattern *> walkToPatternPre(Pattern *pat) override {
return Action::SkipNode(pat);
}
/// Ignore types.
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
return Action::SkipNode();
}
};
/// Given a collection of "linked" expressions, analyzes them for
/// commonalities regarding their types. This will help us compute a
/// "best common type" from the expression types.
class LinkedExprAnalyzer : public ASTWalker {
LinkedTypeInfo <I;
ConstraintSystem &CS;
public:
LinkedExprAnalyzer(LinkedTypeInfo <i, ConstraintSystem &cs) :
LTI(lti), CS(cs) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (isa<LiteralExpr>(expr)) {
LTI.hasLiteral = true;
return Action::SkipNode(expr);
}
if (isa<CollectionExpr>(expr)) {
return Action::Continue(expr);
}
if (auto UDE = dyn_cast<UnresolvedDotExpr>(expr)) {
if (CS.hasType(UDE))
LTI.collectedTypes.insert(CS.getType(UDE).getPointer());
// Don't recurse into the base expression.
return Action::SkipNode(expr);
}
if (isa<ClosureExpr>(expr)) {
return Action::SkipNode(expr);
}
if (auto FVE = dyn_cast<ForceValueExpr>(expr)) {
LTI.collectedTypes.insert(CS.getType(FVE).getPointer());
return Action::SkipNode(expr);
}
if (auto DRE = dyn_cast<DeclRefExpr>(expr)) {
if (auto varDecl = dyn_cast<VarDecl>(DRE->getDecl())) {
if (CS.hasType(DRE)) {
LTI.collectedTypes.insert(CS.getType(DRE).getPointer());
}
return Action::SkipNode(expr);
}
}
// In the case of a function application, we would have already captured
// the return type during constraint generation, so there's no use in
// looking any further.
if (isa<ApplyExpr>(expr) &&
!(isa<BinaryExpr>(expr) || isa<PrefixUnaryExpr>(expr) ||
isa<PostfixUnaryExpr>(expr))) {
return Action::SkipNode(expr);
}
if (auto *binaryExpr = dyn_cast<BinaryExpr>(expr)) {
LTI.binaryExprs.push_back(binaryExpr);
}
if (auto favoredType = CS.getFavoredType(expr)) {
LTI.collectedTypes.insert(favoredType);
return Action::SkipNode(expr);
}
// Optimize branches of a conditional expression separately.
if (auto IE = dyn_cast<TernaryExpr>(expr)) {
CS.optimizeConstraints(IE->getCondExpr());
CS.optimizeConstraints(IE->getThenExpr());
CS.optimizeConstraints(IE->getElseExpr());
return Action::SkipNode(expr);
}
// For exprs of a tuple, avoid favoring. (We need to allow for cases like
// (Int, Int32).)
if (isa<TupleExpr>(expr)) {
return Action::SkipNode(expr);
}
// Coercion exprs have a rigid type, so there's no use in gathering info
// about them.
if (auto *coercion = dyn_cast<CoerceExpr>(expr)) {
// Let's not collect information about types initialized by
// coercions just like we don't for regular initializer calls,
// because that might lead to overly eager type variable merging.
if (!coercion->isLiteralInit())
LTI.collectedTypes.insert(CS.getType(expr).getPointer());
return Action::SkipNode(expr);
}
// Don't walk into subscript expressions - to do so would risk factoring
// the index expression into edge contraction. (We don't want to do this
// if the index expression is a literal type that differs from the return
// type of the subscript operation.)
if (isa<SubscriptExpr>(expr) || isa<DynamicLookupExpr>(expr)) {
return Action::SkipNode(expr);
}
// Don't walk into unresolved member expressions - we avoid merging type
// variables inside UnresolvedMemberExpr and those outside, since they
// should be allowed to behave independently in CS.
if (isa<UnresolvedMemberExpr>(expr)) {
return Action::SkipNode(expr);
}
return Action::Continue(expr);
}
/// Ignore statements.
PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
return Action::SkipNode(stmt);
}
/// Ignore declarations.
PreWalkAction walkToDeclPre(Decl *decl) override {
return Action::SkipNode();
}
/// Ignore patterns.
PreWalkResult<Pattern *> walkToPatternPre(Pattern *pat) override {
return Action::SkipNode(pat);
}
/// Ignore types.
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
return Action::SkipNode();
}
};
/// For a given expression, given information that is global to the
/// expression, attempt to derive a favored type for it.
void computeFavoredTypeForExpr(Expr *expr, ConstraintSystem &CS) {
LinkedTypeInfo lti;
expr->walk(LinkedExprAnalyzer(lti, CS));
// Check whether we can proceed with favoring.
if (llvm::any_of(lti.binaryExprs, [](const BinaryExpr *op) {
auto *ODRE = dyn_cast<OverloadedDeclRefExpr>(op->getFn());
if (!ODRE)
return false;
// Attempting to favor based on operand types is wrong for
// nil-coalescing operator.
auto identifier = ODRE->getDecls().front()->getBaseIdentifier();
return identifier.isNilCoalescingOperator();
})) {
return;
}
if (lti.collectedTypes.size() == 1) {
// TODO: Compute the BCT.
// It's only useful to favor the type instead of
// binding it directly to arguments/result types,
// which means in case it has been miscalculated
// solver can still make progress.
auto favoredTy = (*lti.collectedTypes.begin())->getWithoutSpecifierType();
CS.setFavoredType(expr, favoredTy.getPointer());
// If we have a chain of identical binop expressions with homogeneous
// argument types, we can directly simplify the associated constraint
// graph.
auto simplifyBinOpExprTyVars = [&]() {
// Don't attempt to do linking if there are
// literals intermingled with other inferred types.
if (lti.hasLiteral)
return;
for (auto binExp1 : lti.binaryExprs) {
for (auto binExp2 : lti.binaryExprs) {
if (binExp1 == binExp2)
continue;
auto fnTy1 = CS.getType(binExp1)->getAs<TypeVariableType>();
auto fnTy2 = CS.getType(binExp2)->getAs<TypeVariableType>();
if (!(fnTy1 && fnTy2))
return;
auto ODR1 = dyn_cast<OverloadedDeclRefExpr>(binExp1->getFn());
auto ODR2 = dyn_cast<OverloadedDeclRefExpr>(binExp2->getFn());
if (!(ODR1 && ODR2))
return;
// TODO: We currently limit this optimization to known arithmetic
// operators, but we should be able to broaden this out to
// logical operators as well.
if (!isArithmeticOperatorDecl(ODR1->getDecls()[0]))
return;
if (ODR1->getDecls()[0]->getBaseName() !=
ODR2->getDecls()[0]->getBaseName())
return;
// All things equal, we can merge the tyvars for the function
// types.
auto rep1 = CS.getRepresentative(fnTy1);
auto rep2 = CS.getRepresentative(fnTy2);
if (rep1 != rep2) {
CS.mergeEquivalenceClasses(rep1, rep2,
/*updateWorkList*/ false);
}
auto odTy1 = CS.getType(ODR1)->getAs<TypeVariableType>();
auto odTy2 = CS.getType(ODR2)->getAs<TypeVariableType>();
if (odTy1 && odTy2) {
auto odRep1 = CS.getRepresentative(odTy1);
auto odRep2 = CS.getRepresentative(odTy2);
// Since we'll be choosing the same overload, we can merge
// the overload tyvar as well.
if (odRep1 != odRep2)
CS.mergeEquivalenceClasses(odRep1, odRep2,
/*updateWorkList*/ false);
}
}
}
};
simplifyBinOpExprTyVars();
}
}
/// Determine whether the given parameter type and argument should be
/// "favored" because they match exactly.
bool isFavoredParamAndArg(ConstraintSystem &CS, Type paramTy, Type argTy,
Type otherArgTy = Type()) {
// Determine the argument type.
argTy = argTy->getWithoutSpecifierType();
// Do the types match exactly?
if (paramTy->isEqual(argTy))
return true;
// Don't favor narrowing conversions.
if (argTy->isDouble() && paramTy->isCGFloat())
return false;
llvm::SmallSetVector<ProtocolDecl *, 2> literalProtos;
if (auto argTypeVar = argTy->getAs<TypeVariableType>()) {
auto constraints = CS.getConstraintGraph().gatherConstraints(
argTypeVar, ConstraintGraph::GatheringKind::EquivalenceClass,
[](Constraint *constraint) {
return constraint->getKind() == ConstraintKind::LiteralConformsTo;
});
for (auto constraint : constraints) {
literalProtos.insert(constraint->getProtocol());
}
}
// Dig out the second argument type.
if (otherArgTy)
otherArgTy = otherArgTy->getWithoutSpecifierType();
for (auto literalProto : literalProtos) {
// If there is another, concrete argument, check whether it's type
// conforms to the literal protocol and test against it directly.
// This helps to avoid 'widening' the favored type to the default type for
// the literal.
if (otherArgTy && otherArgTy->getAnyNominal()) {
if (otherArgTy->isEqual(paramTy) &&
CS.lookupConformance(otherArgTy, literalProto)) {
return true;
}
} else if (Type defaultType =
TypeChecker::getDefaultType(literalProto, CS.DC)) {
// If there is a default type for the literal protocol, check whether
// it is the same as the parameter type.
// Check whether there is a default type to compare against.
if (paramTy->isEqual(defaultType) ||
(defaultType->isDouble() && paramTy->isCGFloat()))
return true;
}
}
return false;
}
/// Favor certain overloads in a call based on some basic analysis
/// of the overload set and call arguments.
///
/// \param expr The application.
/// \param isFavored Determine whether the given overload is favored, passing
/// it the "effective" overload type when it's being called.
/// \param mustConsider If provided, a function to detect the presence of
/// overloads which inhibit any overload from being favored.
void favorCallOverloads(ApplyExpr *expr,
ConstraintSystem &CS,
llvm::function_ref<bool(ValueDecl *, Type)> isFavored,
std::function<bool(ValueDecl *)>
mustConsider = nullptr) {
// Find the type variable associated with the function, if any.
auto tyvarType = CS.getType(expr->getFn())->getAs<TypeVariableType>();
if (!tyvarType || CS.getFixedType(tyvarType))
return;
// This type variable is only currently associated with the function
// being applied, and the only constraint attached to it should
// be the disjunction constraint for the overload group.
auto disjunction = CS.getUnboundBindOverloadDisjunction(tyvarType);
if (!disjunction)
return;
// Find the favored constraints and mark them.
SmallVector<Constraint *, 4> newlyFavoredConstraints;
unsigned numFavoredConstraints = 0;
Constraint *firstFavored = nullptr;
for (auto constraint : disjunction->getNestedConstraints()) {
auto *decl = constraint->getOverloadChoice().getDeclOrNull();
if (!decl)
continue;
if (mustConsider && mustConsider(decl)) {
// Roll back any constraints we favored.
for (auto favored : newlyFavoredConstraints)
favored->setFavored(false);
return;
}
Type overloadType = CS.getEffectiveOverloadType(
constraint->getLocator(), constraint->getOverloadChoice(),
/*allowMembers=*/true, CS.DC);
if (!overloadType)
continue;
if (!CS.isDeclUnavailable(decl, constraint->getLocator()) &&
!decl->getAttrs().hasAttribute<DisfavoredOverloadAttr>() &&
isFavored(decl, overloadType)) {
// If we might need to roll back the favored constraints, keep
// track of those we are favoring.
if (mustConsider && !constraint->isFavored())
newlyFavoredConstraints.push_back(constraint);
constraint->setFavored();
++numFavoredConstraints;
if (!firstFavored)
firstFavored = constraint;
}
}
// If there was one favored constraint, set the favored type based on its
// result type.
if (numFavoredConstraints == 1) {
auto overloadChoice = firstFavored->getOverloadChoice();
auto overloadType = CS.getEffectiveOverloadType(
firstFavored->getLocator(), overloadChoice, /*allowMembers=*/true,
CS.DC);
auto resultType = overloadType->castTo<AnyFunctionType>()->getResult();
if (!resultType->hasTypeParameter())
CS.setFavoredType(expr, resultType.getPointer());
}
}
/// Return a pair, containing the total parameter count of a function, coupled
/// with the number of non-default parameters.
std::pair<size_t, size_t> getParamCount(ValueDecl *VD) {
auto fTy = VD->getInterfaceType()->castTo<AnyFunctionType>();
size_t nOperands = fTy->getParams().size();
size_t nNoDefault = 0;
if (auto AFD = dyn_cast<AbstractFunctionDecl>(VD)) {
assert(!AFD->hasImplicitSelfDecl());
for (auto param : *AFD->getParameters()) {
if (!param->isDefaultArgument())
++nNoDefault;
}
} else {
nNoDefault = nOperands;
}
return { nOperands, nNoDefault };
}
bool hasContextuallyFavorableResultType(AnyFunctionType *choice,
Type contextualTy) {
// No restrictions of what result could be.
if (!contextualTy)
return true;
auto resultTy = choice->getResult();
// Result type of the call matches expected contextual type.
return contextualTy->isEqual(resultTy);
}
/// Favor unary operator constraints where we have exact matches
/// for the operand and contextual type.
void favorMatchingUnaryOperators(ApplyExpr *expr,
ConstraintSystem &CS) {
auto *unaryArg = expr->getArgs()->getUnaryExpr();
assert(unaryArg);
// Determine whether the given declaration is favored.
auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
auto fnTy = type->getAs<AnyFunctionType>();
if (!fnTy)
return false;
auto params = fnTy->getParams();
if (params.size() != 1)
return false;
auto paramTy = params[0].getPlainType();
auto argTy = CS.getType(unaryArg);
// There are no CGFloat overloads on some of the unary operators, so
// in order to preserve current behavior, let's not favor overloads
// which would result in conversion from CGFloat to Double; otherwise
// it would lead to ambiguities.
if (argTy->isCGFloat() && paramTy->isDouble())
return false;
return isFavoredParamAndArg(CS, paramTy, argTy) &&
hasContextuallyFavorableResultType(
fnTy,
CS.getContextualType(expr, /*forConstraint=*/false));
};
favorCallOverloads(expr, CS, isFavoredDecl);
}
void favorMatchingOverloadExprs(ApplyExpr *expr,
ConstraintSystem &CS) {
// Find the argument type.
size_t nArgs = expr->getArgs()->size();
auto fnExpr = expr->getFn();
auto mustConsiderVariadicGenericOverloads = [&](ValueDecl *overload) {
if (overload->getAttrs().hasAttribute<DisfavoredOverloadAttr>())
return false;
auto genericContext = overload->getAsGenericContext();
if (!genericContext)
return false;
auto *GPL = genericContext->getGenericParams();
if (!GPL)
return false;
return llvm::any_of(GPL->getParams(),
[&](const GenericTypeParamDecl *GP) {
return GP->isParameterPack();
});
};
// Check to ensure that we have an OverloadedDeclRef, and that we're not
// favoring multiple overload constraints. (Otherwise, in this case
// favoring is useless.
if (auto ODR = dyn_cast<OverloadedDeclRefExpr>(fnExpr)) {
bool haveMultipleApplicableOverloads = false;
for (auto VD : ODR->getDecls()) {
if (VD->getInterfaceType()->is<AnyFunctionType>()) {
auto nParams = getParamCount(VD);
if (nArgs == nParams.first) {
if (haveMultipleApplicableOverloads) {
return;
} else {
haveMultipleApplicableOverloads = true;
}
}
}
}
// Determine whether the given declaration is favored.
auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
// We want to consider all options for calls that might contain the code
// completion location, as missing arguments after the completion
// location are valid (since it might be that they just haven't been
// written yet).
if (CS.isForCodeCompletion())
return false;
if (!type->is<AnyFunctionType>())
return false;
auto paramCount = getParamCount(value);
return nArgs == paramCount.first ||
nArgs == paramCount.second;
};
favorCallOverloads(expr, CS, isFavoredDecl,
mustConsiderVariadicGenericOverloads);
}
// We only currently perform favoring for unary args.
auto *unaryArg = expr->getArgs()->getUnlabeledUnaryExpr();
if (!unaryArg)
return;
if (auto favoredTy = CS.getFavoredType(unaryArg)) {
// Determine whether the given declaration is favored.
auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
auto fnTy = type->getAs<AnyFunctionType>();
if (!fnTy || fnTy->getParams().size() != 1)
return false;
return favoredTy->isEqual(fnTy->getParams()[0].getPlainType());
};
// This is a hack to ensure we always consider the protocol requirement
// itself when calling something that has a default implementation in an
// extension. Otherwise, the extension method might be favored if we're
// inside an extension context, since any archetypes in the parameter
// list could match exactly.
auto mustConsider = [&](ValueDecl *value) -> bool {
return isa<ProtocolDecl>(value->getDeclContext()) ||
mustConsiderVariadicGenericOverloads(value);
};
favorCallOverloads(expr, CS, isFavoredDecl, mustConsider);
}
}
/// Favor binary operator constraints where we have exact matches
/// for the operands and contextual type.
void favorMatchingBinaryOperators(ApplyExpr *expr, ConstraintSystem &CS) {
// If we're generating constraints for a binary operator application,
// there are two special situations to consider:
// 1. If the type checker has any newly created functions with the
// operator's name. If it does, the overloads were created after the
// associated overloaded id expression was created, and we'll need to
// add a new disjunction constraint for the new set of overloads.
// 2. If any component argument expressions (nested or otherwise) are
// literals, we can favor operator overloads whose argument types are
// identical to the literal type, or whose return types are identical
// to any contextual type associated with the application expression.
// Find the argument types.
auto *args = expr->getArgs();
auto *lhs = args->getExpr(0);
auto *rhs = args->getExpr(1);
auto firstArgTy = CS.getType(lhs);
auto secondArgTy = CS.getType(rhs);
auto isOptionalWithMatchingObjectType = [](Type optional,
Type object) -> bool {
if (auto objTy = optional->getRValueType()->getOptionalObjectType())
return objTy->getRValueType()->isEqual(object->getRValueType());
return false;
};
auto isPotentialForcingOpportunity = [&](Type first, Type second) -> bool {
return isOptionalWithMatchingObjectType(first, second) ||
isOptionalWithMatchingObjectType(second, first);
};
// Determine whether the given declaration is favored.
auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
auto fnTy = type->getAs<AnyFunctionType>();
if (!fnTy)
return false;
auto firstFavoredTy = CS.getFavoredType(lhs);
auto secondFavoredTy = CS.getFavoredType(rhs);
auto favoredExprTy = CS.getFavoredType(expr);
if (isArithmeticOperatorDecl(value)) {
// If the parent has been favored on the way down, propagate that
// information to its children.
// TODO: This is only valid for arithmetic expressions.
if (!firstFavoredTy) {
CS.setFavoredType(lhs, favoredExprTy);
firstFavoredTy = favoredExprTy;
}
if (!secondFavoredTy) {
CS.setFavoredType(rhs, favoredExprTy);
secondFavoredTy = favoredExprTy;
}
}
auto params = fnTy->getParams();
if (params.size() != 2)
return false;
auto firstParamTy = params[0].getOldType();
auto secondParamTy = params[1].getOldType();
auto contextualTy = CS.getContextualType(expr, /*forConstraint=*/false);
// Avoid favoring overloads that would require narrowing conversion
// to match the arguments.
{
if (firstArgTy->isDouble() && firstParamTy->isCGFloat())
return false;
if (secondArgTy->isDouble() && secondParamTy->isCGFloat())
return false;
}
return (isFavoredParamAndArg(CS, firstParamTy, firstArgTy, secondArgTy) ||
isFavoredParamAndArg(CS, secondParamTy, secondArgTy,
firstArgTy)) &&
firstParamTy->isEqual(secondParamTy) &&
!isPotentialForcingOpportunity(firstArgTy, secondArgTy) &&
hasContextuallyFavorableResultType(fnTy, contextualTy);
};
favorCallOverloads(expr, CS, isFavoredDecl);
}
/// If \p expr is a call and that call contains the code completion token,
/// add the expressions of all arguments after the code completion token to
/// \p ignoredArguments.
/// Otherwise, returns an empty vector.
/// Assumes that we are solving for code completion.
void getArgumentsAfterCodeCompletionToken(
Expr *expr, ConstraintSystem &CS,
SmallVectorImpl<Expr *> &ignoredArguments) {
assert(CS.isForCodeCompletion());
/// Don't ignore the rhs argument if the code completion token is the lhs of
/// an operator call. Main use case is the implicit `<complete> ~= $match`
/// call created for pattern matching, in which we need to type-check
/// `$match` to get a contextual type for `<complete>`
if (isa<BinaryExpr>(expr)) {
return;
}
auto args = expr->getArgs();
auto argInfo = getCompletionArgInfo(expr, CS);
if (!args || !argInfo) {
return;
}
for (auto argIndex : indices(*args)) {
if (argInfo->isBefore(argIndex)) {
ignoredArguments.push_back(args->get(argIndex).getExpr());
}
}
}
class ConstraintOptimizer : public ASTWalker {
ConstraintSystem &CS;
public:
ConstraintOptimizer(ConstraintSystem &cs) :
CS(cs) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (CS.isArgumentIgnoredForCodeCompletion(expr)) {
return Action::SkipNode(expr);
}
if (auto applyExpr = dyn_cast<ApplyExpr>(expr)) {
if (isa<PrefixUnaryExpr>(applyExpr) ||
isa<PostfixUnaryExpr>(applyExpr)) {
favorMatchingUnaryOperators(applyExpr, CS);
} else if (isa<BinaryExpr>(applyExpr)) {
favorMatchingBinaryOperators(applyExpr, CS);
} else {
favorMatchingOverloadExprs(applyExpr, CS);
}
}
// If the paren expr has a favored type, and the subExpr doesn't,
// propagate downwards. Otherwise, propagate upwards.
if (auto parenExpr = dyn_cast<ParenExpr>(expr)) {
if (!CS.getFavoredType(parenExpr->getSubExpr())) {
CS.setFavoredType(parenExpr->getSubExpr(),
CS.getFavoredType(parenExpr));
} else if (!CS.getFavoredType(parenExpr)) {
CS.setFavoredType(parenExpr,
CS.getFavoredType(parenExpr->getSubExpr()));
}
}
if (isa<ClosureExpr>(expr))
return Action::SkipNode(expr);
return Action::Continue(expr);
}
/// Ignore statements.
PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
return Action::SkipNode(stmt);
}
/// Ignore declarations.
PreWalkAction walkToDeclPre(Decl *decl) override {
return Action::SkipNode();
}
};
} // end anonymous namespace
void TypeVarRefCollector::inferTypeVars(Decl *D) {
// We're only interested in VarDecls.
if (!isa_and_nonnull<VarDecl>(D))
return;
auto ty = CS.getTypeIfAvailable(D);
if (!ty)
return;
SmallPtrSet<TypeVariableType *, 4> typeVars;
ty->getTypeVariables(typeVars);
TypeVars.insert(typeVars.begin(), typeVars.end());
}
void TypeVarRefCollector::inferTypeVars(PackExpansionExpr *E) {
auto expansionType = CS.getType(E)->castTo<PackExpansionType>();
SmallPtrSet<TypeVariableType *, 4> referencedVars;
expansionType->getTypeVariables(referencedVars);
TypeVars.insert(referencedVars.begin(), referencedVars.end());
}
ASTWalker::PreWalkResult<Expr *>
TypeVarRefCollector::walkToExprPre(Expr *expr) {
if (isa<ClosureExpr>(expr))
DCDepth += 1;
if (auto *DRE = dyn_cast<DeclRefExpr>(expr))
inferTypeVars(DRE->getDecl());
// FIXME: We can see UnresolvedDeclRefExprs here because we don't walk into
// patterns when running preCheckTarget, since we don't resolve patterns
// until CSGen. We ought to consider moving pattern resolution into
// pre-checking, which would allow us to pre-check patterns normally.
if (auto *declRef = dyn_cast<UnresolvedDeclRefExpr>(expr)) {
auto name = declRef->getName();
auto loc = declRef->getLoc();
if (name.isSimpleName() && loc.isValid()) {
auto *SF = CS.DC->getParentSourceFile();
auto *D = ASTScope::lookupSingleLocalDecl(SF, name.getFullName(), loc);
inferTypeVars(D);
}
}
if (auto *packElement = getAsExpr<PackElementExpr>(expr)) {
// If environment hasn't been established yet, it means that pack expansion
// appears inside of this closure.
if (auto *outerEnvironment = CS.getPackEnvironment(packElement))
inferTypeVars(outerEnvironment);
}
return Action::Continue(expr);
}
ASTWalker::PostWalkResult<Expr *>
TypeVarRefCollector::walkToExprPost(Expr *expr) {
if (isa<ClosureExpr>(expr))
DCDepth -= 1;
return Action::Continue(expr);
}
ASTWalker::PreWalkResult<Stmt *>
TypeVarRefCollector::walkToStmtPre(Stmt *stmt) {
// If we have a return without any intermediate DeclContexts in a ClosureExpr,
// we need to include any type variables in the closure's result type, since
// the conjunction will generate constraints using that type. We don't need to
// connect to returns in e.g nested closures since we'll connect those when we
// generate constraints for those closures. We also don't need to bother if
// we're generating constraints for the closure itself, since we'll connect
// the conjunction to the closure type variable itself.
if (auto *CE = dyn_cast<ClosureExpr>(DC)) {
if (isa<ReturnStmt>(stmt) && DCDepth == 0 &&
!Locator->directlyAt<ClosureExpr>()) {
SmallPtrSet<TypeVariableType *, 4> typeVars;
CS.getClosureType(CE)->getResult()->getTypeVariables(typeVars);
TypeVars.insert(typeVars.begin(), typeVars.end());
}
}
return Action::Continue(stmt);
}
namespace {
class ConstraintGenerator : public ExprVisitor<ConstraintGenerator, Type> {
ConstraintSystem &CS;
DeclContext *CurDC;
ConstraintSystemPhase CurrPhase;
/// A map from each UnresolvedMemberExpr to the respective (implicit) base
/// found during our walk.
llvm::MapVector<UnresolvedMemberExpr *, Type> UnresolvedBaseTypes;
/// A stack of pack expansions that can open pack elements.
llvm::SmallVector<PackExpansionExpr *, 1> OuterExpansions;
/// Returns false and emits the specified diagnostic if the member reference
/// base is a nil literal. Returns true otherwise.
bool isValidBaseOfMemberRef(Expr *base, Diag<> diagnostic) {
if (auto nilLiteral = dyn_cast<NilLiteralExpr>(base)) {
CS.getASTContext().Diags.diagnose(nilLiteral->getLoc(), diagnostic);
return false;
}
return true;
}
/// Retrieves a matching set of function params for an argument list.
void getMatchingParams(ArgumentList *argList,
SmallVectorImpl<AnyFunctionType::Param> &result) {
for (auto arg : *argList) {
ParameterTypeFlags flags;
auto ty = CS.getType(arg.getExpr());
if (arg.isInOut()) {
ty = ty->getInOutObjectType();
flags = flags.withInOut(true);
}
if (arg.isConst()) {
flags = flags.withCompileTimeConst(true);
}
result.emplace_back(ty, arg.getLabel(), flags);
}
}
/// If the provided type is a tuple, decomposes it into a matching set of
/// function params. Otherwise produces a single parameter of the type.
void decomposeTuple(Type ty,
SmallVectorImpl<AnyFunctionType::Param> &result) {
switch (ty->getKind()) {
case TypeKind::Tuple: {
auto tupleTy = cast<TupleType>(ty.getPointer());
for (auto &elt : tupleTy->getElements())
result.emplace_back(elt.getType(), elt.getName());
return;
}
default:
result.emplace_back(ty, Identifier());
}
}
/// Add constraints for a reference to a named member of the given
/// base type, and return the type of such a reference.
Type addMemberRefConstraints(Expr *expr, Expr *base, DeclNameRef name,