forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNameLookup.cpp
2425 lines (2070 loc) · 86.5 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 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements interfaces for performing name lookup.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/NameLookup.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/DebuggerClient.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/STLExtras.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "namelookup"
using namespace swift;
using namespace swift::namelookup;
void VisibleDeclConsumer::anchor() {}
void VectorDeclConsumer::anchor() {}
void NamedDeclConsumer::anchor() {}
ValueDecl *LookupResultEntry::getBaseDecl() const {
if (BaseDC == nullptr)
return nullptr;
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(BaseDC))
return AFD->getImplicitSelfDecl();
if (auto *PBI = dyn_cast<PatternBindingInitializer>(BaseDC)) {
auto *selfDecl = PBI->getImplicitSelfDecl();
assert(selfDecl);
return selfDecl;
}
auto *nominalDecl = BaseDC->getSelfNominalTypeDecl();
assert(nominalDecl);
return nominalDecl;
}
void DebuggerClient::anchor() {}
void AccessFilteringDeclConsumer::foundDecl(
ValueDecl *D, DeclVisibilityKind reason,
DynamicLookupInfo dynamicLookupInfo) {
if (D->isInvalid())
return;
if (!D->isAccessibleFrom(DC))
return;
ChainedConsumer.foundDecl(D, reason, dynamicLookupInfo);
}
void LookupResultEntry::print(llvm::raw_ostream& out) const {
getValueDecl()->print(out);
if (auto dc = getBaseDecl()) {
out << "\nbase: ";
dc->print(out);
out << "\n";
} else
out << "\n(no-base)\n";
}
bool swift::removeOverriddenDecls(SmallVectorImpl<ValueDecl*> &decls) {
if (decls.size() < 2)
return false;
llvm::SmallPtrSet<ValueDecl*, 8> overridden;
for (auto decl : decls) {
// Don't look at the overrides of operators in protocols. The global
// lookup of operators means that we can find overriding operators that
// aren't relevant to the types in hand, and will fail to type check.
if (isa<ProtocolDecl>(decl->getDeclContext())) {
if (auto func = dyn_cast<FuncDecl>(decl))
if (func->isOperator())
continue;
}
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() == DeclBaseName::createConstructor()) {
/// 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;
}
/// Given a set of declarations whose names and signatures have matched,
/// figure out which of these declarations have been shadowed by others.
static void recordShadowedDeclsAfterSignatureMatch(
ArrayRef<ValueDecl *> decls,
const ModuleDecl *curModule,
llvm::SmallPtrSetImpl<ValueDecl *> &shadowed) {
assert(decls.size() > 1 && "Nothing collided");
// 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.
ASTContext &ctx = curModule->getASTContext();
for (unsigned firstIdx : indices(decls)) {
auto firstDecl = decls[firstIdx];
auto firstModule = firstDecl->getModuleContext();
auto firstSig = firstDecl->getOverloadSignature();
for (unsigned secondIdx : range(firstIdx + 1, decls.size())) {
// Determine whether one module takes precedence over another.
auto secondDecl = decls[secondIdx];
auto secondModule = secondDecl->getModuleContext();
// Swift 4 compatibility hack: Don't shadow properties defined in
// extensions of generic types with properties defined elsewhere.
// This is due to the fact that in Swift 4, we only gave custom overload
// types to properties in extensions of generic types, otherwise we
// used the null type.
if (!ctx.isSwiftVersionAtLeast(5)) {
auto secondSig = secondDecl->getOverloadSignature();
if (firstSig.IsVariable && secondSig.IsVariable)
if (firstSig.InExtensionOfGenericType !=
secondSig.InExtensionOfGenericType)
continue;
}
// 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()->getSelfProtocolDecl() !=
(bool)secondDecl->getDeclContext()->getSelfProtocolDecl()) {
if (firstDecl->getDeclContext()->getSelfProtocolDecl()) {
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)) {
// 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;
}
// Prefer declarations in the any module over those in the standard
// library module.
if (auto swiftModule = ctx.getStdlibModule()) {
if ((firstModule == swiftModule) != (secondModule == swiftModule)) {
// If the second module is the standard library module, the second
// declaration is shadowed by the first.
if (secondModule == swiftModule) {
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;
}
}
// The Foundation overlay introduced Data.withUnsafeBytes, which is
// treated as being ambiguous with SwiftNIO's Data.withUnsafeBytes
// extension. Apply a special-case name shadowing rule to use the
// latter rather than the former, which be the consequence of a more
// significant change to name shadowing in the future.
if (auto owningStruct1
= firstDecl->getDeclContext()->getSelfStructDecl()) {
if (auto owningStruct2
= secondDecl->getDeclContext()->getSelfStructDecl()) {
if (owningStruct1 == owningStruct2 &&
owningStruct1->getName().is("Data") &&
isa<FuncDecl>(firstDecl) && isa<FuncDecl>(secondDecl) &&
firstDecl->getFullName() == secondDecl->getFullName() &&
firstDecl->getBaseName().userFacingName() == "withUnsafeBytes") {
// If the second module is the Foundation module and the first
// is the NIOFoundationCompat module, the second is shadowed by the
// first.
if (firstDecl->getModuleContext()->getName()
.is("NIOFoundationCompat") &&
secondDecl->getModuleContext()->getName().is("Foundation")) {
shadowed.insert(secondDecl);
continue;
}
// If it's the other way around, the first declaration is shadowed
// by the second.
if (secondDecl->getModuleContext()->getName()
.is("NIOFoundationCompat") &&
firstDecl->getModuleContext()->getName().is("Foundation")) {
shadowed.insert(firstDecl);
break;
}
}
}
}
// Prefer declarations in an overlay to similar declarations in
// the Clang module it customizes.
if (firstDecl->hasClangNode() != secondDecl->hasClangNode()) {
auto clangLoader = ctx.getClangModuleLoader();
if (!clangLoader) continue;
if (clangLoader->isInOverlayModuleForImportedModule(
firstDecl->getDeclContext(),
secondDecl->getDeclContext())) {
shadowed.insert(secondDecl);
continue;
}
if (clangLoader->isInOverlayModuleForImportedModule(
secondDecl->getDeclContext(),
firstDecl->getDeclContext())) {
shadowed.insert(firstDecl);
break;
}
}
}
}
}
/// Look through the given set of declarations (that all have the same name),
/// recording those that are shadowed by another declaration in the
/// \c shadowed set.
static void recordShadowedDeclsForImportedInits(
ArrayRef<ConstructorDecl *> ctors,
llvm::SmallPtrSetImpl<ValueDecl *> &shadowed) {
assert(ctors.size() > 1 && "No collisions");
ASTContext &ctx = ctors.front()->getASTContext();
// Find the "best" constructor with this signature.
ConstructorDecl *bestCtor = ctors[0];
for (auto ctor : ctors.slice(1)) {
auto comparison = compareConstructors(ctor, bestCtor, ctx);
if (comparison == ConstructorComparison::Better)
bestCtor = ctor;
}
// Shadow any initializers that are worse.
for (auto ctor : ctors) {
auto comparison = compareConstructors(ctor, bestCtor, ctx);
if (comparison == ConstructorComparison::Worse)
shadowed.insert(ctor);
}
}
/// Look through the given set of declarations (that all have the same name),
/// recording those that are shadowed by another declaration in the
/// \c shadowed set.
static void recordShadowedDecls(ArrayRef<ValueDecl *> decls,
const ModuleDecl *curModule,
llvm::SmallPtrSetImpl<ValueDecl *> &shadowed) {
if (decls.size() < 2)
return;
auto typeResolver = decls[0]->getASTContext().getLazyResolver();
// Categorize all of the declarations based on their overload signatures.
llvm::SmallDenseMap<CanType, llvm::TinyPtrVector<ValueDecl *>> collisions;
llvm::SmallVector<CanType, 2> collisionTypes;
llvm::SmallDenseMap<NominalTypeDecl *, llvm::TinyPtrVector<ConstructorDecl *>>
importedInitializerCollisions;
llvm::TinyPtrVector<NominalTypeDecl *> importedInitializerCollectionTypes;
for (auto decl : decls) {
// Specifically keep track of imported initializers, which can come from
// Objective-C init methods, Objective-C factory methods, renamed C
// functions, or be synthesized by the importer.
if (decl->hasClangNode() ||
(isa<NominalTypeDecl>(decl->getDeclContext()) &&
cast<NominalTypeDecl>(decl->getDeclContext())->hasClangNode())) {
if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
auto nominal = ctor->getDeclContext()->getSelfNominalTypeDecl();
auto &knownInits = importedInitializerCollisions[nominal];
if (knownInits.size() == 1) {
importedInitializerCollectionTypes.push_back(nominal);
}
knownInits.push_back(ctor);
}
}
CanType signature;
if (!isa<TypeDecl>(decl)) {
// We need an interface type here.
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.
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->getOverloadSignatureType();
} else if (decl->getDeclContext()->isTypeContext()) {
// Do not apply shadowing rules for member types.
continue;
}
// Record this declaration based on its signature.
auto &known = collisions[signature];
if (known.size() == 1) {
collisionTypes.push_back(signature);
}
known.push_back(decl);
}
// Check whether we have shadowing for signature collisions.
for (auto signature : collisionTypes) {
recordShadowedDeclsAfterSignatureMatch(collisions[signature], curModule,
shadowed);
}
// Check whether we have shadowing for imported initializer collisions.
for (auto nominal : importedInitializerCollectionTypes) {
recordShadowedDeclsForImportedInits(importedInitializerCollisions[nominal],
shadowed);
}
}
bool swift::removeShadowedDecls(SmallVectorImpl<ValueDecl*> &decls,
const ModuleDecl *curModule) {
// Collect declarations with the same (full) name.
llvm::SmallDenseMap<DeclName, llvm::TinyPtrVector<ValueDecl *>>
collidingDeclGroups;
bool anyCollisions = false;
for (auto decl : decls) {
// Record this declaration based on its full name.
auto &knownDecls = collidingDeclGroups[decl->getFullName()];
if (!knownDecls.empty())
anyCollisions = true;
knownDecls.push_back(decl);
}
// If nothing collided, we're done.
if (!anyCollisions)
return false;
// Walk through the declarations again, marking any declarations that shadow.
llvm::SmallPtrSet<ValueDecl *, 4> shadowed;
for (auto decl : decls) {
auto known = collidingDeclGroups.find(decl->getFullName());
if (known == collidingDeclGroups.end()) {
// We already handled this group.
continue;
}
recordShadowedDecls(known->second, curModule, shadowed);
collidingDeclGroups.erase(known);
}
// If no 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() > AccessLevel::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,
LookupResultEntry lookupResult) {
return matchDiscriminator(discriminator, lookupResult.getValueDecl());
}
template <typename Result>
void namelookup::filterForDiscriminator(SmallVectorImpl<Result> &results,
DebuggerClient *debugClient) {
if (debugClient == nullptr)
return;
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);
}
template void namelookup::filterForDiscriminator<LookupResultEntry>(
SmallVectorImpl<LookupResultEntry> &results, DebuggerClient *debugClient);
void namelookup::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);
}
/// Retrieve the set of type declarations that are directly referenced from
/// the given parsed type representation.
static DirectlyReferencedTypeDecls
directReferencesForTypeRepr(Evaluator &evaluator,
ASTContext &ctx, TypeRepr *typeRepr,
DeclContext *dc);
/// Retrieve the set of type declarations that are directly referenced from
/// the given type.
static DirectlyReferencedTypeDecls directReferencesForType(Type type);
/// Given a set of type declarations, find all of the nominal type declarations
/// that they reference, looking through typealiases as appropriate.
static TinyPtrVector<NominalTypeDecl *>
resolveTypeDeclsToNominal(Evaluator &evaluator,
ASTContext &ctx,
ArrayRef<TypeDecl *> typeDecls,
SmallVectorImpl<ModuleDecl *> &modulesFound,
bool &anyObject);
SelfBounds
SelfBoundsFromWhereClauseRequest::evaluate(
Evaluator &evaluator,
llvm::PointerUnion<TypeDecl *, ExtensionDecl *> decl) const {
auto *typeDecl = decl.dyn_cast<TypeDecl *>();
auto *protoDecl = dyn_cast_or_null<ProtocolDecl>(typeDecl);
auto *extDecl = decl.dyn_cast<ExtensionDecl *>();
DeclContext *dc = protoDecl ? (DeclContext *)protoDecl : (DeclContext *)extDecl;
// A protocol or extension 'where' clause can reference associated types of
// the protocol itself, so we have to start unqualified lookup from 'dc'.
//
// However, the right hand side of a 'Self' conformance constraint must be
// resolved before unqualified lookup into 'dc' can work, so we make an
// exception here and begin lookup from the parent context instead.
auto *lookupDC = dc->getParent();
auto requirements = protoDecl ? protoDecl->getTrailingWhereClause()
: extDecl->getTrailingWhereClause();
ASTContext &ctx = dc->getASTContext();
SelfBounds result;
if (requirements == nullptr)
return result;
for (const auto &req : requirements->getRequirements()) {
// We only care about type constraints.
if (req.getKind() != RequirementReprKind::TypeConstraint)
continue;
// The left-hand side of the type constraint must be 'Self'.
bool isSelfLHS = false;
if (auto typeRepr = req.getSubjectRepr()) {
if (auto identTypeRepr = dyn_cast<SimpleIdentTypeRepr>(typeRepr))
isSelfLHS = (identTypeRepr->getIdentifier() == ctx.Id_Self);
} else if (Type type = req.getSubject()) {
isSelfLHS = type->isEqual(dc->getSelfInterfaceType());
}
if (!isSelfLHS)
continue;
// Resolve the right-hand side.
DirectlyReferencedTypeDecls rhsDecls;
if (auto typeRepr = req.getConstraintRepr()) {
rhsDecls = directReferencesForTypeRepr(evaluator, ctx, typeRepr, lookupDC);
} else if (Type type = req.getConstraint()) {
rhsDecls = directReferencesForType(type);
}
SmallVector<ModuleDecl *, 2> modulesFound;
auto rhsNominals = resolveTypeDeclsToNominal(evaluator, ctx, rhsDecls,
modulesFound,
result.anyObject);
result.decls.insert(result.decls.end(),
rhsNominals.begin(),
rhsNominals.end());
}
return result;
}
SelfBounds swift::getSelfBoundsFromWhereClause(
llvm::PointerUnion<TypeDecl *, ExtensionDecl *> decl) {
auto *typeDecl = decl.dyn_cast<TypeDecl *>();
auto *extDecl = decl.dyn_cast<ExtensionDecl *>();
auto &ctx = typeDecl ? typeDecl->getASTContext()
: extDecl->getASTContext();
return evaluateOrDefault(ctx.evaluator,
SelfBoundsFromWhereClauseRequest{decl}, {});
}
TinyPtrVector<TypeDecl *>
TypeDeclsFromWhereClauseRequest::evaluate(Evaluator &evaluator,
ExtensionDecl *ext) const {
ASTContext &ctx = ext->getASTContext();
TinyPtrVector<TypeDecl *> result;
for (const auto &req : ext->getGenericParams()->getTrailingRequirements()) {
auto resolve = [&](TypeLoc loc) {
DirectlyReferencedTypeDecls decls;
if (auto *typeRepr = loc.getTypeRepr())
decls = directReferencesForTypeRepr(evaluator, ctx, typeRepr, ext);
else if (Type type = loc.getType())
decls = directReferencesForType(type);
result.insert(result.end(), decls.begin(), decls.end());
};
switch (req.getKind()) {
case RequirementReprKind::TypeConstraint:
resolve(req.getSubjectLoc());
resolve(req.getConstraintLoc());
break;
case RequirementReprKind::SameType:
resolve(req.getFirstTypeLoc());
resolve(req.getSecondTypeLoc());
break;
case RequirementReprKind::LayoutConstraint:
resolve(req.getSubjectLoc());
break;
}
}
return result;
}
#pragma mark Member lookup table
void LazyMemberLoader::anchor() {}
void LazyConformanceLoader::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);
/// Add the given member to the lookup table.
void addMember(Decl *members);
/// Add the given members to the lookup table.
void addMembers(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);
}
void dump(llvm::raw_ostream &os) const {
os << "LastExtensionIncluded:\n";
if (LastExtensionIncluded)
LastExtensionIncluded->printContext(os, 2);
else
os << " nullptr\n";
os << "Lookup:\n ";
for (auto &pair : Lookup) {
pair.getFirst().print(os) << ":\n ";
for (auto &decl : pair.getSecond()) {
os << "- ";
decl->dumpRef(os);
os << "\n ";
}
}
os << "\n";
}
LLVM_ATTRIBUTE_DEPRECATED(void dump() const LLVM_ATTRIBUTE_USED,
"only for use within the debugger") {
dump(llvm::errs());
}
// Mark all Decls in this table as not-resident in a table, drop
// references to them. Should only be called when this was not fully-populated
// from an IterableDeclContext.
void clear() {
// LastExtensionIncluded would only be non-null if this was populated from
// an IterableDeclContext (though it might still be null in that case).
assert(LastExtensionIncluded == nullptr);
for (auto const &i : Lookup) {
for (auto d : i.getSecond()) {
d->setAlreadyInLookupTable(false);
}
}
Lookup.clear();
}
// Only allow allocation of member lookup tables using the allocator in
// ASTContext or by doing a placement new.
void *operator new(size_t Bytes, ASTContext &C,
unsigned Alignment = alignof(MemberLookupTable)) {
return C.Allocate(Bytes, Alignment);
}
void *operator new(size_t Bytes, void *Mem) {
assert(Mem);
return Mem;
}
};
namespace {
/// Stores the set of Objective-C methods with a given selector within the
/// Objective-C method lookup table.
struct StoredObjCMethods {
/// The generation count at which this list was last updated.
unsigned Generation = 0;
/// The set of methods with the given selector.
llvm::TinyPtrVector<AbstractFunctionDecl *> Methods;
};
} // end anonymous namespace
/// Class member lookup table, which is a member lookup table with a second
/// table for lookup based on Objective-C selector.
class ClassDecl::ObjCMethodLookupTable
: public llvm::DenseMap<std::pair<ObjCSelector, char>,
StoredObjCMethods>
{
public:
// Only allow allocation of member lookup tables using the allocator in
// ASTContext or by doing a placement new.
void *operator new(size_t Bytes, ASTContext &C,
unsigned Alignment = alignof(MemberLookupTable)) {
return C.Allocate(Bytes, Alignment);
}
void *operator new(size_t Bytes, void *Mem) {
assert(Mem);
return Mem;
}
};
MemberLookupTable::MemberLookupTable(ASTContext &ctx) {
// Register a cleanup with the ASTContext to call the lookup table
// destructor.
ctx.addCleanup([this]() {
this->~MemberLookupTable();
});
}
void MemberLookupTable::addMember(Decl *member) {
// Only value declarations matter.
auto vd = dyn_cast<ValueDecl>(member);
if (!vd)
return;
// @_implements members get added under their declared name.
auto A = vd->getAttrs().getAttribute<ImplementsAttr>();
// Unnamed entities w/o @_implements synonyms cannot be found by name lookup.
if (!A && !vd->hasName())
return;
// If this declaration is already in the lookup table, don't add it
// again.
if (vd->isAlreadyInLookupTable()) {
return;
}
vd->setAlreadyInLookupTable();
// Add this declaration to the lookup set under its compound name and simple
// name.
vd->getFullName().addToLookupTable(Lookup, vd);
// And if given a synonym, under that name too.
if (A)
A->getMemberName().addToLookupTable(Lookup, vd);
}
void MemberLookupTable::addMembers(DeclRange members) {
for (auto member : members) {
addMember(member);
}
}
void MemberLookupTable::updateLookupTable(NominalTypeDecl *nominal) {
// If the last extension we included is the same as the last known extension,
// we're already up-to-date.
if (LastExtensionIncluded == nominal->LastExtension)
return;
// Add members from each of the extensions that we have not yet visited.
for (auto next = LastExtensionIncluded
? LastExtensionIncluded->NextExtension.getPointer()
: nominal->FirstExtension;
next;
(LastExtensionIncluded = next,next = next->NextExtension.getPointer())) {
addMembers(next->getMembers());
}
}
void NominalTypeDecl::addedMember(Decl *member) {
// If we have a lookup table, add the new member to it.
if (LookupTable.getPointer()) {
LookupTable.getPointer()->addMember(member);
}
}
void NominalTypeDecl::addedExtension(ExtensionDecl * ext) {
if (hasLazyMembers())
setLookupTablePopulated(false);
}
void ExtensionDecl::addedMember(Decl *member) {
if (NextExtension.getInt()) {
auto nominal = getExtendedNominal();
if (!nominal)
return;
if (nominal->LookupTable.getPointer() &&
nominal->isLookupTablePopulated()) {
// Make sure we have the complete list of extensions.
// FIXME: This is completely unnecessary. We want to determine whether
// our own extension has already been included in the lookup table.
(void)nominal->getExtensions();
nominal->LookupTable.getPointer()->addMember(member);
}
}
}
// For lack of anywhere more sensible to put it, here's a diagram of the pieces
// involved in finding members and extensions of a NominalTypeDecl.
//
// ┌────────────────────────────┬─┐
// │IterableDeclContext │ │ ┌─────────────────────────────┐
// │------------------- │ │ │┌───────────────┬┐ ▼
// │Decl *LastDecl ───────────┼─┼─────┘│Decl ││ ┌───────────────┬┐
// │Decl *FirstDecl ───────────┼─┼─────▶│---- ││ │Decl ││
// │ │ │ │Decl *NextDecl├┼─▶│---- ││
// │bool HasLazyMembers │ │ ├───────────────┘│ │Decl *NextDecl ││
// │IterableDeclContextKind Kind│ │ │ │ ├───────────────┘│
// │ │ │ │ValueDecl │ │ │
// ├────────────────────────────┘ │ │--------- │ │ValueDecl │
// │ │ │DeclName Name │ │--------- │
// │NominalTypeDecl │ └────────────────┘ │DeclName Name │
// │--------------- │ ▲ └────────────────┘
// │ExtensionDecl *FirstExtension─┼────────┐ │ ▲
// │ExtensionDecl *LastExtension ─┼───────┐│ │ └───┐
// │ │ ││ └──────────────────────┐│
// │MemberLookupTable *LookupTable├─┐ ││ ││
// │bool LookupTableComplete │ │ ││ ┌─────────────────┐ ││
// └──────────────────────────────┘ │ ││ │ExtensionDecl │ ││
// │ ││ │------------- │ ││
// ┌─────────────┘ │└────▶│ExtensionDecl │ ││
// │ │ │ *NextExtension ├──┐ ││
// ▼ │ └─────────────────┘ │ ││
// ┌─────────────────────────────────────┐│ ┌─────────────────┐ │ ││
// │MemberLookupTable ││ │ExtensionDecl │ │ ││
// │----------------- ││ │------------- │ │ ││
// │ExtensionDecl *LastExtensionIncluded ├┴─────▶│ExtensionDecl │◀─┘ ││
// │ │ │ *NextExtension │ ││
// │┌───────────────────────────────────┐│ └─────────────────┘ ││
// ││DenseMap<Declname, ...> LookupTable││ ││
// ││-----------------------------------││ ┌──────────────────────────┐ ││
// ││[NameA] TinyPtrVector<ValueDecl *> ││ │TinyPtrVector<ValueDecl *>│ ││
// ││[NameB] TinyPtrVector<ValueDecl *> ││ │--------------------------│ ││
// ││[NameC] TinyPtrVector<ValueDecl *>─┼┼─▶│[0] ValueDecl * ─────┼─┘│
// │└───────────────────────────────────┘│ │[1] ValueDecl * ─────┼──┘
// └─────────────────────────────────────┘ └──────────────────────────┘
//
// The HasLazyMembers, Kind, and LookupTableComplete fields are packed into
// PointerIntPairs so don't go grepping for them; but for purposes of
// illustration they are effectively their own fields.
//
// MemberLookupTable is populated en-masse when the IterableDeclContext's
// (IDC's) list of Decls is populated. But MemberLookupTable can also be
// populated incrementally by one-name-at-a-time lookups by lookupDirect, in
// which case those Decls are _not_ added to the IDC's list. They are cached in
// the loader they come from, lifecycle-wise, and are added to the
// MemberLookupTable to accelerate subsequent retrieval, but the IDC is not
// considered populated until someone calls getMembers().
//
// If the IDC list is later populated and/or an extension is added _after_
// MemberLookupTable is constructed (and possibly has entries in it),
// MemberLookupTable is purged and reconstructed from IDC's list.
//
// In all lookup routines, the 'ignoreNewExtensions' flag means that
// lookup should only use the set of extensions already observed.
static bool
populateLookupTableEntryFromLazyIDCLoader(ASTContext &ctx,
MemberLookupTable &LookupTable,
DeclName name,
IterableDeclContext *IDC) {
if (IDC->isLoadingLazyMembers()) {
return false;
}
IDC->setLoadingLazyMembers(true);
auto ci = ctx.getOrCreateLazyIterableContextData(IDC,
/*lazyLoader=*/nullptr);
if (auto res = ci->loader->loadNamedMembers(IDC, name.getBaseName(),
ci->memberData)) {
IDC->setLoadingLazyMembers(false);
if (auto s = ctx.Stats) {
++s->getFrontendCounters().NamedLazyMemberLoadSuccessCount;
}
for (auto d : *res) {
LookupTable.addMember(d);
}
return false;
} else {
IDC->setLoadingLazyMembers(false);
if (auto s = ctx.Stats) {