forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNameLookup.cpp
1633 lines (1389 loc) · 57.7 KB
/
NameLookup.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
//===--- NameLookup.cpp - Swift Name Lookup Routines ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements interfaces for performing name lookup.
//
//===----------------------------------------------------------------------===//
#include "NameLookupImpl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTScope.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/DebuggerClient.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/STLExtras.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/TinyPtrVector.h"
using namespace swift;
void DebuggerClient::anchor() {}
void AccessFilteringDeclConsumer::foundDecl(ValueDecl *D,
DeclVisibilityKind reason) {
if (D->getASTContext().LangOpts.EnableAccessControl) {
if (TypeResolver)
TypeResolver->resolveAccessibility(D);
if (D->isInvalid() && !D->hasAccessibility())
return;
if (!D->isAccessibleFrom(DC))
return;
}
ChainedConsumer.foundDecl(D, reason);
}
template <typename Fn>
static void forAllVisibleModules(const DeclContext *DC, const Fn &fn) {
DeclContext *moduleScope = DC->getModuleScopeContext();
if (auto file = dyn_cast<FileUnit>(moduleScope))
file->forAllVisibleModules(fn);
else
cast<ModuleDecl>(moduleScope)->forAllVisibleModules(ModuleDecl::AccessPathTy(), fn);
}
bool swift::removeOverriddenDecls(SmallVectorImpl<ValueDecl*> &decls) {
if (decls.empty())
return false;
ASTContext &ctx = decls.front()->getASTContext();
llvm::SmallPtrSet<ValueDecl*, 8> overridden;
for (auto decl : decls) {
while (auto overrides = decl->getOverriddenDecl()) {
overridden.insert(overrides);
// Because initializers from Objective-C base classes have greater
// visibility than initializers written in Swift classes, we can
// have a "break" in the set of declarations we found, where
// C.init overrides B.init overrides A.init, but only C.init and
// A.init are in the chain. Make sure we still remove A.init from the
// set in this case.
if (decl->getFullName().getBaseName() == ctx.Id_init) {
/// FIXME: Avoid the possibility of an infinite loop by fixing the root
/// cause instead (incomplete circularity detection).
assert(decl != overrides && "Circular class inheritance?");
decl = overrides;
continue;
}
break;
}
}
// If no methods were overridden, we're done.
if (overridden.empty()) return false;
// Erase any overridden declarations
bool anyOverridden = false;
decls.erase(std::remove_if(decls.begin(), decls.end(),
[&](ValueDecl *decl) -> bool {
if (overridden.count(decl) > 0) {
anyOverridden = true;
return true;
}
return false;
}),
decls.end());
return anyOverridden;
}
enum class ConstructorComparison {
Worse,
Same,
Better,
};
/// Determines whether \p ctor1 is a "better" initializer than \p ctor2.
static ConstructorComparison compareConstructors(ConstructorDecl *ctor1,
ConstructorDecl *ctor2,
const swift::ASTContext &ctx) {
bool available1 = !ctor1->getAttrs().isUnavailable(ctx);
bool available2 = !ctor2->getAttrs().isUnavailable(ctx);
// An unavailable initializer is always worse than an available initializer.
if (available1 < available2)
return ConstructorComparison::Worse;
if (available1 > available2)
return ConstructorComparison::Better;
CtorInitializerKind kind1 = ctor1->getInitKind();
CtorInitializerKind kind2 = ctor2->getInitKind();
if (kind1 > kind2)
return ConstructorComparison::Worse;
if (kind1 < kind2)
return ConstructorComparison::Better;
return ConstructorComparison::Same;
}
bool swift::removeShadowedDecls(SmallVectorImpl<ValueDecl*> &decls,
const ModuleDecl *curModule,
LazyResolver *typeResolver) {
// Category declarations by their signatures.
llvm::SmallDenseMap<std::pair<CanType, Identifier>,
llvm::TinyPtrVector<ValueDecl *>>
CollidingDeclGroups;
/// Objective-C initializers are tracked by their context type and
/// full name.
llvm::SmallDenseMap<std::pair<CanType, DeclName>,
llvm::TinyPtrVector<ConstructorDecl *>>
ObjCCollidingConstructors;
bool anyCollisions = false;
for (auto decl : decls) {
// FIXME: Egregious hack to avoid failing when there are no declared types.
// FIXME: Pass this down instead of getting it from the ASTContext.
if (typeResolver)
typeResolver->resolveDeclSignature(decl);
// If the decl is currently being validated, this is likely a recursive
// reference and we'll want to skip ahead so as to avoid having its type
// attempt to desugar itself.
if (!decl->hasValidSignature())
continue;
// FIXME: the canonical type makes a poor signature, because we don't
// canonicalize away default arguments.
auto signature = decl->getInterfaceType()->getCanonicalType();
// FIXME: The type of a variable or subscript doesn't include
// enough context to distinguish entities from different
// constrained extensions, so use the overload signature's
// type. This is layering a partial fix upon a total hack.
if (auto asd = dyn_cast<AbstractStorageDecl>(decl))
signature = asd->getOverloadSignature().InterfaceType;
// If we've seen a declaration with this signature before, note it.
auto &knownDecls =
CollidingDeclGroups[std::make_pair(signature, decl->getName())];
if (!knownDecls.empty())
anyCollisions = true;
knownDecls.push_back(decl);
// Specifically keep track of Objective-C initializers, which can come from
// either init methods or factory methods.
if (decl->hasClangNode()) {
if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
auto ctorSignature
= std::make_pair(ctor->getDeclContext()->getDeclaredInterfaceType()
->getCanonicalType(),
decl->getFullName());
auto &knownCtors = ObjCCollidingConstructors[ctorSignature];
if (!knownCtors.empty())
anyCollisions = true;
knownCtors.push_back(ctor);
}
}
}
// If there were no signature collisions, there is nothing to do.
if (!anyCollisions)
return false;
// Determine the set of declarations that are shadowed by other declarations.
llvm::SmallPtrSet<ValueDecl *, 4> shadowed;
ASTContext &ctx = decls[0]->getASTContext();
for (auto &collidingDecls : CollidingDeclGroups) {
// If only one declaration has this signature, it isn't shadowed by
// anything.
if (collidingDecls.second.size() == 1)
continue;
// Compare each declaration to every other declaration. This is
// unavoidably O(n^2) in the number of declarations, but because they
// all have the same signature, we expect n to remain small.
for (unsigned firstIdx = 0, n = collidingDecls.second.size();
firstIdx != n; ++firstIdx) {
auto firstDecl = collidingDecls.second[firstIdx];
auto firstModule = firstDecl->getModuleContext();
for (unsigned secondIdx = firstIdx + 1; secondIdx != n; ++secondIdx) {
// Determine whether one module takes precedence over another.
auto secondDecl = collidingDecls.second[secondIdx];
auto secondModule = secondDecl->getModuleContext();
// If one declaration is in a protocol or extension thereof and the
// other is not, prefer the one that is not.
if ((bool)firstDecl->getDeclContext()
->getAsProtocolOrProtocolExtensionContext()
!= (bool)secondDecl->getDeclContext()
->getAsProtocolOrProtocolExtensionContext()) {
if (firstDecl->getDeclContext()
->getAsProtocolOrProtocolExtensionContext()) {
shadowed.insert(firstDecl);
break;
} else {
shadowed.insert(secondDecl);
continue;
}
}
// If one declaration is available and the other is not, prefer the
// available one.
if (firstDecl->getAttrs().isUnavailable(ctx) !=
secondDecl->getAttrs().isUnavailable(ctx)) {
if (firstDecl->getAttrs().isUnavailable(ctx)) {
shadowed.insert(firstDecl);
break;
} else {
shadowed.insert(secondDecl);
continue;
}
}
// Don't apply module-shadowing rules to members of protocol types.
if (isa<ProtocolDecl>(firstDecl->getDeclContext()) ||
isa<ProtocolDecl>(secondDecl->getDeclContext()))
continue;
// Prefer declarations in the current module over those in another
// module.
// FIXME: This is a hack. We should query a (lazily-built, cached)
// module graph to determine shadowing.
if ((firstModule == curModule) == (secondModule == curModule))
continue;
// If the first module is the current module, the second declaration
// is shadowed by the first.
if (firstModule == curModule) {
shadowed.insert(secondDecl);
continue;
}
// Otherwise, the first declaration is shadowed by the second. There is
// no point in continuing to compare the first declaration to others.
shadowed.insert(firstDecl);
break;
}
}
}
// Check for collisions among Objective-C initializers. When such collisions
// exist, we pick the
for (const auto &colliding : ObjCCollidingConstructors) {
if (colliding.second.size() == 1)
continue;
// Find the "best" constructor with this signature.
ConstructorDecl *bestCtor = colliding.second[0];
for (auto ctor : colliding.second) {
auto comparison = compareConstructors(ctor, bestCtor, ctx);
if (comparison == ConstructorComparison::Better)
bestCtor = ctor;
}
// Shadow any initializers that are worse.
for (auto ctor : colliding.second) {
auto comparison = compareConstructors(ctor, bestCtor, ctx);
if (comparison == ConstructorComparison::Worse)
shadowed.insert(ctor);
}
}
// If none of the declarations were shadowed, we're done.
if (shadowed.empty())
return false;
// Remove shadowed declarations from the list of declarations.
bool anyRemoved = false;
decls.erase(std::remove_if(decls.begin(), decls.end(),
[&](ValueDecl *vd) {
if (shadowed.count(vd) > 0) {
anyRemoved = true;
return true;
}
return false;
}),
decls.end());
return anyRemoved;
}
namespace {
enum class DiscriminatorMatch {
NoDiscriminator,
Matches,
Different
};
} // end anonymous namespace
static DiscriminatorMatch matchDiscriminator(Identifier discriminator,
const ValueDecl *value) {
if (value->getFormalAccess() > Accessibility::FilePrivate)
return DiscriminatorMatch::NoDiscriminator;
auto containingFile =
dyn_cast<FileUnit>(value->getDeclContext()->getModuleScopeContext());
if (!containingFile)
return DiscriminatorMatch::Different;
if (discriminator == containingFile->getDiscriminatorForPrivateValue(value))
return DiscriminatorMatch::Matches;
return DiscriminatorMatch::Different;
}
static DiscriminatorMatch
matchDiscriminator(Identifier discriminator,
UnqualifiedLookupResult lookupResult) {
return matchDiscriminator(discriminator, lookupResult.getValueDecl());
}
template <typename Result>
static void filterForDiscriminator(SmallVectorImpl<Result> &results,
DebuggerClient *debugClient) {
Identifier discriminator = debugClient->getPreferredPrivateDiscriminator();
if (discriminator.empty())
return;
auto lastMatchIter = std::find_if(results.rbegin(), results.rend(),
[discriminator](Result next) -> bool {
return
matchDiscriminator(discriminator, next) == DiscriminatorMatch::Matches;
});
if (lastMatchIter == results.rend())
return;
Result lastMatch = *lastMatchIter;
auto newEnd = std::remove_if(results.begin(), lastMatchIter.base()-1,
[discriminator](Result next) -> bool {
return
matchDiscriminator(discriminator, next) == DiscriminatorMatch::Different;
});
results.erase(newEnd, results.end());
results.push_back(lastMatch);
}
static void recordLookupOfTopLevelName(DeclContext *topLevelContext,
DeclName name,
bool isCascading) {
auto SF = dyn_cast<SourceFile>(topLevelContext);
if (!SF)
return;
auto *nameTracker = SF->getReferencedNameTracker();
if (!nameTracker)
return;
nameTracker->addTopLevelName(name.getBaseName(), isCascading);
}
/// Determine the local declaration visibility key for an \c ASTScope in which
/// name lookup successfully resolved.
static DeclVisibilityKind getLocalDeclVisibilityKind(const ASTScope *scope) {
switch (scope->getKind()) {
case ASTScopeKind::Preexpanded:
case ASTScopeKind::SourceFile:
case ASTScopeKind::TypeDecl:
case ASTScopeKind::AbstractFunctionDecl:
case ASTScopeKind::TypeOrExtensionBody:
case ASTScopeKind::AbstractFunctionBody:
case ASTScopeKind::DefaultArgument:
case ASTScopeKind::PatternBinding:
case ASTScopeKind::IfStmt:
case ASTScopeKind::GuardStmt:
case ASTScopeKind::RepeatWhileStmt:
case ASTScopeKind::ForEachStmt:
case ASTScopeKind::DoCatchStmt:
case ASTScopeKind::SwitchStmt:
case ASTScopeKind::ForStmt:
case ASTScopeKind::Accessors:
case ASTScopeKind::TopLevelCode:
llvm_unreachable("no local declarations?");
case ASTScopeKind::ExtensionGenericParams:
case ASTScopeKind::GenericParams:
return DeclVisibilityKind::GenericParameter;
case ASTScopeKind::AbstractFunctionParams:
case ASTScopeKind::Closure:
case ASTScopeKind::PatternInitializer: // lazy var 'self'
return DeclVisibilityKind::FunctionParameter;
case ASTScopeKind::AfterPatternBinding:
case ASTScopeKind::ConditionalClause:
case ASTScopeKind::ForEachPattern:
case ASTScopeKind::BraceStmt:
case ASTScopeKind::CatchStmt:
case ASTScopeKind::CaseStmt:
case ASTScopeKind::ForStmtInitializer:
return DeclVisibilityKind::LocalVariable;
}
llvm_unreachable("Unhandled ASTScopeKind in switch.");
}
UnqualifiedLookup::UnqualifiedLookup(DeclName Name, DeclContext *DC,
LazyResolver *TypeResolver,
bool IsKnownNonCascading,
SourceLoc Loc, bool IsTypeLookup,
bool AllowProtocolMembers,
bool IgnoreAccessControl) {
ModuleDecl &M = *DC->getParentModule();
ASTContext &Ctx = M.getASTContext();
const SourceManager &SM = Ctx.SourceMgr;
DebuggerClient *DebugClient = M.getDebugClient();
NamedDeclConsumer Consumer(Name, Results, IsTypeLookup);
Optional<bool> isCascadingUse;
if (IsKnownNonCascading)
isCascadingUse = false;
SmallVector<UnqualifiedLookupResult, 4> UnavailableInnerResults;
if (Loc.isValid() &&
DC->getParentSourceFile()->Kind != SourceFileKind::REPL &&
Ctx.LangOpts.EnableASTScopeLookup) {
// Find the source file in which we are performing the lookup.
SourceFile &sourceFile = *DC->getParentSourceFile();
// Find the scope from which we will initiate unqualified name lookup.
const ASTScope *lookupScope
= sourceFile.getScope().findInnermostEnclosingScope(Loc);
// Operator lookup is always at module scope.
if (Name.isOperator()) {
if (!isCascadingUse.hasValue()) {
DeclContext *innermostDC =
lookupScope->getInnermostEnclosingDeclContext();
isCascadingUse =
innermostDC->isCascadingContextForLookup(
/*functionsAreNonCascading=*/true);
}
lookupScope = &sourceFile.getScope();
}
// Walk scopes outward from the innermost scope until we find something.
ParamDecl *selfDecl = nullptr;
for (auto currentScope = lookupScope; currentScope;
currentScope = currentScope->getParent()) {
// Perform local lookup within this scope.
auto localBindings = currentScope->getLocalBindings();
for (auto local : localBindings) {
Consumer.foundDecl(local,
getLocalDeclVisibilityKind(currentScope));
}
// If we found anything, we're done.
if (!Results.empty())
return;
// When we are in the body of a method, get the 'self' declaration.
if (currentScope->getKind() == ASTScopeKind::AbstractFunctionBody &&
currentScope->getAbstractFunctionDecl()->getDeclContext()
->isTypeContext()) {
selfDecl =
currentScope->getAbstractFunctionDecl()->getImplicitSelfDecl();
continue;
}
// If there is a declaration context associated with this scope, we might
// want to look in it.
if (auto dc = currentScope->getDeclContext()) {
// If we haven't determined whether we have a cascading use, do so now.
if (!isCascadingUse.hasValue()) {
isCascadingUse =
dc->isCascadingContextForLookup(/*functionsAreNonCascading=*/false);
}
// Pattern binding initializers are only interesting insofar as they
// affect lookup in an enclosing nominal type or extension thereof.
if (auto *bindingInit = dyn_cast<PatternBindingInitializer>(dc)) {
if (auto binding = bindingInit->getBinding()) {
// Look for 'self' for a lazy variable initializer.
if (auto singleVar = binding->getSingleVar())
// We only care about lazy variables.
if (singleVar->getAttrs().hasAttribute<LazyAttr>()) {
// 'self' will be listed in the local bindings.
for (auto local : localBindings) {
auto param = dyn_cast<ParamDecl>(local);
if (!param) continue;
// If we have a variable that's the implicit self of its enclosing
// context, mark it as 'self'.
if (auto func = dyn_cast<FuncDecl>(param->getDeclContext())) {
if (param == func->getImplicitSelfDecl()) {
selfDecl = param;
break;
}
}
}
}
}
continue;
}
// Default arguments only have 'static' access to the members of the
// enclosing type, if there is one.
if (isa<DefaultArgumentInitializer>(dc)) continue;
// Functions/initializers/deinitializers are only interesting insofar as
// they affect lookup in an enclosing nominal type or extension thereof.
if (isa<AbstractFunctionDecl>(dc)) continue;
// Subscripts have no lookup of their own.
if (isa<SubscriptDecl>(dc)) continue;
// Closures have no lookup of their own.
if (isa<AbstractClosureExpr>(dc)) continue;
// Top-level declarations have no lookup of their own.
if (isa<TopLevelCodeDecl>(dc)) continue;
// Typealiases have no lookup of their own.
if (isa<TypeAliasDecl>(dc)) continue;
// Lookup in the source file's scope marks the end.
if (isa<SourceFile>(dc)) {
// FIXME: A bit of a hack.
DC = dc;
break;
}
// We have a nominal type or an extension thereof. Perform lookup into
// the nominal type.
auto nominal = dc->getAsNominalTypeOrNominalTypeExtensionContext();
if (!nominal) continue;
// FIXME: This is overkill for name lookup.
if (TypeResolver)
TypeResolver->resolveDeclSignature(nominal);
// Dig out the type we're looking into.
// FIXME: We shouldn't need to compute a type to perform this lookup.
Type lookupType = dc->getSelfTypeInContext();
if (lookupType->hasError()) continue;
// Perform lookup into the type.
NLOptions options = NL_UnqualifiedDefault;
if (isCascadingUse.getValue())
options |= NL_KnownCascadingDependency;
else
options |= NL_KnownNonCascadingDependency;
if (AllowProtocolMembers)
options |= NL_ProtocolMembers;
if (IsTypeLookup)
options |= NL_OnlyTypes;
if (IgnoreAccessControl)
options |= NL_IgnoreAccessibility;
SmallVector<ValueDecl *, 4> lookup;
dc->lookupQualified(lookupType, Name, options, TypeResolver, lookup);
ValueDecl *baseDecl = nominal;
if (selfDecl) baseDecl = selfDecl;
for (auto result : lookup) {
Results.push_back(UnqualifiedLookupResult(baseDecl, result));
}
if (!Results.empty()) {
// Predicate that determines whether a lookup result should
// be unavailable except as a last-ditch effort.
auto unavailableLookupResult =
[&](const UnqualifiedLookupResult &result) {
auto &effectiveVersion = Ctx.LangOpts.EffectiveLanguageVersion;
return result.getValueDecl()->getAttrs()
.isUnavailableInSwiftVersion(effectiveVersion);
};
// If all of the results we found are unavailable, keep looking.
if (std::all_of(Results.begin(), Results.end(),
unavailableLookupResult)) {
UnavailableInnerResults.append(Results.begin(), Results.end());
Results.clear();
} else {
if (DebugClient)
filterForDiscriminator(Results, DebugClient);
return;
}
}
// Forget the 'self' declaration.
selfDecl = nullptr;
}
}
} else {
// Never perform local lookup for operators.
if (Name.isOperator()) {
if (!isCascadingUse.hasValue()) {
isCascadingUse =
DC->isCascadingContextForLookup(/*functionsAreNonCascading=*/true);
}
DC = DC->getModuleScopeContext();
} else {
// If we are inside of a method, check to see if there are any ivars in
// scope, and if so, whether this is a reference to one of them.
// FIXME: We should persist this information between lookups.
while (!DC->isModuleScopeContext()) {
ValueDecl *BaseDecl = nullptr;
ValueDecl *MetaBaseDecl = nullptr;
GenericParamList *GenericParams = nullptr;
Type ExtendedType;
bool isTypeLookup = false;
// If this declcontext is an initializer for a static property, then we're
// implicitly doing a static lookup into the parent declcontext.
if (auto *PBI = dyn_cast<PatternBindingInitializer>(DC))
if (!DC->getParent()->isModuleScopeContext()) {
if (auto *PBD = PBI->getBinding()) {
isTypeLookup = PBD->isStatic();
DC = DC->getParent();
}
}
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(DC)) {
// Look for local variables; normally, the parser resolves these
// for us, but it can't do the right thing inside local types.
// FIXME: when we can parse and typecheck the function body partially
// for code completion, AFD->getBody() check can be removed.
if (Loc.isValid() && AFD->getBody()) {
if (!isCascadingUse.hasValue()) {
isCascadingUse =
!SM.rangeContainsTokenLoc(AFD->getBodySourceRange(), Loc);
}
namelookup::FindLocalVal localVal(SM, Loc, Consumer);
localVal.visit(AFD->getBody());
if (!Results.empty())
return;
for (auto *PL : AFD->getParameterLists())
localVal.checkParameterList(PL);
if (!Results.empty())
return;
}
if (!isCascadingUse.hasValue() || isCascadingUse.getValue())
isCascadingUse = AFD->isCascadingContextForLookup(false);
if (AFD->getDeclContext()->isTypeContext()) {
ExtendedType = AFD->getDeclContext()->getSelfTypeInContext();
BaseDecl = AFD->getImplicitSelfDecl();
MetaBaseDecl = AFD->getDeclContext()
->getAsNominalTypeOrNominalTypeExtensionContext();
DC = DC->getParent();
if (auto *FD = dyn_cast<FuncDecl>(AFD))
if (FD->isStatic())
isTypeLookup = true;
// If we're not in the body of the function, the base declaration
// is the nominal type, not 'self'.
if (Loc.isValid() &&
AFD->getBodySourceRange().isValid() &&
!SM.rangeContainsTokenLoc(AFD->getBodySourceRange(), Loc)) {
BaseDecl = MetaBaseDecl;
}
}
// Look in the generic parameters after checking our local declaration.
GenericParams = AFD->getGenericParams();
} else if (auto *SD = dyn_cast<SubscriptDecl>(DC)) {
GenericParams = SD->getGenericParams();
} else if (auto *ACE = dyn_cast<AbstractClosureExpr>(DC)) {
// Look for local variables; normally, the parser resolves these
// for us, but it can't do the right thing inside local types.
if (Loc.isValid()) {
if (auto *CE = dyn_cast<ClosureExpr>(ACE)) {
namelookup::FindLocalVal localVal(SM, Loc, Consumer);
localVal.visit(CE->getBody());
if (!Results.empty())
return;
localVal.checkParameterList(CE->getParameters());
if (!Results.empty())
return;
}
}
if (!isCascadingUse.hasValue())
isCascadingUse = ACE->isCascadingContextForLookup(false);
} else if (ExtensionDecl *ED = dyn_cast<ExtensionDecl>(DC)) {
ExtendedType = ED->getSelfTypeInContext();
BaseDecl = ED->getAsNominalTypeOrNominalTypeExtensionContext();
MetaBaseDecl = BaseDecl;
if (!isCascadingUse.hasValue())
isCascadingUse = ED->isCascadingContextForLookup(false);
} else if (NominalTypeDecl *ND = dyn_cast<NominalTypeDecl>(DC)) {
ExtendedType = ND->getDeclaredType();
BaseDecl = ND;
MetaBaseDecl = BaseDecl;
if (!isCascadingUse.hasValue())
isCascadingUse = ND->isCascadingContextForLookup(false);
} else if (auto I = dyn_cast<DefaultArgumentInitializer>(DC)) {
// In a default argument, skip immediately out of both the
// initializer and the function.
isCascadingUse = false;
DC = I->getParent()->getParent();
continue;
} else {
assert(isa<TopLevelCodeDecl>(DC) || isa<Initializer>(DC) ||
isa<TypeAliasDecl>(DC));
if (!isCascadingUse.hasValue())
isCascadingUse = DC->isCascadingContextForLookup(false);
}
// Check the generic parameters for something with the given name.
if (GenericParams) {
namelookup::FindLocalVal localVal(SM, Loc, Consumer);
localVal.checkGenericParams(GenericParams);
if (!Results.empty())
return;
}
if (BaseDecl) {
if (TypeResolver)
TypeResolver->resolveDeclSignature(BaseDecl);
NLOptions options = NL_UnqualifiedDefault;
if (isCascadingUse.getValue())
options |= NL_KnownCascadingDependency;
else
options |= NL_KnownNonCascadingDependency;
if (AllowProtocolMembers)
options |= NL_ProtocolMembers;
if (IsTypeLookup)
options |= NL_OnlyTypes;
if (IgnoreAccessControl)
options |= NL_IgnoreAccessibility;
if (ExtendedType->hasError())
continue;
SmallVector<ValueDecl *, 4> Lookup;
DC->lookupQualified(ExtendedType, Name, options, TypeResolver, Lookup);
bool FoundAny = false;
for (auto Result : Lookup) {
// In Swift 3 mode, unqualified lookup skips static methods when
// performing lookup from instance context.
//
// We don't want to carry this forward to Swift 4, since it makes
// for poor diagnostics.
//
// Also, it was quite a special case and not as general as it
// should be -- it didn't apply to properties or subscripts, and
// the opposite case where we're in static context and an instance
// member shadows the module member wasn't handled either.
if (Ctx.isSwiftVersion3() &&
!isTypeLookup &&
isa<FuncDecl>(Result) &&
cast<FuncDecl>(Result)->isStatic()) {
continue;
}
// Classify this declaration.
FoundAny = true;
// Types are local or metatype members.
if (auto TD = dyn_cast<TypeDecl>(Result)) {
if (isa<GenericTypeParamDecl>(TD))
Results.push_back(UnqualifiedLookupResult(Result));
else
Results.push_back(UnqualifiedLookupResult(MetaBaseDecl, Result));
continue;
}
Results.push_back(UnqualifiedLookupResult(BaseDecl, Result));
}
if (FoundAny) {
// Predicate that determines whether a lookup result should
// be unavailable except as a last-ditch effort.
auto unavailableLookupResult =
[&](const UnqualifiedLookupResult &result) {
auto &effectiveVersion = Ctx.LangOpts.EffectiveLanguageVersion;
return result.getValueDecl()->getAttrs()
.isUnavailableInSwiftVersion(effectiveVersion);
};
// If all of the results we found are unavailable, keep looking.
if (std::all_of(Results.begin(), Results.end(),
unavailableLookupResult)) {
UnavailableInnerResults.append(Results.begin(), Results.end());
Results.clear();
FoundAny = false;
} else {
if (DebugClient)
filterForDiscriminator(Results, DebugClient);
return;
}
}
// Check the generic parameters if our context is a generic type or
// extension thereof.
GenericParamList *dcGenericParams = nullptr;
if (auto nominal = dyn_cast<NominalTypeDecl>(DC))
dcGenericParams = nominal->getGenericParams();
else if (auto ext = dyn_cast<ExtensionDecl>(DC))
dcGenericParams = ext->getGenericParams();
else if (auto subscript = dyn_cast<SubscriptDecl>(DC))
dcGenericParams = subscript->getGenericParams();
while (dcGenericParams) {
namelookup::FindLocalVal localVal(SM, Loc, Consumer);
localVal.checkGenericParams(dcGenericParams);
if (!Results.empty())
return;
if (!isa<ExtensionDecl>(DC))
break;
dcGenericParams = dcGenericParams->getOuterParameters();
}
}
DC = DC->getParent();
}
if (!isCascadingUse.hasValue())
isCascadingUse = true;
}
if (auto SF = dyn_cast<SourceFile>(DC)) {
if (Loc.isValid()) {
// Look for local variables in top-level code; normally, the parser
// resolves these for us, but it can't do the right thing for
// local types.
namelookup::FindLocalVal localVal(SM, Loc, Consumer);
localVal.checkSourceFile(*SF);
if (!Results.empty())
return;
}
}
}
// TODO: Does the debugger client care about compound names?
if (Name.isSimpleName()
&& DebugClient && DebugClient->lookupOverrides(Name.getBaseName(), DC,
Loc, IsTypeLookup, Results))
return;
recordLookupOfTopLevelName(DC, Name, isCascadingUse.getValue());
// Add private imports to the extra search list.
SmallVector<ModuleDecl::ImportedModule, 8> extraImports;
if (auto FU = dyn_cast<FileUnit>(DC))
FU->getImportedModules(extraImports, ModuleDecl::ImportFilter::Private);
using namespace namelookup;
SmallVector<ValueDecl *, 8> CurModuleResults;
auto resolutionKind =
IsTypeLookup ? ResolutionKind::TypesOnly : ResolutionKind::Overloadable;
lookupInModule(&M, {}, Name, CurModuleResults, NLKind::UnqualifiedLookup,
resolutionKind, TypeResolver, DC, extraImports);
for (auto VD : CurModuleResults)
Results.push_back(UnqualifiedLookupResult(VD));
if (DebugClient)
filterForDiscriminator(Results, DebugClient);
// Now add any names the DebugClient knows about to the lookup.
if (Name.isSimpleName() && DebugClient)
DebugClient->lookupAdditions(Name.getBaseName(), DC, Loc, IsTypeLookup,
Results);
// If we've found something, we're done.
if (!Results.empty())
return;
// If we still haven't found anything, but we do have some
// declarations that are "unavailable in the current Swift", drop
// those in.
if (!UnavailableInnerResults.empty()) {
Results = std::move(UnavailableInnerResults);
return;
}
if (!Name.isSimpleName())
return;
// Look for a module with the given name.
if (Name.isSimpleName(M.getName())) {
Results.push_back(UnqualifiedLookupResult(&M));
return;
}
ModuleDecl *desiredModule = Ctx.getLoadedModule(Name.getBaseName());
if (!desiredModule && Name == Ctx.TheBuiltinModule->getName())
desiredModule = Ctx.TheBuiltinModule;
if (desiredModule) {
forAllVisibleModules(DC, [&](const ModuleDecl::ImportedModule &import) -> bool {
if (import.second == desiredModule) {
Results.push_back(UnqualifiedLookupResult(import.second));
return false;
}
return true;
});
}
}
TypeDecl* UnqualifiedLookup::getSingleTypeResult() {
if (Results.size() != 1)
return nullptr;
return dyn_cast<TypeDecl>(Results.back().getValueDecl());
}
#pragma mark Member lookup table
void LazyMemberLoader::anchor() {}
/// Lookup table used to store members of a nominal type (and its extensions)
/// for fast retrieval.
class swift::MemberLookupTable {
/// The last extension that was included within the member lookup table's
/// results.
ExtensionDecl *LastExtensionIncluded = nullptr;
/// The type of the internal lookup table.
typedef llvm::DenseMap<DeclName, llvm::TinyPtrVector<ValueDecl *>>
LookupTable;
/// Lookup table mapping names to the set of declarations with that name.
LookupTable Lookup;
public:
/// Create a new member lookup table.
explicit MemberLookupTable(ASTContext &ctx);
/// Update a lookup table with members from newly-added extensions.
void updateLookupTable(NominalTypeDecl *nominal);
/// \brief Add the given member to the lookup table.
void addMember(Decl *members);
/// \brief Add the given members to the lookup table.
void addMembers(DeclRange members);
/// \brief The given extension has been extended with new members; add them
/// if appropriate.
void addExtensionMembers(NominalTypeDecl *nominal,
ExtensionDecl *ext,
DeclRange members);
/// Iterator into the lookup table.
typedef LookupTable::iterator iterator;
iterator begin() { return Lookup.begin(); }
iterator end() { return Lookup.end(); }
iterator find(DeclName name) {
return Lookup.find(name);
}
// Only allow allocation of member lookup tables using the allocator in
// ASTContext or by doing a placement new.