-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathPreCheckTarget.cpp
2703 lines (2328 loc) · 98.1 KB
/
PreCheckTarget.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
//===--- PreCheckTarget.cpp - Pre-checking pass ---------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Pre-checking resolves unqualified name references, type expressions and
// operators.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckType.h"
#include "TypoCorrection.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Parse/Confusables.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/ConstraintSystem.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
using namespace swift;
using namespace constraints;
//===----------------------------------------------------------------------===//
// 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.
auto startLookup = TypeChecker::lookupUnqualified(
DC, startName, UDRE->getLoc(), defaultUnqualifiedLookupOptions);
if (!startLookup) continue;
auto endLookup = TypeChecker::lookupUnqualified(DC, endName, UDRE->getLoc(),
defaultUnqualifiedLookupOptions);
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 diagnoseNonexistentPowerOperator(DiagnosticEngine &Diags,
UnresolvedDeclRefExpr *UDRE,
DeclContext *DC) {
auto name = UDRE->getName().getBaseIdentifier();
if (!(name.isOperator() && name.is("**")))
return false;
DC = DC->getModuleScopeContext();
auto &ctx = DC->getASTContext();
DeclNameRef powerName(ctx.getIdentifier("pow"));
// Look if 'pow(_:_:)' exists within current context.
auto lookUp = TypeChecker::lookupUnqualified(
DC, powerName, UDRE->getLoc(), defaultUnqualifiedLookupOptions);
if (lookUp) {
Diags.diagnose(UDRE->getLoc(), diag::nonexistent_power_operator)
.highlight(UDRE->getSourceRange());
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;
}
/// Find the next element in a chain of members. If this expression is (or
/// could be) the base of such a chain, this will return \c nullptr.
static Expr *getMemberChainSubExpr(Expr *expr) {
assert(expr && "getMemberChainSubExpr called with null expr!");
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(expr)) {
return UDE->getBase();
} else if (auto *CE = dyn_cast<CallExpr>(expr)) {
return CE->getFn();
} else if (auto *BOE = dyn_cast<BindOptionalExpr>(expr)) {
return BOE->getSubExpr();
} else if (auto *FVE = dyn_cast<ForceValueExpr>(expr)) {
return FVE->getSubExpr();
} else if (auto *SE = dyn_cast<SubscriptExpr>(expr)) {
return SE->getBase();
} else if (auto *DSE = dyn_cast<DotSelfExpr>(expr)) {
return DSE->getSubExpr();
} else if (auto *USE = dyn_cast<UnresolvedSpecializeExpr>(expr)) {
return USE->getSubExpr();
} else if (auto *CCE = dyn_cast<CodeCompletionExpr>(expr)) {
return CCE->getBase();
} else {
return nullptr;
}
}
UnresolvedMemberExpr *TypeChecker::getUnresolvedMemberChainBase(Expr *expr) {
if (auto *subExpr = getMemberChainSubExpr(expr))
return getUnresolvedMemberChainBase(subExpr);
else
return dyn_cast<UnresolvedMemberExpr>(expr);
}
static bool isBindOptionalMemberChain(Expr *expr) {
if (isa<BindOptionalExpr>(expr)) {
return true;
} else if (auto *base = getMemberChainSubExpr(expr)) {
return isBindOptionalMemberChain(base);
} else {
return false;
}
}
/// Whether this expression sits at the end of a chain of member accesses.
static bool isMemberChainTail(Expr *expr, Expr *parent) {
assert(expr && "isMemberChainTail called with null expr!");
// If this expression's parent is not itself part of a chain (or, this expr
// has no parent expr), this must be the tail of the chain.
return !parent || getMemberChainSubExpr(parent) != expr;
}
static bool isValidForwardReference(ValueDecl *D, DeclContext *DC,
ValueDecl **localDeclAfterUse) {
*localDeclAfterUse = nullptr;
// References to variables injected by lldb are always valid.
if (isa<VarDecl>(D) && cast<VarDecl>(D)->isDebuggerVar())
return true;
// If we find something in the current context, it must be a forward
// reference, because otherwise if it was in scope, it would have
// been returned by the call to ASTScope::lookupLocalDecls() above.
if (D->getDeclContext()->isLocalContext()) {
do {
if (D->getDeclContext() == DC) {
*localDeclAfterUse = D;
return false;
}
// If we're inside of a 'defer' context, walk up to the parent
// and check again. We don't want 'defer' bodies to forward
// reference bindings in the immediate outer scope.
} while (isa<FuncDecl>(DC) &&
cast<FuncDecl>(DC)->isDeferBody() &&
(DC = DC->getParent()));
}
return true;
}
/// Checks whether this is a BinaryExpr with operator `&` and returns the
/// BinaryExpr, if so.
static BinaryExpr *getCompositionExpr(Expr *expr) {
if (auto *binaryExpr = dyn_cast<BinaryExpr>(expr)) {
// look at the name of the operator, if it is a '&' we can create the
// composition TypeExpr
auto fn = binaryExpr->getFn();
if (auto Overload = dyn_cast<OverloadedDeclRefExpr>(fn)) {
if (llvm::any_of(Overload->getDecls(), [](auto *decl) -> bool {
return decl->getBaseName() == "&";
}))
return binaryExpr;
} else if (auto *Decl = dyn_cast<UnresolvedDeclRefExpr>(fn)) {
if (Decl->getName().isSimpleName() &&
Decl->getName().getBaseName() == "&")
return binaryExpr;
}
}
return nullptr;
}
/// Diagnoses an unqualified `init` expression.
///
/// \param initExpr The \c init expression.
/// \param dc The declaration context of \p initExpr.
///
/// \returns An expression matching `self.init` or `super.init` that can be used
/// to recover, or `nullptr` if cannot recover.
static UnresolvedDotExpr *
diagnoseUnqualifiedInit(UnresolvedDeclRefExpr *initExpr, DeclContext *dc,
ASTContext &ctx) {
const auto loc = initExpr->getLoc();
enum class Suggestion : unsigned {
None = 0,
Self = 1,
Super = 2,
};
Suggestion suggestion = [dc]() {
NominalTypeDecl *nominal = nullptr;
{
auto *typeDC = dc->getInnermostTypeContext();
if (!typeDC) {
// No type context--no suggestion.
return Suggestion::None;
}
nominal = typeDC->getSelfNominalTypeDecl();
}
auto *classDecl = dyn_cast<ClassDecl>(nominal);
if (!classDecl || !classDecl->hasSuperclass()) {
// No class or no superclass--suggest 'self.'.
return Suggestion::Self;
}
if (auto *initDecl = dyn_cast<ConstructorDecl>(dc)) {
if (initDecl->getAttrs().hasAttribute<ConvenienceAttr>()) {
// Innermost context is a convenience initializer--suggest 'self.'.
return Suggestion::Self;
} else {
// Innermost context is a designated initializer--suggest 'super.'.
return Suggestion::Super;
}
}
// Class context but innermost context is not an initializer--suggest
// 'self.'. 'super.' might be possible too, but is far lesss likely to be
// the right answer.
return Suggestion::Self;
}();
auto diag =
ctx.Diags.diagnose(loc, diag::unqualified_init, (unsigned)suggestion);
Expr *base = nullptr;
switch (suggestion) {
case Suggestion::None:
return nullptr;
case Suggestion::Self:
diag.fixItInsert(loc, "self.");
base = new (ctx)
UnresolvedDeclRefExpr(DeclNameRef(ctx.Id_self), DeclRefKind::Ordinary,
initExpr->getNameLoc());
base->setImplicit(true);
break;
case Suggestion::Super:
diag.fixItInsert(loc, "super.");
base = new (ctx) SuperRefExpr(/*Self=*/nullptr, loc, /*Implicit=*/true);
break;
}
return new (ctx)
UnresolvedDotExpr(base, /*dotloc=*/SourceLoc(), initExpr->getName(),
initExpr->getNameLoc(), /*implicit=*/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) {
auto &Context = DC->getASTContext();
DeclNameRef Name = UDRE->getName();
SourceLoc Loc = UDRE->getLoc();
auto errorResult = [&]() -> Expr * {
return new (Context) ErrorExpr(UDRE->getSourceRange());
};
TypeChecker::checkForForbiddenPrefix(Context, Name.getBaseName());
// Try and recover if we have an unqualified 'init'.
if (Name.getBaseName().isConstructor()) {
auto *recoveryExpr = diagnoseUnqualifiedInit(UDRE, DC, Context);
if (!recoveryExpr)
return errorResult();
return recoveryExpr;
}
// Process UnresolvedDeclRefExpr by doing an unqualified lookup.
DeclNameRef LookupName = Name;
if (Name.isCompoundName()) {
auto &context = DC->getASTContext();
// Remove any $ prefixes for lookup
SmallVector<Identifier, 4> lookupLabels;
for (auto label : Name.getArgumentNames()) {
if (label.hasDollarPrefix()) {
auto unprefixed = label.str().drop_front();
lookupLabels.push_back(context.getIdentifier(unprefixed));
} else {
lookupLabels.push_back(label);
}
}
DeclName lookupName(context, Name.getBaseName(), lookupLabels);
LookupName = DeclNameRef(lookupName);
}
// Perform standard value name lookup.
NameLookupOptions lookupOptions = defaultUnqualifiedLookupOptions;
// 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;
LookupResult Lookup;
bool AllDeclRefs = true;
SmallVector<ValueDecl*, 4> ResultValues;
// First, look for a local binding in scope.
if (Loc.isValid() && !Name.isOperator()) {
ASTScope::lookupLocalDecls(DC->getParentSourceFile(),
LookupName.getFullName(), Loc,
/*stopAfterInnermostBraceStmt=*/false,
ResultValues);
for (auto *localDecl : ResultValues) {
Lookup.add(LookupResultEntry(localDecl), /*isOuter=*/false);
}
}
if (!Lookup) {
// Now, look for all local bindings, even forward references, as well
// as type members and top-level declarations.
if (Loc.isInvalid())
DC = DC->getModuleScopeContext();
Lookup = TypeChecker::lookupUnqualified(DC, LookupName, Loc, lookupOptions);
ValueDecl *localDeclAfterUse = nullptr;
AllDeclRefs =
findNonMembers(Lookup.innerResults(), UDRE->getRefKind(),
/*breakOnMember=*/true, ResultValues,
[&](ValueDecl *D) {
return isValidForwardReference(D, DC, &localDeclAfterUse);
});
// If local declaration after use is found, check outer results for
// better matching candidates.
if (ResultValues.empty() && 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);
return errorResult();
}
Lookup.shiftDownResults();
ResultValues.clear();
localDeclAfterUse = nullptr;
AllDeclRefs =
findNonMembers(Lookup.innerResults(), UDRE->getRefKind(),
/*breakOnMember=*/true, ResultValues,
[&](ValueDecl *D) {
return isValidForwardReference(D, DC, &localDeclAfterUse);
});
}
}
}
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) ||
diagnoseNonexistentPowerOperator(Context.Diags, UDRE, DC)) {
return errorResult();
}
// Try ignoring access control.
NameLookupOptions relookupOptions = lookupOptions;
relookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto inaccessibleResults =
TypeChecker::lookupUnqualified(DC, LookupName, Loc, relookupOptions);
if (inaccessibleResults) {
// FIXME: What if the unviable candidates have different levels of access?
const ValueDecl *first = inaccessibleResults.front().getValueDecl();
auto accessLevel =
first->getFormalAccessScope().accessLevelForDiagnostics();
Context.Diags.diagnose(Loc, diag::candidate_inaccessible, first,
accessLevel);
// 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);
}
// 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 errorResult();
}
// Try ignoring missing imports.
relookupOptions |= NameLookupFlags::IgnoreMissingImports;
auto nonImportedResults =
TypeChecker::lookupUnqualified(DC, LookupName, Loc, relookupOptions);
if (nonImportedResults) {
const ValueDecl *first = nonImportedResults.front().getValueDecl();
maybeDiagnoseMissingImportForMember(first, DC, Loc);
// 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 errorResult();
}
// 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;
uint32_t firstConfusableCodepoint = 0;
int totalCodepoints = 0;
int offset = 0;
while ((codepoint = validateUTF8CharacterAndAdvance(buffer,
buffer +
strlen(buffer)))
!= ~0U) {
int length = (buffer - simpleName.get()) - offset;
if (auto expectedCodepoint =
confusable::tryConvertConfusableCharacterToASCII(codepoint)) {
if (firstConfusableCodepoint == 0) {
firstConfusableCodepoint = codepoint;
}
isConfused = true;
expectedIdentifier += expectedCodepoint;
} else {
expectedIdentifier += (char)codepoint;
}
totalCodepoints++;
offset += length;
}
auto emitBasicError = [&] {
if (Name.isSimpleName(Context.Id_self)) {
// `self` gets diagnosed with a different error when it can't be found.
Context.Diags
.diagnose(Loc, diag::cannot_find_self_in_scope)
.highlight(UDRE->getSourceRange());
} else {
Context.Diags
.diagnose(Loc, diag::cannot_find_in_scope, Name,
Name.isOperator())
.highlight(UDRE->getSourceRange());
}
if (!Context.LangOpts.DisableExperimentalClangImporterDiagnostics) {
Context.getClangModuleLoader()->diagnoseTopLevelValue(
Name.getFullName());
}
};
if (!isConfused) {
if (Name.isSimpleName(Context.Id_Self)) {
if (DeclContext *typeContext = DC->getInnermostTypeContext()){
Type SelfType = typeContext->getSelfInterfaceType();
if (typeContext->getSelfClassDecl() &&
!typeContext->getSelfClassDecl()->isForeignReferenceType())
SelfType = DynamicSelfType::get(SelfType, Context);
return new (Context)
TypeExpr(new (Context) SelfTypeRepr(SelfType, Loc));
}
}
TypoCorrectionResults corrections(Name, nameLoc);
// FIXME: Don't perform typo correction inside macro arguments, because it
// will invoke synthesizing declarations in this scope, which will attempt to
// expand this macro which leads to circular reference errors.
if (!namelookup::isInMacroArgument(DC->getParentSourceFile(), UDRE->getLoc())) {
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();
if (totalCodepoints == 1) {
auto charNames = confusable::getConfusableAndBaseCodepointNames(
firstConfusableCodepoint);
Context.Diags
.diagnose(Loc, diag::single_confusable_character,
UDRE->getName().isOperator(), simpleName.str(),
charNames.first, expectedIdentifier, charNames.second)
.fixItReplace(Loc, expectedIdentifier);
} else {
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 errorResult();
}
// FIXME: Need to refactor the way we build an AST node from a lookup result!
auto buildTypeExpr = [&](TypeDecl *D) -> Expr * {
// 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();
bool makeTypeValue = false;
if (isa<GenericTypeParamDecl>(D) &&
cast<GenericTypeParamDecl>(D)->isValue()) {
makeTypeValue = true;
}
if (UDRE->isImplicit()) {
return TypeExpr::createImplicitForDecl(
UDRE->getNameLoc(), D, LookupDC,
// It might happen that LookupDC is null if this is checking
// synthesized code, in that case, don't map the type into context,
// but return as is -- the synthesis should ensure the type is
// correct.
LookupDC ? LookupDC->mapTypeIntoContext(D->getInterfaceType())
: D->getInterfaceType());
} else {
if (makeTypeValue) {
return TypeValueExpr::createForDecl(UDRE->getNameLoc(),
cast<GenericTypeParamDecl>(D));
} else {
return TypeExpr::createForDecl(UDRE->getNameLoc(), D, LookupDC);
}
}
};
// 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())) {
return buildTypeExpr(cast<TypeDecl>(Lookup[0].getValueDecl()));
}
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 errorResult();
}
// 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->getGenericSignature()->getMaxDepth();
unsigned yDepth = yGeneric->getGenericSignature()->getMaxDepth();
return xDepth < yDepth;
});
}
// Filter out macro declarations without `#` if there are valid
// non-macro results.
if (llvm::any_of(ResultValues,
[](const ValueDecl *D) { return !isa<MacroDecl>(D); })) {
ResultValues.erase(
llvm::remove_if(ResultValues,
[](const ValueDecl *D) { return isa<MacroDecl>(D); }),
ResultValues.end());
// If there is only one type reference in results, let's handle
// this in a special way.
if (ResultValues.size() == 1 &&
UDRE->getRefKind() == DeclRefKind::Ordinary &&
isa<TypeDecl>(ResultValues.front())) {
return buildTypeExpr(cast<TypeDecl>(ResultValues.front()));
}
}
// If we are in an @_unsafeInheritExecutor context, swap out
// declarations for their _unsafeInheritExecutor_ counterparts if they
// exist.
if (enclosingUnsafeInheritsExecutor(DC)) {
introduceUnsafeInheritExecutorReplacements(
DC, UDRE->getNameLoc().getBaseNameLoc(), ResultValues);
}
return buildRefExpr(ResultValues, DC, UDRE->getNameLoc(),
UDRE->isImplicit(), UDRE->getFunctionRefInfo());
}
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);
}
auto isInClosureContext = [&](ValueDecl *decl) -> bool {
auto *DC = decl->getDeclContext();
do {
if (dyn_cast<ClosureExpr>(DC))
return true;
} while ((DC = DC->getParent()));
return false;
};
llvm::SmallVector<ValueDecl *, 4> outerAlternatives;
(void)findNonMembers(Lookup.outerResults(), UDRE->getRefKind(),
/*breakOnMember=*/false, outerAlternatives,
/*isValid=*/[&](ValueDecl *choice) -> bool {
// Values that are defined in a closure
// that hasn't been type-checked yet,
// cannot be outer candidates.
if (isInClosureContext(choice)) {
return choice->hasInterfaceType() &&
!choice->isInvalid();
}
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);
}
return errorResult();
}
/// 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().isConstructor())
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 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)->getFunctionRefInfo())>
void tryUpdateDirectCalleeImpl(E *callee, int) {
callee->setFunctionRefInfo(
callee->getFunctionRefInfo().addingApplicationLevel());
}
/// 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.