-
Notifications
You must be signed in to change notification settings - Fork 10.7k
Expand file tree
/
Copy pathDecl.h
More file actions
6553 lines (5435 loc) · 223 KB
/
Decl.h
File metadata and controls
6553 lines (5435 loc) · 223 KB
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 - 2017 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/GenericParamKey.h"
#include "swift/AST/IfConfigClause.h"
#include "swift/AST/LayoutConstraint.h"
#include "swift/AST/TypeAlignments.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/Witness.h"
#include "swift/Basic/Compiler.h"
#include "swift/Basic/InlineBitfield.h"
#include "swift/Basic/OptionalEnum.h"
#include "swift/Basic/Range.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/TrailingObjects.h"
namespace swift {
enum class AccessSemantics : unsigned char;
class AccessorDecl;
class ApplyExpr;
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 DeclRefExpr;
class ForeignErrorConvention;
class LiteralExpr;
class BraceStmt;
class DeclAttributes;
class GenericContext;
class GenericSignature;
class GenericTypeParamDecl;
class GenericTypeParamType;
class LazyResolver;
class ModuleDecl;
class NameAliasType;
class EnumCaseDecl;
class EnumElementDecl;
class ParameterList;
class ParameterTypeFlags;
class Pattern;
struct PrintOptions;
class ProtocolDecl;
class ProtocolType;
struct RawComment;
enum class ResilienceExpansion : unsigned;
class TypeAliasDecl;
class Stmt;
class SubscriptDecl;
class UnboundGenericType;
class ValueDecl;
class VarDecl;
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,
PatternBinding,
Var,
Param,
Let,
StaticVar,
StaticLet,
ClassVar,
ClassLet,
InfixOperator,
PrefixOperator,
PostfixOperator,
PrecedenceGroup,
TypeAlias,
GenericTypeParam,
AssociatedType,
Enum,
Struct,
Class,
Protocol,
GenericEnum,
GenericStruct,
GenericClass,
Subscript,
Constructor,
Destructor,
LocalFunction,
GlobalFunction,
OperatorFunction,
Method,
StaticMethod,
ClassMethod,
Getter,
Setter,
MaterializeForSet,
Addressor,
MutableAddressor,
WillSet,
DidSet,
EnumElement,
Module,
MissingMember,
};
/// Keeps track of stage of circularity checking for the given protocol.
enum class CircularityCheck {
/// Circularity has not yet been checked.
Unchecked,
/// We're currently checking circularity.
Checking,
/// Circularity has already been checked.
Checked
};
/// Keeps track of whether a given class inherits initializers from its
/// superclass.
enum class StoredInheritsSuperclassInits {
/// We have not yet checked.
Unchecked,
/// Superclass initializers are not inherited.
NotInherited,
/// Convenience initializers in the superclass are inherited.
Inherited
};
/// 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,
};
/// Describes if an enum element constructor directly or indirectly references
/// its enclosing type.
enum class ElementRecursiveness {
/// The element does not reference its enclosing type.
NotRecursive,
/// The element is currently being validated, and may references its enclosing
/// type.
PotentiallyRecursive,
/// The element does not reference its enclosing type.
Recursive
};
/// 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 = UnaryOperatorKind::None;
/// Whether this is an instance member.
bool IsInstanceMember = false;
/// Whether this is a property.
bool IsProperty = false;
/// Whether this signature is part of a protocol extension.
bool InProtocolExtension = false;
};
/// Determine whether two overload signatures conflict.
bool conflicting(const OverloadSignature& sig1, const OverloadSignature& sig2,
bool skipProtocolExtensionCheck = false);
/// 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+1+1,
Kind : bitmax(NumDeclKindBits,8),
/// \brief Whether this declaration is invalid.
Invalid : 1,
/// \brief Whether this declaration was implicitly created, e.g.,
/// an implicit constructor in a struct.
Implicit : 1,
/// \brief Whether this declaration was mapped directly from a Clang AST.
///
/// Use getClangNode() to retrieve the corresponding Clang AST.
FromClang : 1,
/// \brief Whether we've already performed early attribute validation.
/// FIXME: This is ugly.
EarlyAttrValidation : 1,
/// \brief Whether this declaration is currently being validated.
BeingValidated : 1,
/// \brief Whether we have started validating the declaration; this *isn't*
/// reset after finishing it.
ValidationStarted : 1,
/// \brief Whether this declaration was added to the surrounding
/// DeclContext of an active #if config clause.
EscapedFromIfConfig : 1
);
SWIFT_INLINE_BITFIELD_FULL(PatternBindingDecl, Decl, 1+2+16,
/// \brief Whether this pattern binding declares static variables.
IsStatic : 1,
/// \brief Whether 'static' or 'class' was used.
StaticSpelling : 2,
: NumPadBits,
/// \brief 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+1+1+4,
/// Whether we are overridden later
Overridden : 1,
/// Whether the getter is mutating.
IsGetterMutating : 1,
/// Whether the setter is mutating.
IsSetterMutating : 1,
/// The storage kind.
StorageKind : 4
);
SWIFT_INLINE_BITFIELD(VarDecl, AbstractStorageDecl, 1+2+1+1+1,
/// \brief Whether this property is a type property (currently unfortunately
/// called 'static').
IsStatic : 1,
/// \brief The specifier associated with this variable or parameter. This
/// determines the storage semantics of the value e.g. mutability.
Specifier : 2,
/// \brief Whether this declaration was an element of a capture list.
IsCaptureList : 1,
/// \brief Whether this vardecl has an initial value bound to it in a way
/// that isn't represented in the AST with an initializer in the pattern
/// binding. This happens in cases like "for i in ...", switch cases, etc.
HasNonPatternBindingInit : 1,
/// \brief 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
);
SWIFT_INLINE_BITFIELD(ParamDecl, VarDecl, 1 + NumDefaultArgumentKindBits,
/// True if the type is implicitly specified in the source, but this has an
/// apparently valid typeRepr. This is used in accessors, which look like:
/// set (value) {
/// but need to get the typeRepr from the property as a whole so Sema can
/// resolve the type.
IsTypeLocImplicit : 1,
/// Information about a symbolic default argument, like #file.
defaultArgumentKind : NumDefaultArgumentKindBits
);
SWIFT_INLINE_BITFIELD(EnumElementDecl, ValueDecl, 3,
/// \brief Whether or not this element has an associated value.
HasArgumentType : 1,
/// \brief Whether or not this element directly or indirectly references
/// the enum type.
Recursiveness : 2
);
SWIFT_INLINE_BITFIELD(AbstractFunctionDecl, ValueDecl, 3+8+5+1+1+1+1+1,
/// \see AbstractFunctionDecl::BodyKind
BodyKind : 3,
/// Import as member status.
IAMStatus : 8,
/// Number of curried parameter lists.
NumParameterLists : 5,
/// Whether we are overridden later.
Overridden : 1,
/// Whether the function body throws.
Throws : 1,
/// Whether this function requires a new vtable entry.
NeedsNewVTableEntry : 1,
/// Whether NeedsNewVTableEntry is valid.
HasComputedNeedsNewVTableEntry : 1,
/// The ResilienceExpansion to use for default arguments.
DefaultArgumentResilienceExpansion : 1
);
SWIFT_INLINE_BITFIELD(FuncDecl, AbstractFunctionDecl, 1+2+1+1+2,
/// Whether this function is a 'static' method.
IsStatic : 1,
/// \brief Whether 'static' or 'class' was used.
StaticSpelling : 2,
/// Whether we are statically dispatched even if overridable
ForcedStaticDispatch : 1,
/// Whether this function has a dynamic Self return type.
HasDynamicSelf : 1,
/// Backing bits for 'self' access kind.
SelfAccess : 2
);
SWIFT_INLINE_BITFIELD(AccessorDecl, FuncDecl, 3+3,
/// The kind of accessor this is.
AccessorKind : 3,
/// The kind of addressor this is.
AddressorKind : 3
);
SWIFT_INLINE_BITFIELD(ConstructorDecl, AbstractFunctionDecl, 3+2+2+1,
/// The body initialization kind (+1), or zero if not yet computed.
///
/// This value is cached but is not serialized, because it is a property
/// of the definition of the constructor that is useful only to semantic
/// analysis and SIL generation.
ComputedBodyInitKind : 3,
/// The kind of initializer we have.
InitKind : 2,
/// The failability of this initializer, which is an OptionalTypeKind.
Failability : 2,
/// 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(TypeDecl, ValueDecl, 1,
/// Whether we have already checked the inheritance clause.
///
/// FIXME: Is this too fine-grained?
CheckedInheritanceClause : 1
);
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,
/// Whether the typealias forwards perfectly to its underlying type.
IsCompatibilityAlias : 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 we have already validated all members of the type that
/// affect layout.
HasValidatedLayout : 1
);
SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+2+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,
/// The stage of the circularity check for this protocol.
Circularity : 2,
: 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+2+2+2+1+3+1+1,
/// Whether this class requires all of its instance variables to
/// have in-class initializers.
RequiresStoredPropertyInits : 1,
/// The stage of the inheritance circularity check for this class.
Circularity : 2,
/// Whether this class inherits its superclass's convenience
/// initializers.
///
/// This is a value of \c StoredInheritsSuperclassInits.
InheritsSuperclassInits : 2,
/// \see ClassDecl::ForeignKind
RawForeignKind : 2,
/// Whether this class contains a destructor decl.
///
/// A fully type-checked class always contains a destructor member, even if
/// it is implicit. This bit is used during parsing and type-checking to
/// control inserting the implicit destructor.
HasDestructorDecl : 1,
/// Whether the class has @objc ancestry.
ObjCKind : 3,
HasMissingDesignatedInitializers : 1,
HasMissingVTableEntries : 1
);
SWIFT_INLINE_BITFIELD(StructDecl, NominalTypeDecl, 1,
/// True if this struct has storage for fields that aren't accessible in
/// Swift.
HasUnreferenceableStorage : 1
);
SWIFT_INLINE_BITFIELD(EnumDecl, NominalTypeDecl, 2+2,
/// The stage of the raw type circularity check for this class.
Circularity : 2,
/// True if the enum has cases and at least one case has associated values.
HasAssociatedValues : 2
);
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(AssociatedTypeDecl, TypeDecl, 1+1,
ComputedOverridden : 1,
HasOverridden : 1
);
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+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 we have already checked the inheritance clause.
///
/// FIXME: Is this too fine-grained?
CheckedInheritanceClause : 1,
/// 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(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;
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.EarlyAttrValidation = false;
Bits.Decl.BeingValidated = false;
Bits.Decl.ValidationStarted = false;
Bits.Decl.EscapedFromIfConfig = false;
}
/// \brief Get the Clang node associated with this declaration.
ClangNode getClangNodeImpl() const;
/// \brief 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); }
/// \brief 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;
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;
/// \brief Retrieve the module in which this declaration resides.
ModuleDecl *getModuleContext() const;
/// getASTContext - Return the ASTContext that this decl lives in.
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 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() 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;
LLVM_ATTRIBUTE_DEPRECATED(
void dump() const LLVM_ATTRIBUTE_USED,
"only for use within the debugger");
LLVM_ATTRIBUTE_DEPRECATED(
void dump(const char *filename) const LLVM_ATTRIBUTE_USED,
"only for use within the debugger");
void dump(raw_ostream &OS, unsigned Indent = 0) const;
/// \brief 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;
/// \brief 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;
/// \brief 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);
/// \brief Return whether this declaration has been determined invalid.
bool isInvalid() const { return Bits.Decl.Invalid; }
/// \brief Mark this declaration invalid.
void setInvalid(bool isInvalid = true) { Bits.Decl.Invalid = isInvalid; }
/// \brief Determine whether this declaration was implicitly generated by the
/// compiler (rather than explicitly written in source code).
bool isImplicit() const { return Bits.Decl.Implicit; }
/// \brief Mark this declaration as implicit.
void setImplicit(bool implicit = true) { Bits.Decl.Implicit = implicit; }
/// Whether we have already done early attribute validation.
bool didEarlyAttrValidation() const { return Bits.Decl.EarlyAttrValidation; }
/// Set whether we've performed early attribute validation.
void setEarlyAttrValidation(bool validated = true) {
Bits.Decl.EarlyAttrValidation = validated;
}
/// Whether the declaration has a valid interface type and
/// generic signature.
bool isBeingValidated() const {
return Bits.Decl.BeingValidated;
}
/// Toggle whether or not the declaration is being validated.
void setIsBeingValidated(bool ibv = true) {
assert(Bits.Decl.BeingValidated != ibv);
Bits.Decl.BeingValidated = ibv;
if (ibv) {
Bits.Decl.ValidationStarted = true;
}
}
bool hasValidationStarted() const { return Bits.Decl.ValidationStarted; }
/// Manually indicate that validation has started for the declaration.
///
/// This is implied by setIsBeingValidated(true) (i.e. starting validation)
/// and so rarely needs to be called directly.
void setValidationStarted() { Bits.Decl.ValidationStarted = true; }
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() const;
Optional<StringRef> getGroupName() const;
Optional<StringRef> getSourceFileName() const;
Optional<unsigned> getSourceOrder() const;
/// \returns the brief comment attached to this declaration.
StringRef getBriefComment() const;
/// \brief Returns true if there is a Clang AST node associated
/// with self.
bool hasClangNode() const {
return Bits.Decl.FromClang;
}
/// \brief Retrieve the Clang AST node from which this declaration was
/// synthesized, if any.
ClangNode getClangNode() const {
if (!Bits.Decl.FromClang)
return ClangNode();
return getClangNodeImpl();
}
/// \brief Retrieve the Clang declaration from which this declaration was
/// synthesized, if any.
const clang::Decl *getClangDecl() const {
if (!Bits.Decl.FromClang)
return nullptr;
return getClangNodeImpl().getAsDecl();
}
/// \brief Retrieve the Clang macro from which this declaration was
/// synthesized, if any.
const clang::MacroInfo *getClangMacro() {
if (!Bits.Decl.FromClang)
return nullptr;
return getClangNodeImpl().getAsMacro();
}
/// \brief Return the GenericContext if the Decl has one.
const GenericContext *getAsGenericContext() const;
bool isPrivateStdlibDecl(bool treatNonBuiltinProtocolsAsPublic = true) const;
/// Whether this declaration is weak-imported.
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;
// Make vanilla new/delete illegal for Decls.
void *operator new(size_t Bytes) = delete;
void operator delete(void *Data) SWIFT_DELETE_OPERATOR_DELETED;
// 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);
return Mem;
}
};
/// \brief Allocates memory for a Decl with the given \p baseSize. If necessary,
/// it includes additional space immediately preceding the Decl for a ClangNode.
/// \note \p baseSize does not need to include space for a ClangNode if
/// requested -- the necessary space will be added automatically.
template <typename DeclTy, typename AllocatorTy>
void *allocateMemoryForDecl(AllocatorTy &allocator, size_t baseSize,
bool includeSpaceForClangNode) {
static_assert(alignof(DeclTy) >= sizeof(void *),
"A pointer must fit in the alignment of the DeclTy!");
size_t size = baseSize;
if (includeSpaceForClangNode)
size += alignof(DeclTy);
void *mem = allocator.Allocate(size, alignof(DeclTy));
if (includeSpaceForClangNode)
mem = reinterpret_cast<char *>(mem) + alignof(DeclTy);
return mem;
}
enum class RequirementReprKind : unsigned {
/// A type bound T : P, where T is a type that depends on a generic
/// parameter and P is some type that should bound T, either as a concrete
/// supertype or a protocol to which T must conform.
TypeConstraint,
/// A same-type requirement T == U, where T and U are types that shall be
/// equivalent.
SameType,
/// A layout bound T : L, where T is a type that depends on a generic
/// parameter and L is some layout specification that should bound T.
LayoutConstraint,
// Note: there is code that packs this enum in a 2-bit bitfield. Audit users
// when adding enumerators.
};
/// \brief A single requirement in a 'where' clause, which places additional
/// restrictions on the generic parameters or associated types of a generic
/// function, type, or protocol.
///
/// This always represents a requirement spelled in the source code. It is
/// never generated implicitly.
///
/// \c GenericParamList assumes these are POD-like.
class RequirementRepr {
SourceLoc SeparatorLoc;
RequirementReprKind Kind : 2;
bool Invalid : 1;
TypeLoc FirstType;
/// The second element represents the right-hand side of the constraint.
/// It can be e.g. a type or a layout constraint.
union {
TypeLoc SecondType;
LayoutConstraintLoc SecondLayout;
};
/// Set during deserialization; used to print out the requirements accurately
/// for the generated interface.
StringRef AsWrittenString;
RequirementRepr(SourceLoc SeparatorLoc, RequirementReprKind Kind,
TypeLoc FirstType, TypeLoc SecondType)
: SeparatorLoc(SeparatorLoc), Kind(Kind), Invalid(false),
FirstType(FirstType), SecondType(SecondType) { }
RequirementRepr(SourceLoc SeparatorLoc, RequirementReprKind Kind,
TypeLoc FirstType, LayoutConstraintLoc SecondLayout)
: SeparatorLoc(SeparatorLoc), Kind(Kind), Invalid(false),
FirstType(FirstType), SecondLayout(SecondLayout) { }
void printImpl(ASTPrinter &OS, bool AsWritten) const;
public:
/// \brief Construct a new type-constraint requirement.
///
/// \param Subject The type that must conform to the given protocol or
/// composition, or be a subclass of the given class type.
/// \param ColonLoc The location of the ':', or an invalid location if
/// this requirement was implied.
/// \param Constraint The protocol or protocol composition to which the
/// subject must conform, or superclass from which the subject must inherit.
static RequirementRepr getTypeConstraint(TypeLoc Subject,
SourceLoc ColonLoc,
TypeLoc Constraint) {
return { ColonLoc, RequirementReprKind::TypeConstraint, Subject, Constraint };
}
/// \brief Construct a new same-type requirement.
///
/// \param FirstType The first type.
/// \param EqualLoc The location of the '==' in the same-type constraint, or
/// an invalid location if this requirement was implied.
/// \param SecondType The second type.
static RequirementRepr getSameType(TypeLoc FirstType,
SourceLoc EqualLoc,
TypeLoc SecondType) {
return { EqualLoc, RequirementReprKind::SameType, FirstType, SecondType };
}
/// \brief Construct a new layout-constraint requirement.
///
/// \param Subject The type that must conform to the given layout
/// requirement.
/// \param ColonLoc The location of the ':', or an invalid location if
/// this requirement was implied.
/// \param Layout The layout requirement to which the
/// subject must conform.
static RequirementRepr getLayoutConstraint(TypeLoc Subject,
SourceLoc ColonLoc,
LayoutConstraintLoc Layout) {
return {ColonLoc, RequirementReprKind::LayoutConstraint, Subject,
Layout};
}
/// \brief Determine the kind of requirement
RequirementReprKind getKind() const { return Kind; }
/// \brief Determine whether this requirement is invalid.