-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDecl.cpp
8362 lines (7094 loc) · 280 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 - 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 the Decl class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Decl.h"
#include "swift/AST/AccessRequests.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignAsyncConvention.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ParseRequests.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ResilienceExpansion.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/SwiftNameTranslation.h"
#include "swift/Basic/Defer.h"
#include "swift/Parse/Lexer.h" // FIXME: Bad dependency
#include "clang/Lex/MacroInfo.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/TypeID.h"
#include "swift/Demangling/ManglingMacros.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Module.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "InlinableText.h"
#include <algorithm>
using namespace swift;
#define DEBUG_TYPE "Serialization"
STATISTIC(NumLazyRequirementSignatures,
"# of lazily-deserialized requirement signatures known");
#undef DEBUG_TYPE
#define DECL(Id, _) \
static_assert((DeclKind::Id == DeclKind::Module) ^ \
IsTriviallyDestructible<Id##Decl>::value, \
"Decls are BumpPtrAllocated; the destructor is never called");
#include "swift/AST/DeclNodes.def"
static_assert(IsTriviallyDestructible<ParameterList>::value,
"ParameterLists are BumpPtrAllocated; the d'tor is never called");
static_assert(IsTriviallyDestructible<GenericParamList>::value,
"GenericParamLists are BumpPtrAllocated; the d'tor isn't called");
const clang::MacroInfo *ClangNode::getAsMacro() const {
if (auto MM = getAsModuleMacro())
return MM->getMacroInfo();
return getAsMacroInfo();
}
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;
}
void ClangNode::dump() const {
#if SWIFT_BUILD_ONLY_SYNTAXPARSERLIB
return; // not needed for the parser library.
#endif
if (auto D = getAsDecl())
D->dump();
else if (auto M = getAsMacro())
M->dump();
else if (auto M = getAsModule())
M->dump();
else
llvm::errs() << "ClangNode contains nullptr\n";
}
// Only allow allocation of Decls using the allocator in ASTContext.
void *Decl::operator new(size_t Bytes, const ASTContext &C,
unsigned Alignment) {
return C.Allocate(Bytes, Alignment);
}
// Only allow allocation of Modules using the allocator in ASTContext.
void *ModuleDecl::operator new(size_t Bytes, const 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(PoundDiagnostic);
TRIVIAL_KIND(PatternBinding);
TRIVIAL_KIND(PrecedenceGroup);
TRIVIAL_KIND(InfixOperator);
TRIVIAL_KIND(PrefixOperator);
TRIVIAL_KIND(PostfixOperator);
TRIVIAL_KIND(TypeAlias);
TRIVIAL_KIND(GenericTypeParam);
TRIVIAL_KIND(AssociatedType);
TRIVIAL_KIND(Protocol);
TRIVIAL_KIND(Constructor);
TRIVIAL_KIND(Destructor);
TRIVIAL_KIND(EnumElement);
TRIVIAL_KIND(Param);
TRIVIAL_KIND(Module);
TRIVIAL_KIND(MissingMember);
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:
if (var->getDeclContext()->isTypeContext())
return DescriptiveDeclKind::Property;
return var->isLet() ? DescriptiveDeclKind::Let
: DescriptiveDeclKind::Var;
case StaticSpellingKind::KeywordStatic:
return DescriptiveDeclKind::StaticProperty;
case StaticSpellingKind::KeywordClass:
return DescriptiveDeclKind::ClassProperty;
}
}
case DeclKind::Subscript: {
auto subscript = cast<SubscriptDecl>(this);
switch (subscript->getCorrectStaticSpelling()) {
case StaticSpellingKind::None:
return DescriptiveDeclKind::Subscript;
case StaticSpellingKind::KeywordStatic:
return DescriptiveDeclKind::StaticSubscript;
case StaticSpellingKind::KeywordClass:
return DescriptiveDeclKind::ClassSubscript;
}
}
case DeclKind::Accessor: {
auto accessor = cast<AccessorDecl>(this);
switch (accessor->getAccessorKind()) {
case AccessorKind::Get:
return DescriptiveDeclKind::Getter;
case AccessorKind::Set:
return DescriptiveDeclKind::Setter;
case AccessorKind::WillSet:
return DescriptiveDeclKind::WillSet;
case AccessorKind::DidSet:
return DescriptiveDeclKind::DidSet;
case AccessorKind::Address:
return DescriptiveDeclKind::Addressor;
case AccessorKind::MutableAddress:
return DescriptiveDeclKind::MutableAddressor;
case AccessorKind::Read:
return DescriptiveDeclKind::ReadAccessor;
case AccessorKind::Modify:
return DescriptiveDeclKind::ModifyAccessor;
}
llvm_unreachable("bad accessor kind");
}
case DeclKind::Func: {
auto func = cast<FuncDecl>(this);
if (func->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;
}
}
case DeclKind::OpaqueType: {
auto *opaqueTypeDecl = cast<OpaqueTypeDecl>(this);
if (dyn_cast_or_null<VarDecl>(opaqueTypeDecl->getNamingDecl()))
return DescriptiveDeclKind::OpaqueVarType;
return DescriptiveDeclKind::OpaqueResultType;
}
}
#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, "conditional block");
ENTRY(PoundDiagnostic, "diagnostic");
ENTRY(PatternBinding, "pattern binding");
ENTRY(Var, "var");
ENTRY(Param, "parameter");
ENTRY(Let, "let");
ENTRY(Property, "property");
ENTRY(StaticProperty, "static property");
ENTRY(ClassProperty, "class property");
ENTRY(PrecedenceGroup, "precedence group");
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(Type, "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(GenericType, "generic type");
ENTRY(Subscript, "subscript");
ENTRY(StaticSubscript, "static subscript");
ENTRY(ClassSubscript, "class 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(Addressor, "address accessor");
ENTRY(MutableAddressor, "mutableAddress accessor");
ENTRY(ReadAccessor, "_read accessor");
ENTRY(ModifyAccessor, "_modify accessor");
ENTRY(EnumElement, "enum case");
ENTRY(Module, "module");
ENTRY(MissingMember, "missing member placeholder");
ENTRY(Requirement, "requirement");
ENTRY(OpaqueResultType, "result");
ENTRY(OpaqueVarType, "type");
}
#undef ENTRY
llvm_unreachable("bad DescriptiveDeclKind");
}
const Decl *Decl::getInnermostDeclWithAvailability() const {
const Decl *enclosingDecl = this;
// Find the innermost enclosing declaration with an @available annotation.
while (enclosingDecl != nullptr) {
if (enclosingDecl->getAttrs().hasAttribute<AvailableAttr>())
return enclosingDecl;
enclosingDecl = enclosingDecl->getDeclContext()->getAsDecl();
}
return nullptr;
}
Optional<llvm::VersionTuple>
Decl::getIntroducedOSVersion(PlatformKind Kind) const {
for (auto *attr: getAttrs()) {
if (auto *ava = dyn_cast<AvailableAttr>(attr)) {
if (ava->Platform == Kind && ava->Introduced) {
return ava->Introduced;
}
}
}
return None;
}
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");
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS,
ReferenceOwnership RO) {
if (RO == ReferenceOwnership::Strong)
return OS << "'strong'";
return OS << "'" << keywordOf(RO) << "'";
}
llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS,
SelfAccessKind SAK) {
switch (SAK) {
case SelfAccessKind::NonMutating: return OS << "'nonmutating'";
case SelfAccessKind::Mutating: return OS << "'mutating'";
case SelfAccessKind::Consuming: return OS << "'__consuming'";
}
llvm_unreachable("Unknown SelfAccessKind");
}
DeclContext *Decl::getInnermostDeclContext() const {
if (auto func = dyn_cast<AbstractFunctionDecl>(this))
return const_cast<AbstractFunctionDecl*>(func);
if (auto subscript = dyn_cast<SubscriptDecl>(this))
return const_cast<SubscriptDecl*>(subscript);
if (auto type = dyn_cast<GenericTypeDecl>(this))
return const_cast<GenericTypeDecl*>(type);
if (auto ext = dyn_cast<ExtensionDecl>(this))
return const_cast<ExtensionDecl*>(ext);
if (auto topLevel = dyn_cast<TopLevelCodeDecl>(this))
return const_cast<TopLevelCodeDecl*>(topLevel);
return getDeclContext();
}
bool Decl::isInvalid() const {
switch (getKind()) {
#define VALUE_DECL(ID, PARENT)
#define DECL(ID, PARENT) \
case DeclKind::ID:
#include "swift/AST/DeclNodes.def"
return Bits.Decl.Invalid;
case DeclKind::Param: {
// Parameters are special because closure parameters may not have type
// annotations. In which case, the interface type request returns
// ErrorType. Therefore, consider parameters with implicit types to always
// be valid.
auto *PD = cast<ParamDecl>(this);
if (!PD->getTypeRepr() && !PD->hasInterfaceType())
return false;
}
LLVM_FALLTHROUGH;
case DeclKind::Enum:
case DeclKind::Struct:
case DeclKind::Class:
case DeclKind::Protocol:
case DeclKind::OpaqueType:
case DeclKind::TypeAlias:
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::Module:
case DeclKind::Var:
case DeclKind::Subscript:
case DeclKind::Constructor:
case DeclKind::Destructor:
case DeclKind::Func:
case DeclKind::EnumElement:
return cast<ValueDecl>(this)->getInterfaceType()->hasError();
case DeclKind::Accessor: {
auto *AD = cast<AccessorDecl>(this);
if (AD->hasInterfaceType() && AD->getInterfaceType()->hasError())
return true;
return AD->getStorage()->isInvalid();
}
}
llvm_unreachable("Unknown decl kind");
}
void Decl::setInvalidBit() { Bits.Decl.Invalid = true; }
void Decl::setInvalid() {
switch (getKind()) {
#define VALUE_DECL(ID, PARENT)
#define DECL(ID, PARENT) \
case DeclKind::ID:
#include "swift/AST/DeclNodes.def"
Bits.Decl.Invalid = true;
return;
case DeclKind::Enum:
case DeclKind::Struct:
case DeclKind::Class:
case DeclKind::Protocol:
case DeclKind::OpaqueType:
case DeclKind::TypeAlias:
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::Module:
case DeclKind::Var:
case DeclKind::Param:
case DeclKind::Subscript:
case DeclKind::Constructor:
case DeclKind::Destructor:
case DeclKind::Func:
case DeclKind::Accessor:
case DeclKind::EnumElement:
cast<ValueDecl>(this)->setInterfaceType(ErrorType::get(getASTContext()));
return;
}
llvm_unreachable("Unknown decl kind");
}
void Decl::setDeclContext(DeclContext *DC) {
Context = DC;
}
bool Decl::isUserAccessible() const {
if (auto VD = dyn_cast<ValueDecl>(this)) {
return VD->isUserAccessible();
}
return true;
}
bool Decl::canHaveComment() const {
return !this->hasClangNode() &&
(isa<ValueDecl>(this) || isa<ExtensionDecl>(this)) &&
!isa<ParamDecl>(this) &&
(!isa<AbstractTypeParamDecl>(this) || isa<AssociatedTypeDecl>(this));
}
ModuleDecl *Decl::getModuleContext() const {
return getDeclContext()->getParentModule();
}
/// Retrieve the diagnostic engine for diagnostics emission.
DiagnosticEngine &Decl::getDiags() const {
return getASTContext().Diags;
}
// 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 checkSourceLocType(SourceLoc (Class::*)(bool) const);
inline TwoChars checkSourceLocType(SourceLoc (Decl::*)(bool) 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");
}
SourceRange Decl::getSourceRangeIncludingAttrs() const {
auto Range = getSourceRange();
// Attributes on AccessorDecl may syntactically belong to PatternBindingDecl.
// e.g. 'override'.
if (auto *AD = dyn_cast<AccessorDecl>(this)) {
// If this is implicit getter, accessor range should not include attributes.
if (AD->isImplicitGetter())
return Range;
// Otherwise, include attributes directly attached to the accessor.
SourceLoc VarLoc = AD->getStorage()->getStartLoc();
for (auto Attr : getAttrs()) {
if (!Attr->getRange().isValid())
continue;
SourceLoc AttrStartLoc = Attr->getRangeWithAt().Start;
if (getASTContext().SourceMgr.isBeforeInBuffer(VarLoc, AttrStartLoc))
Range.widen(AttrStartLoc);
}
return Range;
}
// Attributes on VarDecl syntactically belong to PatternBindingDecl.
if (isa<VarDecl>(this) && !isa<ParamDecl>(this))
return Range;
// Attributes on PatternBindingDecls are attached to VarDecls in AST.
if (auto *PBD = dyn_cast<PatternBindingDecl>(this)) {
for (auto i : range(PBD->getNumPatternEntries()))
PBD->getPattern(i)->forEachVariable([&](VarDecl *VD) {
for (auto Attr : VD->getAttrs())
if (Attr->getRange().isValid())
Range.widen(Attr->getRangeWithAt());
});
}
for (auto Attr : getAttrs()) {
if (Attr->getRange().isValid())
Range.widen(Attr->getRangeWithAt());
}
return Range;
}
SourceLoc Decl::getLocFromSource() const {
switch (getKind()) {
#define DECL(ID, X) \
static_assert(sizeof(checkSourceLocType(&ID##Decl::getLocFromSource)) == 1, \
#ID "Decl is missing getLocFromSource()"); \
case DeclKind::ID: return cast<ID##Decl>(this)->getLocFromSource();
#include "swift/AST/DeclNodes.def"
}
llvm_unreachable("Unknown decl kind");
}
const Decl::CachedExternalSourceLocs *Decl::getSerializedLocs() const {
if (CachedSerializedLocs) {
return CachedSerializedLocs;
}
auto *File = cast<FileUnit>(getDeclContext()->getModuleScopeContext());
assert(File->getKind() == FileUnitKind::SerializedAST &&
"getSerializedLocs() should only be called on decls in "
"a 'SerializedASTFile'");
auto Locs = File->getBasicLocsForDecl(this);
if (!Locs.hasValue()) {
static const Decl::CachedExternalSourceLocs NullLocs{};
return &NullLocs;
}
auto *Result = getASTContext().Allocate<Decl::CachedExternalSourceLocs>();
auto &SM = getASTContext().SourceMgr;
#define CASE(X) \
Result->X = SM.getLocFromExternalSource(Locs->SourceFilePath, Locs->X.Line, \
Locs->X.Column);
CASE(Loc)
CASE(StartLoc)
CASE(EndLoc)
#undef CASE
for (const auto &LineColumnAndLength : Locs->DocRanges) {
auto Start = SM.getLocFromExternalSource(Locs->SourceFilePath,
LineColumnAndLength.first.Line,
LineColumnAndLength.first.Column);
Result->DocRanges.push_back({ Start, LineColumnAndLength.second });
}
return Result;
}
StringRef Decl::getAlternateModuleName() const {
for (auto *Att: Attrs) {
if (auto *OD = dyn_cast<OriginallyDefinedInAttr>(Att)) {
if (OD->isActivePlatform(getASTContext())) {
return OD->OriginalModuleName;
}
}
}
for (auto *DC = getDeclContext(); DC; DC = DC->getParent()) {
if (auto decl = DC->getAsDecl()) {
if (decl == this)
continue;
auto AM = decl->getAlternateModuleName();
if (!AM.empty())
return AM;
}
}
return StringRef();
}
SourceLoc Decl::getLoc(bool SerializedOK) const {
#define DECL(ID, X) \
static_assert(sizeof(checkSourceLocType(&ID##Decl::getLoc)) == 2, \
#ID "Decl is re-defining getLoc()");
#include "swift/AST/DeclNodes.def"
if (isa<ModuleDecl>(this))
return SourceLoc();
// When the decl is context-free, we should get loc from source buffer.
if (!getDeclContext())
return getLocFromSource();
FileUnit *File = dyn_cast<FileUnit>(getDeclContext()->getModuleScopeContext());
if (!File)
return getLocFromSource();
switch(File->getKind()) {
case FileUnitKind::Source:
return getLocFromSource();
case FileUnitKind::SerializedAST: {
if (!SerializedOK)
return SourceLoc();
return getSerializedLocs()->Loc;
}
case FileUnitKind::Builtin:
case FileUnitKind::Synthesized:
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
return SourceLoc();
}
llvm_unreachable("invalid file kind");
}
Optional<CustomAttrNominalPair> Decl::getGlobalActorAttr() const {
auto &ctx = getASTContext();
auto mutableThis = const_cast<Decl *>(this);
return evaluateOrDefault(ctx.evaluator,
GlobalActorAttributeRequest{mutableThis},
None);
}
Expr *AbstractFunctionDecl::getSingleExpressionBody() const {
assert(hasSingleExpressionBody() && "Not a single-expression body");
auto braceStmt = getBody();
assert(braceStmt != nullptr && "No body currently available.");
auto body = getBody()->getLastElement();
if (auto *stmt = body.dyn_cast<Stmt *>()) {
if (auto *returnStmt = dyn_cast<ReturnStmt>(stmt)) {
return returnStmt->getResult();
} else if (isa<FailStmt>(stmt)) {
// We can only get to this point if we're a type-checked ConstructorDecl
// which was originally spelled init?(...) { nil }.
//
// There no longer is a single-expression to return, so ignore null.
return nullptr;
}
}
return body.get<Expr *>();
}
void AbstractFunctionDecl::setSingleExpressionBody(Expr *NewBody) {
assert(hasSingleExpressionBody() && "Not a single-expression body");
auto body = getBody()->getLastElement();
if (auto *stmt = body.dyn_cast<Stmt *>()) {
if (auto *returnStmt = dyn_cast<ReturnStmt>(stmt)) {
returnStmt->setResult(NewBody);
return;
} else if (isa<FailStmt>(stmt)) {
// We can only get to this point if we're a type-checked ConstructorDecl
// which was originally spelled init?(...) { nil }.
//
// We can no longer write the single-expression which is being set on us
// into anything because a FailStmt does not have such a child. As a
// result we need to demand that the NewBody is null.
assert(NewBody == nullptr);
return;
}
}
getBody()->setLastElement(NewBody);
}
bool AbstractStorageDecl::isTransparent() const {
return getAttrs().hasAttribute<TransparentAttr>();
}
bool AbstractFunctionDecl::isTransparent() const {
// Check if the declaration had the attribute.
if (getAttrs().hasAttribute<TransparentAttr>())
return true;
// If this is an accessor, the computation is a bit more involved, so we
// kick off a request.
if (const auto *AD = dyn_cast<AccessorDecl>(this)) {
ASTContext &ctx = getASTContext();
return evaluateOrDefault(ctx.evaluator,
IsAccessorTransparentRequest{const_cast<AccessorDecl *>(AD)},
false);
}
return false;
}
bool ParameterList::hasInternalParameter(StringRef Prefix) const {
for (auto param : *this) {
if (param->hasName() && param->getNameStr().startswith(Prefix))
return true;
auto argName = param->getArgumentName();
if (!argName.empty() && argName.str().startswith(Prefix))
return true;
}
return false;
}
bool Decl::hasUnderscoredNaming() const {
const Decl *D = this;
// If it's a function or subscript with a parameter with leading
// underscore, it's a private function or subscript.
if (isa<AbstractFunctionDecl>(D) || isa<SubscriptDecl>(D)) {
const auto VD = cast<ValueDecl>(D);
if (getParameterList(const_cast<ValueDecl *>(VD))
->hasInternalParameter("_")) {
return true;
}
}
if (const auto PD = dyn_cast<ProtocolDecl>(D)) {
StringRef NameStr = PD->getNameStr();
if (NameStr.startswith("_Builtin")) {
return true;
}
if (NameStr.startswith("_ExpressibleBy")) {
return true;
}
}
if (const auto ImportD = dyn_cast<ImportDecl>(D)) {
if (const auto *Mod = ImportD->getModule()) {
if (Mod->isSwiftShimsModule()) {
return true;
}
}
}
const auto VD = dyn_cast<ValueDecl>(D);
if (!VD || !VD->hasName()) {
return false;
}
if (!VD->getBaseName().isSpecial() &&
VD->getBaseIdentifier().str().startswith("_")) {
return true;
}
return false;
}
bool Decl::isPrivateStdlibDecl(bool treatNonBuiltinProtocolsAsPublic) const {
const Decl *D = this;
if (auto ExtD = dyn_cast<ExtensionDecl>(D)) {
Type extTy = ExtD->getExtendedType();
return extTy.isPrivateStdlibType(treatNonBuiltinProtocolsAsPublic);
}
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;
if (isa<ProtocolDecl>(D)) {
if (treatNonBuiltinProtocolsAsPublic)
return false;
}
if (D->getAttrs().hasAttribute<ShowInInterfaceAttr>()) {
return false;
}
return hasUnderscoredNaming();
}
bool Decl::isStdlibDecl() const {
DeclContext *DC = getDeclContext();
return DC->isModuleScopeContext() &&
DC->getParentModule()->isStdlibModule();
}
AvailabilityContext Decl::getAvailabilityForLinkage() const {
auto containingContext =
AvailabilityInference::annotatedAvailableRange(this, getASTContext());
if (containingContext.hasValue())
return *containingContext;
if (auto *accessor = dyn_cast<AccessorDecl>(this))
return accessor->getStorage()->getAvailabilityForLinkage();
if (auto *ext = dyn_cast<ExtensionDecl>(this))
if (auto *nominal = ext->getExtendedNominal())
return nominal->getAvailabilityForLinkage();
auto *dc = getDeclContext();
if (auto *ext = dyn_cast<ExtensionDecl>(dc))
return ext->getAvailabilityForLinkage();
else if (auto *nominal = dyn_cast<NominalTypeDecl>(dc))
return nominal->getAvailabilityForLinkage();
return AvailabilityContext::alwaysAvailable();
}
bool Decl::isAlwaysWeakImported() const {
// For a Clang declaration, trust Clang.
if (auto clangDecl = getClangDecl()) {
return clangDecl->isWeakImported();
}
if (getAttrs().hasAttribute<WeakLinkedAttr>())
return true;
if (auto *accessor = dyn_cast<AccessorDecl>(this))
return accessor->getStorage()->isAlwaysWeakImported();
if (auto *ext = dyn_cast<ExtensionDecl>(this))
if (auto *nominal = ext->getExtendedNominal())
return nominal->isAlwaysWeakImported();
auto *dc = getDeclContext();
if (auto *ext = dyn_cast<ExtensionDecl>(dc))
return ext->isAlwaysWeakImported();
if (auto *nominal = dyn_cast<NominalTypeDecl>(dc))
return nominal->isAlwaysWeakImported();
return false;
}
bool Decl::isWeakImported(ModuleDecl *fromModule) const {
if (fromModule == nullptr) {
return (isAlwaysWeakImported() ||
!getAvailabilityForLinkage().isAlwaysAvailable());
}
if (getModuleContext() == fromModule)
return false;
if (isAlwaysWeakImported())
return true;
auto containingContext = getAvailabilityForLinkage();
if (containingContext.isAlwaysAvailable())
return false;
auto fromContext = AvailabilityContext::forDeploymentTarget(
fromModule->getASTContext());
return !fromContext.isContainedIn(containingContext);
}
GenericContext::GenericContext(DeclContextKind Kind, DeclContext *Parent,
GenericParamList *Params)
: _GenericContext(), DeclContext(Kind, Parent) {
if (Params) {
Params->setDeclContext(this);
GenericParamsAndBit.setPointerAndInt(Params, false);
}
}
TypeArrayView<GenericTypeParamType>
GenericContext::getInnermostGenericParamTypes() const {
if (auto sig = getGenericSignature())
return sig->getInnermostGenericParams();
else
return { };
}
/// Retrieve the generic requirements.
ArrayRef<Requirement> GenericContext::getGenericRequirements() const {
if (auto sig = getGenericSignature())
return sig->getRequirements();
else
return { };
}
GenericParamList *GenericContext::getGenericParams() const {
return evaluateOrDefault(getASTContext().evaluator,
GenericParamListRequest{
const_cast<GenericContext *>(this)}, nullptr);
}
GenericParamList *GenericContext::getParsedGenericParams() const {
if (GenericParamsAndBit.getInt())
return nullptr;
return GenericParamsAndBit.getPointer();
}
bool GenericContext::hasComputedGenericSignature() const {
return GenericSigAndBit.getInt();
}
bool GenericContext::isComputingGenericSignature() const {
return getASTContext().evaluator.hasActiveRequest(
GenericSignatureRequest{const_cast<GenericContext*>(this)});
}
GenericSignature GenericContext::getGenericSignature() const {
return evaluateOrDefault(
getASTContext().evaluator,
GenericSignatureRequest{const_cast<GenericContext *>(this)}, nullptr);
}
GenericEnvironment *GenericContext::getGenericEnvironment() const {
if (auto genericSig = getGenericSignature())
return genericSig->getGenericEnvironment();
return nullptr;
}
void GenericContext::setGenericSignature(GenericSignature genericSig) {
assert(!GenericSigAndBit.getPointer() && "Generic signature cannot be changed");
getASTContext().evaluator.cacheOutput(GenericSignatureRequest{this},
std::move(genericSig));
}
SourceRange GenericContext::getGenericTrailingWhereClauseSourceRange() const {
if (const auto *where = getTrailingWhereClause())
return where->getSourceRange();
return SourceRange();
}
ImportDecl *ImportDecl::create(ASTContext &Ctx, DeclContext *DC,