-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathNameLookup.cpp
4259 lines (3617 loc) · 155 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/ASTWalker.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/ConformanceAttributes.h"
#include "swift/AST/DebuggerClient.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/MacroDeclaration.h"
#include "swift/AST/ModuleNameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PotentialMacroExpansions.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Debug.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/ClangImporter/ClangImporterRequests.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Parse/Lexer.h"
#include "swift/Strings.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <deque>
#define DEBUG_TYPE "namelookup"
using namespace swift;
using namespace swift::namelookup;
void VisibleDeclConsumer::anchor() {}
void VectorDeclConsumer::anchor() {}
ValueDecl *LookupResultEntry::getBaseDecl() const {
if (BaseDC == nullptr)
return nullptr;
return BaseDecl;
}
void LookupResult::filter(
llvm::function_ref<bool(LookupResultEntry, bool)> pred) {
size_t index = 0;
size_t originalFirstOuter = IndexOfFirstOuterResult;
Results.erase(std::remove_if(Results.begin(), Results.end(),
[&](LookupResultEntry result) -> bool {
auto isInner = index < originalFirstOuter;
++index;
if (pred(result, !isInner))
return false;
// Need to remove this, which means, if it is
// an inner result, the outer results need to
// shift down.
if (isInner)
--IndexOfFirstOuterResult;
return true;
}),
Results.end());
}
void LookupResult::shiftDownResults() {
// Remove inner results.
Results.erase(Results.begin(), Results.begin() + IndexOfFirstOuterResult);
IndexOfFirstOuterResult = 0;
if (Results.empty())
return;
// Compute IndexOfFirstOuterResult.
const DeclContext *dcInner = Results.front().getValueDecl()->getDeclContext();
for (auto &&result : Results) {
const DeclContext *dc = result.getValueDecl()->getDeclContext();
if (dc == dcInner ||
(dc->isModuleScopeContext() && dcInner->isModuleScopeContext()))
++IndexOfFirstOuterResult;
else
break;
}
}
void swift::simple_display(llvm::raw_ostream &out,
UnqualifiedLookupOptions options) {
using Flag = std::pair<UnqualifiedLookupFlags, StringRef>;
Flag possibleFlags[] = {
{UnqualifiedLookupFlags::AllowProtocolMembers, "AllowProtocolMembers"},
{UnqualifiedLookupFlags::IgnoreAccessControl, "IgnoreAccessControl"},
{UnqualifiedLookupFlags::IncludeOuterResults, "IncludeOuterResults"},
{UnqualifiedLookupFlags::TypeLookup, "TypeLookup"},
{UnqualifiedLookupFlags::MacroLookup, "MacroLookup"},
{UnqualifiedLookupFlags::ModuleLookup, "ModuleLookup"},
{UnqualifiedLookupFlags::DisregardSelfBounds, "DisregardSelfBounds"},
{UnqualifiedLookupFlags::IgnoreMissingImports, "IgnoreMissingImports"},
{UnqualifiedLookupFlags::ABIProviding, "ABIProviding"},
};
auto flagsToPrint = llvm::make_filter_range(
possibleFlags, [&](Flag flag) { return options.contains(flag.first); });
out << "{ ";
interleave(
flagsToPrint, [&](Flag flag) { out << flag.second; },
[&] { out << ", "; });
out << " }";
}
void DebuggerClient::anchor() {}
void AccessFilteringDeclConsumer::foundDecl(
ValueDecl *D, DeclVisibilityKind reason,
DynamicLookupInfo dynamicLookupInfo) {
if (!D->isAccessibleFrom(DC))
return;
ChainedConsumer.foundDecl(D, reason, dynamicLookupInfo);
}
void UsableFilteringDeclConsumer::foundDecl(
ValueDecl *D, DeclVisibilityKind reason,
DynamicLookupInfo dynamicLookupInfo) {
switch (reason) {
case DeclVisibilityKind::LocalDecl:
case DeclVisibilityKind::FunctionParameter:
// A type context cannot close over variables defined in outer type
// contexts.
if (isa<VarDecl>(D) &&
D->getDeclContext()->getInnermostTypeContext() != typeContext) {
return;
}
break;
case DeclVisibilityKind::MemberOfOutsideNominal:
case DeclVisibilityKind::MemberOfCurrentNominal:
case DeclVisibilityKind::MemberOfSuper:
case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal:
case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal:
case DeclVisibilityKind::DynamicLookup:
// Members on 'Self' including inherited/derived ones are always usable.
break;
case DeclVisibilityKind::GenericParameter:
// Generic params are type decls and are always usable from nested context.
break;
case DeclVisibilityKind::VisibleAtTopLevel: {
// Skip when Loc is within the decl's own initializer. We only need to do
// this for top-level decls since local decls are already excluded from
// their own initializer by virtue of the ASTScope lookup.
if (auto *VD = dyn_cast<VarDecl>(D)) {
// Only check if the VarDecl has the same (or parent) context to avoid
// grabbing the end location for every decl with an initializer
if (auto *init = VD->getParentInitializer()) {
auto *varContext = VD->getDeclContext();
if (DC == varContext || DC->isChildContextOf(varContext)) {
auto initRange = Lexer::getCharSourceRangeFromSourceRange(
SM, init->getSourceRange());
if (initRange.isValid() && initRange.contains(Loc))
return;
}
}
}
break;
}
}
// Filter out shadowed decls. Do this for only usable values even though
// unusable values actually can shadow outer values, because compilers might
// be able to diagnose it with fix-it to add the qualification. E.g.
// func foo(global: T) {}
// struct Outer {
// func foo(outer: T) {}
// func test() {
// struct Inner {
// func test() {
// <HERE>
// }
// }
// }
// }
// In this case 'foo(global:)' is shadowed by 'foo(outer:)', but 'foo(outer:)'
// is _not_ usable because it's outside the current type context, whereas
// 'foo(global:)' is still usable with 'ModuleName.' qualification.
// FIXME: (for code completion,) If a global value or a static type member is
// shadowd, we should suggest it with prefix (e.g. 'ModuleName.value').
auto inserted = SeenNames.insert({D->getBaseName(), {D, reason}});
if (!inserted.second) {
auto shadowingReason = inserted.first->second.second;
auto *shadowingD = inserted.first->second.first;
// A type decl cannot have overloads, and shadows everything outside the
// scope.
if (isa<TypeDecl>(shadowingD))
return;
switch (shadowingReason) {
case DeclVisibilityKind::LocalDecl:
case DeclVisibilityKind::FunctionParameter:
// Local func and var/let with a conflicting name.
// func foo() {
// func value(arg: Int) {}
// var value = ""
// }
// In this case, 'var value' wins, regardless of their source order.
// So, for confilicting local values in the same decl context, even if the
// 'var value' is reported after 'func value', don't shadow it, but we
// shadow everything with the name after that.
if (reason == DeclVisibilityKind::LocalDecl &&
isa<VarDecl>(D) && !isa<VarDecl>(shadowingD) &&
shadowingD->getDeclContext() == D->getDeclContext()) {
// Replace the shadowing decl so we shadow subsequent conflicting decls.
inserted.first->second = {D, reason};
break;
}
// Otherwise, a local value shadows everything outside the scope.
return;
case DeclVisibilityKind::GenericParameter:
// A Generic parameter is a type name. It shadows everything outside the
// generic context.
return;
case DeclVisibilityKind::MemberOfCurrentNominal:
case DeclVisibilityKind::MemberOfSuper:
case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal:
case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal:
case DeclVisibilityKind::DynamicLookup:
switch (reason) {
case DeclVisibilityKind::MemberOfCurrentNominal:
case DeclVisibilityKind::MemberOfSuper:
case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal:
case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal:
case DeclVisibilityKind::DynamicLookup:
// Members on the current type context don't shadow members with the
// same base name on the current type contxt. They are overloads.
break;
default:
// Members of a type context shadows values/types outside.
return;
}
break;
case DeclVisibilityKind::MemberOfOutsideNominal:
// For static values, it's unclear _which_ type context (i.e. this type,
// super classes, conforming protocols) this decl was found in. For now,
// consider all the outer nominals are the same.
if (reason == DeclVisibilityKind::MemberOfOutsideNominal)
break;
// Values outside the nominal are shadowed.
return;
case DeclVisibilityKind::VisibleAtTopLevel:
// Top level decls don't shadow anything.
// Well, that's not true. Decls in the current module shadows decls in
// the imported modules. But we don't care them here.
break;
}
}
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";
auto abiRole = ABIRoleInfo(getValueDecl());
out << "provides API=" << abiRole.providesAPI()
<< ", provides ABI=" << abiRole.providesABI() << "\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->getBaseName().isConstructor()) {
/// 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->isUnavailable();
bool available2 = !ctor2->isUnavailable();
// 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;
}
static bool isMemberImplementation(ValueDecl *VD) {
return VD->isObjCMemberImplementation();
}
static bool isMemberImplementation(OperatorDecl *VD) {
return false;
}
static bool isMemberImplementation(PrecedenceGroupDecl *VD) {
return false;
}
/// Given a set of declarations whose names and interface types have matched,
/// figure out which of these declarations have been shadowed by others.
template <typename T>
static void recordShadowedDeclsAfterTypeMatch(
ArrayRef<T> decls,
const DeclContext *dc,
llvm::SmallPtrSetImpl<T> &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.
auto *curModule = dc->getParentModule();
ASTContext &ctx = curModule->getASTContext();
auto &imports = ctx.getImportCache();
for (unsigned firstIdx : indices(decls)) {
auto firstDecl = decls[firstIdx];
auto firstModule = firstDecl->getModuleContext();
auto firstDC = firstDecl->getDeclContext();
bool firstTopLevel = firstDC->isModuleScopeContext();
auto name = firstDecl->getBaseName();
auto isShadowed = [&](ArrayRef<ImportPath::Access> paths) {
for (auto path : paths) {
if (path.matches(name))
return false;
}
return true;
};
auto isScopedImport = [&](ArrayRef<ImportPath::Access> paths) {
for (auto path : paths) {
if (path.empty())
continue;
if (path.matches(name))
return true;
}
return false;
};
auto isPrivateImport = [&](ModuleDecl *module) {
auto file = dc->getParentSourceFile();
if (!file) return false;
for (const auto &import : file->getImports()) {
if (import.options.contains(ImportFlags::PrivateImport)
&& import.module.importedModule == module
&& import.module.accessPath.matches(name))
return true;
}
return false;
};
bool firstPrivate = isPrivateImport(firstModule);
for (unsigned secondIdx : range(firstIdx + 1, decls.size())) {
// Determine whether one module takes precedence over another.
auto secondDecl = decls[secondIdx];
auto secondModule = secondDecl->getModuleContext();
auto secondDC = secondDecl->getDeclContext();
bool secondTopLevel = secondDC->isModuleScopeContext();
bool secondPrivate = isPrivateImport(secondModule);
// For member types, we skip most of the below rules. Instead, we allow
// member types defined in a subclass to shadow member types defined in
// a superclass.
if (isa<TypeDecl>(firstDecl) &&
isa<TypeDecl>(secondDecl) &&
!firstTopLevel &&
!secondTopLevel) {
auto *firstClass = firstDecl->getDeclContext()->getSelfClassDecl();
auto *secondClass = secondDecl->getDeclContext()->getSelfClassDecl();
if (firstClass && secondClass && firstClass != secondClass) {
if (firstClass->isSuperclassOf(secondClass)) {
shadowed.insert(firstDecl);
continue;
} else if (secondClass->isSuperclassOf(firstClass)) {
shadowed.insert(secondDecl);
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;
}
}
continue;
}
// Top-level type declarations in a module shadow other declarations
// visible through the module's imports.
//
// [Backward compatibility] Note that members of types have the same
// shadowing check, but we do it after dropping unavailable members.
if (firstModule != secondModule &&
firstTopLevel && secondTopLevel) {
auto firstPaths = imports.getAllAccessPathsNotShadowedBy(
firstModule, secondModule, dc);
auto secondPaths = imports.getAllAccessPathsNotShadowedBy(
secondModule, firstModule, dc);
// Check if one module shadows the other.
if (isShadowed(firstPaths)) {
shadowed.insert(firstDecl);
break;
} else if (isShadowed(secondPaths)) {
shadowed.insert(secondDecl);
continue;
}
// If neither module shadows the other, but one was imported with
// '@_private import' in dc, we want to favor that module. This makes
// name lookup in this file behave more like name lookup in the file we
// imported from, avoiding headaches for source-transforming tools.
if (!firstPrivate && secondPrivate) {
shadowed.insert(firstDecl);
break;
} else if (firstPrivate && !secondPrivate) {
shadowed.insert(secondDecl);
continue;
}
// We might be in a situation where neither module shadows the
// other, but one declaration is visible via a scoped import.
bool firstScoped = isScopedImport(firstPaths);
bool secondScoped = isScopedImport(secondPaths);
if (!firstScoped && secondScoped) {
shadowed.insert(firstDecl);
break;
} else if (firstScoped && !secondScoped) {
shadowed.insert(secondDecl);
continue;
}
}
// Member implementations are usually filtered out by access control.
// They're sometimes visible in contexts that can directly access storage,
// though, and there they should shadow the matching imported declaration.
if (firstDC != secondDC
&& firstDC->getImplementedObjCContext() ==
secondDC->getImplementedObjCContext()) {
if (isMemberImplementation(firstDecl) && secondDecl->hasClangNode()) {
shadowed.insert(secondDecl);
continue;
}
if (isMemberImplementation(secondDecl) && firstDecl->hasClangNode()) {
shadowed.insert(firstDecl);
continue;
}
}
// 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) && isa<ValueDecl>(firstDecl)) {
auto secondSig = cast<ValueDecl>(secondDecl)->getOverloadSignature();
auto firstSig = cast<ValueDecl>(firstDecl)->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->isUnavailable() != secondDecl->isUnavailable()) {
if (firstDecl->isUnavailable()) {
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;
// [Backward compatibility] For members of types, the general module
// shadowing check is performed after unavailable candidates have
// already been dropped.
if (firstModule != secondModule &&
!firstTopLevel && !secondTopLevel) {
auto firstPaths = imports.getAllAccessPathsNotShadowedBy(
firstModule, secondModule, dc);
auto secondPaths = imports.getAllAccessPathsNotShadowedBy(
secondModule, firstModule, dc);
// Check if one module shadows the other.
if (isShadowed(firstPaths)) {
shadowed.insert(firstDecl);
break;
} else if (isShadowed(secondPaths)) {
shadowed.insert(secondDecl);
continue;
}
}
// 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;
}
}
// Next, prefer any other module over the _Concurrency module.
if (auto concurModule = ctx.getLoadedModule(ctx.Id_Concurrency)) {
if ((firstModule == concurModule) != (secondModule == concurModule)) {
// If second module is _Concurrency, then it is shadowed by first.
if (secondModule == concurModule) {
shadowed.insert(secondDecl);
continue;
}
// Otherwise, the first declaration is shadowed by the second.
shadowed.insert(firstDecl);
break;
}
}
// Next, prefer any other module over the _StringProcessing module.
if (auto spModule = ctx.getLoadedModule(ctx.Id_StringProcessing)) {
if ((firstModule == spModule) != (secondModule == spModule)) {
// If second module is _StringProcessing, then it is shadowed by
// first.
if (secondModule == spModule) {
shadowed.insert(secondDecl);
continue;
}
// Otherwise, the first declaration is shadowed by the second.
shadowed.insert(firstDecl);
break;
}
}
// Next, prefer any other module over the Observation module.
if (auto obsModule = ctx.getLoadedModule(ctx.Id_Observation)) {
if ((firstModule == obsModule) != (secondModule == obsModule)) {
// If second module is (_)Observation, then it is shadowed by
// first.
if (secondModule == obsModule) {
shadowed.insert(secondDecl);
continue;
}
// Otherwise, the first declaration is shadowed by the second.
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->getName() == secondDecl->getName() &&
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;
}
}
}
}
}
/// Return an extended info for a function types that removes the use of
/// the thrown error type, if present.
///
/// Returns \c None when no adjustment is needed.
static std::optional<ASTExtInfo>
extInfoRemovingThrownError(AnyFunctionType *fnType) {
if (!fnType->hasExtInfo())
return std::nullopt;
auto extInfo = fnType->getExtInfo();
if (!extInfo.isThrowing() || !extInfo.getThrownError())
return std::nullopt;
return extInfo.withThrows(true, Type());
}
/// Remove the thrown error type.
static CanType removeThrownError(Type type) {
return type.transformRec([](TypeBase *type) -> std::optional<Type> {
if (auto funcTy = dyn_cast<FunctionType>(type)) {
if (auto newExtInfo = extInfoRemovingThrownError(funcTy)) {
return FunctionType::get(
funcTy->getParams(), funcTy->getResult(), *newExtInfo)
->getCanonicalType();
}
return std::nullopt;
}
if (auto genericFuncTy = dyn_cast<GenericFunctionType>(type)) {
if (auto newExtInfo = extInfoRemovingThrownError(genericFuncTy)) {
return GenericFunctionType::get(
genericFuncTy->getGenericSignature(),
genericFuncTy->getParams(), genericFuncTy->getResult(),
*newExtInfo)
->getCanonicalType();
}
return std::nullopt;
}
return std::nullopt;
})->getCanonicalType();
}
/// Given a set of declarations whose names and generic signatures have matched,
/// figure out which of these declarations have been shadowed by others.
static void recordShadowedDeclsAfterSignatureMatch(
ArrayRef<ValueDecl *> decls,
const DeclContext *dc,
llvm::SmallPtrSetImpl<ValueDecl *> &shadowed) {
assert(decls.size() > 1 && "Nothing collided");
// Categorize all of the declarations based on their overload types.
llvm::SmallDenseMap<CanType, llvm::TinyPtrVector<ValueDecl *>> collisions;
llvm::SmallVector<CanType, 2> collisionTypes;
for (auto decl : decls) {
assert(!isa<TypeDecl>(decl));
CanType type;
// 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))
type = asd->getOverloadSignatureType();
else
type = removeThrownError(decl->getInterfaceType()->getCanonicalType());
// Strip `@Sendable` annotations for declarations that come from
// or are exposed to Objective-C to make it possible to introduce
// new annotations without breaking shadowing rules.
//
// This is a narrow fix for specific backwards-incompatible cases
// we know about, it could be extended to use `isObjC()` in the
// future if we find problematic cases were a more general change
// is required.
if (decl->hasClangNode() || decl->getAttrs().hasAttribute<ObjCAttr>()) {
type =
type->stripConcurrency(/*recursive=*/true, /*dropGlobalActor=*/false)
->getCanonicalType();
}
// Record this declaration based on its signature.
auto &known = collisions[type];
if (known.size() == 1) {
collisionTypes.push_back(type);
}
known.push_back(decl);
}
// Check whether we have shadowing for signature collisions.
for (auto type : collisionTypes) {
ArrayRef<ValueDecl *> collidingDecls = collisions[type];
recordShadowedDeclsAfterTypeMatch(collidingDecls, dc,
shadowed);
}
}
/// 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 DeclContext *dc,
llvm::SmallPtrSetImpl<ValueDecl *> &shadowed) {
if (decls.size() < 2)
return;
llvm::TinyPtrVector<ValueDecl *> typeDecls;
// Categorize all of the declarations based on their overload signatures.
llvm::SmallDenseMap<const GenericSignatureImpl *,
llvm::TinyPtrVector<ValueDecl *>> collisions;
llvm::SmallVector<const GenericSignatureImpl *, 2> collisionSignatures;
llvm::SmallDenseMap<NominalTypeDecl *,
llvm::TinyPtrVector<ConstructorDecl *>>
importedInitializerCollisions;
llvm::TinyPtrVector<NominalTypeDecl *> importedInitializerCollisionTypes;
for (auto decl : decls) {
if (auto *typeDecl = dyn_cast<TypeDecl>(decl)) {
typeDecls.push_back(typeDecl);
continue;
}
// 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) {
importedInitializerCollisionTypes.push_back(nominal);
}
knownInits.push_back(ctor);
}
}
// 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->isRecursiveValidation())
continue;
// Record this declaration based on its signature.
auto *dc = decl->getInnermostDeclContext();
auto signature = dc->getGenericSignatureOfContext().getCanonicalSignature();
auto &known = collisions[signature.getPointer()];
if (known.size() == 1) {
collisionSignatures.push_back(signature.getPointer());
}
known.push_back(decl);
}
// Check whether we have shadowing for type declarations.
if (typeDecls.size() > 1) {
ArrayRef<ValueDecl *> collidingDecls = typeDecls;
recordShadowedDeclsAfterTypeMatch(collidingDecls, dc, shadowed);
}
// Check whether we have shadowing for signature collisions.
for (auto signature : collisionSignatures) {
ArrayRef<ValueDecl *> collidingDecls = collisions[signature];
recordShadowedDeclsAfterSignatureMatch(collidingDecls, dc, shadowed);
}
// Check whether we have shadowing for imported initializer collisions.
for (auto nominal : importedInitializerCollisionTypes) {
recordShadowedDeclsForImportedInits(importedInitializerCollisions[nominal],
shadowed);
}
}
static void
recordShadowedDecls(ArrayRef<OperatorDecl *> decls, const DeclContext *dc,
llvm::SmallPtrSetImpl<OperatorDecl *> &shadowed) {
// Always considered to have the same signature.
recordShadowedDeclsAfterTypeMatch(decls, dc, shadowed);
}
static void
recordShadowedDecls(ArrayRef<PrecedenceGroupDecl *> decls,
const DeclContext *dc,
llvm::SmallPtrSetImpl<PrecedenceGroupDecl *> &shadowed) {
// Always considered to have the same type.
recordShadowedDeclsAfterTypeMatch(decls, dc, shadowed);
}
template <typename T, typename Container>
static bool removeShadowedDeclsImpl(Container &decls, const DeclContext *dc) {
// Collect declarations with the same (full) name.
llvm::SmallDenseMap<DeclName, llvm::TinyPtrVector<T>> collidingDeclGroups;
bool anyCollisions = false;
for (auto decl : decls) {
// Record this declaration based on its full name.
auto &knownDecls = collidingDeclGroups[decl->getName()];
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<T, 4> shadowed;
for (auto decl : decls) {
auto known = collidingDeclGroups.find(decl->getName());