forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathModule.cpp
1632 lines (1385 loc) · 55.2 KB
/
Module.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
//===--- Module.cpp - Swift Language Module Implementation ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Module class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Module.h"
#include "swift/AST/AST.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/LinkLibrary.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PrintOptions.h"
#include "swift/Basic/SourceManager.h"
#include "clang/Basic/Module.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Builtin Module Name lookup
//===----------------------------------------------------------------------===//
class BuiltinUnit::LookupCache {
/// The cache of identifiers we've already looked up. We use a
/// single hashtable for both types and values as a minor
/// optimization; this prevents us from having both a builtin type
/// and a builtin value with the same name, but that's okay.
llvm::DenseMap<Identifier, ValueDecl*> Cache;
public:
void lookupValue(Identifier Name, NLKind LookupKind, const BuiltinUnit &M,
SmallVectorImpl<ValueDecl*> &Result);
};
BuiltinUnit::LookupCache &BuiltinUnit::getCache() const {
// FIXME: This leaks. Sticking this into ASTContext isn't enough because then
// the DenseMap will leak.
if (!Cache)
const_cast<BuiltinUnit *>(this)->Cache = llvm::make_unique<LookupCache>();
return *Cache;
}
void BuiltinUnit::LookupCache::lookupValue(
Identifier Name, NLKind LookupKind, const BuiltinUnit &M,
SmallVectorImpl<ValueDecl*> &Result) {
// Only qualified lookup ever finds anything in the builtin module.
if (LookupKind != NLKind::QualifiedLookup) return;
ValueDecl *&Entry = Cache[Name];
ASTContext &Ctx = M.getParentModule()->getASTContext();
if (!Entry) {
if (Type Ty = getBuiltinType(Ctx, Name.str())) {
TypeAliasDecl *TAD = new (Ctx) TypeAliasDecl(SourceLoc(), Name,
SourceLoc(),
TypeLoc::withoutLoc(Ty),
const_cast<BuiltinUnit*>(&M));
TAD->computeType();
TAD->setAccessibility(Accessibility::Public);
Entry = TAD;
}
}
if (!Entry)
Entry = getBuiltinValueDecl(Ctx, Name);
if (Entry)
Result.push_back(Entry);
}
// Out-of-line because std::unique_ptr wants LookupCache to be complete.
BuiltinUnit::BuiltinUnit(ModuleDecl &M)
: FileUnit(FileUnitKind::Builtin, M) {
M.getASTContext().addDestructorCleanup(*this);
}
//===----------------------------------------------------------------------===//
// Normal Module Name Lookup
//===----------------------------------------------------------------------===//
class SourceFile::LookupCache {
/// A lookup map for value decls. When declarations are added they are added
/// under all variants of the name they can be found under.
class DeclMap {
llvm::DenseMap<DeclName, TinyPtrVector<ValueDecl*>> Members;
public:
void add(ValueDecl *VD) {
if (!VD->hasName()) return;
VD->getFullName().addToLookupTable(Members, VD);
}
void clear() {
Members.shrink_and_clear();
}
decltype(Members)::const_iterator begin() const { return Members.begin(); }
decltype(Members)::const_iterator end() const { return Members.end(); }
decltype(Members)::const_iterator find(DeclName Name) const {
return Members.find(Name);
}
};
DeclMap TopLevelValues;
DeclMap ClassMembers;
bool MemberCachePopulated = false;
template<typename Range>
void doPopulateCache(Range decls, bool onlyOperators);
void addToMemberCache(DeclRange decls);
void populateMemberCache(const SourceFile &SF);
public:
typedef ModuleDecl::AccessPathTy AccessPathTy;
LookupCache(const SourceFile &SF);
/// Throw away as much memory as possible.
void invalidate();
void lookupValue(AccessPathTy AccessPath, DeclName Name,
NLKind LookupKind, SmallVectorImpl<ValueDecl*> &Result);
void lookupVisibleDecls(AccessPathTy AccessPath,
VisibleDeclConsumer &Consumer,
NLKind LookupKind);
void lookupClassMembers(AccessPathTy AccessPath,
VisibleDeclConsumer &consumer,
const SourceFile &SF);
void lookupClassMember(AccessPathTy accessPath,
DeclName name,
SmallVectorImpl<ValueDecl*> &results,
const SourceFile &SF);
SmallVector<ValueDecl *, 0> AllVisibleValues;
};
using SourceLookupCache = SourceFile::LookupCache;
SourceLookupCache &SourceFile::getCache() const {
if (!Cache) {
const_cast<SourceFile *>(this)->Cache =
llvm::make_unique<SourceLookupCache>(*this);
}
return *Cache;
}
template<typename Range>
void SourceLookupCache::doPopulateCache(Range decls,
bool onlyOperators) {
for (Decl *D : decls) {
if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
if (onlyOperators ? VD->getName().isOperator() : VD->hasName()) {
// Cache the value under both its compound name and its full name.
TopLevelValues.add(VD);
}
if (NominalTypeDecl *NTD = dyn_cast<NominalTypeDecl>(D))
doPopulateCache(NTD->getMembers(), true);
if (ExtensionDecl *ED = dyn_cast<ExtensionDecl>(D))
doPopulateCache(ED->getMembers(), true);
}
}
void SourceLookupCache::populateMemberCache(const SourceFile &SF) {
for (const Decl *D : SF.Decls) {
if (const NominalTypeDecl *NTD = dyn_cast<NominalTypeDecl>(D)) {
addToMemberCache(NTD->getMembers());
} else if (const ExtensionDecl *ED = dyn_cast<ExtensionDecl>(D)) {
addToMemberCache(ED->getMembers());
}
}
MemberCachePopulated = true;
}
void SourceLookupCache::addToMemberCache(DeclRange decls) {
for (Decl *D : decls) {
auto VD = dyn_cast<ValueDecl>(D);
if (!VD)
continue;
if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {
assert(!VD->canBeAccessedByDynamicLookup() &&
"inner types cannot be accessed by dynamic lookup");
addToMemberCache(NTD->getMembers());
} else if (VD->canBeAccessedByDynamicLookup()) {
ClassMembers.add(VD);
}
}
}
/// Populate our cache on the first name lookup.
SourceLookupCache::LookupCache(const SourceFile &SF) {
doPopulateCache(llvm::makeArrayRef(SF.Decls), false);
}
void SourceLookupCache::lookupValue(AccessPathTy AccessPath, DeclName Name,
NLKind LookupKind,
SmallVectorImpl<ValueDecl*> &Result) {
// If this import is specific to some named type or decl ("import Swift.int")
// then filter out any lookups that don't match.
if (!ModuleDecl::matchesAccessPath(AccessPath, Name))
return;
auto I = TopLevelValues.find(Name);
if (I == TopLevelValues.end()) return;
Result.reserve(I->second.size());
for (ValueDecl *Elt : I->second)
Result.push_back(Elt);
}
void SourceLookupCache::lookupVisibleDecls(AccessPathTy AccessPath,
VisibleDeclConsumer &Consumer,
NLKind LookupKind) {
assert(AccessPath.size() <= 1 && "can only refer to top-level decls");
if (!AccessPath.empty()) {
auto I = TopLevelValues.find(AccessPath.front().first);
if (I == TopLevelValues.end()) return;
for (auto vd : I->second)
Consumer.foundDecl(vd, DeclVisibilityKind::VisibleAtTopLevel);
return;
}
for (auto &tlv : TopLevelValues) {
for (ValueDecl *vd : tlv.second) {
// Declarations are added under their full and simple names. Skip the
// entry for the simple name so that we report each declaration once.
if (tlv.first.isSimpleName() && !vd->getFullName().isSimpleName())
continue;
Consumer.foundDecl(vd, DeclVisibilityKind::VisibleAtTopLevel);
}
}
}
void SourceLookupCache::lookupClassMembers(AccessPathTy accessPath,
VisibleDeclConsumer &consumer,
const SourceFile &SF) {
if (!MemberCachePopulated)
populateMemberCache(SF);
assert(accessPath.size() <= 1 && "can only refer to top-level decls");
if (!accessPath.empty()) {
for (auto &member : ClassMembers) {
// Non-simple names are also stored under their simple name, so make
// sure to only report them once.
if (!member.first.isSimpleName())
continue;
for (ValueDecl *vd : member.second) {
Type ty = vd->getDeclContext()->getDeclaredTypeOfContext();
if (auto nominal = ty->getAnyNominal())
if (nominal->getName() == accessPath.front().first)
consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup);
}
}
return;
}
for (auto &member : ClassMembers) {
// Non-simple names are also stored under their simple name, so make sure to
// only report them once.
if (!member.first.isSimpleName())
continue;
for (ValueDecl *vd : member.second)
consumer.foundDecl(vd, DeclVisibilityKind::DynamicLookup);
}
}
void SourceLookupCache::lookupClassMember(AccessPathTy accessPath,
DeclName name,
SmallVectorImpl<ValueDecl*> &results,
const SourceFile &SF) {
if (!MemberCachePopulated)
populateMemberCache(SF);
assert(accessPath.size() <= 1 && "can only refer to top-level decls");
auto iter = ClassMembers.find(name);
if (iter == ClassMembers.end())
return;
if (!accessPath.empty()) {
for (ValueDecl *vd : iter->second) {
Type ty = vd->getDeclContext()->getDeclaredTypeOfContext();
if (auto nominal = ty->getAnyNominal())
if (nominal->getName() == accessPath.front().first)
results.push_back(vd);
}
return;
}
results.append(iter->second.begin(), iter->second.end());
}
void SourceLookupCache::invalidate() {
TopLevelValues.clear();
ClassMembers.clear();
MemberCachePopulated = false;
// std::move AllVisibleValues into a temporary to destroy its contents.
using SameSizeSmallVector = decltype(AllVisibleValues);
(void)SameSizeSmallVector{std::move(AllVisibleValues)};
}
//===----------------------------------------------------------------------===//
// Module Implementation
//===----------------------------------------------------------------------===//
ModuleDecl::ModuleDecl(Identifier name, ASTContext &ctx)
: TypeDecl(DeclKind::Module, &ctx, name, SourceLoc(), { }),
DeclContext(DeclContextKind::Module, nullptr) {
ctx.addDestructorCleanup(*this);
setImplicit();
setType(ModuleType::get(this));
setAccessibility(Accessibility::Public);
}
void Module::addFile(FileUnit &newFile) {
assert(!isa<DerivedFileUnit>(newFile) &&
"DerivedFileUnits are added automatically");
// Require Main and REPL files to be the first file added.
assert(Files.empty() ||
!isa<SourceFile>(newFile) ||
cast<SourceFile>(newFile).Kind == SourceFileKind::Library ||
cast<SourceFile>(newFile).Kind == SourceFileKind::SIL);
Files.push_back(&newFile);
switch (newFile.getKind()) {
case FileUnitKind::Source:
case FileUnitKind::ClangModule: {
for (auto File : Files) {
if (isa<DerivedFileUnit>(File))
return;
}
auto DFU = new (getASTContext()) DerivedFileUnit(*this);
Files.push_back(DFU);
break;
}
case FileUnitKind::Builtin:
case FileUnitKind::SerializedAST:
break;
case FileUnitKind::Derived:
llvm_unreachable("DerivedFileUnits are added automatically");
}
}
void Module::removeFile(FileUnit &existingFile) {
// Do a reverse search; usually the file to be deleted will be at the end.
std::reverse_iterator<decltype(Files)::iterator> I(Files.end()),
E(Files.begin());
I = std::find(I, E, &existingFile);
assert(I != E);
// Adjust for the std::reverse_iterator offset.
++I;
Files.erase(I.base());
}
DerivedFileUnit &Module::getDerivedFileUnit() const {
for (auto File : Files) {
if (auto DFU = dyn_cast<DerivedFileUnit>(File))
return *DFU;
}
llvm_unreachable("the client should not be calling this function if "
"there is no DerivedFileUnit");
}
VarDecl *Module::getDSOHandle() {
if (DSOHandleAndFlags.getPointer())
return DSOHandleAndFlags.getPointer();
auto unsafeMutablePtr = getASTContext().getUnsafeMutablePointerDecl();
if (!unsafeMutablePtr)
return nullptr;
Type arg;
auto &ctx = getASTContext();
if (auto voidDecl = ctx.getVoidDecl()) {
arg = voidDecl->getDeclaredInterfaceType();
} else {
arg = TupleType::getEmpty(ctx);
}
Type type = BoundGenericType::get(unsafeMutablePtr, Type(), { arg });
auto handleVar = new (ctx) VarDecl(/*IsStatic=*/false, /*IsLet=*/false,
SourceLoc(),
ctx.getIdentifier("__dso_handle"),
type, Files[0]);
handleVar->setImplicit(true);
handleVar->getAttrs().add(
new (ctx) SILGenNameAttr("__dso_handle", /*Implicit=*/true));
handleVar->setAccessibility(Accessibility::Internal);
DSOHandleAndFlags.setPointer(handleVar);
return handleVar;
}
#define FORWARD(name, args) \
for (const FileUnit *file : getFiles()) \
file->name args;
void Module::lookupValue(AccessPathTy AccessPath, DeclName Name,
NLKind LookupKind,
SmallVectorImpl<ValueDecl*> &Result) const {
FORWARD(lookupValue, (AccessPath, Name, LookupKind, Result));
}
TypeDecl * Module::lookupLocalType(StringRef MangledName) const {
for (auto file : getFiles()) {
auto TD = file->lookupLocalType(MangledName);
if (TD)
return TD;
}
return nullptr;
}
void Module::lookupMember(SmallVectorImpl<ValueDecl*> &results,
DeclContext *container, DeclName name,
Identifier privateDiscriminator) const {
size_t oldSize = results.size();
bool alreadyInPrivateContext = false;
switch (container->getContextKind()) {
case DeclContextKind::SerializedLocal:
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::Initializer:
case DeclContextKind::TopLevelCodeDecl:
case DeclContextKind::AbstractFunctionDecl:
llvm_unreachable("This context does not support lookup.");
case DeclContextKind::FileUnit:
llvm_unreachable("Use FileUnit::lookupValue instead.");
case DeclContextKind::ExtensionDecl:
llvm_unreachable("Use ExtensionDecl::lookupDirect instead.");
case DeclContextKind::Module: {
assert(container == this);
this->lookupValue({}, name, NLKind::QualifiedLookup, results);
break;
}
case DeclContextKind::NominalTypeDecl: {
auto nominal = cast<NominalTypeDecl>(container);
auto lookupResults = nominal->lookupDirect(name);
// Filter out declarations from other modules.
std::copy_if(lookupResults.begin(), lookupResults.end(),
std::back_inserter(results),
[this](const ValueDecl *VD) -> bool {
return VD->getModuleContext() == this;
});
alreadyInPrivateContext =
(nominal->getFormalAccess() == Accessibility::Private);
break;
}
}
// Filter by private-discriminator, or filter out private decls if there isn't
// one...unless we're already in a private context, in which case everything
// is private and a discriminator is unnecessary.
if (alreadyInPrivateContext) {
assert(privateDiscriminator.empty() && "unnecessary private-discriminator");
// Don't remove anything; everything here is private anyway.
} else if (privateDiscriminator.empty()) {
auto newEnd = std::remove_if(results.begin()+oldSize, results.end(),
[](const ValueDecl *VD) -> bool {
return VD->getFormalAccess() <= Accessibility::Private;
});
results.erase(newEnd, results.end());
} else {
auto newEnd = std::remove_if(results.begin()+oldSize, results.end(),
[=](const ValueDecl *VD) -> bool {
if (VD->getFormalAccess() > Accessibility::Private)
return true;
auto enclosingFile =
cast<FileUnit>(VD->getDeclContext()->getModuleScopeContext());
auto discriminator = enclosingFile->getDiscriminatorForPrivateValue(VD);
return discriminator != privateDiscriminator;
});
results.erase(newEnd, results.end());
}
}
void BuiltinUnit::lookupValue(Module::AccessPathTy accessPath, DeclName name,
NLKind lookupKind,
SmallVectorImpl<ValueDecl*> &result) const {
getCache().lookupValue(name.getBaseName(), lookupKind, *this, result);
}
DerivedFileUnit::DerivedFileUnit(Module &M)
: FileUnit(FileUnitKind::Derived, M) {
M.getASTContext().addDestructorCleanup(*this);
}
void DerivedFileUnit::lookupValue(Module::AccessPathTy accessPath,
DeclName name,
NLKind lookupKind,
SmallVectorImpl<ValueDecl*> &result) const {
// If this import is specific to some named type or decl ("import Swift.int")
// then filter out any lookups that don't match.
if (!Module::matchesAccessPath(accessPath, name))
return;
for (auto D : DerivedDecls) {
if (D->getFullName().matchesRef(name))
result.push_back(D);
}
}
void DerivedFileUnit::lookupVisibleDecls(Module::AccessPathTy accessPath,
VisibleDeclConsumer &consumer,
NLKind lookupKind) const {
assert(accessPath.size() <= 1 && "can only refer to top-level decls");
Identifier Id;
if (!accessPath.empty()) {
Id = accessPath.front().first;
}
for (auto D : DerivedDecls) {
if (Id.empty() || D->getName() == Id)
consumer.foundDecl(D, DeclVisibilityKind::VisibleAtTopLevel);
}
}
void DerivedFileUnit::getTopLevelDecls(SmallVectorImpl<swift::Decl *> &results)
const {
results.append(DerivedDecls.begin(), DerivedDecls.end());
}
void SourceFile::lookupValue(Module::AccessPathTy accessPath, DeclName name,
NLKind lookupKind,
SmallVectorImpl<ValueDecl*> &result) const {
getCache().lookupValue(accessPath, name, lookupKind, result);
}
void Module::lookupVisibleDecls(AccessPathTy AccessPath,
VisibleDeclConsumer &Consumer,
NLKind LookupKind) const {
FORWARD(lookupVisibleDecls, (AccessPath, Consumer, LookupKind));
}
void SourceFile::lookupVisibleDecls(Module::AccessPathTy AccessPath,
VisibleDeclConsumer &Consumer,
NLKind LookupKind) const {
getCache().lookupVisibleDecls(AccessPath, Consumer, LookupKind);
}
void Module::lookupClassMembers(AccessPathTy accessPath,
VisibleDeclConsumer &consumer) const {
FORWARD(lookupClassMembers, (accessPath, consumer));
}
void SourceFile::lookupClassMembers(Module::AccessPathTy accessPath,
VisibleDeclConsumer &consumer) const {
getCache().lookupClassMembers(accessPath, consumer, *this);
}
void Module::lookupClassMember(AccessPathTy accessPath,
DeclName name,
SmallVectorImpl<ValueDecl*> &results) const {
FORWARD(lookupClassMember, (accessPath, name, results));
}
void SourceFile::lookupClassMember(Module::AccessPathTy accessPath,
DeclName name,
SmallVectorImpl<ValueDecl*> &results) const {
getCache().lookupClassMember(accessPath, name, results, *this);
}
void Module::getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &Results) const {
FORWARD(getLocalTypeDecls, (Results));
}
void Module::getTopLevelDecls(SmallVectorImpl<Decl*> &Results) const {
FORWARD(getTopLevelDecls, (Results));
}
void SourceFile::getTopLevelDecls(SmallVectorImpl<Decl*> &Results) const {
Results.append(Decls.begin(), Decls.end());
}
void SourceFile::getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &Results) const {
Results.append(LocalTypeDecls.begin(), LocalTypeDecls.end());
}
void Module::getDisplayDecls(SmallVectorImpl<Decl*> &Results) const {
// FIXME: Should this do extra access control filtering?
FORWARD(getDisplayDecls, (Results));
}
DeclContext *BoundGenericType::getGenericParamContext(
DeclContext *gpContext) const {
// If no context was provided, use the declaration itself.
if (!gpContext)
return getDecl();
assert(gpContext->getDeclaredTypeOfContext()->getAnyNominal() == getDecl() &&
"not a valid context");
return gpContext;
}
ArrayRef<Substitution> BoundGenericType::getSubstitutions(
Module *module,
LazyResolver *resolver,
DeclContext *gpContext) {
// FIXME: If there is no module, infer one. This is a hack for callers that
// don't have access to the module. It will have to go away once we're
// properly differentiating bound generic types based on the protocol
// conformances visible from a given module.
if (!module) {
module = getDecl()->getParentModule();
}
// Check the context, introducing the default if needed.
gpContext = getGenericParamContext(gpContext);
// If we already have a cached copy of the substitutions, return them.
auto *canon = getCanonicalType()->castTo<BoundGenericType>();
const ASTContext &ctx = canon->getASTContext();
if (auto known = ctx.getSubstitutions(canon, gpContext))
return *known;
// Compute the set of substitutions.
llvm::SmallPtrSet<ArchetypeType *, 8> knownArchetypes;
SmallVector<ArchetypeType *, 8> archetypeStack;
TypeSubstitutionMap substitutions;
auto genericParams = gpContext->getGenericParamsOfContext();
unsigned index = 0;
for (Type arg : canon->getGenericArgs()) {
auto gp = genericParams->getParams()[index++];
auto archetype = gp->getArchetype();
substitutions[archetype] = arg;
}
// Collect all of the archetypes.
SmallVector<ArchetypeType *, 2> allArchetypesList;
ArrayRef<ArchetypeType *> allArchetypes = genericParams->getAllArchetypes();
if (genericParams->getOuterParameters()) {
SmallVector<const GenericParamList *, 2> allGenericParams;
unsigned numArchetypes = 0;
for (; genericParams; genericParams = genericParams->getOuterParameters()) {
allGenericParams.push_back(genericParams);
numArchetypes += genericParams->getAllArchetypes().size();
}
allArchetypesList.reserve(numArchetypes);
for (auto gp = allGenericParams.rbegin(), gpEnd = allGenericParams.rend();
gp != gpEnd; ++gp) {
allArchetypesList.append((*gp)->getAllArchetypes().begin(),
(*gp)->getAllArchetypes().end());
}
allArchetypes = allArchetypesList;
}
// For each of the archetypes, compute the substitution.
bool hasTypeVariables = canon->hasTypeVariable();
SmallVector<Substitution, 4> resultSubstitutions;
resultSubstitutions.resize(allArchetypes.size());
index = 0;
for (auto archetype : allArchetypes) {
// Substitute into the type.
SubstOptions options;
if (hasTypeVariables)
options |= SubstFlags::IgnoreMissing;
auto type = Type(archetype).subst(module, substitutions, options);
if (!type)
type = ErrorType::get(module->getASTContext());
SmallVector<ProtocolConformance *, 4> conformances;
if (type->is<TypeVariableType>() || type->isTypeParameter()) {
// If the type is a type variable or is dependent, just fill in null
// conformances. FIXME: It seems like we should record these as
// requirements (?).
conformances.assign(archetype->getConformsTo().size(), nullptr);
} else {
// Find the conformances.
for (auto proto : archetype->getConformsTo()) {
auto conforms = module->lookupConformance(type, proto, resolver);
switch (conforms.getInt()) {
case ConformanceKind::Conforms:
conformances.push_back(conforms.getPointer());
break;
case ConformanceKind::UncheckedConforms:
conformances.push_back(nullptr);
break;
case ConformanceKind::DoesNotConform:
conformances.push_back(nullptr);
break;
}
}
}
// Record this substitution.
resultSubstitutions[index] = {archetype, type,
ctx.AllocateCopy(conformances)};
++index;
}
// Before recording substitutions, make sure we didn't end up doing it
// recursively.
if (auto known = ctx.getSubstitutions(canon, gpContext))
return *known;
// Copy and record the substitutions.
auto permanentSubs = ctx.AllocateCopy(resultSubstitutions,
hasTypeVariables
? AllocationArena::ConstraintSolver
: AllocationArena::Permanent);
ctx.setSubstitutions(canon, gpContext, permanentSubs);
return permanentSubs;
}
LookupConformanceResult Module::lookupConformance(Type type,
ProtocolDecl *protocol,
LazyResolver *resolver) {
ASTContext &ctx = getASTContext();
// An archetype conforms to a protocol if the protocol is listed in the
// archetype's list of conformances.
if (auto archetype = type->getAs<ArchetypeType>()) {
if (protocol->isSpecificProtocol(KnownProtocolKind::AnyObject)) {
if (archetype->requiresClass())
return { nullptr, ConformanceKind::Conforms };
return { nullptr, ConformanceKind::DoesNotConform };
}
for (auto ap : archetype->getConformsTo()) {
if (ap == protocol || ap->inheritsFrom(protocol))
return { nullptr, ConformanceKind::Conforms };
}
if (!archetype->getSuperclass()) {
return { nullptr, ConformanceKind::DoesNotConform };
}
}
// An existential conforms to a protocol if the protocol is listed in the
// existential's list of conformances and the existential conforms to
// itself.
if (type->isExistentialType()) {
SmallVector<ProtocolDecl *, 4> protocols;
type->getAnyExistentialTypeProtocols(protocols);
// Due to an IRGen limitation, witness tables cannot be passed from an
// existential to an archetype parameter, so for now we restrict this to
// @objc protocols.
for (auto proto : protocols) {
if (!proto->isObjC() &&
!proto->isSpecificProtocol(KnownProtocolKind::AnyObject))
return { nullptr, ConformanceKind::DoesNotConform };
}
// If the existential type cannot be represented or the protocol does not
// conform to itself, there's no point in looking further.
if (!protocol->existentialConformsToSelf() ||
!protocol->existentialTypeSupported(resolver))
return { nullptr, ConformanceKind::DoesNotConform };
// Special-case AnyObject, which may not be in the list of conformances.
if (protocol->isSpecificProtocol(KnownProtocolKind::AnyObject)) {
return { nullptr, type->isClassExistentialType()
? ConformanceKind::Conforms
: ConformanceKind::DoesNotConform };
}
// Look for this protocol within the existential's list of conformances.
for (auto proto : protocols) {
if (proto == protocol || proto->inheritsFrom(protocol)) {
return { nullptr, ConformanceKind::Conforms };
}
}
// We didn't find our protocol in the existential's list; it doesn't
// conform.
return { nullptr, ConformanceKind::DoesNotConform };
}
// Check for protocol conformance of archetype via superclass requirement.
if (auto archetype = type->getAs<ArchetypeType>()) {
if (auto super = archetype->getSuperclass()) {
auto inheritedConformance = lookupConformance(super, protocol, resolver);
switch (inheritedConformance.getInt()) {
case ConformanceKind::DoesNotConform:
return { nullptr, ConformanceKind::DoesNotConform };
case ConformanceKind::UncheckedConforms:
return inheritedConformance;
case ConformanceKind::Conforms:
auto result =
ctx.getInheritedConformance(type, inheritedConformance.getPointer());
return { result, ConformanceKind::Conforms };
}
}
}
// UnresolvedType is a placeholder for an unknown type used when generating
// diagnostics. We consider it to conform to all protocols, since the
// intended type might have.
if (type->is<UnresolvedType>()) {
return {
ctx.getConformance(type, protocol, protocol->getLoc(), this,
ProtocolConformanceState::Complete),
ConformanceKind::Conforms
};
}
auto nominal = type->getAnyNominal();
// If we don't have a nominal type, there are no conformances.
// FIXME: We may have implicit conformances for some cases. Handle those
// here.
if (!nominal) {
return { nullptr, ConformanceKind::DoesNotConform };
}
// Find the (unspecialized) conformance.
SmallVector<ProtocolConformance *, 2> conformances;
if (!nominal->lookupConformance(this, protocol, conformances))
return { nullptr, ConformanceKind::DoesNotConform };
// FIXME: Ambiguity resolution.
auto conformance = conformances.front();
// Rebuild inherited conformances based on the root normal conformance.
// FIXME: This is a hack to work around our inability to handle multiple
// levels of substitution through inherited conformances elsewhere in the
// compiler.
if (auto inherited = dyn_cast<InheritedProtocolConformance>(conformance)) {
// Dig out the conforming nominal type.
auto rootConformance = inherited->getRootNormalConformance();
auto conformingNominal
= rootConformance->getType()->getClassOrBoundGenericClass();
// Map up to our superclass's type.
Type superclassTy = type->getSuperclass(resolver);
while (superclassTy->getAnyNominal() != conformingNominal)
superclassTy = superclassTy->getSuperclass(resolver);
// Compute the conformance for the inherited type.
auto inheritedConformance = lookupConformance(superclassTy, protocol,
resolver);
switch (inheritedConformance.getInt()) {
case ConformanceKind::DoesNotConform:
llvm_unreachable("We already found the inherited conformance");
case ConformanceKind::UncheckedConforms:
return inheritedConformance;
case ConformanceKind::Conforms:
// Create inherited conformance below.
break;
}
// Create the inherited conformance entry.
conformance
= ctx.getInheritedConformance(type, inheritedConformance.getPointer());
return { conformance, ConformanceKind::Conforms };
}
// If the type is specialized, find the conformance for the generic type.
if (type->isSpecialized()) {
// Figure out the type that's explicitly conforming to this protocol.
Type explicitConformanceType = conformance->getType();
DeclContext *explicitConformanceDC = conformance->getDeclContext();
// If the explicit conformance is associated with a type that is different
// from the type we're checking, retrieve generic conformance.
if (!explicitConformanceType->isEqual(type)) {
// Gather the substitutions we need to map the generic conformance to
// the specialized conformance.
SmallVector<Substitution, 4> substitutionsVec;
auto substitutions = type->gatherAllSubstitutions(this, substitutionsVec,
resolver,
explicitConformanceDC);
// Create the specialized conformance entry.
auto result = ctx.getSpecializedConformance(type, conformance,
substitutions);
return { result, ConformanceKind::Conforms };
}
}
// Record and return the simple conformance.
return { conformance, ConformanceKind::Conforms };
}
namespace {
template <typename T>
using OperatorMap = SourceFile::OperatorMap<T>;
template <typename T>
struct OperatorKind {
static_assert(static_cast<T*>(nullptr), "Only usable with operators");
};
template <>
struct OperatorKind<PrefixOperatorDecl> {
static const auto value = DeclKind::PrefixOperator;
};
template <>
struct OperatorKind<InfixOperatorDecl> {
static const auto value = DeclKind::InfixOperator;
};
template <>
struct OperatorKind<PostfixOperatorDecl> {
static const auto value = DeclKind::PostfixOperator;
};
}
template <typename Op, typename T>
static Op *lookupOperator(T &container, Identifier name) {
return cast_or_null<Op>(container.lookupOperator(name,
OperatorKind<Op>::value));
}
/// A helper class to sneak around C++ access control rules.
class SourceFile::Impl {
public:
/// Only intended for use by lookupOperatorDeclForName.
static ArrayRef<std::pair<Module::ImportedModule, SourceFile::ImportOptions>>
getImportsForSourceFile(const SourceFile &SF) {
return SF.Imports;
}
};
template<typename OP_DECL>
static Optional<OP_DECL *>
lookupOperatorDeclForName(Module *M, SourceLoc Loc, Identifier Name,
OperatorMap<OP_DECL *> SourceFile::*OP_MAP);
// Returns None on error, Optional(nullptr) if no operator decl found, or
// Optional(decl) if decl was found.
template<typename OP_DECL>
static Optional<OP_DECL *>
lookupOperatorDeclForName(const FileUnit &File, SourceLoc Loc, Identifier Name,
bool includePrivate,
OperatorMap<OP_DECL *> SourceFile::*OP_MAP)
{
switch (File.getKind()) {
case FileUnitKind::Builtin:
case FileUnitKind::Derived:
// The Builtin module declares no operators, nor do derived units.
return nullptr;
case FileUnitKind::Source:
break;
case FileUnitKind::SerializedAST:
case FileUnitKind::ClangModule:
return lookupOperator<OP_DECL>(cast<LoadedFile>(File), Name);
}
auto &SF = cast<SourceFile>(File);
assert(SF.ASTStage >= SourceFile::NameBound);
// Look for an operator declaration in the current module.
auto found = (SF.*OP_MAP).find(Name);
if (found != (SF.*OP_MAP).end() && (includePrivate || found->second.getInt()))
return found->second.getPointer();
// Look for imported operator decls.
// Record whether they come from re-exported modules.