forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLookupVisibleDecls.cpp
818 lines (703 loc) · 29.5 KB
/
LookupVisibleDecls.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
//===--- LookupVisibleDecls - Swift Name Lookup Routines ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the lookupVisibleDecls interface for visiting named
// declarations.
//
//===----------------------------------------------------------------------===//
#include "NameLookupImpl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/AST.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include <set>
using namespace swift;
void VisibleDeclConsumer::anchor() {}
void VectorDeclConsumer::anchor() {}
void NamedDeclConsumer::anchor() {}
namespace {
struct LookupState {
private:
/// If \c false, an unqualified lookup of all visible decls in a
/// DeclContext.
///
/// If \c true, lookup of all visible members of a given object (possibly of
/// metatype type).
unsigned IsQualified : 1;
/// Is this a qualified lookup on a metatype?
unsigned IsOnMetatype : 1;
/// Did we recurse into a superclass?
unsigned IsOnSuperclass : 1;
unsigned InheritsSuperclassInitializers : 1;
LookupState()
: IsQualified(0), IsOnMetatype(0), IsOnSuperclass(0),
InheritsSuperclassInitializers(0) {}
public:
LookupState(const LookupState &) = default;
static LookupState makeQualified() {
LookupState Result;
Result.IsQualified = 1;
return Result;
}
static LookupState makeUnqualified() {
LookupState Result;
Result.IsQualified = 0;
return Result;
}
bool isQualified() const { return IsQualified; }
bool isOnMetatype() const { return IsOnMetatype; }
bool isOnSuperclass() const { return IsOnSuperclass; }
bool isInheritsSuperclassInitializers() const {
return InheritsSuperclassInitializers;
}
LookupState withOnMetatype() const {
auto Result = *this;
Result.IsOnMetatype = 1;
return Result;
}
LookupState withOnSuperclass() const {
auto Result = *this;
Result.IsOnSuperclass = 1;
return Result;
}
LookupState withInheritsSuperclassInitializers() const {
auto Result = *this;
Result.InheritsSuperclassInitializers = 1;
return Result;
}
LookupState withoutInheritsSuperclassInitializers() const {
auto Result = *this;
Result.InheritsSuperclassInitializers = 0;
return Result;
}
};
} // unnamed namespace
static bool areTypeDeclsVisibleInLookupMode(LookupState LS) {
// Nested type declarations can be accessed only with unqualified lookup or
// on metatypes.
return !LS.isQualified() || LS.isOnMetatype();
}
static bool isDeclVisibleInLookupMode(ValueDecl *Member, LookupState LS,
const DeclContext *FromContext,
LazyResolver *TypeResolver) {
if (TypeResolver)
TypeResolver->resolveDeclSignature(Member);
// Check accessibility when relevant.
if (!Member->getDeclContext()->isLocalContext() &&
!isa<GenericTypeParamDecl>(Member) && !isa<ParamDecl>(Member) &&
FromContext->getASTContext().LangOpts.EnableAccessControl) {
if (Member->isInvalid() && !Member->hasAccessibility())
return false;
if (!Member->isAccessibleFrom(FromContext))
return false;
}
if (auto *FD = dyn_cast<FuncDecl>(Member)) {
// Cannot call static functions on non-metatypes.
if (!LS.isOnMetatype() && FD->isStatic())
return false;
// Otherwise, either call a function or curry it.
return true;
}
if (auto *VD = dyn_cast<VarDecl>(Member)) {
// Cannot use static properties on non-metatypes.
if (!(LS.isQualified() && LS.isOnMetatype()) && VD->isStatic())
return false;
// Cannot use instance properties on metatypes.
if (LS.isOnMetatype() && !VD->isStatic())
return false;
return true;
}
if (isa<EnumElementDecl>(Member)) {
// Cannot reference enum elements on non-metatypes.
if (!(LS.isQualified() && LS.isOnMetatype()))
return false;
}
if (auto CD = dyn_cast<ConstructorDecl>(Member)) {
// Constructors with stub implementations cannot be called in Swift.
if (CD->hasStubImplementation())
return false;
if (LS.isQualified() && LS.isOnSuperclass()) {
// Cannot call initializers from a superclass, except for inherited
// convenience initializers.
return LS.isInheritsSuperclassInitializers() && CD->isInheritable();
}
}
if (isa<TypeDecl>(Member))
return areTypeDeclsVisibleInLookupMode(LS);
return true;
}
/// Lookup members in extensions of \p LookupType, using \p BaseType as the
/// underlying type when checking any constraints on the extensions.
static void doGlobalExtensionLookup(Type BaseType,
Type LookupType,
SmallVectorImpl<ValueDecl *> &FoundDecls,
const DeclContext *CurrDC,
LookupState LS,
DeclVisibilityKind Reason,
LazyResolver *TypeResolver) {
auto nominal = LookupType->getAnyNominal();
// Look in each extension of this type.
for (auto extension : nominal->getExtensions()) {
bool validatedExtension = false;
if (TypeResolver && extension->isProtocolExtensionContext()) {
if (!TypeResolver->isProtocolExtensionUsable(
const_cast<DeclContext *>(CurrDC), BaseType, extension)) {
continue;
}
validatedExtension = true;
}
for (auto Member : extension->getMembers()) {
if (auto VD = dyn_cast<ValueDecl>(Member))
if (isDeclVisibleInLookupMode(VD, LS, CurrDC, TypeResolver)) {
// Resolve the extension, if we haven't done so already.
if (!validatedExtension && TypeResolver) {
TypeResolver->resolveExtension(extension);
validatedExtension = true;
}
FoundDecls.push_back(VD);
}
}
}
// Handle shadowing.
removeShadowedDecls(FoundDecls, CurrDC->getParentModule(), TypeResolver);
}
/// \brief Enumerate immediate members of the type \c LookupType and its
/// extensions, as seen from the context \c CurrDC.
///
/// Don't do lookup into superclasses or implemented protocols. Uses
/// \p BaseType as the underlying type when checking any constraints on the
/// extensions.
static void lookupTypeMembers(Type BaseType, Type LookupType,
VisibleDeclConsumer &Consumer,
const DeclContext *CurrDC, LookupState LS,
DeclVisibilityKind Reason,
LazyResolver *TypeResolver) {
NominalTypeDecl *D = LookupType->getAnyNominal();
assert(D && "should have a nominal type");
bool LookupFromChildDeclContext = false;
const DeclContext *TempDC = CurrDC;
while (!TempDC->isModuleContext()) {
if (TempDC == D) {
LookupFromChildDeclContext = true;
break;
}
TempDC = TempDC->getParent();
}
SmallVector<ValueDecl*, 2> FoundDecls;
if (LookupFromChildDeclContext) {
// Current decl context is contained inside 'D', so generic parameters
// are visible.
if (D->getGenericParams())
for (auto Param : *D->getGenericParams())
if (isDeclVisibleInLookupMode(Param, LS, CurrDC, TypeResolver))
FoundDecls.push_back(Param);
}
for (Decl *Member : D->getMembers()) {
if (auto *VD = dyn_cast<ValueDecl>(Member))
if (isDeclVisibleInLookupMode(VD, LS, CurrDC, TypeResolver))
FoundDecls.push_back(VD);
}
doGlobalExtensionLookup(BaseType, LookupType, FoundDecls, CurrDC, LS, Reason,
TypeResolver);
// Report the declarations we found to the consumer.
for (auto *VD : FoundDecls)
Consumer.foundDecl(VD, Reason);
}
/// Enumerate AnyObject declarations as seen from context \c CurrDC.
static void doDynamicLookup(VisibleDeclConsumer &Consumer,
const DeclContext *CurrDC,
LookupState LS,
LazyResolver *TypeResolver) {
class DynamicLookupConsumer : public VisibleDeclConsumer {
VisibleDeclConsumer &ChainedConsumer;
LookupState LS;
const DeclContext *CurrDC;
LazyResolver *TypeResolver;
llvm::DenseSet<std::pair<Identifier, CanType>> FunctionsReported;
llvm::DenseSet<CanType> SubscriptsReported;
llvm::DenseSet<std::pair<Identifier, CanType>> PropertiesReported;
public:
explicit DynamicLookupConsumer(VisibleDeclConsumer &ChainedConsumer,
LookupState LS, const DeclContext *CurrDC,
LazyResolver *TypeResolver)
: ChainedConsumer(ChainedConsumer), LS(LS), CurrDC(CurrDC),
TypeResolver(TypeResolver) {}
void foundDecl(ValueDecl *D, DeclVisibilityKind Reason) override {
// If the declaration has an override, name lookup will also have found
// the overridden method. Skip this declaration, because we prefer the
// overridden method.
if (D->getOverriddenDecl())
return;
// Initializers cannot be found by dynamic lookup.
if (isa<ConstructorDecl>(D))
return;
// Check if we already reported a decl with the same signature.
if (auto *FD = dyn_cast<FuncDecl>(D)) {
assert(FD->getImplicitSelfDecl() && "should not find free functions");
(void)FD;
// Get the type without the first uncurry level with 'self'.
CanType T = D->getType()
->castTo<AnyFunctionType>()
->getResult()
->getCanonicalType();
auto Signature = std::make_pair(D->getName(), T);
if (!FunctionsReported.insert(Signature).second)
return;
} else if (isa<SubscriptDecl>(D)) {
auto Signature = D->getType()->getCanonicalType();
if (!SubscriptsReported.insert(Signature).second)
return;
} else if (isa<VarDecl>(D)) {
auto Signature =
std::make_pair(D->getName(), D->getType()->getCanonicalType());
if (!PropertiesReported.insert(Signature).second)
return;
} else {
llvm_unreachable("unhandled decl kind");
}
if (isDeclVisibleInLookupMode(D, LS, CurrDC, TypeResolver))
ChainedConsumer.foundDecl(D, DeclVisibilityKind::DynamicLookup);
}
};
DynamicLookupConsumer ConsumerWrapper(Consumer, LS, CurrDC, TypeResolver);
CurrDC->getParentSourceFile()->forAllVisibleModules(
[&](Module::ImportedModule Import) {
Import.second->lookupClassMembers(Import.first, ConsumerWrapper);
});
}
namespace {
typedef llvm::SmallPtrSet<TypeDecl *, 8> VisitedSet;
}
static DeclVisibilityKind getReasonForSuper(DeclVisibilityKind Reason) {
switch (Reason) {
case DeclVisibilityKind::MemberOfCurrentNominal:
case DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal:
case DeclVisibilityKind::MemberOfSuper:
return DeclVisibilityKind::MemberOfSuper;
case DeclVisibilityKind::MemberOfOutsideNominal:
return DeclVisibilityKind::MemberOfOutsideNominal;
default:
llvm_unreachable("should not see this kind");
}
}
static void lookupDeclsFromProtocolsBeingConformedTo(
Type BaseTy, VisibleDeclConsumer &Consumer, LookupState LS,
const DeclContext *FromContext, DeclVisibilityKind Reason,
LazyResolver *TypeResolver, VisitedSet &Visited) {
NominalTypeDecl *CurrNominal = BaseTy->getAnyNominal();
if (!CurrNominal)
return;
for (auto Conformance : CurrNominal->getAllConformances()) {
auto Proto = Conformance->getProtocol();
if (!Proto->isAccessibleFrom(FromContext))
continue;
DeclVisibilityKind ReasonForThisProtocol;
if (Reason == DeclVisibilityKind::MemberOfCurrentNominal)
ReasonForThisProtocol =
DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal;
else
ReasonForThisProtocol = getReasonForSuper(Reason);
auto NormalConformance = Conformance->getRootNormalConformance();
for (auto Member : Proto->getMembers()) {
if (auto *ATD = dyn_cast<AssociatedTypeDecl>(Member)) {
// Skip type decls if they aren't visible, or any type that has a
// witness. This cuts down on duplicates.
if (areTypeDeclsVisibleInLookupMode(LS) &&
(!NormalConformance->hasTypeWitness(ATD) ||
NormalConformance->usesDefaultDefinition(ATD))) {
Consumer.foundDecl(ATD, ReasonForThisProtocol);
}
continue;
}
if (auto *VD = dyn_cast<ValueDecl>(Member)) {
if (TypeResolver)
TypeResolver->resolveDeclSignature(VD);
// Skip value requirements that have corresponding witnesses. This cuts
// down on duplicates.
if (!NormalConformance->hasWitness(VD) ||
NormalConformance->usesDefaultDefinition(VD) ||
NormalConformance->getWitness(VD, nullptr) == nullptr) {
Consumer.foundDecl(VD, ReasonForThisProtocol);
}
}
}
// Add members from any extensions.
SmallVector<ValueDecl *, 2> FoundDecls;
doGlobalExtensionLookup(BaseTy, Proto->getDeclaredType(), FoundDecls,
FromContext, LS, ReasonForThisProtocol,
TypeResolver);
for (auto *VD : FoundDecls)
Consumer.foundDecl(VD, ReasonForThisProtocol);
}
}
static void
lookupVisibleMemberDeclsImpl(Type BaseTy, VisibleDeclConsumer &Consumer,
const DeclContext *CurrDC, LookupState LS,
DeclVisibilityKind Reason,
LazyResolver *TypeResolver, VisitedSet &Visited);
static void lookupVisibleProtocolMemberDecls(
Type BaseTy, ProtocolType *PT, VisibleDeclConsumer &Consumer,
const DeclContext *CurrDC, LookupState LS, DeclVisibilityKind Reason,
LazyResolver *TypeResolver, VisitedSet &Visited) {
if (PT->getDecl()->isSpecificProtocol(KnownProtocolKind::AnyObject)) {
// Handle AnyObject in a special way.
doDynamicLookup(Consumer, CurrDC, LS, TypeResolver);
return;
}
if (!Visited.insert(PT->getDecl()).second)
return;
for (auto Proto : PT->getDecl()->getInheritedProtocols(nullptr))
lookupVisibleProtocolMemberDecls(BaseTy, Proto->getDeclaredType(), Consumer, CurrDC,
LS, getReasonForSuper(Reason), TypeResolver,
Visited);
lookupTypeMembers(BaseTy, PT, Consumer, CurrDC, LS, Reason, TypeResolver);
}
static void lookupVisibleMemberDeclsImpl(
Type BaseTy, VisibleDeclConsumer &Consumer, const DeclContext *CurrDC,
LookupState LS, DeclVisibilityKind Reason, LazyResolver *TypeResolver,
VisitedSet &Visited) {
// Just look through l-valueness. It doesn't affect name lookup.
assert(BaseTy && "lookup into null type");
BaseTy = BaseTy->getRValueType();
// Handle metatype references, as in "some_type.some_member". These are
// special and can't have extensions.
if (auto MTT = BaseTy->getAs<AnyMetatypeType>()) {
// The metatype represents an arbitrary named type: dig through to the
// declared type to see what we're dealing with.
Type Ty = MTT->getInstanceType();
// Just perform normal dot lookup on the type see if we find extensions or
// anything else. For example, type SomeTy.SomeMember can look up static
// functions, and can even look up non-static functions as well (thus
// getting the address of the member).
lookupVisibleMemberDeclsImpl(Ty, Consumer, CurrDC,
LookupState::makeQualified().withOnMetatype(),
Reason, TypeResolver, Visited);
return;
}
// Lookup module references, as on some_module.some_member. These are
// special and can't have extensions.
if (ModuleType *MT = BaseTy->getAs<ModuleType>()) {
AccessFilteringDeclConsumer FilteringConsumer(CurrDC, Consumer,
TypeResolver);
MT->getModule()->lookupVisibleDecls(Module::AccessPathTy(),
FilteringConsumer,
NLKind::QualifiedLookup);
return;
}
// If the base is a protocol, enumerate its members.
if (ProtocolType *PT = BaseTy->getAs<ProtocolType>()) {
lookupVisibleProtocolMemberDecls(BaseTy, PT, Consumer, CurrDC, LS, Reason,
TypeResolver, Visited);
return;
}
// If the base is a protocol composition, enumerate members of the protocols.
if (auto PC = BaseTy->getAs<ProtocolCompositionType>()) {
for (auto Proto : PC->getProtocols())
lookupVisibleMemberDeclsImpl(Proto, Consumer, CurrDC, LS, Reason,
TypeResolver, Visited);
return;
}
// Enumerate members of archetype's requirements.
if (ArchetypeType *Archetype = BaseTy->getAs<ArchetypeType>()) {
for (auto Proto : Archetype->getConformsTo())
lookupVisibleProtocolMemberDecls(
BaseTy, Proto->getDeclaredType(), Consumer, CurrDC, LS,
getReasonForSuper(Reason), TypeResolver, Visited);
if (auto superclass = Archetype->getSuperclass())
lookupVisibleMemberDeclsImpl(superclass, Consumer, CurrDC, LS,
getReasonForSuper(Reason), TypeResolver,
Visited);
return;
}
do {
NominalTypeDecl *CurNominal = BaseTy->getAnyNominal();
if (!CurNominal)
break;
// Look in for members of a nominal type.
lookupTypeMembers(BaseTy, BaseTy, Consumer, CurrDC, LS, Reason,
TypeResolver);
lookupDeclsFromProtocolsBeingConformedTo(BaseTy, Consumer, LS, CurrDC,
Reason, TypeResolver, Visited);
// If we have a class type, look into its superclass.
ClassDecl *CurClass = dyn_cast<ClassDecl>(CurNominal);
if (CurClass && CurClass->hasSuperclass()) {
BaseTy = CurClass->getSuperclass();
Reason = getReasonForSuper(Reason);
bool InheritsSuperclassInitializers =
CurClass->inheritsSuperclassInitializers(TypeResolver);
if (LS.isOnSuperclass() && !InheritsSuperclassInitializers)
LS = LS.withoutInheritsSuperclassInitializers();
else if (!LS.isOnSuperclass()) {
LS = LS.withOnSuperclass();
if (InheritsSuperclassInitializers)
LS = LS.withInheritsSuperclassInitializers();
}
} else {
break;
}
} while (1);
}
namespace {
struct FoundDeclTy {
ValueDecl *D;
DeclVisibilityKind Reason;
FoundDeclTy(ValueDecl *D, DeclVisibilityKind Reason)
: D(D), Reason(Reason) {}
friend bool operator==(const FoundDeclTy &LHS, const FoundDeclTy &RHS) {
return LHS.D == RHS.D;
}
friend bool operator<(const FoundDeclTy &LHS, const FoundDeclTy &RHS) {
return LHS.D < RHS.D;
}
};
/// Similar to swift::conflicting, but lenient about protocol extensions which
/// don't affect code completion's concept of overloading.
static bool relaxedConflicting(const OverloadSignature &sig1,
const OverloadSignature &sig2) {
// If the base names are different, they can't conflict.
if (sig1.Name.getBaseName() != sig2.Name.getBaseName())
return false;
// If one is a compound name and the other is not, they do not conflict
// if one is a property and the other is a non-nullary function.
if (sig1.Name.isCompoundName() != sig2.Name.isCompoundName()) {
return !((sig1.IsProperty && sig2.Name.getArgumentNames().size() > 0) ||
(sig2.IsProperty && sig1.Name.getArgumentNames().size() > 0));
}
// Allow null property types to match non-null ones, which only happens when
// one property is from a generic extension and the other is not.
if (sig1.InterfaceType != sig2.InterfaceType) {
if (!sig1.IsProperty || !sig2.IsProperty)
return false;
if (sig1.InterfaceType && sig2.InterfaceType)
return false;
}
return sig1.Name == sig2.Name && sig1.UnaryOperator == sig2.UnaryOperator &&
sig1.IsInstanceMember == sig2.IsInstanceMember;
}
class OverrideFilteringConsumer : public VisibleDeclConsumer {
public:
std::set<ValueDecl *> AllFoundDecls;
std::map<Identifier, std::set<ValueDecl *>> FoundDecls;
llvm::SetVector<FoundDeclTy> DeclsToReport;
Type BaseTy;
const DeclContext *DC;
OverrideFilteringConsumer(Type BaseTy, const DeclContext *DC)
: BaseTy(BaseTy->getRValueType()), DC(DC) {
assert(DC && BaseTy);
}
void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason) override {
if (!AllFoundDecls.insert(VD).second)
return;
if (VD->isInvalid()) {
FoundDecls[VD->getName()].insert(VD);
DeclsToReport.insert(FoundDeclTy(VD, Reason));
return;
}
auto &PossiblyConflicting = FoundDecls[VD->getName()];
// Check all overridden decls.
{
auto *CurrentVD = VD->getOverriddenDecl();
while (CurrentVD) {
if (!AllFoundDecls.insert(CurrentVD).second)
break;
if (PossiblyConflicting.count(CurrentVD)) {
PossiblyConflicting.erase(CurrentVD);
PossiblyConflicting.insert(VD);
bool Erased = DeclsToReport.remove(
FoundDeclTy(CurrentVD, DeclVisibilityKind::LocalVariable));
assert(Erased);
(void)Erased;
DeclsToReport.insert(FoundDeclTy(VD, Reason));
return;
}
CurrentVD = CurrentVD->getOverriddenDecl();
}
}
// Does it make sense to substitute types?
bool shouldSubst = !isa<UnboundGenericType>(BaseTy.getPointer()) &&
!isa<AnyMetatypeType>(BaseTy.getPointer()) &&
!BaseTy->isAnyExistentialType();
ModuleDecl *M = DC->getParentModule();
auto FoundSignature = VD->getOverloadSignature();
if (FoundSignature.InterfaceType && shouldSubst) {
auto subs = BaseTy->getMemberSubstitutions(VD->getDeclContext());
if (auto CT = FoundSignature.InterfaceType.subst(M, subs, None))
FoundSignature.InterfaceType = CT->getCanonicalType();
}
for (auto I = PossiblyConflicting.begin(), E = PossiblyConflicting.end();
I != E; ++I) {
auto *OtherVD = *I;
if (OtherVD->isInvalid()) {
// For some invalid decls it might be impossible to compute the
// signature, for example, if the types could not be resolved.
continue;
}
auto OtherSignature = OtherVD->getOverloadSignature();
if (OtherSignature.InterfaceType && shouldSubst) {
auto subs = BaseTy->getMemberSubstitutions(OtherVD->getDeclContext());
if (auto CT = OtherSignature.InterfaceType.subst(M, subs, None))
OtherSignature.InterfaceType = CT->getCanonicalType();
}
if (relaxedConflicting(FoundSignature, OtherSignature)) {
if (VD->getFormalAccess() > OtherVD->getFormalAccess()) {
PossiblyConflicting.erase(I);
PossiblyConflicting.insert(VD);
bool Erased = DeclsToReport.remove(
FoundDeclTy(OtherVD, DeclVisibilityKind::LocalVariable));
assert(Erased);
(void)Erased;
DeclsToReport.insert(FoundDeclTy(VD, Reason));
}
return;
}
}
PossiblyConflicting.insert(VD);
DeclsToReport.insert(FoundDeclTy(VD, Reason));
}
};
} // unnamed namespace
/// \brief Enumerate all members in \c BaseTy (including members of extensions,
/// superclasses and implemented protocols), as seen from the context \c CurrDC.
///
/// This operation corresponds to a standard "dot" lookup operation like "a.b"
/// where 'self' is the type of 'a'. This operation is only valid after name
/// binding.
static void lookupVisibleMemberDecls(
Type BaseTy, VisibleDeclConsumer &Consumer, const DeclContext *CurrDC,
LookupState LS, DeclVisibilityKind Reason, LazyResolver *TypeResolver) {
OverrideFilteringConsumer ConsumerWrapper(BaseTy, CurrDC);
VisitedSet Visited;
lookupVisibleMemberDeclsImpl(BaseTy, ConsumerWrapper, CurrDC, LS, Reason,
TypeResolver, Visited);
// Report the declarations we found to the real consumer.
for (const auto &DeclAndReason : ConsumerWrapper.DeclsToReport)
Consumer.foundDecl(DeclAndReason.D, DeclAndReason.Reason);
}
void swift::lookupVisibleDecls(VisibleDeclConsumer &Consumer,
const DeclContext *DC,
LazyResolver *TypeResolver,
bool IncludeTopLevel,
SourceLoc Loc) {
const Module &M = *DC->getParentModule();
const SourceManager &SM = DC->getASTContext().SourceMgr;
auto Reason = DeclVisibilityKind::MemberOfCurrentNominal;
// 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.
while (!DC->isModuleScopeContext()) {
const ValueDecl *BaseDecl = nullptr;
GenericParamList *GenericParams = nullptr;
Type ExtendedType;
auto LS = LookupState::makeUnqualified();
// Skip initializer contexts, we will not find any declarations there.
if (isa<Initializer>(DC)) {
DC = DC->getParent();
LS = LS.withOnMetatype();
}
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()) {
namelookup::FindLocalVal(SM, Loc, Consumer).visit(AFD->getBody());
}
for (auto *P : AFD->getBodyParamPatterns())
namelookup::FindLocalVal(SM, Loc, Consumer)
.checkPattern(P, DeclVisibilityKind::FunctionParameter);
// Constructors and destructors don't have 'self' in parameter patterns.
if (isa<ConstructorDecl>(AFD) || isa<DestructorDecl>(AFD))
Consumer.foundDecl(AFD->getImplicitSelfDecl(),
DeclVisibilityKind::FunctionParameter);
if (AFD->getExtensionType()) {
ExtendedType = AFD->getExtensionType();
BaseDecl = AFD->getImplicitSelfDecl();
DC = DC->getParent();
if (DC->isProtocolExtensionContext())
ExtendedType = DC->getProtocolSelf()->getArchetype();
if (auto *FD = dyn_cast<FuncDecl>(AFD))
if (FD->isStatic())
ExtendedType = MetatypeType::get(ExtendedType);
}
// Look in the generic parameters after checking our local declaration.
GenericParams = AFD->getGenericParams();
} else if (auto ACE = dyn_cast<AbstractClosureExpr>(DC)) {
if (Loc.isValid()) {
auto CE = cast<ClosureExpr>(ACE);
namelookup::FindLocalVal(SM, Loc, Consumer).visit(CE->getBody());
if (auto P = CE->getParams()) {
namelookup::FindLocalVal(SM, Loc, Consumer)
.checkPattern(P, DeclVisibilityKind::FunctionParameter);
}
}
} else if (auto ED = dyn_cast<ExtensionDecl>(DC)) {
ExtendedType = ED->getExtendedType();
if (ExtendedType)
BaseDecl = ExtendedType->getNominalOrBoundGenericNominal();
} else if (auto ND = dyn_cast<NominalTypeDecl>(DC)) {
ExtendedType = ND->getDeclaredType();
BaseDecl = ND;
}
if (BaseDecl && ExtendedType) {
::lookupVisibleMemberDecls(ExtendedType, Consumer, DC, LS, Reason,
TypeResolver);
}
// Check the generic parameters for something with the given name.
if (GenericParams) {
namelookup::FindLocalVal(SM, Loc, Consumer)
.checkGenericParams(GenericParams,
DeclVisibilityKind::GenericParameter);
}
DC = DC->getParent();
Reason = DeclVisibilityKind::MemberOfOutsideNominal;
}
SmallVector<Module::ImportedModule, 8> extraImports;
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(SM, Loc, Consumer).checkSourceFile(*SF);
}
if (IncludeTopLevel) {
auto &cached = SF->getCachedVisibleDecls();
if (!cached.empty()) {
for (auto result : cached)
Consumer.foundDecl(result, DeclVisibilityKind::VisibleAtTopLevel);
return;
}
SF->getImportedModules(extraImports, Module::ImportFilter::Private);
}
}
if (IncludeTopLevel) {
using namespace namelookup;
SmallVector<ValueDecl *, 0> moduleResults;
auto &mutableM = const_cast<Module&>(M);
lookupVisibleDeclsInModule(&mutableM, {}, moduleResults,
NLKind::UnqualifiedLookup,
ResolutionKind::Overloadable,
TypeResolver, DC, extraImports);
for (auto result : moduleResults)
Consumer.foundDecl(result, DeclVisibilityKind::VisibleAtTopLevel);
if (auto SF = dyn_cast<SourceFile>(DC))
SF->cacheVisibleDecls(std::move(moduleResults));
}
}
void swift::lookupVisibleMemberDecls(VisibleDeclConsumer &Consumer, Type BaseTy,
const DeclContext *CurrDC,
LazyResolver *TypeResolver) {
assert(CurrDC);
::lookupVisibleMemberDecls(BaseTy, Consumer, CurrDC,
LookupState::makeQualified(),
DeclVisibilityKind::MemberOfCurrentNominal,
TypeResolver);
}