forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDecl.cpp
4372 lines (3678 loc) · 144 KB
/
Decl.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
//===--- Decl.cpp - Swift Language Decl ASTs ------------------------------===//
//
// 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 Decl class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Decl.h"
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/AST.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/TypeLoc.h"
#include "clang/Lex/MacroInfo.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/raw_ostream.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Basic/Fallthrough.h"
#include "clang/Basic/CharInfo.h"
#include "clang/AST/DeclObjC.h"
#include <algorithm>
using namespace swift;
bool impl::isTestingEnabled(const ValueDecl *VD) {
return VD->getModuleContext()->isTestingEnabled();
}
clang::SourceLocation ClangNode::getLocation() const {
if (auto D = getAsDecl())
return D->getLocation();
if (auto M = getAsMacro())
return M->getDefinitionLoc();
return clang::SourceLocation();
}
clang::SourceRange ClangNode::getSourceRange() const {
if (auto D = getAsDecl())
return D->getSourceRange();
if (auto M = getAsMacro())
return clang::SourceRange(M->getDefinitionLoc(), M->getDefinitionEndLoc());
return clang::SourceLocation();
}
const clang::Module *ClangNode::getClangModule() const {
if (auto *M = getAsModule())
return M;
if (auto *ID = dyn_cast_or_null<clang::ImportDecl>(getAsDecl()))
return ID->getImportedModule();
return nullptr;
}
// Only allow allocation of Decls using the allocator in ASTContext.
void *Decl::operator new(size_t Bytes, ASTContext &C,
unsigned Alignment) {
return C.Allocate(Bytes, Alignment);
}
// Only allow allocation of Modules using the allocator in ASTContext.
void *Module::operator new(size_t Bytes, ASTContext &C,
unsigned Alignment) {
return C.Allocate(Bytes, Alignment);
}
StringRef Decl::getKindName(DeclKind K) {
switch (K) {
#define DECL(Id, Parent) case DeclKind::Id: return #Id;
#include "swift/AST/DeclNodes.def"
}
llvm_unreachable("bad DeclKind");
}
DescriptiveDeclKind Decl::getDescriptiveKind() const {
#define TRIVIAL_KIND(Kind) \
case DeclKind::Kind: \
return DescriptiveDeclKind::Kind
switch (getKind()) {
TRIVIAL_KIND(Import);
TRIVIAL_KIND(Extension);
TRIVIAL_KIND(EnumCase);
TRIVIAL_KIND(TopLevelCode);
TRIVIAL_KIND(IfConfig);
TRIVIAL_KIND(PatternBinding);
TRIVIAL_KIND(InfixOperator);
TRIVIAL_KIND(PrefixOperator);
TRIVIAL_KIND(PostfixOperator);
TRIVIAL_KIND(TypeAlias);
TRIVIAL_KIND(GenericTypeParam);
TRIVIAL_KIND(AssociatedType);
TRIVIAL_KIND(Protocol);
TRIVIAL_KIND(Subscript);
TRIVIAL_KIND(Constructor);
TRIVIAL_KIND(Destructor);
TRIVIAL_KIND(EnumElement);
TRIVIAL_KIND(Param);
TRIVIAL_KIND(Module);
case DeclKind::Enum:
return cast<EnumDecl>(this)->getGenericParams()
? DescriptiveDeclKind::GenericEnum
: DescriptiveDeclKind::Enum;
case DeclKind::Struct:
return cast<StructDecl>(this)->getGenericParams()
? DescriptiveDeclKind::GenericStruct
: DescriptiveDeclKind::Struct;
case DeclKind::Class:
return cast<ClassDecl>(this)->getGenericParams()
? DescriptiveDeclKind::GenericClass
: DescriptiveDeclKind::Class;
case DeclKind::Var: {
auto var = cast<VarDecl>(this);
switch (var->getCorrectStaticSpelling()) {
case StaticSpellingKind::None:
return var->isLet()? DescriptiveDeclKind::Let
: DescriptiveDeclKind::Var;
case StaticSpellingKind::KeywordStatic:
return var->isLet()? DescriptiveDeclKind::StaticLet
: DescriptiveDeclKind::StaticVar;
case StaticSpellingKind::KeywordClass:
return var->isLet()? DescriptiveDeclKind::ClassLet
: DescriptiveDeclKind::ClassVar;
}
}
case DeclKind::Func: {
auto func = cast<FuncDecl>(this);
// First, check for an accessor.
switch (func->getAccessorKind()) {
case AccessorKind::NotAccessor:
// Other classifications below.
break;
case AccessorKind::IsGetter:
return DescriptiveDeclKind::Getter;
case AccessorKind::IsSetter:
return DescriptiveDeclKind::Setter;
case AccessorKind::IsWillSet:
return DescriptiveDeclKind::WillSet;
case AccessorKind::IsDidSet:
return DescriptiveDeclKind::DidSet;
case AccessorKind::IsAddressor:
return DescriptiveDeclKind::Addressor;
case AccessorKind::IsMutableAddressor:
return DescriptiveDeclKind::MutableAddressor;
case AccessorKind::IsMaterializeForSet:
return DescriptiveDeclKind::MaterializeForSet;
}
if (!func->getName().empty() && func->getName().isOperator())
return DescriptiveDeclKind::OperatorFunction;
if (func->getDeclContext()->isLocalContext())
return DescriptiveDeclKind::LocalFunction;
if (func->getDeclContext()->isModuleScopeContext())
return DescriptiveDeclKind::GlobalFunction;
// We have a method.
switch (func->getCorrectStaticSpelling()) {
case StaticSpellingKind::None:
return DescriptiveDeclKind::Method;
case StaticSpellingKind::KeywordStatic:
return DescriptiveDeclKind::StaticMethod;
case StaticSpellingKind::KeywordClass:
return DescriptiveDeclKind::ClassMethod;
}
}
}
#undef TRIVIAL_KIND
llvm_unreachable("bad DescriptiveDeclKind");
}
StringRef Decl::getDescriptiveKindName(DescriptiveDeclKind K) {
#define ENTRY(Kind, String) case DescriptiveDeclKind::Kind: return String
switch (K) {
ENTRY(Import, "import");
ENTRY(Extension, "extension");
ENTRY(EnumCase, "case");
ENTRY(TopLevelCode, "top-level code");
ENTRY(IfConfig, "if configuration");
ENTRY(PatternBinding, "pattern binding");
ENTRY(Var, "var");
ENTRY(Param, "parameter");
ENTRY(Let, "let");
ENTRY(StaticVar, "static var");
ENTRY(StaticLet, "static let");
ENTRY(ClassVar, "class var");
ENTRY(ClassLet, "class let");
ENTRY(InfixOperator, "infix operator");
ENTRY(PrefixOperator, "prefix operator");
ENTRY(PostfixOperator, "postfix operator");
ENTRY(TypeAlias, "type alias");
ENTRY(GenericTypeParam, "generic parameter");
ENTRY(AssociatedType, "associated type");
ENTRY(Enum, "enum");
ENTRY(Struct, "struct");
ENTRY(Class, "class");
ENTRY(Protocol, "protocol");
ENTRY(GenericEnum, "generic enum");
ENTRY(GenericStruct, "generic struct");
ENTRY(GenericClass, "generic class");
ENTRY(Subscript, "subscript");
ENTRY(Constructor, "initializer");
ENTRY(Destructor, "deinitializer");
ENTRY(LocalFunction, "local function");
ENTRY(GlobalFunction, "global function");
ENTRY(OperatorFunction, "operator function");
ENTRY(Method, "instance method");
ENTRY(StaticMethod, "static method");
ENTRY(ClassMethod, "class method");
ENTRY(Getter, "getter");
ENTRY(Setter, "setter");
ENTRY(WillSet, "willSet observer");
ENTRY(DidSet, "didSet observer");
ENTRY(MaterializeForSet, "materializeForSet accessor");
ENTRY(Addressor, "address accessor");
ENTRY(MutableAddressor, "mutableAddress accessor");
ENTRY(EnumElement, "enum element");
ENTRY(Module, "module");
}
#undef ENTRY
llvm_unreachable("bad DescriptiveDeclKind");
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS,
StaticSpellingKind SSK) {
switch (SSK) {
case StaticSpellingKind::None:
return OS << "<none>";
case StaticSpellingKind::KeywordStatic:
return OS << "'static'";
case StaticSpellingKind::KeywordClass:
return OS << "'class'";
}
llvm_unreachable("bad StaticSpellingKind");
}
DeclContext *Decl::getInnermostDeclContext() {
if (auto func = dyn_cast<AbstractFunctionDecl>(this))
return func;
if (auto nominal = dyn_cast<NominalTypeDecl>(this))
return nominal;
if (auto ext = dyn_cast<ExtensionDecl>(this))
return ext;
if (auto topLevel = dyn_cast<TopLevelCodeDecl>(this))
return topLevel;
return getDeclContext();
}
DeclContext *Decl::getDeclContextForModule() const {
if (auto module = dyn_cast<ModuleDecl>(this))
return const_cast<ModuleDecl *>(module);
return nullptr;
}
void Decl::setDeclContext(DeclContext *DC) {
Context = DC;
}
bool Decl::isUserAccessible() const {
if (auto VD = dyn_cast<VarDecl>(this)){
return VD->isUserAccessible();
}
return true;
}
Module *Decl::getModuleContext() const {
return getDeclContext()->getParentModule();
}
// Helper functions to verify statically whether source-location
// functions have been overridden.
typedef const char (&TwoChars)[2];
template<typename Class>
inline char checkSourceLocType(SourceLoc (Class::*)() const);
inline TwoChars checkSourceLocType(SourceLoc (Decl::*)() const);
template<typename Class>
inline char checkSourceRangeType(SourceRange (Class::*)() const);
inline TwoChars checkSourceRangeType(SourceRange (Decl::*)() const);
SourceRange Decl::getSourceRange() const {
switch (getKind()) {
#define DECL(ID, PARENT) \
static_assert(sizeof(checkSourceRangeType(&ID##Decl::getSourceRange)) == 1, \
#ID "Decl is missing getSourceRange()"); \
case DeclKind::ID: return cast<ID##Decl>(this)->getSourceRange();
#include "swift/AST/DeclNodes.def"
}
llvm_unreachable("Unknown decl kind");
}
SourceLoc Decl::getLoc() const {
switch (getKind()) {
#define DECL(ID, X) \
static_assert(sizeof(checkSourceLocType(&ID##Decl::getLoc)) == 1, \
#ID "Decl is missing getLoc()"); \
case DeclKind::ID: return cast<ID##Decl>(this)->getLoc();
#include "swift/AST/DeclNodes.def"
}
llvm_unreachable("Unknown decl kind");
}
bool Decl::isTransparent() const {
// Check if the declaration had the attribute.
if (getAttrs().hasAttribute<TransparentAttr>())
return true;
// Check if this is a function declaration which is within a transparent
// extension.
if (const AbstractFunctionDecl *FD = dyn_cast<AbstractFunctionDecl>(this)) {
if (const ExtensionDecl *ED = dyn_cast<ExtensionDecl>(FD->getParent()))
if (ED->isTransparent())
return true;
}
// If this is an accessor, check if the transparent attribute was set
// on the value decl.
if (const FuncDecl *FD = dyn_cast<FuncDecl>(this)) {
if (auto *ASD = FD->getAccessorStorageDecl())
return ASD->isTransparent();
}
return false;
}
bool Decl::isBeingTypeChecked() {
auto decl = this;
while (true) {
if (decl->DeclBits.BeingTypeChecked)
return true;
auto dc = decl->getDeclContext();
if (auto nominal = dyn_cast<NominalTypeDecl>(dc))
decl = nominal;
else if (auto ext = dyn_cast<ExtensionDecl>(dc))
decl = ext;
else
break;
}
return false;
}
bool Decl::isPrivateStdlibDecl(bool whitelistProtocols) const {
const Decl *D = this;
if (auto ExtD = dyn_cast<ExtensionDecl>(D))
return ExtD->getExtendedType().isPrivateStdlibType(whitelistProtocols);
DeclContext *DC = D->getDeclContext()->getModuleScopeContext();
if (DC->getParentModule()->isBuiltinModule() ||
DC->getParentModule()->isSwiftShimsModule())
return true;
if (!DC->getParentModule()->isSystemModule())
return false;
auto FU = dyn_cast<FileUnit>(DC);
if (!FU)
return false;
// Check for Swift module and overlays.
if (!DC->getParentModule()->isStdlibModule() &&
FU->getKind() != FileUnitKind::SerializedAST)
return false;
auto hasInternalParameter = [](ArrayRef<const Pattern *> Pats) -> bool {
bool hasInternalParam = false;
for (auto Pat : Pats) {
Pat->forEachVariable([&](VarDecl *Param) {
if (Param->hasName() && Param->getNameStr().startswith("_")) {
hasInternalParam = true;
}
});
}
return hasInternalParam;
};
if (auto AFD = dyn_cast<AbstractFunctionDecl>(D)) {
// Hide '~>' functions (but show the operator, because it defines
// precedence).
if (AFD->getNameStr() == "~>")
return true;
// If it's a function with a parameter with leading underscore, it's a
// private function.
if (hasInternalParameter(AFD->getBodyParamPatterns()))
return true;
}
if (auto SubscriptD = dyn_cast<SubscriptDecl>(D)) {
if (hasInternalParameter(SubscriptD->getIndices()))
return true;
}
if (auto PD = dyn_cast<ProtocolDecl>(D)) {
StringRef NameStr = PD->getNameStr();
if (NameStr.startswith("_Builtin"))
return true;
if (NameStr.startswith("_") && NameStr.endswith("LiteralConvertible"))
return true;
if (whitelistProtocols)
return false;
}
if (auto ImportD = dyn_cast<ImportDecl>(D)) {
if (ImportD->getModule()->isSwiftShimsModule())
return true;
}
auto VD = dyn_cast<ValueDecl>(D);
if (!VD || !VD->hasName())
return false;
// If the name has leading underscore then it's a private symbol.
if (VD->getNameStr().startswith("_"))
return true;
return false;
}
bool Decl::isWeakImported(Module *fromModule) const {
// For a Clang declaration, trust Clang.
if (auto clangDecl = getClangDecl()) {
return clangDecl->isWeakImported();
}
// FIXME: Implement using AvailableAttr::getMinVersionAvailability().
return false;
}
GenericParamList::GenericParamList(SourceLoc LAngleLoc,
ArrayRef<GenericTypeParamDecl *> Params,
SourceLoc WhereLoc,
MutableArrayRef<RequirementRepr> Requirements,
SourceLoc RAngleLoc)
: Brackets(LAngleLoc, RAngleLoc), NumParams(Params.size()),
WhereLoc(WhereLoc), Requirements(Requirements),
OuterParameters(nullptr),
FirstTrailingWhereArg(Requirements.size()),
Builder(nullptr)
{
std::uninitialized_copy(Params.begin(), Params.end(),
reinterpret_cast<GenericTypeParamDecl **>(this + 1));
}
GenericParamList *
GenericParamList::create(ASTContext &Context,
SourceLoc LAngleLoc,
ArrayRef<GenericTypeParamDecl *> Params,
SourceLoc RAngleLoc) {
unsigned Size = sizeof(GenericParamList)
+ sizeof(GenericTypeParamDecl *) * Params.size();
void *Mem = Context.Allocate(Size, alignof(GenericParamList));
return new (Mem) GenericParamList(LAngleLoc, Params, SourceLoc(),
MutableArrayRef<RequirementRepr>(),
RAngleLoc);
}
GenericParamList *
GenericParamList::create(const ASTContext &Context,
SourceLoc LAngleLoc,
ArrayRef<GenericTypeParamDecl *> Params,
SourceLoc WhereLoc,
MutableArrayRef<RequirementRepr> Requirements,
SourceLoc RAngleLoc) {
unsigned Size = sizeof(GenericParamList)
+ sizeof(GenericTypeParamDecl *) * Params.size();
void *Mem = Context.Allocate(Size, alignof(GenericParamList));
return new (Mem) GenericParamList(LAngleLoc, Params,
WhereLoc,
Context.AllocateCopy(Requirements),
RAngleLoc);
}
void GenericParamList::addTrailingWhereClause(
ASTContext &ctx,
SourceLoc trailingWhereLoc,
ArrayRef<RequirementRepr> trailingRequirements) {
assert(TrailingWhereLoc.isInvalid() &&
"Already have a trailing where clause?");
TrailingWhereLoc = trailingWhereLoc;
FirstTrailingWhereArg = Requirements.size();
// Create a unified set of requirements.
auto newRequirements = ctx.AllocateUninitialized<RequirementRepr>(
Requirements.size() + trailingRequirements.size());
std::memcpy(newRequirements.data(), Requirements.data(),
Requirements.size() * sizeof(RequirementRepr));
std::memcpy(newRequirements.data() + Requirements.size(),
trailingRequirements.data(),
trailingRequirements.size() * sizeof(RequirementRepr));
Requirements = newRequirements;
}
GenericSignature *
GenericParamList::getAsCanonicalGenericSignature(
llvm::DenseMap<ArchetypeType *, Type> &archetypeMap,
ASTContext &C) const {
SmallVector<GenericTypeParamType *, 4> params;
SmallVector<Requirement, 4> requirements;
getAsGenericSignatureElements(C, archetypeMap, params, requirements);
// Canonicalize the types in the signature.
for (auto ¶m : params)
param = cast<GenericTypeParamType>(param->getCanonicalType());
for (auto &reqt : requirements)
reqt = Requirement(reqt.getKind(),
reqt.getFirstType()->getCanonicalType(),
reqt.getSecondType()->getCanonicalType());
return GenericSignature::get(params, requirements, /*isKnownCanonical=*/true);
}
ArrayRef<Substitution>
GenericParamList::getForwardingSubstitutions(ASTContext &C) {
SmallVector<Substitution, 4> subs;
// TODO: IRGen wants substitutions for secondary archetypes.
// for (auto ¶m : params->getNestedGenericParams()) {
// ArchetypeType *archetype = param.getAsTypeParam()->getArchetype();
for (auto archetype : getAllNestedArchetypes()) {
// "Check conformance" on each declared protocol to build a
// conformance map.
SmallVector<ProtocolConformance *, 2> conformances;
for (ProtocolDecl *conformsTo : archetype->getConformsTo()) {
(void)conformsTo;
conformances.push_back(nullptr);
}
// Build an identity mapping with the derived conformances.
auto replacement = SubstitutedType::get(archetype, archetype, C);
subs.push_back({archetype, replacement, C.AllocateCopy(conformances)});
}
return C.AllocateCopy(subs);
}
// Helper for getAsGenericSignatureElements to remap an archetype in a
// requirement to a canonical dependent type.
Type
ArchetypeType::getAsDependentType(
const llvm::DenseMap<ArchetypeType*, Type> &archetypeMap) {
// Map associated archetypes to DependentMemberTypes.
if (auto parent = getParent()) {
auto assocTy = getAssocType();
assert(assocTy);
Type base = parent->getAsDependentType(archetypeMap);
return DependentMemberType::get(base, assocTy, getASTContext());
}
// Map primary archetypes to generic type parameters.
auto found = archetypeMap.find(this);
assert(found != archetypeMap.end()
&& "did not find generic param for archetype");
return found->second;
}
static Type getAsDependentType(Type t,
const llvm::DenseMap<ArchetypeType*, Type> &archetypeMap) {
if (!t->hasArchetype())
return t;
return t.transform([&](Type type) -> Type {
if (auto arch = type->getAs<ArchetypeType>())
return arch->getAsDependentType(archetypeMap);
return type;
});
}
// A helper to recursively collect the generic parameters from the outer levels
// of a generic parameter list.
void
GenericParamList::getAsGenericSignatureElements(ASTContext &C,
llvm::DenseMap<ArchetypeType *, Type> &archetypeMap,
SmallVectorImpl<GenericTypeParamType *> &genericParams,
SmallVectorImpl<Requirement> &requirements) const {
// Collect outer generic parameters first.
if (OuterParameters) {
OuterParameters->getAsGenericSignatureElements(C, archetypeMap,
genericParams,
requirements);
}
// Collect our parameters.
for (auto paramIndex : indices(getParams())) {
auto param = getParams()[paramIndex];
auto typeParamTy = param->getDeclaredType()->castTo<GenericTypeParamType>();
// Make sure we didn't visit this param already in the parent.
auto found = archetypeMap.find(param->getArchetype());
if (found != archetypeMap.end()) {
assert(found->second->isEqual(typeParamTy));
continue;
}
// Set up a mapping we can use to remap requirements to dependent types.
ArchetypeType *archetype = getPrimaryArchetypes()[paramIndex];
archetypeMap[archetype] = typeParamTy;
genericParams.push_back(typeParamTy);
requirements.push_back(Requirement(RequirementKind::WitnessMarker,
typeParamTy, typeParamTy));
// Collect conformance requirements declared on the archetype.
if (auto super = archetype->getSuperclass()) {
requirements.push_back(Requirement(RequirementKind::Conformance,
typeParamTy, super));
}
for (auto proto : archetype->getConformsTo()) {
requirements.push_back(Requirement(RequirementKind::Conformance,
typeParamTy, proto->getDeclaredType()));
}
}
// FIXME: Emit WitnessMarker requirements for associated types in an order
// that preserves AllArchetypes order but otherwise makes no sense.
for (auto assocTy : getAssociatedArchetypes()) {
auto depTy = getAsDependentType(assocTy, archetypeMap);
requirements.push_back(Requirement(RequirementKind::WitnessMarker,
depTy, depTy));
// Add conformance requirements for this associated archetype.
for (const auto &repr : getRequirements()) {
// Handle same-type requirements at last.
if (repr.getKind() != RequirementKind::Conformance)
continue;
// Primary conformance declarations would have already been gathered as
// conformance requirements of the archetype.
if (auto arch = repr.getSubject()->getAs<ArchetypeType>())
if (!arch->getParent())
continue;
auto depTyOfReqt = getAsDependentType(repr.getSubject(), archetypeMap);
if (depTyOfReqt.getPointer() != depTy.getPointer())
continue;
Requirement reqt(RequirementKind::Conformance,
getAsDependentType(repr.getSubject(), archetypeMap),
getAsDependentType(repr.getConstraint(), archetypeMap));
requirements.push_back(reqt);
}
}
// Add all of the same-type requirements.
if (Builder) {
for (auto req : Builder->getSameTypeRequirements()) {
auto firstType = req.first->getDependentType(*Builder, false);
Type secondType;
if (auto concrete = req.second.dyn_cast<Type>())
secondType = getAsDependentType(concrete, archetypeMap);
else if (auto secondPA =
req.second.dyn_cast<ArchetypeBuilder::PotentialArchetype*>())
secondType = secondPA->getDependentType(*Builder, false);
if (firstType->is<ErrorType>() || secondType->is<ErrorType>())
continue;
requirements.push_back(Requirement(RequirementKind::SameType,
firstType, secondType));
}
}
}
/// \brief Add the nested archetypes of the given archetype to the set
/// of all archetypes.
void GenericParamList::addNestedArchetypes(ArchetypeType *archetype,
SmallPtrSetImpl<ArchetypeType*> &known,
SmallVectorImpl<ArchetypeType*> &all) {
for (auto nested : archetype->getNestedTypes()) {
auto nestedArch = nested.second.getAsArchetype();
if (!nestedArch)
continue;
if (known.insert(nestedArch).second) {
assert(!nestedArch->isPrimary() && "Unexpected primary archetype");
all.push_back(nestedArch);
addNestedArchetypes(nestedArch, known, all);
}
}
}
ArrayRef<ArchetypeType*>
GenericParamList::deriveAllArchetypes(ArrayRef<GenericTypeParamDecl *> params,
SmallVectorImpl<ArchetypeType*> &all) {
// This should be kept in sync with ArchetypeBuilder::getAllArchetypes().
assert(all.empty());
llvm::SmallPtrSet<ArchetypeType*, 8> known;
// Collect all the primary archetypes.
for (auto param : params) {
auto archetype = param->getArchetype();
if (known.insert(archetype).second)
all.push_back(archetype);
}
// Collect all the nested archetypes.
for (auto param : params) {
auto archetype = param->getArchetype();
addNestedArchetypes(archetype, known, all);
}
return all;
}
TrailingWhereClause::TrailingWhereClause(
SourceLoc whereLoc,
ArrayRef<RequirementRepr> requirements)
: WhereLoc(whereLoc),
NumRequirements(requirements.size())
{
memcpy(getRequirements().data(), requirements.data(),
NumRequirements * sizeof(RequirementRepr));
}
TrailingWhereClause *TrailingWhereClause::create(
ASTContext &ctx,
SourceLoc whereLoc,
ArrayRef<RequirementRepr> requirements) {
unsigned size = sizeof(TrailingWhereClause)
+ requirements.size() * sizeof(RequirementRepr);
void *mem = ctx.Allocate(size, alignof(TrailingWhereClause));
return new (mem) TrailingWhereClause(whereLoc, requirements);
}
ImportDecl *ImportDecl::create(ASTContext &Ctx, DeclContext *DC,
SourceLoc ImportLoc, ImportKind Kind,
SourceLoc KindLoc,
ArrayRef<AccessPathElement> Path,
ClangNode ClangN) {
assert(!Path.empty());
assert(Kind == ImportKind::Module || Path.size() > 1);
assert(ClangN.isNull() || ClangN.getAsModule() ||
isa<clang::ImportDecl>(ClangN.getAsDecl()));
size_t Size = sizeof(ImportDecl) + Path.size() * sizeof(AccessPathElement);
void *ptr = allocateMemoryForDecl<ImportDecl>(Ctx, Size, !ClangN.isNull());
auto D = new (ptr) ImportDecl(DC, ImportLoc, Kind, KindLoc, Path);
if (ClangN)
D->setClangNode(ClangN);
return D;
}
ImportDecl::ImportDecl(DeclContext *DC, SourceLoc ImportLoc, ImportKind K,
SourceLoc KindLoc, ArrayRef<AccessPathElement> Path)
: Decl(DeclKind::Import, DC), ImportLoc(ImportLoc), KindLoc(KindLoc),
NumPathElements(Path.size()) {
ImportDeclBits.ImportKind = static_cast<unsigned>(K);
assert(getImportKind() == K && "not enough bits for ImportKind");
std::uninitialized_copy(Path.begin(), Path.end(), getPathBuffer());
}
ImportKind ImportDecl::getBestImportKind(const ValueDecl *VD) {
switch (VD->getKind()) {
case DeclKind::Import:
case DeclKind::Extension:
case DeclKind::PatternBinding:
case DeclKind::TopLevelCode:
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
case DeclKind::EnumCase:
case DeclKind::IfConfig:
llvm_unreachable("not a ValueDecl");
case DeclKind::AssociatedType:
case DeclKind::Constructor:
case DeclKind::Destructor:
case DeclKind::GenericTypeParam:
case DeclKind::Subscript:
case DeclKind::EnumElement:
case DeclKind::Param:
llvm_unreachable("not a top-level ValueDecl");
case DeclKind::Protocol:
return ImportKind::Protocol;
case DeclKind::Class:
return ImportKind::Class;
case DeclKind::Enum:
return ImportKind::Enum;
case DeclKind::Struct:
return ImportKind::Struct;
case DeclKind::TypeAlias: {
Type underlyingTy = cast<TypeAliasDecl>(VD)->getUnderlyingType();
return getBestImportKind(underlyingTy->getAnyNominal());
}
case DeclKind::Func:
return ImportKind::Func;
case DeclKind::Var:
return ImportKind::Var;
case DeclKind::Module:
return ImportKind::Module;
}
llvm_unreachable("bad DeclKind");
}
Optional<ImportKind>
ImportDecl::findBestImportKind(ArrayRef<ValueDecl *> Decls) {
assert(!Decls.empty());
ImportKind FirstKind = ImportDecl::getBestImportKind(Decls.front());
// FIXME: Only functions can be overloaded.
if (Decls.size() == 1)
return FirstKind;
if (FirstKind != ImportKind::Func)
return None;
for (auto NextDecl : Decls.slice(1)) {
if (ImportDecl::getBestImportKind(NextDecl) != FirstKind)
return None;
}
return FirstKind;
}
template <typename T>
static void
loadAllConformances(const T *container,
const LazyLoaderArray<ProtocolConformance*> &loaderInfo) {
if (!loaderInfo.isLazy())
return;
// Don't try to load conformances re-entrant-ly.
auto resolver = loaderInfo.getLoader();
auto contextData = loaderInfo.getLoaderContextData();
const_cast<LazyLoaderArray<ProtocolConformance*> &>(loaderInfo) = {};
SmallVector<ProtocolConformance *, 8> Conformances;
resolver->loadAllConformances(container, contextData, Conformances);
const_cast<T *>(container)->setConformances(
container->getASTContext().AllocateCopy(Conformances));
}
DeclRange NominalTypeDecl::getMembers(bool forceDelayedMembers) const {
loadAllMembers();
if (forceDelayedMembers)
const_cast<NominalTypeDecl*>(this)->forceDelayedMemberDecls();
return IterableDeclContext::getMembers();
}
void NominalTypeDecl::setMemberLoader(LazyMemberLoader *resolver,
uint64_t contextData) {
IterableDeclContext::setLoader(resolver, contextData);
}
void NominalTypeDecl::setConformanceLoader(LazyMemberLoader *resolver,
uint64_t contextData) {
assert(!HaveConformanceLoader &&
"Already have a conformance loader");
HaveConformanceLoader = true;
getASTContext().recordConformanceLoader(this, resolver, contextData);
}
std::pair<LazyMemberLoader *, uint64_t>
NominalTypeDecl::takeConformanceLoaderSlow() {
assert(HaveConformanceLoader && "no conformance loader?");
HaveConformanceLoader = false;
return getASTContext().takeConformanceLoader(this);
}
ExtensionDecl::ExtensionDecl(SourceLoc extensionLoc,
TypeLoc extendedType,
MutableArrayRef<TypeLoc> inherited,
DeclContext *parent,
TrailingWhereClause *trailingWhereClause)
: Decl(DeclKind::Extension, parent),
DeclContext(DeclContextKind::ExtensionDecl, parent),
IterableDeclContext(IterableDeclContextKind::ExtensionDecl),
ExtensionLoc(extensionLoc),
ExtendedType(extendedType),
Inherited(inherited),
TrailingWhere(trailingWhereClause)
{
ExtensionDeclBits.Validated = false;
ExtensionDeclBits.CheckedInheritanceClause = false;
ExtensionDeclBits.DefaultAndMaxAccessLevel = 0;
ExtensionDeclBits.HaveConformanceLoader = false;
}
ExtensionDecl *ExtensionDecl::create(ASTContext &ctx, SourceLoc extensionLoc,
TypeLoc extendedType,
MutableArrayRef<TypeLoc> inherited,
DeclContext *parent,
TrailingWhereClause *trailingWhereClause,
ClangNode clangNode) {
unsigned size = sizeof(ExtensionDecl);
void *declPtr = allocateMemoryForDecl<ExtensionDecl>(ctx, size,
!clangNode.isNull());
// Construct the extension.
auto result = ::new (declPtr) ExtensionDecl(extensionLoc, extendedType,
inherited, parent,
trailingWhereClause);
if (clangNode)
result->setClangNode(clangNode);
return result;
}
void ExtensionDecl::setGenericParams(GenericParamList *params) {
GenericParams = params;
if (GenericParams) {
for (auto param : *GenericParams)
param->setDeclContext(this);
}
}
void ExtensionDecl::setGenericSignature(GenericSignature *sig) {
assert(!GenericSig && "Already have generic signature");
GenericSig = sig;
}
DeclRange ExtensionDecl::getMembers(bool forceDelayedMembers) const {
loadAllMembers();
return IterableDeclContext::getMembers();
}
void ExtensionDecl::setMemberLoader(LazyMemberLoader *resolver,
uint64_t contextData) {
IterableDeclContext::setLoader(resolver, contextData);
}
void ExtensionDecl::setConformanceLoader(LazyMemberLoader *resolver,
uint64_t contextData) {
assert(!ExtensionDeclBits.HaveConformanceLoader &&
"Already have a conformance loader");
ExtensionDeclBits.HaveConformanceLoader = true;
getASTContext().recordConformanceLoader(this, resolver, contextData);
}
std::pair<LazyMemberLoader *, uint64_t>
ExtensionDecl::takeConformanceLoaderSlow() {
assert(ExtensionDeclBits.HaveConformanceLoader && "no conformance loader?");
ExtensionDeclBits.HaveConformanceLoader = false;
return getASTContext().takeConformanceLoader(this);
}
bool ExtensionDecl::isConstrainedExtension() const {
auto nominal = getExtendedType()->getAnyNominal();
// Error case: erroneous extension.
if (!nominal)
return false;
// Non-generic extension.
if (!getGenericSignature())
return false;
// If the generic signature differs from that of the nominal type, it's a
// constrained extension.
return getGenericSignature()->getCanonicalSignature()
!= nominal->getGenericSignature()->getCanonicalSignature();
}