-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckConstraints.cpp
3004 lines (2542 loc) · 104 KB
/
TypeCheckConstraints.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
//===--- TypeCheckConstraints.cpp - Constraint-based Type Checking --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides high-level entry points that use constraint
// systems for type checking, as well as a few miscellaneous helper
// functions that support the constraint system.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "TypeChecker.h"
#include "MiscDiagnostics.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/TypeCheckerDebugConsumer.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Parse/Lexer.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
#include <iterator>
#include <map>
#include <memory>
#include <utility>
#include <tuple>
using namespace swift;
using namespace constraints;
//===----------------------------------------------------------------------===//
// Type variable implementation.
//===----------------------------------------------------------------------===//
#pragma mark Type variable implementation
void TypeVariableType::Implementation::print(llvm::raw_ostream &OS) {
getTypeVariable()->print(OS, PrintOptions());
}
TypeBase *TypeVariableType::getBaseBeingSubstituted() {
auto impl = this->getImpl();
auto archetype = impl.getArchetype();
if (archetype)
return archetype;
if (auto locator = impl.getLocator())
if (auto anchor = locator->getAnchor())
if (auto anchorType = anchor->getType())
if (!(anchorType->getAs<TypeVariableType>() ||
anchorType->getAs<AnyFunctionType>()))
return anchorType.getPointer();
if (auto proto = impl.literalConformanceProto) {
return proto->getType()->
getAs<MetatypeType>()->
getInstanceType().getPointer();
}
return this;
}
SavedTypeVariableBinding::SavedTypeVariableBinding(TypeVariableType *typeVar)
: TypeVarAndOptions(typeVar, typeVar->getImpl().Options),
ParentOrFixed(typeVar->getImpl().ParentOrFixed) { }
void SavedTypeVariableBinding::restore() {
auto *typeVar = getTypeVariable();
typeVar->getImpl().Options = getOptions();
typeVar->getImpl().ParentOrFixed = ParentOrFixed;
}
ArchetypeType *TypeVariableType::Implementation::getArchetype() const {
// Check whether we have a path that terminates at an archetype locator.
if (!locator || locator->getPath().empty() ||
locator->getPath().back().getKind() != ConstraintLocator::Archetype)
return nullptr;
// Retrieve the archetype.
return locator->getPath().back().getArchetype();
}
// Only allow allocation of resolved overload set list items using the
// allocator in ASTContext.
void *ResolvedOverloadSetListItem::operator new(size_t bytes,
ConstraintSystem &cs,
unsigned alignment) {
return cs.getAllocator().Allocate(bytes, alignment);
}
void *operator new(size_t bytes, ConstraintSystem& cs,
size_t alignment) {
return cs.getAllocator().Allocate(bytes, alignment);
}
bool constraints::computeTupleShuffle(ArrayRef<TupleTypeElt> fromTuple,
ArrayRef<TupleTypeElt> toTuple,
SmallVectorImpl<int> &sources,
SmallVectorImpl<unsigned> &variadicArgs) {
const int unassigned = -3;
SmallVector<bool, 4> consumed(fromTuple.size(), false);
sources.clear();
variadicArgs.clear();
sources.assign(toTuple.size(), unassigned);
// Match up any named elements.
for (unsigned i = 0, n = toTuple.size(); i != n; ++i) {
const auto &toElt = toTuple[i];
// Skip unnamed elements.
if (!toElt.hasName())
continue;
// Find the corresponding named element.
int matched = -1;
{
int index = 0;
for (auto field : fromTuple) {
if (field.getName() == toElt.getName() && !consumed[index]) {
matched = index;
break;
}
++index;
}
}
if (matched == -1)
continue;
// Record this match.
sources[i] = matched;
consumed[matched] = true;
}
// Resolve any unmatched elements.
unsigned fromNext = 0, fromLast = fromTuple.size();
auto skipToNextAvailableInput = [&] {
while (fromNext != fromLast && consumed[fromNext])
++fromNext;
};
skipToNextAvailableInput();
for (unsigned i = 0, n = toTuple.size(); i != n; ++i) {
// Check whether we already found a value for this element.
if (sources[i] != unassigned)
continue;
const auto &elt2 = toTuple[i];
// Variadic tuple elements match the rest of the input elements.
if (elt2.isVararg()) {
// Collect the remaining (unnamed) inputs.
while (fromNext != fromLast) {
// Labeled elements can't be adopted into varargs even if
// they're non-mandatory. There isn't a really strong reason
// for this, though.
if (fromTuple[fromNext].hasName())
return true;
variadicArgs.push_back(fromNext);
consumed[fromNext] = true;
skipToNextAvailableInput();
}
sources[i] = TupleShuffleExpr::Variadic;
// Keep looking at subsequent arguments. Non-variadic arguments may
// follow the variadic one.
continue;
}
// If there aren't any more inputs, we are done.
if (fromNext == fromLast) {
return true;
}
// Otherwise, assign this input to the next output element.
// Fail if the input element is named and we're trying to match it with
// something with a different label.
if (fromTuple[fromNext].hasName() && elt2.hasName())
return true;
sources[i] = fromNext;
consumed[fromNext] = true;
skipToNextAvailableInput();
}
// Complain if we didn't reach the end of the inputs.
if (fromNext != fromLast) {
return true;
}
// If we got here, we should have claimed all the arguments.
assert(std::find(consumed.begin(), consumed.end(), false) == consumed.end());
return false;
}
Expr *ConstraintLocatorBuilder::trySimplifyToExpr() const {
SmallVector<LocatorPathElt, 4> pathBuffer;
Expr *anchor = getLocatorParts(pathBuffer);
ArrayRef<LocatorPathElt> path = pathBuffer;
Expr *targetAnchor;
SmallVector<LocatorPathElt, 4> targetPathBuffer;
SourceRange range;
simplifyLocator(anchor, path, targetAnchor, targetPathBuffer, range);
return (path.empty() ? anchor : nullptr);
}
bool constraints::hasTrailingClosure(const ConstraintLocatorBuilder &locator) {
if (Expr *e = locator.trySimplifyToExpr()) {
if (ParenExpr *parenExpr = dyn_cast<ParenExpr>(e)) {
return parenExpr->hasTrailingClosure();
} else if (TupleExpr *tupleExpr = dyn_cast<TupleExpr>(e)) {
return tupleExpr->hasTrailingClosure();
}
}
return false;
}
//===----------------------------------------------------------------------===//
// High-level entry points.
//===----------------------------------------------------------------------===//
static unsigned getNumArgs(ValueDecl *value) {
if (!isa<FuncDecl>(value)) return ~0U;
AnyFunctionType *fnTy = value->getType()->castTo<AnyFunctionType>();
if (value->getDeclContext()->isTypeContext())
fnTy = fnTy->getResult()->castTo<AnyFunctionType>();
Type argTy = fnTy->getInput();
if (auto tuple = argTy->getAs<TupleType>()) {
return tuple->getNumElements();
} else {
return 1;
}
}
static bool matchesDeclRefKind(ValueDecl *value, DeclRefKind refKind) {
if (value->getType()->is<ErrorType>())
return true;
switch (refKind) {
// An ordinary reference doesn't ignore anything.
case DeclRefKind::Ordinary:
return true;
// A binary-operator reference only honors FuncDecls with a certain type.
case DeclRefKind::BinaryOperator:
return (getNumArgs(value) == 2);
case DeclRefKind::PrefixOperator:
return (!value->getAttrs().hasAttribute<PostfixAttr>() &&
getNumArgs(value) == 1);
case DeclRefKind::PostfixOperator:
return (value->getAttrs().hasAttribute<PostfixAttr>() &&
getNumArgs(value) == 1);
}
llvm_unreachable("bad declaration reference kind");
}
static bool containsDeclRefKind(LookupResult &lookupResult,
DeclRefKind refKind) {
for (auto candidate : lookupResult) {
ValueDecl *D = candidate.Decl;
if (!D || !D->hasType())
continue;
if (matchesDeclRefKind(D, refKind))
return true;
}
return false;
}
/// Emit a diagnostic with a fixit hint for an invalid binary operator, showing
/// how to split it according to splitCandidate.
static void diagnoseBinOpSplit(UnresolvedDeclRefExpr *UDRE,
std::pair<unsigned, bool> splitCandidate,
Diag<Identifier, Identifier, bool> diagID,
TypeChecker &TC) {
unsigned splitLoc = splitCandidate.first;
bool isBinOpFirst = splitCandidate.second;
StringRef nameStr = UDRE->getName().getBaseName().str();
auto startStr = nameStr.substr(0, splitLoc);
auto endStr = nameStr.drop_front(splitLoc);
// One valid split found, it is almost certainly the right answer.
auto diag = TC.diagnose(UDRE->getLoc(), diagID,
TC.Context.getIdentifier(startStr),
TC.Context.getIdentifier(endStr), isBinOpFirst);
// Highlight the whole operator.
diag.highlight(UDRE->getLoc());
// Insert whitespace on the left if the binop is at the start, or to the
// right if it is end.
if (isBinOpFirst)
diag.fixItInsert(UDRE->getLoc(), " ");
else
diag.fixItInsertAfter(UDRE->getLoc(), " ");
// Insert a space between the operators.
diag.fixItInsert(UDRE->getLoc().getAdvancedLoc(splitLoc), " ");
}
/// If we failed lookup of a binary operator, check to see it to see if
/// it is a binary operator juxtaposed with a unary operator (x*-4) that
/// needs whitespace. If so, emit specific diagnostics for it and return true,
/// otherwise return false.
static bool diagnoseOperatorJuxtaposition(UnresolvedDeclRefExpr *UDRE,
DeclContext *DC,
TypeChecker &TC) {
Identifier name = UDRE->getName().getBaseName();
StringRef nameStr = name.str();
if (!name.isOperator() || nameStr.size() < 2)
return false;
bool isBinOp = UDRE->getRefKind() == DeclRefKind::BinaryOperator;
// If this is a binary operator, relex the token, to decide whether it has
// whitespace around it or not. If it does "x +++ y", then it isn't likely to
// be a case where a space was forgotten.
if (isBinOp) {
auto tok = Lexer::getTokenAtLocation(TC.Context.SourceMgr, UDRE->getLoc());
if (tok.getKind() != tok::oper_binary_unspaced)
return false;
}
// Okay, we have a failed lookup of a multicharacter operator. Check to see if
// lookup succeeds if part is split off, and record the matches found.
//
// In the case of a binary operator, the bool indicated is false if the
// first half of the split is the unary operator (x!*4) or true if it is the
// binary operator (x*+4).
std::vector<std::pair<unsigned, bool>> WorkableSplits;
// Check all the potential splits.
for (unsigned splitLoc = 1, e = nameStr.size(); splitLoc != e; ++splitLoc) {
// For it to be a valid split, the start and end section must be valid
// operators, splitting a unicode code point isn't kosher.
auto startStr = nameStr.substr(0, splitLoc);
auto endStr = nameStr.drop_front(splitLoc);
if (!Lexer::isOperator(startStr) || !Lexer::isOperator(endStr))
continue;
auto startName = TC.Context.getIdentifier(startStr);
auto endName = TC.Context.getIdentifier(endStr);
// Perform name lookup for the first and second pieces. If either fail to
// be found, then it isn't a valid split.
NameLookupOptions LookupOptions = defaultUnqualifiedLookupOptions;
// This is only used for diagnostics, so always use KnownPrivate.
LookupOptions |= NameLookupFlags::KnownPrivate;
auto startLookup = TC.lookupUnqualified(DC, startName, UDRE->getLoc(),
LookupOptions);
if (!startLookup) continue;
auto endLookup = TC.lookupUnqualified(DC, endName, UDRE->getLoc(),
LookupOptions);
if (!endLookup) continue;
// If the overall operator is a binary one, then we're looking at
// juxtaposed binary and unary operators.
if (isBinOp) {
// Look to see if the candidates found could possibly match.
if (containsDeclRefKind(startLookup, DeclRefKind::PostfixOperator) &&
containsDeclRefKind(endLookup, DeclRefKind::BinaryOperator))
WorkableSplits.push_back({ splitLoc, false });
if (containsDeclRefKind(startLookup, DeclRefKind::BinaryOperator) &&
containsDeclRefKind(endLookup, DeclRefKind::PrefixOperator))
WorkableSplits.push_back({ splitLoc, true });
} else {
// Otherwise, it is two of the same kind, e.g. "!!x" or "!~x".
if (containsDeclRefKind(startLookup, UDRE->getRefKind()) &&
containsDeclRefKind(endLookup, UDRE->getRefKind()))
WorkableSplits.push_back({ splitLoc, false });
}
}
switch (WorkableSplits.size()) {
case 0:
// No splits found, can't produce this diagnostic.
return false;
case 1:
// One candidate: produce an error with a fixit on it.
if (isBinOp)
diagnoseBinOpSplit(UDRE, WorkableSplits[0],
diag::unspaced_binary_operator_fixit, TC);
else
TC.diagnose(UDRE->getLoc().getAdvancedLoc(WorkableSplits[0].first),
diag::unspaced_unary_operator);
return true;
default:
// Otherwise, we have to produce a series of notes listing the various
// options.
TC.diagnose(UDRE->getLoc(), isBinOp ? diag::unspaced_binary_operator :
diag::unspaced_unary_operator)
.highlight(UDRE->getLoc());
if (isBinOp) {
for (auto candidateSplit : WorkableSplits)
diagnoseBinOpSplit(UDRE, candidateSplit,
diag::unspaced_binary_operators_candidate, TC);
}
return true;
}
}
/// Bind an UnresolvedDeclRefExpr by performing name lookup and
/// returning the resultant expression. Context is the DeclContext used
/// for the lookup.
Expr *TypeChecker::
resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE, DeclContext *DC) {
// Process UnresolvedDeclRefExpr by doing an unqualified lookup.
DeclName Name = UDRE->getName();
SourceLoc Loc = UDRE->getLoc();
// Perform standard value name lookup.
NameLookupOptions LookupOptions = defaultUnqualifiedLookupOptions;
if (isa<AbstractFunctionDecl>(DC))
LookupOptions |= NameLookupFlags::KnownPrivate;
auto Lookup = lookupUnqualified(DC, Name, Loc, LookupOptions);
if (!Lookup) {
// If we failed lookup of an operator, check to see it to see if it is
// because two operators are juxtaposed e.g. (x*-4) that needs whitespace.
// If so, emit specific diagnostics for it.
if (diagnoseOperatorJuxtaposition(UDRE, DC, *this)) {
return new (Context) ErrorExpr(UDRE->getSourceRange());
}
// TODO: Name will be a compound name if it was written explicitly as
// one, but we should also try to propagate labels into this.
DeclNameLoc nameLoc = UDRE->getNameLoc();
performTypoCorrection(DC, UDRE->getRefKind(), Type(), Name, Loc,
LookupOptions, Lookup);
diagnose(Loc, diag::use_unresolved_identifier, Name, Name.isOperator())
.highlight(UDRE->getSourceRange());
// Note all the correction candidates.
for (auto &result : Lookup) {
noteTypoCorrection(Name, nameLoc, result);
}
// TODO: consider recovering from here. We may want some way to suppress
// downstream diagnostics, though.
return new (Context) ErrorExpr(UDRE->getSourceRange());
}
// FIXME: Need to refactor the way we build an AST node from a lookup result!
bool AllDeclRefs = true;
SmallVector<ValueDecl*, 4> ResultValues;
for (auto Result : Lookup) {
// If we find a member, then all of the results aren't non-members.
bool IsMember = Result.Base && !isa<ModuleDecl>(Result.Base);
if (IsMember && !isa<TypeDecl>(Result.Decl)) {
AllDeclRefs = false;
break;
}
ValueDecl *D = Result.Decl;
if (!D->hasType()) {
assert(D->getDeclContext()->isLocalContext());
if (!D->isInvalid()) {
diagnose(Loc, diag::use_local_before_declaration, Name);
diagnose(D, diag::decl_declared_here, Name);
}
return new (Context) ErrorExpr(UDRE->getSourceRange());
}
if (matchesDeclRefKind(D, UDRE->getRefKind()))
ResultValues.push_back(D);
}
// If we have an unambiguous reference to a type decl, form a TypeExpr. This
// doesn't handle specialized decls since they are processed when the
// UnresolvedSpecializeExpr is seen.
if (!UDRE->isSpecialized() &&
ResultValues.size() == 1 && UDRE->getRefKind() == DeclRefKind::Ordinary &&
isa<TypeDecl>(ResultValues[0])) {
// FIXME: This is odd.
if (isa<ModuleDecl>(ResultValues[0])) {
return new (Context) DeclRefExpr(ResultValues[0], UDRE->getNameLoc(),
/*implicit=*/false,
AccessSemantics::Ordinary,
ResultValues[0]->getType());
}
return TypeExpr::createForDecl(Loc, cast<TypeDecl>(ResultValues[0]),
UDRE->isImplicit());
}
if (AllDeclRefs) {
// Diagnose uses of operators that found no matching candidates.
if (ResultValues.empty()) {
assert(UDRE->getRefKind() != DeclRefKind::Ordinary);
diagnose(Loc, diag::use_nonmatching_operator, Name.getBaseName(),
UDRE->getRefKind() == DeclRefKind::BinaryOperator ? 0 :
UDRE->getRefKind() == DeclRefKind::PrefixOperator ? 1 : 2);
return new (Context) ErrorExpr(UDRE->getSourceRange());
}
// For operators, sort the results so that non-generic operations come
// first.
// Note: this is part of a performance hack to prefer non-generic operators
// to generic operators, because the former is far more efficient to check.
if (UDRE->getRefKind() != DeclRefKind::Ordinary) {
std::stable_sort(ResultValues.begin(), ResultValues.end(),
[&](ValueDecl *x, ValueDecl *y) -> bool {
auto xGeneric = x->getInterfaceType()->getAs<GenericFunctionType>();
auto yGeneric = y->getInterfaceType()->getAs<GenericFunctionType>();
if (static_cast<bool>(xGeneric) != static_cast<bool>(yGeneric)) {
return xGeneric? false : true;
}
if (!xGeneric)
return false;
unsigned xDepth = xGeneric->getGenericParams().back()->getDepth();
unsigned yDepth = yGeneric->getGenericParams().back()->getDepth();
return xDepth < yDepth;
});
}
return buildRefExpr(ResultValues, DC, UDRE->getNameLoc(),
UDRE->isImplicit(), UDRE->isSpecialized());
}
ResultValues.clear();
bool AllMemberRefs = true;
bool PromotedInstanceRef = false;
ValueDecl *Base = 0;
for (auto Result : Lookup) {
// Track the base for member declarations.
if (Result.Base && !isa<ModuleDecl>(Result.Base)) {
ResultValues.push_back(Result.Decl);
if (Base && Result.Base != Base) {
AllMemberRefs = false;
break;
}
if (Result.IsPromotedInstanceRef) {
PromotedInstanceRef = true;
}
Base = Result.Base;
continue;
}
AllMemberRefs = false;
break;
}
if (AllMemberRefs) {
Expr *BaseExpr;
if (auto NTD = dyn_cast<NominalTypeDecl>(Base)) {
BaseExpr = TypeExpr::createForDecl(Loc, NTD, /*implicit=*/true,
PromotedInstanceRef);
} else {
BaseExpr = new (Context) DeclRefExpr(Base, UDRE->getNameLoc(),
/*implicit=*/true);
}
// Otherwise, form an UnresolvedDotExpr and sema will resolve it based on
// type information.
return new (Context) UnresolvedDotExpr(BaseExpr, SourceLoc(), Name,
UDRE->getNameLoc(),
UDRE->isImplicit());
}
// FIXME: If we reach this point, the program we're being handed is likely
// very broken, but it's still conceivable that this may happen due to
// invalid shadowed declarations.
// llvm_unreachable("Can't represent lookup result");
return new (Context) ErrorExpr(UDRE->getSourceRange());
}
/// If an expression references 'self.init' or 'super.init' in an
/// initializer context, returns the implicit 'self' decl of the constructor.
/// Otherwise, return nil.
VarDecl *
TypeChecker::getSelfForInitDelegationInConstructor(DeclContext *DC,
UnresolvedDotExpr *ctorRef) {
// If the reference isn't to a constructor, we're done.
if (ctorRef->getName().getBaseName() != Context.Id_init)
return nullptr;
if (auto ctorContext
= dyn_cast_or_null<ConstructorDecl>(DC->getInnermostMethodContext())) {
auto nestedArg = ctorRef->getBase();
if (auto inout = dyn_cast<InOutExpr>(nestedArg))
nestedArg = inout->getSubExpr();
if (nestedArg->isSuperExpr())
return ctorContext->getImplicitSelfDecl();
if (auto declRef = dyn_cast<DeclRefExpr>(nestedArg))
if (declRef->getDecl()->getName() == Context.Id_self)
return ctorContext->getImplicitSelfDecl();
}
return nullptr;
}
namespace {
class PreCheckExpression : public ASTWalker {
TypeChecker &TC;
DeclContext *DC;
/// A stack of expressions being walked, used to determine where to
/// insert RebindSelfInConstructorExpr nodes.
llvm::SmallVector<Expr *, 8> ExprStack;
/// The 'self' variable to use when rebinding 'self' in a constructor.
VarDecl *UnresolvedCtorSelf = nullptr;
/// The expression that will be wrapped by a RebindSelfInConstructorExpr
/// node when visited.
Expr *UnresolvedCtorRebindTarget = nullptr;
/// The expressions that are direct arguments of call expressions.
llvm::SmallPtrSet<Expr *, 4> CallArgs;
public:
PreCheckExpression(TypeChecker &tc, DeclContext *dc) : TC(tc), DC(dc) { }
bool walkToClosureExprPre(ClosureExpr *expr);
std::pair<bool, Expr *> walkToExprPre(Expr *expr) override {
// If this is a call, record the argument expression.
if (auto call = dyn_cast<CallExpr>(expr)) {
CallArgs.insert(call->getArg());
}
// If this is an unresolved member with a call argument (e.g.,
// .some(x)), record the argument expression.
if (auto unresolvedMember = dyn_cast<UnresolvedMemberExpr>(expr)) {
if (auto arg = unresolvedMember->getArgument())
CallArgs.insert(arg);
}
// Local function used to finish up processing before returning. Every
// return site should call through here.
auto finish = [&](bool recursive, Expr *expr) {
// If we're going to recurse, record this expression on the stack.
if (recursive)
ExprStack.push_back(expr);
return std::make_pair(recursive, expr);
};
// For capture lists, we typecheck the decls they contain.
if (auto captureList = dyn_cast<CaptureListExpr>(expr)) {
// Validate the capture list.
for (auto capture : captureList->getCaptureList()) {
TC.typeCheckDecl(capture.Init, true);
TC.typeCheckDecl(capture.Init, false);
TC.typeCheckDecl(capture.Var, true);
TC.typeCheckDecl(capture.Var, false);
}
return finish(true, expr);
}
// For closures, type-check the patterns and result type as written,
// but do not walk into the body. That will be type-checked after
// we've determine the complete function type.
if (auto closure = dyn_cast<ClosureExpr>(expr))
return finish(walkToClosureExprPre(closure), expr);
if (auto unresolved = dyn_cast<UnresolvedDeclRefExpr>(expr)) {
TC.checkForForbiddenPrefix(unresolved);
return finish(true, TC.resolveDeclRefExpr(unresolved, DC));
}
if (auto PlaceholderE = dyn_cast<EditorPlaceholderExpr>(expr)) {
if (!PlaceholderE->getTypeLoc().isNull()) {
if (!TC.validateType(PlaceholderE->getTypeLoc(), DC))
expr->setType(PlaceholderE->getTypeLoc().getType());
}
return finish(true, expr);
}
return finish(true, expr);
}
Expr *walkToExprPost(Expr *expr) override {
// Remove this expression from the stack.
assert(ExprStack.back() == expr);
ExprStack.pop_back();
// Fold sequence expressions.
if (auto seqExpr = dyn_cast<SequenceExpr>(expr)) {
auto result = TC.foldSequence(seqExpr, DC);
if (auto typeResult = simplifyTypeExpr(result)) {
return typeResult;
}
return result;
}
// Type check the type parameters in an UnresolvedSpecializeExpr.
if (auto us = dyn_cast<UnresolvedSpecializeExpr>(expr)) {
for (TypeLoc &type : us->getUnresolvedParams()) {
if (TC.validateType(type, DC))
return nullptr;
}
// If this is a reference type a specialized type, form a TypeExpr.
if (auto *dre = dyn_cast<DeclRefExpr>(us->getSubExpr())) {
if (auto *TD = dyn_cast<TypeDecl>(dre->getDecl())) {
SmallVector<TypeRepr*, 4> TypeReprs;
for (auto elt : us->getUnresolvedParams())
TypeReprs.push_back(elt.getTypeRepr());
auto angles = SourceRange(us->getLAngleLoc(), us->getRAngleLoc());
return TypeExpr::createForSpecializedDecl(dre->getLoc(),
TD,
TC.Context.AllocateCopy(TypeReprs),
angles);
}
}
return expr;
}
// If we're about to step out of a ClosureExpr, restore the DeclContext.
if (auto *ce = dyn_cast<ClosureExpr>(expr)) {
assert(DC == ce && "DeclContext imbalance");
DC = ce->getParent();
}
// Strip off any AutoClosures that were produced by a previous type check
// so that we don't choke in CSGen.
// FIXME: we shouldn't double typecheck, but it looks like code completion
// may do so in some circumstances. rdar://21466394
if (auto autoClosure = dyn_cast<AutoClosureExpr>(expr))
return autoClosure->getSingleExpressionBody();
// A 'self.init' or 'super.init' application inside a constructor will
// evaluate to void, with the initializer's result implicitly rebound
// to 'self'. Recognize the unresolved constructor expression and
// determine where to place the RebindSelfInConstructorExpr node.
// When updating this logic, also update
// RebindSelfInConstructorExpr::getCalledConstructor.
if (auto unresolvedDot = dyn_cast<UnresolvedDotExpr>(expr)) {
if (auto self
= TC.getSelfForInitDelegationInConstructor(DC, unresolvedDot)) {
// Walk our ancestor expressions looking for the appropriate place
// to insert the RebindSelfInConstructorExpr.
Expr *target = nullptr;
bool foundApply = false;
bool foundRebind = false;
for (auto ancestor : reversed(ExprStack)) {
if (isa<RebindSelfInConstructorExpr>(ancestor)) {
// If we already have a rebind, then we're re-typechecking an
// expression and are done.
foundRebind = true;
break;
}
// Recognize applications.
if (auto apply = dyn_cast<ApplyExpr>(ancestor)) {
// If we already saw an application, we're done.
if (foundApply)
break;
// If the function being called is not our unresolved initializer
// reference, we're done.
if (apply->getFn()->getSemanticsProvidingExpr() != unresolvedDot)
break;
foundApply = true;
target = ancestor;
continue;
}
// Look through identity, force-value, and 'try' expressions.
if (isa<IdentityExpr>(ancestor) ||
isa<ForceValueExpr>(ancestor) ||
isa<AnyTryExpr>(ancestor)) {
if (target)
target = ancestor;
continue;
}
// No other expression kinds are permitted.
break;
}
// If we found a rebind target, note the insertion point.
if (target && !foundRebind) {
UnresolvedCtorRebindTarget = target;
UnresolvedCtorSelf = self;
}
}
}
// If the expression we've found is the intended target of an
// RebindSelfInConstructorExpr, wrap it in the
// RebindSelfInConstructorExpr.
if (expr == UnresolvedCtorRebindTarget) {
expr = new (TC.Context) RebindSelfInConstructorExpr(expr,
UnresolvedCtorSelf);
UnresolvedCtorRebindTarget = nullptr;
return expr;
}
// If this is a sugared type that needs to be folded into a single
// TypeExpr, do it.
if (auto *simplified = simplifyTypeExpr(expr))
return simplified;
return expr;
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *stmt) override {
// Never walk into statements.
return { false, stmt };
}
/// Simplify expressions which are type sugar productions that got parsed
/// as expressions due to the parser not knowing which identifiers are
/// type names.
TypeExpr *simplifyTypeExpr(Expr *E);
};
}
/// Perform prechecking of a ClosureExpr before we dive into it. This returns
/// true for single-expression closures, where we want the body to be considered
/// part of this larger expression.
bool PreCheckExpression::walkToClosureExprPre(ClosureExpr *closure) {
// Validate the parameters.
TypeResolutionOptions options;
options |= TR_AllowUnspecifiedTypes;
options |= TR_AllowUnboundGenerics;
options |= TR_InExpression;
bool hadParameterError = false;
if (TC.typeCheckParameterList(closure->getParameters(), DC, options)) {
closure->setType(ErrorType::get(TC.Context));
// If we encounter an error validating the parameter list, don't bail.
// Instead, go on to validate any potential result type, and bail
// afterwards. This allows for better diagnostics, and keeps the
// closure expression type well-formed.
hadParameterError = true;
}
// Validate the result type, if present.
if (closure->hasExplicitResultType() &&
TC.validateType(closure->getExplicitResultTypeLoc(), DC,
TR_InExpression)) {
closure->setType(ErrorType::get(TC.Context));
return false;
}
if (hadParameterError)
return false;
// If the closure has a multi-statement body, we don't walk into it
// here.
if (!closure->hasSingleExpressionBody())
return false;
// Update the current DeclContext to be the closure we're about to
// recurse into.
assert(DC == closure->getParent() && "Decl context isn't correct");
DC = closure;
return true;
}
/// Simplify expressions which are type sugar productions that got parsed
/// as expressions due to the parser not knowing which identifiers are
/// type names.
TypeExpr *PreCheckExpression::simplifyTypeExpr(Expr *E) {
// Don't try simplifying a call argument, because we don't want to
// simplify away the required ParenExpr/TupleExpr.
if (CallArgs.count(E) > 0) return nullptr;
// Fold 'T.Type' or 'T.Protocol' into a metatype when T is a TypeExpr.
if (auto *MRE = dyn_cast<UnresolvedDotExpr>(E)) {
auto *TyExpr = dyn_cast<TypeExpr>(MRE->getBase());
if (!TyExpr) return nullptr;
auto *InnerTypeRepr = TyExpr->getTypeRepr();
if (MRE->getName() == TC.Context.Id_Protocol) {
assert(!TyExpr->isImplicit() && InnerTypeRepr &&
"This doesn't work on implicit TypeExpr's, "
"TypeExpr should have been built correctly in the first place");
auto *NewTypeRepr =
new (TC.Context) ProtocolTypeRepr(InnerTypeRepr,
MRE->getNameLoc().getBaseNameLoc());
return new (TC.Context) TypeExpr(TypeLoc(NewTypeRepr, Type()));
}
if (MRE->getName() == TC.Context.Id_Type) {
assert(!TyExpr->isImplicit() && InnerTypeRepr &&
"This doesn't work on implicit TypeExpr's, "
"TypeExpr should have been built correctly in the first place");
auto *NewTypeRepr =
new (TC.Context) MetatypeTypeRepr(InnerTypeRepr,
MRE->getNameLoc().getBaseNameLoc());
return new (TC.Context) TypeExpr(TypeLoc(NewTypeRepr, Type()));
}
}
// Fold T? into an optional type when T is a TypeExpr.
if (isa<OptionalEvaluationExpr>(E) || isa<BindOptionalExpr>(E)) {
TypeExpr *TyExpr;
SourceLoc QuestionLoc;
if (auto *OOE = dyn_cast<OptionalEvaluationExpr>(E)) {
TyExpr = dyn_cast<TypeExpr>(OOE->getSubExpr());
QuestionLoc = OOE->getLoc();
} else {
TyExpr = dyn_cast<TypeExpr>(cast<BindOptionalExpr>(E)->getSubExpr());
QuestionLoc = cast<BindOptionalExpr>(E)->getQuestionLoc();
}
if (!TyExpr) return nullptr;
auto *InnerTypeRepr = TyExpr->getTypeRepr();
assert(!TyExpr->isImplicit() && InnerTypeRepr &&
"This doesn't work on implicit TypeExpr's, "
"the TypeExpr should have been built correctly in the first place");
// The optional evaluation is passed through.
if (isa<OptionalEvaluationExpr>(E))
return TyExpr;
auto *NewTypeRepr =
new (TC.Context) OptionalTypeRepr(InnerTypeRepr, QuestionLoc);
return new (TC.Context) TypeExpr(TypeLoc(NewTypeRepr, Type()));
}
// Fold T! into an IUO type when T is a TypeExpr.
if (auto *FVE = dyn_cast<ForceValueExpr>(E)) {
auto *TyExpr = dyn_cast<TypeExpr>(FVE->getSubExpr());
if (!TyExpr) return nullptr;
auto *InnerTypeRepr = TyExpr->getTypeRepr();
assert(!TyExpr->isImplicit() && InnerTypeRepr &&
"This doesn't work on implicit TypeExpr's, "
"the TypeExpr should have been built correctly in the first place");
auto *NewTypeRepr =
new (TC.Context) ImplicitlyUnwrappedOptionalTypeRepr(InnerTypeRepr,
FVE->getExclaimLoc());
return new (TC.Context) TypeExpr(TypeLoc(NewTypeRepr, Type()));
}
// Fold (T) into a type T with parens around it.
if (auto *PE = dyn_cast<ParenExpr>(E)) {
auto *TyExpr = dyn_cast<TypeExpr>(PE->getSubExpr());
if (!TyExpr) return nullptr;
TypeRepr *InnerTypeRepr[] = { TyExpr->getTypeRepr() };
assert(!TyExpr->isImplicit() && InnerTypeRepr[0] &&
"SubscriptExpr doesn't work on implicit TypeExpr's, "
"the TypeExpr should have been built correctly in the first place");
auto *NewTypeRepr = TupleTypeRepr::create(TC.Context, InnerTypeRepr,
PE->getSourceRange(),
SourceLoc(), 1);
return new (TC.Context) TypeExpr(TypeLoc(NewTypeRepr, Type()));
}
// Fold a tuple expr like (T1,T2) into a tuple type (T1,T2).
if (auto *TE = dyn_cast<TupleExpr>(E)) {
if (TE->hasTrailingClosure() ||
// FIXME: Decide what to do about (). It could be a type or an expr.
TE->getNumElements() == 0)
return nullptr;
SmallVector<TypeRepr *, 4> Elts;
unsigned EltNo = 0;
for (auto Elt : TE->getElements()) {
auto *eltTE = dyn_cast<TypeExpr>(Elt);
if (!eltTE) return nullptr;
assert(eltTE->getTypeRepr() && !eltTE->isImplicit() &&
"This doesn't work on implicit TypeExpr's, the "
"TypeExpr should have been built correctly in the first place");
// If the tuple element has a label, propagate it.