-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathLookupVisibleDecls.cpp
1336 lines (1137 loc) · 46.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
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
//===--- LookupVisibleDecls - 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 the lookupVisibleDecls interface for visiting named
// declarations.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "clang/AST/DeclObjC.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/ModuleNameLookup.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/STLExtras.h"
#include "swift/ClangImporter/ClangImporterRequests.h"
#include "swift/Sema/IDETypeCheckingRequests.h"
#include "swift/Sema/IDETypeChecking.h"
#include "clang/Basic/Module.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/SetVector.h"
#include <set>
using namespace swift;
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;
/// Should instance members be included even if lookup is performed on a type?
unsigned IncludeInstanceMembers : 1;
/// Should derived protocol requirements be included?
/// This option is only for override completion lookup.
unsigned IncludeDerivedRequirements : 1;
/// Should protocol extension members be included?
unsigned IncludeProtocolExtensionMembers : 1;
LookupState()
: IsQualified(0), IsOnMetatype(0), IsOnSuperclass(0),
InheritsSuperclassInitializers(0), IncludeInstanceMembers(0),
IncludeDerivedRequirements(0), IncludeProtocolExtensionMembers(0) {}
public:
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;
}
bool isIncludingInstanceMembers() const { return IncludeInstanceMembers; }
bool isIncludingDerivedRequirements() const {
return IncludeDerivedRequirements;
}
bool isIncludingProtocolExtensionMembers() const {
return IncludeProtocolExtensionMembers;
}
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;
}
LookupState withIncludedInstanceMembers() const {
auto Result = *this;
Result.IncludeInstanceMembers = 1;
return Result;
}
LookupState withIncludedDerivedRequirements() const {
auto Result = *this;
Result.IncludeDerivedRequirements = 1;
return Result;
}
LookupState withIncludeProtocolExtensionMembers() const {
auto Result = *this;
Result.IncludeProtocolExtensionMembers = 1;
return Result;
}
};
} // end anonymous 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) {
// Accessors are never visible directly in the source language.
if (isa<AccessorDecl>(Member))
return false;
// Check access when relevant.
if (!Member->getDeclContext()->isLocalContext() &&
!isa<GenericTypeParamDecl>(Member) && !isa<ParamDecl>(Member)) {
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 *SD = dyn_cast<SubscriptDecl>(Member)) {
// Cannot use static subscripts on non-metatypes.
if (!LS.isOnMetatype() && SD->isStatic())
return false;
// Cannot use instance subscript on metatypes.
if (LS.isOnMetatype() && !SD->isStatic() && !LS.isIncludingInstanceMembers())
return false;
return true;
}
if (auto *VD = dyn_cast<VarDecl>(Member)) {
// Cannot use static properties on non-metatypes.
if (!LS.isOnMetatype() && VD->isStatic())
return false;
// Cannot use instance properties on metatypes.
if (LS.isOnMetatype() && !VD->isStatic() && !LS.isIncludingInstanceMembers())
return false;
return true;
}
if (isa<EnumElementDecl>(Member)) {
// Cannot reference enum elements on non-metatypes.
if (!LS.isOnMetatype())
return false;
}
if (auto CD = dyn_cast<ConstructorDecl>(Member)) {
if (!LS.isQualified())
return false;
// Constructors with stub implementations cannot be called in Swift.
if (CD->hasStubImplementation())
return false;
if (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;
}
/// Collect visible members from \p Parent into \p FoundDecls .
static void collectVisibleMemberDecls(const DeclContext *CurrDC, LookupState LS,
Type BaseType,
IterableDeclContext *Parent,
SmallVectorImpl<ValueDecl *> &FoundDecls) {
for (auto Member : Parent->getAllMembers()) {
auto *VD = dyn_cast<ValueDecl>(Member);
if (!VD)
continue;
if (!isDeclVisibleInLookupMode(VD, LS, CurrDC))
continue;
if (!evaluateOrDefault(CurrDC->getASTContext().evaluator,
IsDeclApplicableRequest(DeclApplicabilityOwner(CurrDC, BaseType, VD)),
false))
continue;
FoundDecls.push_back(VD);
}
}
/// 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,
NominalTypeDecl *LookupType,
SmallVectorImpl<ValueDecl *> &FoundDecls,
const DeclContext *CurrDC,
LookupState LS,
DeclVisibilityKind Reason) {
// Look in each extension of this type.
for (auto extension : LookupType->getExtensions()) {
if (!evaluateOrDefault(CurrDC->getASTContext().evaluator,
IsDeclApplicableRequest(DeclApplicabilityOwner(CurrDC, BaseType,
extension)), false))
continue;
collectVisibleMemberDecls(CurrDC, LS, BaseType, extension, FoundDecls);
}
// Handle shadowing.
removeShadowedDecls(FoundDecls, CurrDC);
}
/// 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, NominalTypeDecl *LookupType,
VisibleDeclConsumer &Consumer,
const DeclContext *CurrDC, LookupState LS,
DeclVisibilityKind Reason) {
assert(!BaseType->hasTypeParameter());
assert(LookupType && "should have a nominal type");
// Skip lookup on invertible protocols. They have no members.
if (auto *proto = dyn_cast<ProtocolDecl>(LookupType))
if (proto->getInvertibleProtocolKind())
return;
Consumer.onLookupNominalTypeMembers(LookupType, Reason);
SmallVector<ValueDecl*, 2> FoundDecls;
collectVisibleMemberDecls(CurrDC, LS, BaseType, LookupType, FoundDecls);
doGlobalExtensionLookup(BaseType, LookupType, FoundDecls, CurrDC, LS, Reason);
// 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) {
class DynamicLookupConsumer : public VisibleDeclConsumer {
VisibleDeclConsumer &ChainedConsumer;
LookupState LS;
const DeclContext *CurrDC;
llvm::DenseSet<std::pair<DeclBaseName, CanType>> FunctionsReported;
llvm::DenseSet<CanType> SubscriptsReported;
llvm::DenseSet<std::pair<Identifier, CanType>> PropertiesReported;
public:
explicit DynamicLookupConsumer(VisibleDeclConsumer &ChainedConsumer,
LookupState LS, const DeclContext *CurrDC)
: ChainedConsumer(ChainedConsumer), LS(LS), CurrDC(CurrDC) {}
void foundDecl(ValueDecl *D, DeclVisibilityKind Reason,
DynamicLookupInfo) 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;
// If the declaration is not @objc, it cannot be called dynamically.
if (!D->isObjC())
return;
// If the declaration is objc_direct, it cannot be called dynamically.
if (auto clangDecl = D->getClangDecl()) {
if (auto objCMethod = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) {
if (objCMethod->isDirectMethod())
return;
} else if (auto objCProperty = dyn_cast<clang::ObjCPropertyDecl>(clangDecl)) {
if (objCProperty->isDirectProperty())
return;
}
}
if (D->isRecursiveValidation())
return;
switch (D->getKind()) {
#define DECL(ID, SUPER) \
case DeclKind::ID:
#define VALUE_DECL(ID, SUPER)
#include "swift/AST/DeclNodes.def"
llvm_unreachable("not a ValueDecl!");
// Types cannot be found by dynamic lookup.
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::TypeAlias:
case DeclKind::Enum:
case DeclKind::Class:
case DeclKind::Struct:
case DeclKind::Protocol:
case DeclKind::OpaqueType:
case DeclKind::BuiltinTuple:
return;
// Macros cannot be found by dynamic lookup.
case DeclKind::Macro:
return;
// Initializers cannot be found by dynamic lookup.
case DeclKind::Constructor:
case DeclKind::Destructor:
return;
// These cases are probably impossible here but can also just
// be safely ignored.
case DeclKind::Param:
case DeclKind::Module:
case DeclKind::EnumElement:
return;
// For other kinds of values, check if we already reported a decl
// with the same signature.
case DeclKind::Accessor:
case DeclKind::Func: {
auto FD = cast<FuncDecl>(D);
assert(FD->hasImplicitSelfDecl() && "should not find free functions");
(void)FD;
if (FD->isInvalid())
break;
// Get the type without the first uncurry level with 'self'.
CanType T = FD->getMethodInterfaceType()->getCanonicalType();
auto Signature = std::make_pair(D->getBaseName(), T);
if (!FunctionsReported.insert(Signature).second)
return;
break;
}
case DeclKind::Subscript: {
auto Signature = D->getInterfaceType()->getCanonicalType();
if (!SubscriptsReported.insert(Signature).second)
return;
break;
}
case DeclKind::Var: {
auto *VD = cast<VarDecl>(D);
auto Signature =
std::make_pair(VD->getName(),
VD->getInterfaceType()->getCanonicalType());
if (!PropertiesReported.insert(Signature).second)
return;
break;
}
}
if (isDeclVisibleInLookupMode(D, LS, CurrDC))
ChainedConsumer.foundDecl(D, DeclVisibilityKind::DynamicLookup,
DynamicLookupInfo::AnyObject);
}
};
DynamicLookupConsumer ConsumerWrapper(Consumer, LS, CurrDC);
for (auto Import : namelookup::getAllImports(CurrDC)) {
Import.importedModule->lookupClassMembers(Import.accessPath,
ConsumerWrapper);
}
}
namespace {
typedef llvm::SmallPtrSet<const TypeDecl *, 8> VisitedSet;
} // end anonymous namespace
static DeclVisibilityKind getReasonForSuper(DeclVisibilityKind Reason) {
switch (Reason) {
case DeclVisibilityKind::MemberOfCurrentNominal:
case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal:
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,
VisitedSet &Visited) {
NominalTypeDecl *CurrNominal = BaseTy->getAnyNominal();
if (!CurrNominal)
return;
for (auto Conformance : CurrNominal->getAllConformances()) {
auto Proto = Conformance->getProtocol();
// Skip conformances to invertible protocols. They have no members.
if (Proto->getInvertibleProtocolKind())
continue;
if (!Proto->isAccessibleFrom(FromContext))
continue;
// Skip unsatisfied conditional conformances.
// We can't check them if this type has an UnboundGenericType or if they
// couldn't be computed, so assume they conform in such cases.
if (!BaseTy->hasUnboundGenericType()) {
if (auto res = Conformance->getConditionalRequirementsIfAvailable()) {
if (!res->empty() && !checkConformance(BaseTy, Proto))
continue;
}
}
DeclVisibilityKind ReasonForThisProtocol;
if (Conformance->getKind() == ProtocolConformanceKind::Inherited)
ReasonForThisProtocol = getReasonForSuper(Reason);
else if (Reason == DeclVisibilityKind::MemberOfCurrentNominal)
ReasonForThisProtocol =
DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal;
else
ReasonForThisProtocol = getReasonForSuper(Reason);
if (auto NormalConformance = dyn_cast<NormalProtocolConformance>(
Conformance->getRootConformance())) {
Consumer.onLookupNominalTypeMembers(Proto, ReasonForThisProtocol);
for (auto Member : Proto->getMembers()) {
// Skip associated types and value requirements that aren't visible
// or have a corresponding witness.
if (auto *ATD = dyn_cast<AssociatedTypeDecl>(Member)) {
if (areTypeDeclsVisibleInLookupMode(LS) &&
!Conformance->hasTypeWitness(ATD)) {
Consumer.foundDecl(ATD, ReasonForThisProtocol);
}
} else if (auto *VD = dyn_cast<ValueDecl>(Member)) {
if (!isDeclVisibleInLookupMode(VD, LS, FromContext))
continue;
if (isa<TypeAliasDecl>(VD)) {
// Typealias declarations of the protocol are always visible in
// types that inherits from it.
Consumer.foundDecl(VD, ReasonForThisProtocol);
continue;
}
if (!VD->isProtocolRequirement())
continue;
// Whether the given witness corresponds to a derived requirement.
const auto isDerivedRequirement = [Proto](const ValueDecl *Witness) {
return Witness->isImplicit() &&
Proto->getKnownDerivableProtocolKind();
};
DeclVisibilityKind ReasonForThisDecl = ReasonForThisProtocol;
if (const auto Witness = NormalConformance->getWitness(VD)) {
auto *WD = Witness.getDecl();
if (WD->getName() == VD->getName()) {
if (LS.isIncludingDerivedRequirements() &&
Reason == DeclVisibilityKind::MemberOfCurrentNominal &&
isDerivedRequirement(WD)) {
ReasonForThisDecl =
DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal;
} else if (!LS.isIncludingProtocolExtensionMembers() &&
WD->getDeclContext()->getExtendedProtocolDecl()) {
// Don't skip this requirement.
// Witnesses in protocol extensions aren't reported.
} else {
// lookupVisibleMemberDecls() generally prefers witness members
// over requirements.
continue;
}
}
}
Consumer.foundDecl(VD, ReasonForThisDecl);
}
}
}
// Add members from any extensions.
if (LS.isIncludingProtocolExtensionMembers()) {
SmallVector<ValueDecl *, 2> FoundDecls;
doGlobalExtensionLookup(BaseTy, Proto,
FoundDecls, FromContext, LS,
ReasonForThisProtocol);
for (auto *VD : FoundDecls)
Consumer.foundDecl(VD, ReasonForThisProtocol);
}
}
}
static void
lookupVisibleProtocolMemberDecls(Type BaseTy, ProtocolDecl *PD,
VisibleDeclConsumer &Consumer,
const DeclContext *CurrDC, LookupState LS,
DeclVisibilityKind Reason,
VisitedSet &Visited) {
if (!Visited.insert(PD).second)
return;
lookupTypeMembers(BaseTy, PD, Consumer, CurrDC, LS, Reason);
// Collect members from the inherited protocols.
for (auto Proto : PD->getInheritedProtocols())
lookupVisibleProtocolMemberDecls(BaseTy, Proto, Consumer, CurrDC, LS,
getReasonForSuper(Reason), Visited);
}
static void lookupVisibleCxxNamespaceMemberDecls(
EnumDecl *swiftDecl, const clang::NamespaceDecl *clangNamespace,
VisibleDeclConsumer &Consumer, VisitedSet &Visited) {
if (!Visited.insert(swiftDecl).second)
return;
auto &ctx = swiftDecl->getASTContext();
auto namespaceDecl = clangNamespace;
// This is only to keep track of the members we've already seen.
llvm::SmallPtrSet<Decl *, 16> addedMembers;
for (auto redecl : namespaceDecl->redecls()) {
for (auto member : redecl->decls()) {
auto lookupAndAddMembers = [&](DeclName name) {
auto allResults = evaluateOrDefault(
ctx.evaluator, ClangDirectLookupRequest({swiftDecl, redecl, name}),
{});
for (auto found : allResults) {
auto clangMember = found.get<clang::NamedDecl *>();
if (auto importedDecl =
ctx.getClangModuleLoader()->importDeclDirectly(
cast<clang::NamedDecl>(clangMember))) {
if (addedMembers.insert(importedDecl).second) {
if (importedDecl->getDeclContext()->getAsDecl() != swiftDecl) {
return;
}
Consumer.foundDecl(cast<ValueDecl>(importedDecl),
DeclVisibilityKind::MemberOfCurrentNominal);
}
}
}
};
auto namedDecl = dyn_cast<clang::NamedDecl>(member);
if (!namedDecl)
continue;
auto name = ctx.getClangModuleLoader()->importName(namedDecl);
if (!name)
continue;
lookupAndAddMembers(name);
// Unscoped enums could have their enumerators present
// in the parent namespace.
if (auto *ed = dyn_cast<clang::EnumDecl>(member)) {
if (!ed->isScoped()) {
for (const auto *ecd : ed->enumerators()) {
auto name = ctx.getClangModuleLoader()->importName(ecd);
if (!name)
continue;
lookupAndAddMembers(name);
}
}
}
}
}
}
static void lookupVisibleMemberDeclsImpl(
Type BaseTy, VisibleDeclConsumer &Consumer, const DeclContext *CurrDC,
LookupState LS, DeclVisibilityKind Reason, VisitedSet &Visited) {
// Just look through l-valueness. It doesn't affect name lookup.
assert(BaseTy && "lookup into null type");
assert(!BaseTy->hasTypeParameter());
assert(!BaseTy->hasLValueType());
// 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();
if (Ty->is<AnyMetatypeType>())
return;
LookupState subLS = LookupState::makeQualified().withOnMetatype();
if (LS.isIncludingInstanceMembers()) {
subLS = subLS.withIncludedInstanceMembers();
}
if (LS.isIncludingDerivedRequirements()) {
subLS = subLS.withIncludedDerivedRequirements();
}
if (LS.isIncludingProtocolExtensionMembers()) {
subLS = subLS.withIncludeProtocolExtensionMembers();
}
// 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, subLS, Reason, 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);
MT->getModule()->lookupVisibleDecls(ImportPath::Access(),
FilteringConsumer,
NLKind::QualifiedLookup);
return;
}
// If the base is AnyObject, we are doing dynamic lookup.
if (BaseTy->isAnyObject()) {
doDynamicLookup(Consumer, CurrDC, LS);
return;
}
// If the base is a protocol, enumerate its members.
if (ProtocolType *PT = BaseTy->getAs<ProtocolType>()) {
lookupVisibleProtocolMemberDecls(BaseTy, PT->getDecl(),
Consumer, CurrDC, LS, Reason, Visited);
return;
}
// If the base is a protocol composition, enumerate members of the protocols.
if (auto PC = BaseTy->getAs<ProtocolCompositionType>()) {
for (auto Member : PC->getMembers())
lookupVisibleMemberDeclsImpl(Member, Consumer, CurrDC, LS, Reason,
Visited);
return;
}
if (auto *existential = BaseTy->getAs<ExistentialType>()) {
auto constraint = existential->getConstraintType();
lookupVisibleMemberDeclsImpl(constraint, Consumer, CurrDC, LS, Reason,
Visited);
return;
}
// Enumerate members of archetype's requirements.
if (ArchetypeType *Archetype = BaseTy->getAs<ArchetypeType>()) {
for (auto Proto : Archetype->getConformsTo())
lookupVisibleProtocolMemberDecls(
BaseTy, Proto, Consumer, CurrDC, LS,
Reason, Visited);
if (auto superclass = Archetype->getSuperclass())
lookupVisibleMemberDeclsImpl(superclass, Consumer, CurrDC, LS,
Reason, Visited);
return;
}
// Lookup members of C++ namespace without looking type members, as
// C++ namespace uses lazy lookup.
if (auto *ET = BaseTy->getAs<EnumType>()) {
if (auto *clangNamespace = dyn_cast_or_null<clang::NamespaceDecl>(
ET->getDecl()->getClangDecl())) {
lookupVisibleCxxNamespaceMemberDecls(ET->getDecl(), clangNamespace,
Consumer, Visited);
}
}
// The members of a dynamic 'Self' type are the members of its static
// class type.
if (auto *const DS = BaseTy->getAs<DynamicSelfType>()) {
BaseTy = DS->getSelfType();
}
auto *NTD = BaseTy->getAnyNominal();
if (NTD == nullptr)
return;
lookupTypeMembers(BaseTy, NTD, Consumer, CurrDC, LS, Reason);
// Look into protocols only on the current nominal to avoid repeatedly
// visiting inherited conformances.
lookupDeclsFromProtocolsBeingConformedTo(BaseTy, Consumer, LS, CurrDC,
Reason, Visited);
auto *CD = dyn_cast<ClassDecl>(NTD);
if (!CD || !CD->hasSuperclass())
return;
// We have a superclass; switch state and look into the inheritance chain.
llvm::SmallPtrSet<ClassDecl *, 8> Ancestors;
Ancestors.insert(CD);
Reason = getReasonForSuper(Reason);
LS = LS.withOnSuperclass();
if (CD->inheritsSuperclassInitializers())
LS = LS.withInheritsSuperclassInitializers();
CD = CD->getSuperclassDecl();
// Look into the inheritance chain.
do {
// FIXME: This path is no substitute for an actual circularity check.
// The real fix is to check that the superclass doesn't introduce a
// circular reference before it's written into the AST.
if (!Ancestors.insert(CD).second)
break;
lookupTypeMembers(BaseTy, CD, Consumer, CurrDC, LS, Reason);
if (!CD->inheritsSuperclassInitializers())
LS = LS.withoutInheritsSuperclassInitializers();
} while ((CD = CD->getSuperclassDecl()));
}
swift::DynamicLookupInfo::DynamicLookupInfo(
SubscriptDecl *subscript, Type baseType,
DeclVisibilityKind originalVisibility)
: kind(KeyPathDynamicMember) {
keypath.subscript = subscript;
keypath.baseType = baseType;
keypath.originalVisibility = originalVisibility;
}
const DynamicLookupInfo::KeyPathDynamicMemberInfo &
swift::DynamicLookupInfo::getKeyPathDynamicMember() const {
assert(kind == KeyPathDynamicMember);
return keypath;
}
namespace {
struct FoundDeclTy {
ValueDecl *D;
DeclVisibilityKind Reason;
DynamicLookupInfo dynamicLookupInfo;
FoundDeclTy(ValueDecl *D, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo)
: D(D), Reason(Reason), dynamicLookupInfo(dynamicLookupInfo) {}
friend bool operator==(const FoundDeclTy &LHS, const FoundDeclTy &RHS) {
// If this ever changes - e.g. to include Reason - be sure to also update
// DenseMapInfo<FoundDeclTy>::getHashValue().
return LHS.D == RHS.D;
}
};
} // end anonymous namespace
namespace llvm {
template <> struct DenseMapInfo<FoundDeclTy> {
static inline FoundDeclTy getEmptyKey() {
return FoundDeclTy{nullptr, DeclVisibilityKind::LocalDecl, {}};
}
static inline FoundDeclTy getTombstoneKey() {
return FoundDeclTy{reinterpret_cast<ValueDecl *>(0x1),
DeclVisibilityKind::LocalDecl,
{}};
}
static unsigned getHashValue(const FoundDeclTy &Val) {
// Note: FoundDeclTy::operator== only considers D, so don't hash Reason here.
return llvm::hash_value(Val.D);
}
static bool isEqual(const FoundDeclTy &LHS, const FoundDeclTy &RHS) {
return LHS == RHS;
}
};
} // namespace llvm
// If a class 'Base' conforms to 'Proto', and my base type is a subclass
// 'Derived' of 'Base', use 'Base' not 'Derived' as the 'Self' type in the
// substitution map.
static Type getBaseTypeForMember(const ValueDecl *OtherVD,
Type BaseTy) {
if (auto *Proto = OtherVD->getDeclContext()->getSelfProtocolDecl()) {
if (BaseTy->getClassOrBoundGenericClass()) {
if (auto Conformance = lookupConformance(BaseTy, Proto)) {
auto *Superclass = Conformance.getConcrete()
->getRootConformance()
->getType()
->getClassOrBoundGenericClass();
return BaseTy->getSuperclassForDecl(Superclass);
}
}
}
return BaseTy;
}
namespace {
class OverrideFilteringConsumer : public VisibleDeclConsumer {
public:
llvm::SmallVector<std::pair<NominalTypeDecl *, DeclVisibilityKind>, 2>
nominals;
llvm::SetVector<FoundDeclTy> Results;
llvm::SmallVector<ValueDecl *, 8> Decls;
llvm::SetVector<FoundDeclTy> FilteredResults;
llvm::DenseMap<DeclBaseName, llvm::SmallVector<ValueDecl *, 2>> DeclsByName;
Type BaseTy;
const DeclContext *DC;
OverrideFilteringConsumer(Type BaseTy, const DeclContext *DC)
: BaseTy(BaseTy->getMetatypeInstanceType()),
DC(DC) {
assert(!BaseTy->hasLValueType());
assert(DC && BaseTy);
}
void onLookupNominalTypeMembers(NominalTypeDecl *NTD,
DeclVisibilityKind Reason) override {
nominals.emplace_back(NTD, Reason);
}
void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) override {
if (!Results.insert({VD, Reason, dynamicLookupInfo}))
return;
DeclsByName[VD->getBaseName()] = {};
Decls.push_back(VD);
}
void filterDecls(VisibleDeclConsumer &Consumer) {
for (auto nominal : nominals) {
Consumer.onLookupNominalTypeMembers(nominal.first, nominal.second);
}
removeOverriddenDecls(Decls);
removeShadowedDecls(Decls, DC);
size_t index = 0;
for (const auto &DeclAndReason : Results) {
if (index >= Decls.size())
break;
if (DeclAndReason.D != Decls[index])
continue;
++index;
auto *const VD = DeclAndReason.D;
const auto Reason = DeclAndReason.Reason;
// If this kind of declaration doesn't participate in overriding, there's
// no filtering to do here.
if (!isa<AbstractFunctionDecl>(VD) &&
!isa<AbstractStorageDecl>(VD) &&
!isa<AssociatedTypeDecl>(VD)) {
FilteredResults.insert(DeclAndReason);
continue;
}
if (VD->isRecursiveValidation())
continue;
auto &PossiblyConflicting = DeclsByName[VD->getBaseName()];
if (VD->isInvalid()) {
FilteredResults.insert(DeclAndReason);
PossiblyConflicting.push_back(VD);
continue;
}
ModuleDecl *M = DC->getParentModule();
// If the base type is AnyObject, we might be doing a dynamic
// lookup, so the base type won't match the type of the member's
// context type.
//
// If the base type is not a nominal type, we can't substitute
// the member type.
//
// If the member is a free function and not a member of a type,
// don't substitute either.
bool shouldSubst = (Reason != DeclVisibilityKind::DynamicLookup &&
!BaseTy->isAnyObject() && !BaseTy->hasTypeVariable() &&
!BaseTy->hasUnboundGenericType() &&
(BaseTy->getNominalOrBoundGenericNominal() ||
BaseTy->is<ArchetypeType>()) &&
VD->getDeclContext()->isTypeContext());
/// Substitute generic parameters in the signature of a found decl. The
/// returned type can be used to determine if we have already found a
/// conflicting declaration.
auto substGenericArgs = [&](CanType SignatureType, ValueDecl *VD,
Type BaseTy) -> CanType {
if (!SignatureType || !shouldSubst) {
return SignatureType;
}
if (auto GenFuncSignature =
SignatureType->getAs<GenericFunctionType>()) {
GenericEnvironment *GenEnv;
if (auto *GenCtx = VD->getAsGenericContext()) {
GenEnv = GenCtx->getGenericEnvironment();
} else {
GenEnv = DC->getGenericEnvironmentOfContext();
}
auto subs = BaseTy->getMemberSubstitutionMap(VD, GenEnv);
auto CT = GenFuncSignature->substGenericArgs(subs);
if (!CT->hasError()) {
return CT->getCanonicalType();
}
}
return SignatureType;
};
auto FoundSignature = VD->getOverloadSignature();
auto FoundSignatureType =
substGenericArgs(VD->getOverloadSignatureType(), VD, BaseTy);
bool FoundConflicting = false;
for (auto I = PossiblyConflicting.begin(), E = PossiblyConflicting.end();
I != E; ++I) {
auto *const OtherVD = *I;
if (OtherVD->isRecursiveValidation())
continue;
if (OtherVD->isInvalid())
continue;
auto OtherSignature = OtherVD->getOverloadSignature();
auto ActualBaseTy = getBaseTypeForMember(OtherVD, BaseTy);
auto OtherSignatureType = substGenericArgs(
OtherVD->getOverloadSignatureType(), OtherVD, ActualBaseTy);
if (conflicting(M->getASTContext(), FoundSignature, FoundSignatureType,
OtherSignature, OtherSignatureType,
/*wouldConflictInSwift5*/nullptr,
/*skipProtocolExtensionCheck*/true)) {
FoundConflicting = true;
if (!VD->isUnavailable()) {
bool preferVD = (
// Prefer derived requirements over their witnesses.
Reason == DeclVisibilityKind::
MemberOfProtocolDerivedByCurrentNominal ||
// Prefer available one.
OtherVD->isUnavailable() ||
// Prefer more accessible one.
VD->getFormalAccess() > OtherVD->getFormalAccess());
if (preferVD) {
FilteredResults.remove(