-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathCSGen.cpp
4369 lines (3642 loc) · 168 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 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 {
/// 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());
}
}
}
} // 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,
FunctionRefInfo functionRefInfo,
ArrayRef<ValueDecl *> outerAlternatives) {
// The base must have a member of the given name, such that accessing
// that member through the base returns a value convertible to the type
// of this expression.
auto baseTy = CS.getType(base);
if (isa<ErrorExpr>(base)) {
return CS.createTypeVariable(
CS.getConstraintLocator(expr, ConstraintLocator::Member),
TVO_CanBindToHole);
}
unsigned options = (TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
if (!OuterExpansions.empty())
options |= TVO_CanBindToPack;
auto tv = CS.createTypeVariable(
CS.getConstraintLocator(expr, ConstraintLocator::Member),
options);
SmallVector<OverloadChoice, 4> outerChoices;
for (auto decl : outerAlternatives) {
outerChoices.push_back(OverloadChoice(Type(), decl, functionRefInfo));
}
CS.addValueMemberConstraint(
baseTy, name, tv, CurDC, functionRefInfo, outerChoices,
CS.getConstraintLocator(expr, ConstraintLocator::Member));
return tv;
}
/// Add constraints for a reference to a specific member of the given
/// base type, and return the type of such a reference.
Type addMemberRefConstraints(Expr *expr, Expr *base, ValueDecl *decl,
FunctionRefInfo functionRefInfo) {
// If we're referring to an invalid declaration, fail.
if (!decl)
return nullptr;
if (decl->isInvalid())
return nullptr;
auto memberLocator =
CS.getConstraintLocator(expr, ConstraintLocator::Member);
auto tv = CS.createTypeVariable(memberLocator,
TVO_CanBindToLValue | TVO_CanBindToNoEscape);
OverloadChoice choice =
OverloadChoice(CS.getType(base), decl, functionRefInfo);
auto locator = CS.getConstraintLocator(expr, ConstraintLocator::Member);
CS.addBindOverloadConstraint(tv, choice, locator, CurDC);
return tv;
}
/// Add constraints for a subscript operation.
Type addSubscriptConstraints(
Expr *anchor, Type baseTy, ValueDecl *declOrNull, ArgumentList *argList,
ConstraintLocator *locator = nullptr,
SmallVectorImpl<TypeVariableType *> *addedTypeVars = nullptr) {
// Locators used in this expression.
if (locator == nullptr)
locator = CS.getConstraintLocator(anchor);
auto fnLocator =
CS.getConstraintLocator(locator,
ConstraintLocator::ApplyFunction);
auto memberLocator =
CS.getConstraintLocator(locator,
ConstraintLocator::SubscriptMember);
auto resultLocator =
CS.getConstraintLocator(locator,
ConstraintLocator::FunctionResult);
CS.associateArgumentList(memberLocator, argList);
Type outputTy;
// For an integer subscript expression on an array slice type, instead of
// introducing a new type variable we can easily obtain the element type.
if (isa<SubscriptExpr>(anchor)) {
auto isLValueBase = false;
auto baseObjTy = baseTy;
if (baseObjTy->is<LValueType>()) {
isLValueBase = true;
baseObjTy = baseObjTy->getWithoutSpecifierType();
}
if (auto elementTy = baseObjTy->isArrayType()) {
if (auto arraySliceTy =
dyn_cast<ArraySliceType>(baseObjTy.getPointer())) {
baseObjTy = arraySliceTy->getDesugaredType();
}
if (argList->isUnlabeledUnary() &&
isa<IntegerLiteralExpr>(argList->getExpr(0))) {
outputTy = elementTy;
if (isLValueBase)
outputTy = LValueType::get(outputTy);
}
}
}
if (outputTy.isNull()) {
outputTy = CS.createTypeVariable(resultLocator,
TVO_CanBindToLValue | TVO_CanBindToNoEscape);
if (addedTypeVars)
addedTypeVars->push_back(outputTy->castTo<TypeVariableType>());
}
// FIXME: This can only happen when diagnostics successfully type-checked
// sub-expression of the subscript and mutated AST, but under normal
// circumstances subscript should never have InOutExpr as a direct child
// until type checking is complete and expression is re-written.
// Proper fix for such situation requires preventing diagnostics from
// re-writing AST after successful type checking of the sub-expressions.
if (auto inoutTy = baseTy->getAs<InOutType>()) {
baseTy = LValueType::get(inoutTy->getObjectType());
}
// Add the member constraint for a subscript declaration.
// FIXME: weak name!
auto memberTy = CS.createTypeVariable(
memberLocator, TVO_CanBindToLValue | TVO_CanBindToNoEscape);
if (addedTypeVars)
addedTypeVars->push_back(memberTy);
// FIXME: synthesizeMaterializeForSet() wants to statically dispatch to
// a known subscript here. This might be cleaner if we split off a new
// UnresolvedSubscriptExpr from SubscriptExpr.
if (auto decl = declOrNull) {
OverloadChoice choice = OverloadChoice(
baseTy, decl, FunctionRefInfo::doubleBaseNameApply());
CS.addBindOverloadConstraint(memberTy, choice, memberLocator,
CurDC);
} else {
CS.addValueMemberConstraint(baseTy, DeclNameRef::createSubscript(),
memberTy, CurDC,
FunctionRefInfo::doubleBaseNameApply(),
/*outerAlternatives=*/{}, memberLocator);
}
SmallVector<AnyFunctionType::Param, 8> params;
getMatchingParams(argList, params);
// Add the constraint that the index expression's type be convertible
// to the input type of the subscript operator.
CS.addConstraint(ConstraintKind::ApplicableFunction,
FunctionType::get(params, outputTy),
memberTy,
fnLocator);
Type fixedOutputType =
CS.getFixedTypeRecursive(outputTy, /*wantRValue=*/false);
if (!fixedOutputType->isTypeVariableOrMember()) {
outputTy = fixedOutputType;
}
return outputTy;
}
Type openPackElement(Type packType, ConstraintLocator *locator,
PackExpansionExpr *packElementEnvironment) {
if (!packElementEnvironment) {
return CS.createTypeVariable(locator,
TVO_CanBindToHole | TVO_CanBindToNoEscape);
}
// The type of a PackElementExpr is the opened pack element archetype
// of the pack reference.
OpenPackElementType openPackElement(CS, locator, packElementEnvironment);
return openPackElement(packType, /*packRepr*/ nullptr);
}
public:
ConstraintGenerator(ConstraintSystem &CS, DeclContext *DC)
: CS(CS), CurDC(DC ? DC : CS.DC), CurrPhase(CS.getPhase()) {
// Although constraint system is initialized in `constraint
// generation` phase, we have to set it here manually because e.g.
// result builders could generate constraints for its body
// in the middle of the solving.
CS.setPhase(ConstraintSystemPhase::ConstraintGeneration);
// Pick up the saved stack of pack expansions so we can continue
// to handle pack element references inside the closure body.
if (auto *ACE = dyn_cast<AbstractClosureExpr>(CurDC)) {
OuterExpansions = CS.getCapturedExpansions(ACE);
}
}
virtual ~ConstraintGenerator() {
CS.setPhase(CurrPhase);
}
ConstraintSystem &getConstraintSystem() const { return CS; }
void pushPackExpansionExpr(PackExpansionExpr *expr) {
OuterExpansions.push_back(expr);
SmallVector<ASTNode, 2> expandedPacks;
collectExpandedPacks(expr, expandedPacks);
for (auto pack : expandedPacks) {
if (auto *elementExpr = getAsExpr<PackElementExpr>(pack)) {
CS.addPackEnvironment(elementExpr, expr);
}
}
auto *patternLoc = CS.getConstraintLocator(
expr, ConstraintLocator::PackExpansionPattern);
auto patternType = CS.createTypeVariable(
patternLoc,
TVO_CanBindToPack | TVO_CanBindToNoEscape | TVO_CanBindToHole);
auto *shapeLoc =
CS.getConstraintLocator(expr, ConstraintLocator::PackShape);
auto *shapeTypeVar = CS.createTypeVariable(
shapeLoc, TVO_CanBindToPack | TVO_CanBindToHole);
auto expansionType = PackExpansionType::get(patternType, shapeTypeVar);
CS.setType(expr, expansionType);
}
/// Records a fix for an invalid AST node, and returns a potential hole
/// type variable for it.
Type recordInvalidNode(ASTNode node) {
CS.recordFix(
IgnoreInvalidASTNode::create(CS, CS.getConstraintLocator(node)));
return CS.createTypeVariable(CS.getConstraintLocator(node),
TVO_CanBindToHole);
}
virtual Type visitErrorExpr(ErrorExpr *E) {
return recordInvalidNode(E);
}
virtual Type visitCodeCompletionExpr(CodeCompletionExpr *E) {
CS.Options |= ConstraintSystemFlags::SuppressDiagnostics;
auto locator = CS.getConstraintLocator(E);
return CS.createTypeVariable(locator, TVO_CanBindToLValue |
TVO_CanBindToNoEscape |
TVO_CanBindToHole);
}
Type visitNilLiteralExpr(NilLiteralExpr *expr) {
auto literalTy = visitLiteralExpr(expr);
// Allow `nil` to be a hole so we can diagnose it via a fix
// if it turns out that there is no contextual information.
if (auto *typeVar = literalTy->getAs<TypeVariableType>())
CS.recordPotentialHole(typeVar);
return literalTy;
}
Type visitFloatLiteralExpr(FloatLiteralExpr *expr) {
auto &ctx = CS.getASTContext();
// Get the _MaxBuiltinFloatType decl, or look for it if it's not cached.
auto maxFloatTypeDecl = ctx.get_MaxBuiltinFloatTypeDecl();
if (!maxFloatTypeDecl ||
!maxFloatTypeDecl->getDeclaredInterfaceType()->is<BuiltinFloatType>()) {
ctx.Diags.diagnose(expr->getLoc(), diag::no_MaxBuiltinFloatType_found);
return nullptr;
}
return visitLiteralExpr(expr);
}
Type visitLiteralExpr(LiteralExpr *expr) {
// If the expression has already been assigned a type; just use that type.
if (expr->getType())
return expr->getType();
auto protocol = TypeChecker::getLiteralProtocol(CS.getASTContext(), expr);
if (!protocol)
return nullptr;
auto tv = CS.createTypeVariable(CS.getConstraintLocator(expr),
TVO_PrefersSubtypeBinding |
TVO_CanBindToNoEscape);
CS.addConstraint(ConstraintKind::LiteralConformsTo, tv,
protocol->getDeclaredInterfaceType(),
CS.getConstraintLocator(expr));
return tv;
}
Type
visitInterpolatedStringLiteralExpr(InterpolatedStringLiteralExpr *expr) {
// Dig out the ExpressibleByStringInterpolation protocol.
auto &ctx = CS.getASTContext();
auto interpolationProto = TypeChecker::getProtocol(
ctx, expr->getLoc(),
KnownProtocolKind::ExpressibleByStringInterpolation);
if (!interpolationProto) {
ctx.Diags.diagnose(expr->getStartLoc(),
diag::interpolation_missing_proto);
return nullptr;
}
// The type of the expression must conform to the
// ExpressibleByStringInterpolation protocol.
auto locator = CS.getConstraintLocator(expr);
auto tv = CS.createTypeVariable(locator,
TVO_PrefersSubtypeBinding |
TVO_CanBindToNoEscape);
CS.addConstraint(ConstraintKind::LiteralConformsTo, tv,
interpolationProto->getDeclaredInterfaceType(),
locator);
if (auto appendingExpr = expr->getAppendingExpr()) {
auto associatedTypeDecl = interpolationProto->getAssociatedType(
ctx.Id_StringInterpolation);
if (associatedTypeDecl == nullptr) {
ctx.Diags.diagnose(expr->getStartLoc(),
diag::interpolation_broken_proto);
return nullptr;
}
auto interpolationTV =
CS.createTypeVariable(locator, TVO_CanBindToNoEscape);
auto interpolationType =
DependentMemberType::get(tv, associatedTypeDecl);
CS.addConstraint(ConstraintKind::Equal, interpolationTV,
interpolationType, locator);
auto appendingExprType = CS.getType(appendingExpr);
auto appendingLocator = CS.getConstraintLocator(appendingExpr);
SmallVector<TypeVariableType *, 2> referencedVars;
if (auto *tap = getAsExpr<TapExpr>(appendingExpr)) {
// Collect all of the variable references that appear
// in the tap body, otherwise tap expression is going
// to get disconnected from the context.
if (auto *body = tap->getBody()) {
TypeVarRefCollector refCollector(
CS, tap->getVar()->getDeclContext(), locator);
body->walk(refCollector);
auto vars = refCollector.getTypeVars();
referencedVars.append(vars.begin(), vars.end());
}
}
// Must be Conversion; if it's Equal, then in semi-rare cases, the
// interpolation temporary variable cannot be @lvalue.
CS.addUnsolvedConstraint(Constraint::create(
CS, ConstraintKind::Conversion, appendingExprType, interpolationTV,
appendingLocator, referencedVars));
}
return tv;
}
Type visitMagicIdentifierLiteralExpr(MagicIdentifierLiteralExpr *expr) {
#ifdef SWIFT_BUILD_SWIFT_SYNTAX
auto &ctx = CS.getASTContext();
if (ctx.LangOpts.hasFeature(Feature::BuiltinMacros)) {
auto kind = MagicIdentifierLiteralExpr::getKindString(expr->getKind())
.drop_front();
auto protocol =
TypeChecker::getLiteralProtocol(CS.getASTContext(), expr);
if (!protocol)
return Type();
auto macroIdent = ctx.getIdentifier(kind);
auto macros = lookupMacros(Identifier(), macroIdent,
FunctionRefInfo::unappliedBaseName(),
MacroRole::Expression);
if (!macros.empty()) {
// Introduce an overload set for the macro reference.
auto locator = CS.getConstraintLocator(expr);
auto macroRefType = Type(CS.createTypeVariable(locator, 0));
CS.addOverloadSet(macroRefType, macros, CurDC, locator);
// FIXME: Can this be encoded in the macro definition somehow?
CS.addConstraint(ConstraintKind::LiteralConformsTo, macroRefType,
protocol->getDeclaredInterfaceType(),
CS.getConstraintLocator(expr));
return macroRefType;
}
}
// Fall through to use old implementation.
#endif
switch (expr->getKind()) {
// Magic pointer identifiers are of type UnsafeMutableRawPointer.
#define MAGIC_POINTER_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \
case MagicIdentifierLiteralExpr::NAME:
#include "swift/AST/MagicIdentifierKinds.def"
{
auto &ctx = CS.getASTContext();
if (TypeChecker::requirePointerArgumentIntrinsics(ctx, expr->getLoc()))
return nullptr;
return ctx.getUnsafeRawPointerType();
}
default:
// Others are actual literals and should be handled like any literal.
return visitLiteralExpr(expr);
}
llvm_unreachable("Unhandled MagicIdentifierLiteralExpr in switch.");
}
Type visitObjectLiteralExpr(ObjectLiteralExpr *expr) {
auto *exprLoc = CS.getConstraintLocator(expr);
CS.associateArgumentList(exprLoc, expr->getArgs());
// If the expression has already been assigned a type; just use that type.
if (expr->getType())
return expr->getType();
auto &ctx = CS.getASTContext();
auto &de = ctx.Diags;
auto protocol = TypeChecker::getLiteralProtocol(ctx, expr);
if (!protocol) {
de.diagnose(expr->getLoc(), diag::use_unknown_object_literal_protocol,
expr->getLiteralKindPlainName());
return nullptr;
}
auto witnessType = CS.createTypeVariable(
exprLoc, TVO_PrefersSubtypeBinding | TVO_CanBindToNoEscape |
TVO_CanBindToHole);
CS.addConstraint(ConstraintKind::LiteralConformsTo, witnessType,
protocol->getDeclaredInterfaceType(), exprLoc);
// The arguments are required to be argument-convertible to the
// idealized parameter type of the initializer, which generally
// simplifies the first label (e.g. "colorLiteralRed:") by stripping
// all the redundant stuff about literals (leaving e.g. "red:").
// Constraint application will quietly rewrite the type of 'args' to
// use the right labels before forming the call to the initializer.
auto constrName = TypeChecker::getObjectLiteralConstructorName(ctx, expr);
assert(constrName);
auto *constr = dyn_cast_or_null<ConstructorDecl>(
protocol->getSingleRequirement(constrName));
if (!constr) {
de.diagnose(protocol, diag::object_literal_broken_proto);
return nullptr;
}
auto *memberLoc =
CS.getConstraintLocator(expr, ConstraintLocator::ConstructorMember);
auto *fnLoc =
CS.getConstraintLocator(expr, ConstraintLocator::ApplyFunction);
auto *memberTypeLoc = CS.getConstraintLocator(
fnLoc, LocatorPathElt::ConstructorMemberType());
auto *memberType =
CS.createTypeVariable(memberTypeLoc, TVO_CanBindToNoEscape);
CS.addValueMemberConstraint(MetatypeType::get(witnessType, ctx),
DeclNameRef(constrName), memberType, CurDC,
FunctionRefInfo::doubleBaseNameApply(), {},
memberLoc);
SmallVector<AnyFunctionType::Param, 8> params;
getMatchingParams(expr->getArgs(), params);
auto resultType = CS.createTypeVariable(
CS.getConstraintLocator(expr, ConstraintLocator::FunctionResult),
TVO_CanBindToNoEscape);
CS.addConstraint(ConstraintKind::ApplicableFunction,
FunctionType::get(params, resultType), memberType,
fnLoc);
if (constr->isFailable())
return OptionalType::get(witnessType);
return witnessType;
}
Type visitRegexLiteralExpr(RegexLiteralExpr *E) {
// Retrieve the computed Regex type from the compiler regex library.
auto ty = E->getRegexType();
if (!ty)
return recordInvalidNode(E);
return ty;
}
PackExpansionExpr *getParentPackExpansionExpr(Expr *E) const {
auto *current = E;
while (auto *parent = CS.getParentExpr(current)) {
if (auto *expansion = dyn_cast<PackExpansionExpr>(parent)) {
return expansion;
}
current = parent;
}
return nullptr;
}
Type visitDeclRefExpr(DeclRefExpr *E) {
auto locator = CS.getConstraintLocator(E);
auto invalidateReference = [&]() -> Type {
auto *hole = CS.createTypeVariable(locator, TVO_CanBindToHole);
(void)CS.recordFix(AllowRefToInvalidDecl::create(CS, locator));
CS.setType(E, hole);
return hole;
};
Type knownType;
if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
knownType = CS.getTypeIfAvailable(VD);
if (!knownType)
knownType = VD->getTypeInContext();
if (knownType) {
// An out-of-scope type variable(s) could appear the type of
// a declaration only in diagnostic mode when invalid variable
// declaration is recursively referenced inside of a multi-statement
// closure located somewhere within its initializer e.g.:
// `let x = [<call>] { ... print(x) }`. It happens because the
// variable assumes the result type of its initializer unless
// its specified explicitly.
if (isa<ClosureExpr>(CurDC) && knownType->hasTypeVariable()) {
if (knownType.findIf([&](Type type) {
auto *typeVar = type->getAs<TypeVariableType>();
if (!typeVar || CS.getFixedType(typeVar))
return false;
return !CS.isActiveTypeVariable(typeVar);
}))
return invalidateReference();
}
// If the known type has an error, bail out.
if (knownType->hasError()) {
return invalidateReference();
}
// value packs cannot be referenced without `each` immediately
// preceding them.
if (auto *expansionType = knownType->getAs<PackExpansionType>()) {
if (!isExpr<PackElementExpr>(CS.getParentExpr(E))) {
auto packType = expansionType->getPatternType();
(void)CS.recordFix(
IgnoreMissingEachKeyword::create(CS, packType, locator));
return openPackElement(packType, locator,
getParentPackExpansionExpr(E));
}
}
}
}
// If declaration is invalid, let's turn it into a potential hole
// and keep generating constraints.
// For code completion, we still resolve the overload and replace error
// types inside the function decl with placeholders
// (in getTypeOfReference) so we can match non-error param types.
if (!knownType && E->getDecl()->isInvalid() &&
!CS.isForCodeCompletion()) {
return invalidateReference();
}
unsigned options = (TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
if (!OuterExpansions.empty())
options |= TVO_CanBindToPack;
// Create an overload choice referencing this declaration and immediately
// resolve it. This records the overload for use later.
auto tv = CS.createTypeVariable(locator, options);
OverloadChoice choice =
OverloadChoice(Type(), E->getDecl(), E->getFunctionRefInfo());
CS.resolveOverload(locator, tv, choice, CurDC);
return tv;
}
Type visitOtherConstructorDeclRefExpr(OtherConstructorDeclRefExpr *E) {
return E->getType();
}
Type visitSuperRefExpr(SuperRefExpr *E) {
if (E->getType())
return E->getType();
// Resolve the super type of 'self'.
auto *selfDecl = E->getSelf();
DeclContext *typeContext = selfDecl->getDeclContext()->getParent();
assert(typeContext);
auto selfTy =
CS.DC->mapTypeIntoContext(typeContext->getDeclaredInterfaceType());
auto superclassTy = selfTy->getSuperclass();
if (!superclassTy)
return Type();
if (selfDecl->getInterfaceType()->is<MetatypeType>())
superclassTy = MetatypeType::get(superclassTy);
return superclassTy;
}
Type
resolveTypeReferenceInExpression(TypeRepr *repr,
TypeResolutionOptions options,
const ConstraintLocatorBuilder &locator) {
// Introduce type variables for unbound generics.
const auto genericOpener = OpenUnboundGenericType(CS, locator);
const auto placeholderHandler = HandlePlaceholderType(CS, locator);
// Add a PackElementOf constraint for 'each T' type reprs.
PackExpansionExpr *elementEnv = nullptr;
if (!OuterExpansions.empty()) {
options |= TypeResolutionFlags::AllowPackReferences;
elementEnv = OuterExpansions.back();
}
const auto packElementOpener = OpenPackElementType(CS, locator, elementEnv);
const auto result = TypeResolution::resolveContextualType(
repr, CS.DC, options, genericOpener, placeholderHandler,
packElementOpener);
if (result->hasError()) {
CS.recordFix(
IgnoreInvalidASTNode::create(CS, CS.getConstraintLocator(locator)));
return CS.createTypeVariable(CS.getConstraintLocator(repr),
TVO_CanBindToHole);
}
// Diagnose top-level usages of placeholder types.
if (auto *ty = dyn_cast<PlaceholderTypeRepr>(repr->getWithoutParens())) {
auto *loc = CS.getConstraintLocator(locator, {LocatorPathElt::PlaceholderType(ty)});
CS.recordFix(IgnoreInvalidPlaceholder::create(CS, loc));
}
return result;
}
Type visitTypeExpr(TypeExpr *E) {
Type type;
// If this is an implicit TypeExpr, don't validate its contents.
auto *const locator = CS.getConstraintLocator(E);
if (E->isImplicit()) {
type = CS.getInstanceType(CS.cacheType(E));
assert(type && "Implicit type expr must have type set!");
type = CS.replaceInferableTypesWithTypeVars(type, locator);
} else {
auto *repr = E->getTypeRepr();
assert(repr && "Explicit node has no type repr!");
type = resolveTypeReferenceInExpression(
repr, TypeResolverContext::InExpression, locator);
}
if (!type || type->hasError()) return Type();
return MetatypeType::get(type);
}
Type visitTypeValueExpr(TypeValueExpr *E) {
auto locator = CS.getConstraintLocator(E);
auto type = resolveTypeReferenceInExpression(E->getParamTypeRepr(),
TypeResolverContext::InExpression,
locator);
if (!type || type->hasError()) {
return Type();
}
auto archetype = type->castTo<ArchetypeType>();
E->setParamType(archetype);
return archetype->getValueType();
}
Type visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *expr) {
llvm_unreachable("Already type-checked");
}
Type visitOverloadedDeclRefExpr(OverloadedDeclRefExpr *expr) {
// For a reference to an overloaded declaration, we create a type variable
// that will be equal to different types depending on which overload
// is selected.
auto locator = CS.getConstraintLocator(expr);
auto tv = CS.createTypeVariable(locator,
TVO_CanBindToLValue | TVO_CanBindToNoEscape);
ArrayRef<ValueDecl*> decls = expr->getDecls();
SmallVector<OverloadChoice, 4> choices;
for (unsigned i = 0, n = decls.size(); i != n; ++i) {
// If the result is invalid, skip it.
// FIXME: Note this as invalid, in case we don't find a solution,
// so we don't let errors cascade further.
if (decls[i]->isInvalid())
continue;
OverloadChoice choice =
OverloadChoice(Type(), decls[i], expr->getFunctionRefInfo());
choices.push_back(choice);
}
if (choices.empty()) {
// There are no suitable overloads. Just fail.
return nullptr;
}
// Record this overload set.
CS.addOverloadSet(tv, choices, CurDC, locator);
return tv;
}
Type visitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *expr) {
// This is an error case, where we're trying to use type inference
// to help us determine which declaration the user meant to refer to.
// FIXME: Do we need to note that we're doing some kind of recovery?
return CS.createTypeVariable(CS.getConstraintLocator(expr),
TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
}
Type visitMemberRefExpr(MemberRefExpr *expr) {
return addMemberRefConstraints(
expr, expr->getBase(), expr->getMember().getDecl(),
/*FIXME:*/ FunctionRefInfo::doubleBaseNameApply());
}
Type visitDynamicMemberRefExpr(DynamicMemberRefExpr *expr) {
llvm_unreachable("Already typechecked");
}
void setUnresolvedBaseType(UnresolvedMemberExpr *UME, Type ty) {
UnresolvedBaseTypes.insert({UME, ty});
}
Type getUnresolvedBaseType(UnresolvedMemberExpr *UME) {
auto result = UnresolvedBaseTypes.find(UME);
assert(result != UnresolvedBaseTypes.end());
return result->second;
}
virtual Type visitUnresolvedMemberExpr(UnresolvedMemberExpr *expr) {
auto baseLocator = CS.getConstraintLocator(
expr,
ConstraintLocator::MemberRefBase);
auto memberLocator
= CS.getConstraintLocator(expr, ConstraintLocator::UnresolvedMember);