/
Decl.h
7317 lines (6013 loc) · 251 KB
/
Decl.h
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.h - Swift Language Declaration ASTs ---------------*- C++ -*-===//
//
// 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 defines the Decl class and subclasses.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_DECL_H
#define SWIFT_DECL_H
#include "swift/AST/AccessScope.h"
#include "swift/AST/Attr.h"
#include "swift/AST/CaptureInfo.h"
#include "swift/AST/ClangNode.h"
#include "swift/AST/ConcreteDeclRef.h"
#include "swift/AST/DefaultArgumentKind.h"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/GenericParamKey.h"
#include "swift/AST/IfConfigClause.h"
#include "swift/AST/LayoutConstraint.h"
#include "swift/AST/StorageImpl.h"
#include "swift/AST/TypeAlignments.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/Types.h"
#include "swift/AST/Witness.h"
#include "swift/Basic/ArrayRefView.h"
#include "swift/Basic/Compiler.h"
#include "swift/Basic/Debug.h"
#include "swift/Basic/InlineBitfield.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/Basic/OptionalEnum.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/Located.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/TrailingObjects.h"
#include <type_traits>
namespace swift {
enum class AccessSemantics : unsigned char;
class AccessorDecl;
class ApplyExpr;
class AvailabilityContext;
class GenericEnvironment;
class ArchetypeType;
class ASTContext;
struct ASTNode;
class ASTPrinter;
class ASTWalker;
class ConstructorDecl;
class DestructorDecl;
class DiagnosticEngine;
class DynamicSelfType;
class Type;
class Expr;
class CaptureListExpr;
class DeclRefExpr;
class ForeignAsyncConvention;
class ForeignErrorConvention;
class LiteralExpr;
class BraceStmt;
class DeclAttributes;
class GenericContext;
class GenericParamList;
class GenericSignature;
class GenericTypeParamDecl;
class GenericTypeParamType;
class ModuleDecl;
class NamedPattern;
class EnumCaseDecl;
class EnumElementDecl;
class ParameterList;
class ParameterTypeFlags;
class Pattern;
struct PrintOptions;
struct PropertyWrapperBackingPropertyInfo;
struct PropertyWrapperTypeInfo;
struct PropertyWrapperMutability;
class ProtocolDecl;
class ProtocolType;
struct RawComment;
enum class ResilienceExpansion : unsigned;
class TrailingWhereClause;
class TypeAliasDecl;
class Stmt;
class SubscriptDecl;
class UnboundGenericType;
class ValueDecl;
class VarDecl;
class OpaqueReturnTypeRepr;
namespace ast_scope {
class AbstractPatternEntryScope;
class PatternEntryDeclScope;
class PatternEntryInitializerScope;
} // namespace ast_scope
enum class DeclKind : uint8_t {
#define DECL(Id, Parent) Id,
#define LAST_DECL(Id) Last_Decl = Id,
#define DECL_RANGE(Id, FirstId, LastId) \
First_##Id##Decl = FirstId, Last_##Id##Decl = LastId,
#include "swift/AST/DeclNodes.def"
};
enum : unsigned { NumDeclKindBits =
countBitsUsed(static_cast<unsigned>(DeclKind::Last_Decl)) };
/// Fine-grained declaration kind that provides a description of the
/// kind of entity a declaration represents, as it would be used in
/// diagnostics.
///
/// For example, \c FuncDecl is a single declaration class, but it has
/// several descriptive entries depending on whether it is an
/// operator, global function, local function, method, (observing)
/// accessor, etc.
enum class DescriptiveDeclKind : uint8_t {
Import,
Extension,
EnumCase,
TopLevelCode,
IfConfig,
PoundDiagnostic,
PatternBinding,
Var,
Param,
Let,
Property,
StaticProperty,
ClassProperty,
InfixOperator,
PrefixOperator,
PostfixOperator,
PrecedenceGroup,
TypeAlias,
GenericTypeParam,
AssociatedType,
Type,
Enum,
Struct,
Class,
Protocol,
GenericEnum,
GenericStruct,
GenericClass,
GenericType,
Subscript,
StaticSubscript,
ClassSubscript,
Constructor,
Destructor,
LocalFunction,
GlobalFunction,
OperatorFunction,
Method,
StaticMethod,
ClassMethod,
Getter,
Setter,
Addressor,
MutableAddressor,
ReadAccessor,
ModifyAccessor,
WillSet,
DidSet,
EnumElement,
Module,
MissingMember,
Requirement,
OpaqueResultType,
OpaqueVarType
};
/// Describes which spelling was used in the source for the 'static' or 'class'
/// keyword.
enum class StaticSpellingKind : uint8_t {
None,
KeywordStatic,
KeywordClass,
};
/// Keeps track of whether an enum has cases that have associated values.
enum class AssociatedValueCheck {
/// We have not yet checked.
Unchecked,
/// The enum contains no cases or all cases contain no associated values.
NoAssociatedValues,
/// The enum contains at least one case with associated values.
HasAssociatedValues,
};
/// Diagnostic printing of \c StaticSpellingKind.
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, StaticSpellingKind SSK);
/// Encapsulation of the overload signature of a given declaration,
/// which is used to determine uniqueness of a declaration within a
/// given context.
///
/// Two definitions in the same context may not have the same overload
/// signature.
struct OverloadSignature {
/// The full name of the declaration.
DeclName Name;
/// The kind of unary operator.
UnaryOperatorKind UnaryOperator;
/// Whether this is an instance member.
unsigned IsInstanceMember : 1;
/// Whether this is a variable.
unsigned IsVariable : 1;
/// Whether this is a function.
unsigned IsFunction : 1;
/// Whether this is a enum element.
unsigned IsEnumElement : 1;
/// Whether this is a nominal type.
unsigned IsNominal : 1;
/// Whether this is a type alias.
unsigned IsTypeAlias : 1;
/// Whether this signature is part of a protocol extension.
unsigned InProtocolExtension : 1;
/// Whether this signature is of a member defined in an extension of a generic
/// type.
unsigned InExtensionOfGenericType : 1;
/// Whether this declaration has an opaque return type.
unsigned HasOpaqueReturnType : 1;
/// Whether this declaration is 'async'
unsigned HasAsync : 1;
OverloadSignature()
: UnaryOperator(UnaryOperatorKind::None), IsInstanceMember(false),
IsVariable(false), IsFunction(false), InProtocolExtension(false),
InExtensionOfGenericType(false), HasOpaqueReturnType(false),
HasAsync(false) {}
};
/// Determine whether two overload signatures conflict.
///
/// \param sig1 The overload signature of the first declaration.
/// \param sig2 The overload signature of the second declaration.
/// \param skipProtocolExtensionCheck If \c true, members of protocol extensions
/// will be allowed to conflict with members of protocol declarations.
bool conflicting(const OverloadSignature& sig1, const OverloadSignature& sig2,
bool skipProtocolExtensionCheck = false);
/// Determine whether two overload signatures and overload types conflict.
///
/// \param ctx The AST context.
/// \param sig1 The overload signature of the first declaration.
/// \param sig1Type The overload type of the first declaration.
/// \param sig2 The overload signature of the second declaration.
/// \param sig2Type The overload type of the second declaration.
/// \param wouldConflictInSwift5 If non-null, the referenced boolean will be set
/// to \c true iff the function returns \c false for this version of
/// Swift, but the given overloads will conflict in Swift 5 mode.
/// \param skipProtocolExtensionCheck If \c true, members of protocol extensions
/// will be allowed to conflict with members of protocol declarations.
bool conflicting(ASTContext &ctx,
const OverloadSignature& sig1, CanType sig1Type,
const OverloadSignature& sig2, CanType sig2Type,
bool *wouldConflictInSwift5 = nullptr,
bool skipProtocolExtensionCheck = false);
/// The kind of artificial main to generate.
enum class ArtificialMainKind : uint8_t {
NSApplicationMain,
UIApplicationMain,
TypeMain,
};
/// Decl - Base class for all declarations in Swift.
class alignas(1 << DeclAlignInBits) Decl {
protected:
union { uint64_t OpaqueBits;
SWIFT_INLINE_BITFIELD_BASE(Decl, bitmax(NumDeclKindBits,8)+1+1+1+1+1,
Kind : bitmax(NumDeclKindBits,8),
/// Whether this declaration is invalid.
Invalid : 1,
/// Whether this declaration was implicitly created, e.g.,
/// an implicit constructor in a struct.
Implicit : 1,
/// Whether this declaration was mapped directly from a Clang AST.
///
/// Use getClangNode() to retrieve the corresponding Clang AST.
FromClang : 1,
/// Whether this declaration was added to the surrounding
/// DeclContext of an active #if config clause.
EscapedFromIfConfig : 1,
/// Whether this declaration is syntactically scoped inside of
/// a local context, but should behave like a top-level
/// declaration for name lookup purposes. This is used by
/// lldb.
Hoisted : 1
);
SWIFT_INLINE_BITFIELD_FULL(PatternBindingDecl, Decl, 1+2+16,
/// Whether this pattern binding declares static variables.
IsStatic : 1,
/// Whether 'static' or 'class' was used.
StaticSpelling : 2,
: NumPadBits,
/// The number of pattern binding declarations.
NumPatternEntries : 16
);
SWIFT_INLINE_BITFIELD_FULL(EnumCaseDecl, Decl, 32,
: NumPadBits,
/// The number of tail-allocated element pointers.
NumElements : 32
);
SWIFT_INLINE_BITFIELD(ValueDecl, Decl, 1+1+1,
AlreadyInLookupTable : 1,
/// Whether we have already checked whether this declaration is a
/// redeclaration.
CheckedRedeclaration : 1,
/// Whether the decl can be accessed by swift users; for instance,
/// a.storage for lazy var a is a decl that cannot be accessed.
IsUserAccessible : 1
);
SWIFT_INLINE_BITFIELD(AbstractStorageDecl, ValueDecl, 1,
/// Whether this property is a type property (currently unfortunately
/// called 'static').
IsStatic : 1
);
SWIFT_INLINE_BITFIELD(VarDecl, AbstractStorageDecl, 1+1+1+1+1+1,
/// Encodes whether this is a 'let' binding.
Introducer : 1,
/// Whether this declaration captures the 'self' param under the same name.
IsSelfParamCapture : 1,
/// Whether this is a property used in expressions in the debugger.
/// It is up to the debugger to instruct SIL how to access this variable.
IsDebuggerVar : 1,
/// Whether this is the backing storage for a lazy property.
IsLazyStorageProperty : 1,
/// Whether this is the backing storage for a property wrapper.
IsPropertyWrapperBackingProperty : 1,
/// Whether this is a lazily top-level global variable from the main file.
IsTopLevelGlobal : 1
);
SWIFT_INLINE_BITFIELD(ParamDecl, VarDecl, 1+2+NumDefaultArgumentKindBits,
/// Whether we've computed the specifier yet.
SpecifierComputed : 1,
/// The specifier associated with this parameter. This determines
/// the storage semantics of the value e.g. mutability.
Specifier : 2,
/// Information about a symbolic default argument, like #file.
defaultArgumentKind : NumDefaultArgumentKindBits
);
SWIFT_INLINE_BITFIELD(SubscriptDecl, VarDecl, 2,
StaticSpelling : 2
);
SWIFT_INLINE_BITFIELD(AbstractFunctionDecl, ValueDecl, 3+8+1+1+1+1+1+1,
/// \see AbstractFunctionDecl::BodyKind
BodyKind : 3,
/// Import as member status.
IAMStatus : 8,
/// Whether the function has an implicit 'self' parameter.
HasImplicitSelfDecl : 1,
/// Whether we are overridden later.
Overridden : 1,
/// Whether the function is async.
Async : 1,
/// Whether the function body throws.
Throws : 1,
/// Whether this member was synthesized as part of a derived
/// protocol conformance.
Synthesized : 1,
/// Whether this member's body consists of a single expression.
HasSingleExpressionBody : 1
);
SWIFT_INLINE_BITFIELD(FuncDecl, AbstractFunctionDecl, 1+1+2+1+1+2+1,
/// Whether we've computed the 'static' flag yet.
IsStaticComputed : 1,
/// Whether this function is a 'static' method.
IsStatic : 1,
/// Whether 'static' or 'class' was used.
StaticSpelling : 2,
/// Whether we are statically dispatched even if overridable
ForcedStaticDispatch : 1,
/// Whether we've computed the 'self' access kind yet.
SelfAccessComputed : 1,
/// Backing bits for 'self' access kind.
SelfAccess : 2,
/// Whether this is a top-level function which should be treated
/// as if it were in local context for the purposes of capture
/// analysis.
HasTopLevelLocalContextCaptures : 1
);
SWIFT_INLINE_BITFIELD(AccessorDecl, FuncDecl, 4 + 1 + 1,
/// The kind of accessor this is.
AccessorKind : 4,
/// Whether the accessor is transparent.
IsTransparent : 1,
/// Whether we have computed the above.
IsTransparentComputed : 1);
SWIFT_INLINE_BITFIELD(ConstructorDecl, AbstractFunctionDecl, 1+1,
/// Whether this constructor can fail, by building an Optional type.
Failable : 1,
/// Whether this initializer is a stub placed into a subclass to
/// catch invalid delegations to a designated initializer not
/// overridden by the subclass. A stub will always trap at runtime.
///
/// Initializer stubs can be invoked from Objective-C or through
/// the Objective-C runtime; there is no way to directly express
/// an object construction that will invoke a stub.
HasStubImplementation : 1
);
SWIFT_INLINE_BITFIELD_EMPTY(TypeDecl, ValueDecl);
SWIFT_INLINE_BITFIELD_EMPTY(AbstractTypeParamDecl, TypeDecl);
SWIFT_INLINE_BITFIELD_FULL(GenericTypeParamDecl, AbstractTypeParamDecl, 16+16,
: NumPadBits,
Depth : 16,
Index : 16
);
SWIFT_INLINE_BITFIELD_EMPTY(GenericTypeDecl, TypeDecl);
SWIFT_INLINE_BITFIELD(TypeAliasDecl, GenericTypeDecl, 1+1,
/// Whether the typealias forwards perfectly to its underlying type.
IsCompatibilityAlias : 1,
/// Whether this was a global typealias synthesized by the debugger.
IsDebuggerAlias : 1
);
SWIFT_INLINE_BITFIELD(NominalTypeDecl, GenericTypeDecl, 1+1+1,
/// Whether we have already added implicitly-defined initializers
/// to this declaration.
AddedImplicitInitializers : 1,
/// Whether there is are lazily-loaded conformances for this nominal type.
HasLazyConformances : 1,
/// Whether this nominal type is having its semantic members resolved.
IsComputingSemanticMembers : 1
);
SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+1+1+8+16,
/// Whether the \c RequiresClass bit is valid.
RequiresClassValid : 1,
/// Whether this is a class-bounded protocol.
RequiresClass : 1,
/// Whether the \c ExistentialConformsToSelf bit is valid.
ExistentialConformsToSelfValid : 1,
/// Whether the existential of this protocol conforms to itself.
ExistentialConformsToSelf : 1,
/// Whether the \c ExistentialTypeSupported bit is valid.
ExistentialTypeSupportedValid : 1,
/// Whether the existential of this protocol can be represented.
ExistentialTypeSupported : 1,
/// True if the protocol has requirements that cannot be satisfied (e.g.
/// because they could not be imported from Objective-C).
HasMissingRequirements : 1,
/// Whether we've computed the inherited protocols list yet.
InheritedProtocolsValid : 1,
/// Whether we have a lazy-loaded requirement signature.
HasLazyRequirementSignature : 1,
: NumPadBits,
/// If this is a compiler-known protocol, this will be a KnownProtocolKind
/// value, plus one. Otherwise, it will be 0.
KnownProtocol : 8, // '8' for speed. This only needs 6.
/// The number of requirements in the requirement signature.
NumRequirementsInSignature : 16
);
SWIFT_INLINE_BITFIELD(ClassDecl, NominalTypeDecl, 1+1+2+1+1+1+1+1,
/// Whether this class inherits its superclass's convenience initializers.
InheritsSuperclassInits : 1,
ComputedInheritsSuperclassInits : 1,
/// \see ClassDecl::ForeignKind
RawForeignKind : 2,
HasMissingDesignatedInitializers : 1,
ComputedHasMissingDesignatedInitializers : 1,
HasMissingVTableEntries : 1,
ComputedHasMissingVTableEntries : 1,
/// Whether instances of this class are incompatible
/// with weak and unowned references.
IsIncompatibleWithWeakReferences : 1
);
SWIFT_INLINE_BITFIELD(
StructDecl, NominalTypeDecl, 1 + 1,
/// True if this struct has storage for fields that aren't accessible in
/// Swift.
HasUnreferenceableStorage : 1,
/// True if this struct is imported from C++ and does not have trivial value witness functions.
IsCxxNonTrivial : 1);
SWIFT_INLINE_BITFIELD(EnumDecl, NominalTypeDecl, 2+1,
/// True if the enum has cases and at least one case has associated values.
HasAssociatedValues : 2,
/// True if the enum has at least one case that has some availability
/// attribute. A single bit because it's lazily computed along with the
/// HasAssociatedValues bit.
HasAnyUnavailableValues : 1
);
SWIFT_INLINE_BITFIELD(ModuleDecl, TypeDecl, 1+1+1+1+1+1+1+1+1+1,
/// If the module was or is being compiled with `-enable-testing`.
TestingEnabled : 1,
/// If the module failed to load
FailedToLoad : 1,
/// Whether the module is resilient.
///
/// \sa ResilienceStrategy
RawResilienceStrategy : 1,
/// Whether all imports have been resolved. Used to detect circular imports.
HasResolvedImports : 1,
/// If the module was or is being compiled with `-enable-private-imports`.
PrivateImportsEnabled : 1,
/// If the module is compiled with `-enable-implicit-dynamic`.
ImplicitDynamicEnabled : 1,
/// Whether the module is a system module.
IsSystemModule : 1,
/// Whether the module was imported from Clang (or, someday, maybe another
/// language).
IsNonSwiftModule : 1,
/// Whether this module is the main module.
IsMainModule : 1,
/// Whether this module has incremental dependency information available.
HasIncrementalInfo : 1
);
SWIFT_INLINE_BITFIELD(PrecedenceGroupDecl, Decl, 1+2,
/// Is this an assignment operator?
IsAssignment : 1,
/// The group's associativity. A value of the Associativity enum.
Associativity : 2
);
SWIFT_INLINE_BITFIELD(ImportDecl, Decl, 3+8,
ImportKind : 3,
/// The number of elements in this path.
NumPathElements : 8
);
SWIFT_INLINE_BITFIELD(ExtensionDecl, Decl, 3+1,
/// An encoding of the default and maximum access level for this extension.
///
/// This is encoded as (1 << (maxAccess-1)) | (1 << (defaultAccess-1)),
/// which works because the maximum is always greater than or equal to the
/// default, and 'private' is never used. 0 represents an uncomputed value.
DefaultAndMaxAccessLevel : 3,
/// Whether there is are lazily-loaded conformances for this extension.
HasLazyConformances : 1
);
SWIFT_INLINE_BITFIELD(IfConfigDecl, Decl, 1,
/// Whether this decl is missing its closing '#endif'.
HadMissingEnd : 1
);
SWIFT_INLINE_BITFIELD(PoundDiagnosticDecl, Decl, 1+1,
/// `true` if the diagnostic is an error, `false` if it's a warning.
IsError : 1,
/// Whether this diagnostic has already been emitted.
HasBeenEmitted : 1
);
SWIFT_INLINE_BITFIELD(MissingMemberDecl, Decl, 1+2,
NumberOfFieldOffsetVectorEntries : 1,
NumberOfVTableEntries : 2
);
} Bits;
// Storage for the declaration attributes.
DeclAttributes Attrs;
/// The next declaration in the list of declarations within this
/// member context.
Decl *NextDecl = nullptr;
friend class DeclIterator;
friend class IterableDeclContext;
friend class MemberLookupTable;
private:
llvm::PointerUnion<DeclContext *, ASTContext *> Context;
Decl(const Decl&) = delete;
void operator=(const Decl&) = delete;
SourceLoc getLocFromSource() const;
struct CachedExternalSourceLocs {
SourceLoc Loc;
SourceLoc StartLoc;
SourceLoc EndLoc;
SmallVector<CharSourceRange, 4> DocRanges;
};
mutable CachedExternalSourceLocs const *CachedSerializedLocs = nullptr;
const CachedExternalSourceLocs *getSerializedLocs() const;
protected:
Decl(DeclKind kind, llvm::PointerUnion<DeclContext *, ASTContext *> context)
: Context(context) {
Bits.OpaqueBits = 0;
Bits.Decl.Kind = unsigned(kind);
Bits.Decl.Invalid = false;
Bits.Decl.Implicit = false;
Bits.Decl.FromClang = false;
Bits.Decl.EscapedFromIfConfig = false;
Bits.Decl.Hoisted = false;
}
/// Get the Clang node associated with this declaration.
ClangNode getClangNodeImpl() const;
/// Set the Clang node associated with this declaration.
void setClangNode(ClangNode Node);
void updateClangNode(ClangNode node) {
assert(hasClangNode());
setClangNode(node);
}
friend class ClangImporter;
DeclContext *getDeclContextForModule() const;
public:
DeclKind getKind() const { return DeclKind(Bits.Decl.Kind); }
/// Retrieve the name of the given declaration kind.
///
/// This name should only be used for debugging dumps and other
/// developer aids, and should never be part of a diagnostic or exposed
/// to the user of the compiler in any way.
static StringRef getKindName(DeclKind K);
/// Retrieve the descriptive kind for this declaration.
DescriptiveDeclKind getDescriptiveKind() const;
/// Produce a name for the given descriptive declaration kind, which
/// is suitable for use in diagnostics.
static StringRef getDescriptiveKindName(DescriptiveDeclKind K);
/// Whether swift users should be able to access this decl. For instance,
/// var a.storage for lazy var a is an inaccessible decl. An inaccessible decl
/// has to be implicit; but an implicit decl does not have to be inaccessible,
/// for instance, self.
bool isUserAccessible() const;
/// Determine if the decl can have a comment. If false, a comment will
/// not be serialized.
bool canHaveComment() const;
LLVM_READONLY
DeclContext *getDeclContext() const {
if (auto dc = Context.dyn_cast<DeclContext *>())
return dc;
return getDeclContextForModule();
}
void setDeclContext(DeclContext *DC);
/// Retrieve the innermost declaration context corresponding to this
/// declaration, which will either be the declaration itself (if it's
/// also a declaration context) or its declaration context.
DeclContext *getInnermostDeclContext() const;
/// Retrieve the module in which this declaration resides.
LLVM_READONLY
ModuleDecl *getModuleContext() const;
/// getASTContext - Return the ASTContext that this decl lives in.
LLVM_READONLY
ASTContext &getASTContext() const {
if (auto dc = Context.dyn_cast<DeclContext *>())
return dc->getASTContext();
return *Context.get<ASTContext *>();
}
const DeclAttributes &getAttrs() const {
return Attrs;
}
DeclAttributes &getAttrs() {
return Attrs;
}
/// Returns the introduced OS version in the given platform kind specified
/// by @available attribute.
/// This function won't consider the parent context to get the information.
Optional<llvm::VersionTuple> getIntroducedOSVersion(PlatformKind Kind) const;
/// Returns the starting location of the entire declaration.
SourceLoc getStartLoc() const { return getSourceRange().Start; }
/// Returns the end location of the entire declaration.
SourceLoc getEndLoc() const { return getSourceRange().End; }
/// Returns the preferred location when referring to declarations
/// in diagnostics.
SourceLoc getLoc(bool SerializedOK = true) const;
/// Returns the source range of the entire declaration.
SourceRange getSourceRange() const;
/// Returns the source range of the declaration including its attributes.
SourceRange getSourceRangeIncludingAttrs() const;
SourceLoc TrailingSemiLoc;
/// Returns the appropriate kind of entry point to generate for this class,
/// based on its attributes.
///
/// It is an error to call this on a type that does not have either an
/// *ApplicationMain or an main attribute.
ArtificialMainKind getArtificialMainKind() const;
SWIFT_DEBUG_DUMP;
SWIFT_DEBUG_DUMPER(dump(const char *filename));
void dump(raw_ostream &OS, unsigned Indent = 0) const;
/// Pretty-print the given declaration.
///
/// \param OS Output stream to which the declaration will be printed.
void print(raw_ostream &OS) const;
void print(raw_ostream &OS, const PrintOptions &Opts) const;
/// Pretty-print the given declaration.
///
/// \param Printer ASTPrinter object.
///
/// \param Opts Options to control how pretty-printing is performed.
///
/// \returns true if the declaration was printed or false if the print options
/// required the declaration to be skipped from printing.
bool print(ASTPrinter &Printer, const PrintOptions &Opts) const;
/// Determine whether this declaration should be printed when
/// encountered in its declaration context's list of members.
bool shouldPrintInContext(const PrintOptions &PO) const;
bool walk(ASTWalker &walker);
/// Return whether this declaration has been determined invalid.
bool isInvalid() const;
/// Mark this declaration invalid.
void setInvalid();
/// Determine whether this declaration was implicitly generated by the
/// compiler (rather than explicitly written in source code).
bool isImplicit() const { return Bits.Decl.Implicit; }
/// Mark this declaration as implicit.
void setImplicit(bool implicit = true) { Bits.Decl.Implicit = implicit; }
/// Determine whether this declaration is syntactically scoped inside of
/// a local context, but should behave like a top-level declaration
/// for name lookup purposes. This is used by lldb.
bool isHoisted() const { return Bits.Decl.Hoisted; }
/// Set whether this declaration should be syntactically scoped inside
/// of a local context, but should behave like a top-level declaration,
/// but should behave like a top-level declaration. This is used by lldb.
void setHoisted(bool hoisted = true) { Bits.Decl.Hoisted = hoisted; }
public:
bool escapedFromIfConfig() const {
return Bits.Decl.EscapedFromIfConfig;
}
void setEscapedFromIfConfig(bool Escaped) {
Bits.Decl.EscapedFromIfConfig = Escaped;
}
/// \returns the unparsed comment attached to this declaration.
RawComment getRawComment(bool SerializedOK = false) const;
Optional<StringRef> getGroupName() const;
Optional<StringRef> getSourceFileName() const;
Optional<unsigned> getSourceOrder() const;
/// \returns the brief comment attached to this declaration.
StringRef getBriefComment() const;
/// Returns true if there is a Clang AST node associated
/// with self.
bool hasClangNode() const {
return Bits.Decl.FromClang;
}
/// Retrieve the Clang AST node from which this declaration was
/// synthesized, if any.
LLVM_READONLY
ClangNode getClangNode() const {
if (!Bits.Decl.FromClang)
return ClangNode();
return getClangNodeImpl();
}
/// Retrieve the Clang declaration from which this declaration was
/// synthesized, if any.
LLVM_READONLY
const clang::Decl *getClangDecl() const {
if (!Bits.Decl.FromClang)
return nullptr;
return getClangNodeImpl().getAsDecl();
}
/// Retrieve the Clang macro from which this declaration was
/// synthesized, if any.
LLVM_READONLY
const clang::MacroInfo *getClangMacro() {
if (!Bits.Decl.FromClang)
return nullptr;
return getClangNodeImpl().getAsMacro();
}
/// Return the GenericContext if the Decl has one.
LLVM_READONLY
const GenericContext *getAsGenericContext() const;
bool hasUnderscoredNaming() const;
bool isPrivateStdlibDecl(bool treatNonBuiltinProtocolsAsPublic = true) const;
/// Check if this is a declaration defined at the top level of the Swift module
bool isStdlibDecl() const;
AvailabilityContext getAvailabilityForLinkage() const;
/// Whether this declaration or one of its outer contexts has the
/// @_weakLinked attribute.
bool isAlwaysWeakImported() const;
/// Whether this declaration is weak-imported from the given module,
/// either because of the presence of the @_weakLinked attribute, or
/// because of availability.
///
/// Note that \p fromModule should either be the "main module" or
/// nullptr. (This is because when it is non-null, we query the
/// current deployment target, and not the deployment target that
/// the module was built with.)
///
/// If \p fromModule is the main module, this returns false when the
/// declaration is part of the main module, or if the declaration is
/// at least as available as the current deployment target.
///
/// If \p fromModule is null, we instead return true if the
/// declaration is meant to be weak linked with _some_ deployment
/// target; that is, the presence of the @_weakLinked attribute or
/// any kind of availability is enough, irrespective of the current
/// deployment target.
bool isWeakImported(ModuleDecl *fromModule) const;
/// Returns true if the nature of this declaration allows overrides.
/// Note that this does not consider whether it is final or whether
/// the class it's on is final.
///
/// If this returns true, the decl can be safely casted to ValueDecl.
bool isPotentiallyOverridable() const;
/// Returns true if this Decl cannot be seen by any other source file
bool isPrivateToEnclosingFile() const;
/// Retrieve the global actor attribute that applies to this declaration,
/// if any.
///
/// This is the "raw" global actor attribute as written directly on the
/// declaration, along with the nominal type declaration to which it refers,
/// without any inference rules applied.
Optional<std::pair<CustomAttr *, NominalTypeDecl *>>
getGlobalActorAttr() const;
/// If an alternative module name is specified for this decl, e.g. using
/// @_originalDefinedIn attribute, this function returns this module name.
StringRef getAlternateModuleName() const;
// Is this Decl an SPI? It can be directly marked with @_spi or is defined in
// an @_spi context.
bool isSPI() const;
// List the SPI groups declared with @_spi or inherited by this decl.
//
// SPI groups are inherited from the parent contexts only if the local decl
// doesn't declare any @_spi.
ArrayRef<Identifier> getSPIGroups() const;
/// Emit a diagnostic tied to this declaration.
template<typename ...ArgTypes>
InFlightDiagnostic diagnose(
Diag<ArgTypes...> ID,
typename detail::PassArgument<ArgTypes>::type... Args) const {
return getDiags().diagnose(this, ID, std::move(Args)...);
}
/// Retrieve the diagnostic engine for diagnostics emission.
LLVM_READONLY
DiagnosticEngine &getDiags() const;
// Make vanilla new/delete illegal for Decls.
void *operator new(size_t Bytes) = delete;
void operator delete(void *Data) = delete;
// Only allow allocation of Decls using the allocator in ASTContext
// or by doing a placement new.
void *operator new(size_t Bytes, const ASTContext &C,
unsigned Alignment = alignof(Decl));
void *operator new(size_t Bytes, void *Mem) {
assert(Mem);