forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTypeCheckConstraints.cpp
4063 lines (3468 loc) · 142 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 - 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 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 "MiscDiagnostics.h"
#include "SolutionResult.h"
#include "TypeChecker.h"
#include "TypeCheckType.h"
#include "TypoCorrection.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Statistic.h"
#include "swift/Parse/Confusables.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 "llvm/Support/Format.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());
}
SavedTypeVariableBinding::SavedTypeVariableBinding(TypeVariableType *typeVar)
: TypeVar(typeVar), Options(typeVar->getImpl().getRawOptions()),
ParentOrFixed(typeVar->getImpl().ParentOrFixed) { }
void SavedTypeVariableBinding::restore() {
TypeVar->getImpl().setRawOptions(Options);
TypeVar->getImpl().ParentOrFixed = ParentOrFixed;
}
GenericTypeParamType *
TypeVariableType::Implementation::getGenericParameter() const {
return locator ? locator->getGenericParameter() : nullptr;
}
bool TypeVariableType::Implementation::isClosureType() const {
if (!(locator && locator->getAnchor()))
return false;
return isExpr<ClosureExpr>(locator->getAnchor()) && locator->getPath().empty();
}
bool TypeVariableType::Implementation::isClosureParameterType() const {
if (!(locator && locator->getAnchor()))
return false;
return isExpr<ClosureExpr>(locator->getAnchor()) &&
locator->isLastElement<LocatorPathElt::TupleElement>();
}
bool TypeVariableType::Implementation::isClosureResultType() const {
if (!(locator && locator->getAnchor()))
return false;
return isExpr<ClosureExpr>(locator->getAnchor()) &&
locator->isLastElement<LocatorPathElt::ClosureResult>();
}
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<unsigned> &sources) {
const unsigned unassigned = -1;
SmallVector<bool, 4> consumed(fromTuple.size(), false);
sources.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;
// If there aren't any more inputs, we are done.
if (fromNext == fromLast) {
return true;
}
// Otherwise, assign this input to the next output element.
const auto &elt2 = toTuple[i];
assert(!elt2.isVararg());
// 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;
auto anchor = getLocatorParts(pathBuffer);
// Locators are not guaranteed to have an anchor
// if constraint system is used to verify generic
// requirements.
if (!anchor.is<Expr *>())
return nullptr;
ArrayRef<LocatorPathElt> path = pathBuffer;
SourceRange range;
simplifyLocator(anchor, path, range);
return (path.empty() ? getAsExpr(anchor) : nullptr);
}
//===----------------------------------------------------------------------===//
// High-level entry points.
//===----------------------------------------------------------------------===//
static unsigned getNumArgs(ValueDecl *value) {
if (auto *func = dyn_cast<FuncDecl>(value))
return func->getParameters()->size();
return ~0U;
}
static bool matchesDeclRefKind(ValueDecl *value, DeclRefKind refKind) {
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.getValueDecl();
if (!D)
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(ASTContext &Context, UnresolvedDeclRefExpr *UDRE,
std::pair<unsigned, bool> splitCandidate,
Diag<Identifier, Identifier, bool> diagID) {
unsigned splitLoc = splitCandidate.first;
bool isBinOpFirst = splitCandidate.second;
StringRef nameStr = UDRE->getName().getBaseIdentifier().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 = Context.Diags.diagnose(
UDRE->getLoc(), diagID, Context.getIdentifier(startStr),
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) {
Identifier name = UDRE->getName().getBaseIdentifier();
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.
auto &Context = DC->getASTContext();
if (isBinOp) {
auto tok = Lexer::getTokenAtLocation(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;
DeclNameRef startName(Context.getIdentifier(startStr));
DeclNameRef endName(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 = TypeChecker::lookupUnqualified(
DC, startName, UDRE->getLoc(), LookupOptions);
if (!startLookup) continue;
auto endLookup = TypeChecker::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(Context, UDRE, WorkableSplits[0],
diag::unspaced_binary_operator_fixit);
else
Context.Diags.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.
Context.Diags
.diagnose(UDRE->getLoc(), isBinOp ? diag::unspaced_binary_operator
: diag::unspaced_unary_operator)
.highlight(UDRE->getLoc());
if (isBinOp) {
for (auto candidateSplit : WorkableSplits)
diagnoseBinOpSplit(Context, UDRE, candidateSplit,
diag::unspaced_binary_operators_candidate);
}
return true;
}
}
static bool diagnoseRangeOperatorMisspell(DiagnosticEngine &Diags,
UnresolvedDeclRefExpr *UDRE) {
auto name = UDRE->getName().getBaseIdentifier();
if (!name.isOperator())
return false;
auto corrected = StringRef();
if (name.str() == ".." || name.str() == "...." ||
name.str() == ".…" || name.str() == "…" || name.str() == "….")
corrected = "...";
else if (name.str() == "...<" || name.str() == "....<" ||
name.str() == "…<")
corrected = "..<";
if (!corrected.empty()) {
Diags
.diagnose(UDRE->getLoc(), diag::cannot_find_in_scope_corrected,
UDRE->getName(), true, corrected)
.highlight(UDRE->getSourceRange())
.fixItReplace(UDRE->getSourceRange(), corrected);
return true;
}
return false;
}
static bool diagnoseIncDecOperator(DiagnosticEngine &Diags,
UnresolvedDeclRefExpr *UDRE) {
auto name = UDRE->getName().getBaseIdentifier();
if (!name.isOperator())
return false;
auto corrected = StringRef();
if (name.str() == "++")
corrected = "+= 1";
else if (name.str() == "--")
corrected = "-= 1";
if (!corrected.empty()) {
Diags
.diagnose(UDRE->getLoc(), diag::cannot_find_in_scope_corrected,
UDRE->getName(), true, corrected)
.highlight(UDRE->getSourceRange());
return true;
}
return false;
}
static bool findNonMembers(ArrayRef<LookupResultEntry> lookupResults,
DeclRefKind refKind, bool breakOnMember,
SmallVectorImpl<ValueDecl *> &ResultValues,
llvm::function_ref<bool(ValueDecl *)> isValid) {
bool AllDeclRefs = true;
for (auto Result : lookupResults) {
// If we find a member, then all of the results aren't non-members.
bool IsMember =
(Result.getBaseDecl() && !isa<ModuleDecl>(Result.getBaseDecl()));
if (IsMember) {
AllDeclRefs = false;
if (breakOnMember)
break;
continue;
}
ValueDecl *D = Result.getValueDecl();
if (!isValid(D))
return false;
if (matchesDeclRefKind(D, refKind))
ResultValues.push_back(D);
}
return AllDeclRefs;
}
/// 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.
DeclNameRef Name = UDRE->getName();
SourceLoc Loc = UDRE->getLoc();
// Perform standard value name lookup.
NameLookupOptions lookupOptions = defaultUnqualifiedLookupOptions;
if (isa<AbstractFunctionDecl>(DC))
lookupOptions |= NameLookupFlags::KnownPrivate;
// TODO: Include all of the possible members to give a solver a
// chance to diagnose name shadowing which requires explicit
// name/module qualifier to access top-level name.
lookupOptions |= NameLookupFlags::IncludeOuterResults;
auto Lookup = TypeChecker::lookupUnqualified(DC, Name, Loc, lookupOptions);
auto &Context = DC->getASTContext();
if (!Lookup) {
// If we failed lookup of an operator, check to see if this is a range
// operator misspelling. Otherwise try to diagnose a juxtaposition
// e.g. (x*-4) that needs whitespace.
if (diagnoseRangeOperatorMisspell(Context.Diags, UDRE) ||
diagnoseIncDecOperator(Context.Diags, UDRE) ||
diagnoseOperatorJuxtaposition(UDRE, DC)) {
return new (Context) ErrorExpr(UDRE->getSourceRange());
}
// Try ignoring access control.
NameLookupOptions relookupOptions = lookupOptions;
relookupOptions |= NameLookupFlags::KnownPrivate;
relookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto inaccessibleResults =
TypeChecker::lookupUnqualified(DC, Name, Loc, relookupOptions);
if (inaccessibleResults) {
// FIXME: What if the unviable candidates have different levels of access?
const ValueDecl *first = inaccessibleResults.front().getValueDecl();
Context.Diags.diagnose(
Loc, diag::candidate_inaccessible, first->getBaseName(),
first->getFormalAccessScope().accessLevelForDiagnostics());
// FIXME: If any of the candidates (usually just one) are in the same
// module we could offer a fix-it.
for (auto lookupResult : inaccessibleResults) {
auto *VD = lookupResult.getValueDecl();
VD->diagnose(diag::decl_declared_here, VD->getName());
}
// Don't try to recover here; we'll get more access-related diagnostics
// downstream if the type of the inaccessible decl is also inaccessible.
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();
Identifier simpleName = Name.getBaseIdentifier();
const char *buffer = simpleName.get();
llvm::SmallString<64> expectedIdentifier;
bool isConfused = false;
uint32_t codepoint;
int offset = 0;
while ((codepoint = validateUTF8CharacterAndAdvance(buffer,
buffer +
strlen(buffer)))
!= ~0U) {
int length = (buffer - simpleName.get()) - offset;
if (auto expectedCodepoint =
confusable::tryConvertConfusableCharacterToASCII(codepoint)) {
isConfused = true;
expectedIdentifier += expectedCodepoint;
} else {
expectedIdentifier += (char)codepoint;
}
offset += length;
}
auto emitBasicError = [&] {
Context.Diags
.diagnose(Loc, diag::cannot_find_in_scope, Name,
Name.isOperator())
.highlight(UDRE->getSourceRange());
};
if (!isConfused) {
if (Name.isSimpleName(Context.Id_Self)) {
if (DeclContext *typeContext = DC->getInnermostTypeContext()){
Type SelfType = typeContext->getSelfInterfaceType();
if (typeContext->getSelfClassDecl())
SelfType = DynamicSelfType::get(SelfType, Context);
SelfType = DC->mapTypeIntoContext(SelfType);
return new (Context)
TypeExpr(new (Context) FixedTypeRepr(SelfType, Loc));
}
}
TypoCorrectionResults corrections(Name, nameLoc);
TypeChecker::performTypoCorrection(DC, UDRE->getRefKind(), Type(),
lookupOptions, corrections);
if (auto typo = corrections.claimUniqueCorrection()) {
auto diag = Context.Diags.diagnose(
Loc, diag::cannot_find_in_scope_corrected, Name,
Name.isOperator(), typo->CorrectedName.getBaseIdentifier().str());
diag.highlight(UDRE->getSourceRange());
typo->addFixits(diag);
} else {
emitBasicError();
}
corrections.noteAllCandidates();
} else {
emitBasicError();
Context.Diags
.diagnose(Loc, diag::confusable_character,
UDRE->getName().isOperator(), simpleName.str(),
expectedIdentifier)
.fixItReplace(Loc, expectedIdentifier);
}
// 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!
SmallVector<ValueDecl*, 4> ResultValues;
ValueDecl *localDeclAfterUse = nullptr;
auto isValid = [&](ValueDecl *D) {
// FIXME: The source-location checks won't make sense once
// EnableASTScopeLookup is the default.
//
// Note that we allow forward references to types, because they cannot
// capture.
if (Loc.isValid() && D->getLoc().isValid() &&
D->getDeclContext()->isLocalContext() &&
D->getDeclContext() == DC &&
Context.SourceMgr.isBeforeInBuffer(Loc, D->getLoc()) &&
!isa<TypeDecl>(D)) {
localDeclAfterUse = D;
return false;
}
return true;
};
bool AllDeclRefs =
findNonMembers(Lookup.innerResults(), UDRE->getRefKind(),
/*breakOnMember=*/true, ResultValues, isValid);
// If local declaration after use is found, check outer results for
// better matching candidates.
if (localDeclAfterUse) {
auto innerDecl = localDeclAfterUse;
while (localDeclAfterUse) {
if (Lookup.outerResults().empty()) {
Context.Diags.diagnose(Loc, diag::use_local_before_declaration, Name);
Context.Diags.diagnose(innerDecl, diag::decl_declared_here,
localDeclAfterUse->getName());
Expr *error = new (Context) ErrorExpr(UDRE->getSourceRange());
return error;
}
Lookup.shiftDownResults();
ResultValues.clear();
localDeclAfterUse = nullptr;
AllDeclRefs =
findNonMembers(Lookup.innerResults(), UDRE->getRefKind(),
/*breakOnMember=*/true, ResultValues, isValid);
}
}
// If we have an unambiguous reference to a type decl, form a TypeExpr.
if (Lookup.size() == 1 && UDRE->getRefKind() == DeclRefKind::Ordinary &&
isa<TypeDecl>(Lookup[0].getValueDecl())) {
auto *D = cast<TypeDecl>(Lookup[0].getValueDecl());
// FIXME: This is odd.
if (isa<ModuleDecl>(D)) {
return new (Context) DeclRefExpr(D, UDRE->getNameLoc(),
/*Implicit=*/false,
AccessSemantics::Ordinary,
D->getInterfaceType());
}
auto *LookupDC = Lookup[0].getDeclContext();
if (UDRE->isImplicit()) {
return TypeExpr::createImplicitForDecl(
UDRE->getNameLoc(), D, LookupDC,
LookupDC->mapTypeIntoContext(D->getInterfaceType()));
} else {
return TypeExpr::createForDecl(UDRE->getNameLoc(), D, LookupDC);
}
}
if (AllDeclRefs) {
// Diagnose uses of operators that found no matching candidates.
if (ResultValues.empty()) {
assert(UDRE->getRefKind() != DeclRefKind::Ordinary);
Context.Diags.diagnose(
Loc, diag::use_nonmatching_operator, Name,
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->getFunctionRefKind());
}
ResultValues.clear();
bool AllMemberRefs = true;
ValueDecl *Base = nullptr;
DeclContext *BaseDC = nullptr;
for (auto Result : Lookup) {
auto ThisBase = Result.getBaseDecl();
// Track the base for member declarations.
if (ThisBase && !isa<ModuleDecl>(ThisBase)) {
auto Value = Result.getValueDecl();
ResultValues.push_back(Value);
if (Base && ThisBase != Base) {
AllMemberRefs = false;
break;
}
Base = ThisBase;
BaseDC = Result.getDeclContext();
continue;
}
AllMemberRefs = false;
break;
}
if (AllMemberRefs) {
Expr *BaseExpr;
if (auto PD = dyn_cast<ProtocolDecl>(Base)) {
auto selfParam = PD->getGenericParams()->getParams().front();
BaseExpr = TypeExpr::createImplicitForDecl(
UDRE->getNameLoc(), selfParam,
/*DC*/ nullptr,
DC->mapTypeIntoContext(selfParam->getInterfaceType()));
} else if (auto NTD = dyn_cast<NominalTypeDecl>(Base)) {
BaseExpr = TypeExpr::createImplicitForDecl(
UDRE->getNameLoc(), NTD, BaseDC,
DC->mapTypeIntoContext(NTD->getInterfaceType()));
} else {
BaseExpr = new (Context) DeclRefExpr(Base, UDRE->getNameLoc(),
/*Implicit=*/true);
}
llvm::SmallVector<ValueDecl *, 4> outerAlternatives;
(void)findNonMembers(Lookup.outerResults(), UDRE->getRefKind(),
/*breakOnMember=*/false, outerAlternatives,
/*isValid=*/[](ValueDecl *choice) -> bool {
return !choice->isInvalid();
});
// Otherwise, form an UnresolvedDotExpr and sema will resolve it based on
// type information.
return new (Context) UnresolvedDotExpr(
BaseExpr, SourceLoc(), Name, UDRE->getNameLoc(), UDRE->isImplicit(),
Context.AllocateCopy(outerAlternatives));
}
// 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.
//
// Make sure we emit a diagnostic, since returning an ErrorExpr without
// producing one will break things downstream.
Context.Diags.diagnose(Loc, diag::ambiguous_decl_ref, Name);
for (auto Result : Lookup) {
auto *Decl = Result.getValueDecl();
Context.Diags.diagnose(Decl, diag::decl_declared_here, Decl->getName());
}
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() != DeclBaseName::createConstructor())
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() == DC->getASTContext().Id_self)
return ctorContext->getImplicitSelfDecl();
}
return nullptr;
}
namespace {
/// Update the function reference kind based on adding a direct call to a
/// callee with this kind.
FunctionRefKind addingDirectCall(FunctionRefKind kind) {
switch (kind) {
case FunctionRefKind::Unapplied:
return FunctionRefKind::SingleApply;
case FunctionRefKind::SingleApply:
case FunctionRefKind::DoubleApply:
return FunctionRefKind::DoubleApply;
case FunctionRefKind::Compound:
return FunctionRefKind::Compound;
}
llvm_unreachable("Unhandled FunctionRefKind in switch.");
}
/// Update a direct callee expression node that has a function reference kind
/// based on seeing a call to this callee.
template<typename E,
typename = decltype(((E*)nullptr)->getFunctionRefKind())>
void tryUpdateDirectCalleeImpl(E *callee, int) {
callee->setFunctionRefKind(addingDirectCall(callee->getFunctionRefKind()));
}
/// Version of tryUpdateDirectCalleeImpl for when the callee
/// expression type doesn't carry a reference.
template<typename E>
void tryUpdateDirectCalleeImpl(E *callee, ...) { }
/// The given expression is the direct callee of a call expression; mark it to
/// indicate that it has been called.
void markDirectCallee(Expr *callee) {
while (true) {
// Look through identity expressions.
if (auto identity = dyn_cast<IdentityExpr>(callee)) {
callee = identity->getSubExpr();
continue;
}
// Look through unresolved 'specialize' expressions.
if (auto specialize = dyn_cast<UnresolvedSpecializeExpr>(callee)) {
callee = specialize->getSubExpr();
continue;
}
// Look through optional binding.
if (auto bindOptional = dyn_cast<BindOptionalExpr>(callee)) {
callee = bindOptional->getSubExpr();
continue;
}
// Look through forced binding.
if (auto force = dyn_cast<ForceValueExpr>(callee)) {
callee = force->getSubExpr();
continue;
}
// Calls compose.
if (auto call = dyn_cast<CallExpr>(callee)) {
callee = call->getFn();
continue;
}
// We're done.
break;
}
// Cast the callee to its most-specific class, then try to perform an
// update. If the expression node has a declaration reference in it, the
// update will succeed. Otherwise, we're done propagating.
switch (callee->getKind()) {
#define EXPR(Id, Parent) \
case ExprKind::Id: \
tryUpdateDirectCalleeImpl(cast<Id##Expr>(callee), 0); \
break;
#include "swift/AST/ExprNodes.def"
}
}
class PreCheckExpression : public ASTWalker {
ASTContext &Ctx;
DeclContext *DC;
Expr *ParentExpr;
/// 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;
/// 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);
/// Simplify unresolved dot expressions which are nested type productions.
TypeExpr *simplifyNestedTypeExpr(UnresolvedDotExpr *UDE);
TypeExpr *simplifyUnresolvedSpecializeExpr(UnresolvedSpecializeExpr *USE);
/// Simplify a key path expression into a canonical form.
void resolveKeyPathExpr(KeyPathExpr *KPE);
/// Simplify constructs like `UInt32(1)` into `1 as UInt32` if
/// the type conforms to the expected literal protocol.
Expr *simplifyTypeConstructionWithLiteralArg(Expr *E);
/// In Swift < 5, diagnose and correct invalid multi-argument or
/// argument-labeled interpolations.
void correctInterpolationIfStrange(InterpolatedStringLiteralExpr *ISLE) {
// These expressions are valid in Swift 5+.
if (getASTContext().isSwiftVersionAtLeast(5))
return;
/// Diagnoses appendInterpolation(...) calls with multiple
/// arguments or argument labels and corrects them.
class StrangeInterpolationRewriter : public ASTWalker {
ASTContext &Context;
public:
StrangeInterpolationRewriter(ASTContext &Ctx) : Context(Ctx) {}
virtual bool walkToDeclPre(Decl *D) {
// We don't want to look inside decls.
return false;
}
virtual std::pair<bool, Expr *> walkToExprPre(Expr *E) {
// One InterpolatedStringLiteralExpr should never be nested inside
// another except as a child of a CallExpr, and we don't recurse into
// the children of CallExprs.
assert(!isa<InterpolatedStringLiteralExpr>(E) &&
"StrangeInterpolationRewriter found nested interpolation?");
// We only care about CallExprs.
if (!isa<CallExpr>(E))
return { true, E };
auto call = cast<CallExpr>(E);
if (auto callee = dyn_cast<UnresolvedDotExpr>(call->getFn())) {
if (callee->getName().getBaseName() ==
Context.Id_appendInterpolation) {
Expr *newArg = nullptr;
SourceLoc lParen, rParen;
if (call->getNumArguments() > 1) {
auto *args = cast<TupleExpr>(call->getArg());
lParen = args->getLParenLoc();
rParen = args->getRParenLoc();
Expr *secondArg = args->getElement(1);
Context.Diags
.diagnose(secondArg->getLoc(),
diag::string_interpolation_list_changing)
.highlightChars(secondArg->getLoc(), rParen);
Context.Diags
.diagnose(secondArg->getLoc(),
diag::string_interpolation_list_insert_parens)
.fixItInsertAfter(lParen, "(")
.fixItInsert(rParen, ")");
newArg = args;
}
else if(call->getNumArguments() == 1 &&
call->getArgumentLabels().front() != Identifier()) {
auto *args = cast<TupleExpr>(call->getArg());
newArg = args->getElement(0);
lParen = args->getLParenLoc();
rParen = args->getRParenLoc();
SourceLoc argLabelLoc = call->getArgumentLabelLoc(0),
argLoc = newArg->getStartLoc();
Context.Diags
.diagnose(argLabelLoc,
diag::string_interpolation_label_changing)
.highlightChars(argLabelLoc, argLoc);
Context.Diags
.diagnose(argLabelLoc,
diag::string_interpolation_remove_label,
call->getArgumentLabels().front())
.fixItRemoveChars(argLabelLoc, argLoc);
}
// If newArg is no longer null, we need to build a new
// appendInterpolation(_:) call that takes it to replace the bad
// appendInterpolation(...) call.
if (newArg) {
auto newCallee = new (Context) UnresolvedDotExpr(
callee->getBase(), /*dotloc=*/SourceLoc(),
DeclNameRef(Context.Id_appendInterpolation),