forked from apple/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Attr.h
2141 lines (1768 loc) · 74.3 KB
/
Attr.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
//===--- Attr.h - Swift Language Attribute 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 classes related to declaration attributes.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_ATTR_H
#define SWIFT_ATTR_H
#include "swift/Basic/Debug.h"
#include "swift/Basic/InlineBitfield.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/Basic/UUID.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/OptimizationMode.h"
#include "swift/Basic/Version.h"
#include "swift/Basic/Located.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/AttrKind.h"
#include "swift/AST/AutoDiff.h"
#include "swift/AST/ConcreteDeclRef.h"
#include "swift/AST/DeclNameLoc.h"
#include "swift/AST/KnownProtocols.h"
#include "swift/AST/Ownership.h"
#include "swift/AST/PlatformKind.h"
#include "swift/AST/Requirement.h"
#include "swift/AST/TrailingCallArguments.h"
#include "swift/AST/TypeLoc.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TrailingObjects.h"
#include "llvm/Support/VersionTuple.h"
namespace swift {
class ASTPrinter;
class ASTContext;
struct PrintOptions;
class Decl;
class AbstractFunctionDecl;
class FuncDecl;
class ClassDecl;
class GenericFunctionType;
class LazyConformanceLoader;
class LazyMemberLoader;
class PatternBindingInitializer;
class TrailingWhereClause;
/// TypeAttributes - These are attributes that may be applied to types.
class TypeAttributes {
// Get a SourceLoc for every possible attribute that can be parsed in source.
// the presence of the attribute is indicated by its location being set.
SourceLoc AttrLocs[TAK_Count];
public:
/// AtLoc - This is the location of the first '@' in the attribute specifier.
/// If this is an empty attribute specifier, then this will be an invalid loc.
SourceLoc AtLoc;
struct Convention {
StringRef Name = {};
DeclNameRef WitnessMethodProtocol = {};
Located<StringRef> ClangType = Located<StringRef>(StringRef(), {});
/// Convenience factory function to create a Swift convention.
///
/// Don't use this function if you are creating a C convention as you
/// probably need a ClangType field as well.
static Convention makeSwiftConvention(StringRef name) {
return {name, DeclNameRef(), Located<StringRef>("", {})};
}
};
Optional<Convention> ConventionArguments;
// Indicates whether the type's '@differentiable' attribute has a 'linear'
// argument.
bool linear = false;
// For an opened existential type, the known ID.
Optional<UUID> OpenedID;
// For a reference to an opaque return type, the mangled name and argument
// index into the generic signature.
struct OpaqueReturnTypeRef {
StringRef mangledName;
unsigned index;
};
Optional<OpaqueReturnTypeRef> OpaqueReturnTypeOf;
TypeAttributes() {}
bool isValid() const { return AtLoc.isValid(); }
bool isLinear() const {
assert(
!linear ||
(linear && has(TAK_differentiable)) &&
"Linear shouldn't have been true if there's no `@differentiable`");
return linear;
}
void clearAttribute(TypeAttrKind A) {
AttrLocs[A] = SourceLoc();
}
bool has(TypeAttrKind A) const {
return getLoc(A).isValid();
}
SourceLoc getLoc(TypeAttrKind A) const {
return AttrLocs[A];
}
void setOpaqueReturnTypeOf(StringRef mangling, unsigned index) {
OpaqueReturnTypeOf = OpaqueReturnTypeRef{mangling, index};
}
void setAttr(TypeAttrKind A, SourceLoc L) {
assert(!L.isInvalid() && "Cannot clear attribute with this method");
AttrLocs[A] = L;
}
void getAttrLocs(SmallVectorImpl<SourceLoc> &Locs) const {
for (auto Loc : AttrLocs) {
if (Loc.isValid())
Locs.push_back(Loc);
}
}
// This attribute list is empty if no attributes are specified. Note that
// the presence of the leading @ is not enough to tell, because we want
// clients to be able to remove attributes they process until they get to
// an empty list.
bool empty() const {
for (SourceLoc elt : AttrLocs)
if (elt.isValid())
return false;
return true;
}
bool hasConvention() const { return ConventionArguments.hasValue(); }
/// Returns the primary calling convention string.
///
/// Note: For C conventions, this may not represent the full convention.
StringRef getConventionName() const {
return ConventionArguments.getValue().Name;
}
/// Show the string enclosed between @convention(..)'s parentheses.
///
/// For example, @convention(foo, bar) will give the string "foo, bar".
void getConventionArguments(SmallVectorImpl<char> &buffer) const;
bool hasOwnership() const {
return getOwnership() != ReferenceOwnership::Strong;
}
ReferenceOwnership getOwnership() const {
#define REF_STORAGE(Name, name, ...) \
if (has(TAK_sil_##name)) return ReferenceOwnership::Name;
#include "swift/AST/ReferenceStorage.def"
return ReferenceOwnership::Strong;
}
void clearOwnership() {
#define REF_STORAGE(Name, name, ...) \
clearAttribute(TAK_sil_##name);
#include "swift/AST/ReferenceStorage.def"
}
bool hasOpenedID() const { return OpenedID.hasValue(); }
UUID getOpenedID() const { return *OpenedID; }
/// Given a name like "autoclosure", return the type attribute ID that
/// corresponds to it. This returns TAK_Count on failure.
///
static TypeAttrKind getAttrKindFromString(StringRef Str);
/// Return the name (like "autoclosure") for an attribute ID.
static const char *getAttrName(TypeAttrKind kind);
};
class alignas(1 << AttrAlignInBits) AttributeBase {
public:
/// The location of the '@'.
const SourceLoc AtLoc;
/// The source range of the attribute.
const SourceRange Range;
/// The location of the attribute.
SourceLoc getLocation() const { return Range.Start; }
/// Return the source range of the attribute.
SourceRange getRange() const { return Range; }
SourceRange getRangeWithAt() const {
if (AtLoc.isValid())
return {AtLoc, Range.End};
return Range;
}
// Only allow allocation of attributes using the allocator in ASTContext
// or by doing a placement new.
void *operator new(size_t Bytes, ASTContext &C,
unsigned Alignment = alignof(AttributeBase));
void operator delete(void *Data) throw() { }
void *operator new(size_t Bytes, void *Mem) throw() { return Mem; }
// Make vanilla new/delete illegal for attributes.
void *operator new(size_t Bytes) throw() = delete;
AttributeBase(const AttributeBase &) = delete;
protected:
AttributeBase(SourceLoc AtLoc, SourceRange Range)
: AtLoc(AtLoc), Range(Range) {}
};
class DeclAttributes;
enum class DeclKind : uint8_t;
/// Represents one declaration attribute.
class DeclAttribute : public AttributeBase {
friend class DeclAttributes;
protected:
union {
uint64_t OpaqueBits;
SWIFT_INLINE_BITFIELD_BASE(DeclAttribute, bitmax(NumDeclAttrKindBits,8)+1+1,
Kind : bitmax(NumDeclAttrKindBits,8),
// Whether this attribute was implicitly added.
Implicit : 1,
Invalid : 1
);
SWIFT_INLINE_BITFIELD(ObjCAttr, DeclAttribute, 1+1+1,
/// Whether this attribute has location information that trails the main
/// record, which contains the locations of the parentheses and any names.
HasTrailingLocationInfo : 1,
/// Whether the name is implicit, produced as the result of caching.
ImplicitName : 1,
/// Whether the @objc was inferred using Swift 3's deprecated inference
/// rules.
Swift3Inferred : 1
);
SWIFT_INLINE_BITFIELD(DynamicReplacementAttr, DeclAttribute, 1,
/// Whether this attribute has location information that trails the main
/// record, which contains the locations of the parentheses and any names.
HasTrailingLocationInfo : 1
);
SWIFT_INLINE_BITFIELD(AbstractAccessControlAttr, DeclAttribute, 3,
AccessLevel : 3
);
SWIFT_INLINE_BITFIELD_FULL(AlignmentAttr, DeclAttribute, 32,
: NumPadBits,
// The alignment value.
Value : 32
);
SWIFT_INLINE_BITFIELD(ClangImporterSynthesizedTypeAttr, DeclAttribute, 1,
kind : 1
);
SWIFT_INLINE_BITFIELD(EffectsAttr, DeclAttribute, NumEffectsKindBits,
kind : NumEffectsKindBits
);
SWIFT_INLINE_BITFIELD(InlineAttr, DeclAttribute, NumInlineKindBits,
kind : NumInlineKindBits
);
SWIFT_INLINE_BITFIELD(OptimizeAttr, DeclAttribute, NumOptimizationModeBits,
mode : NumOptimizationModeBits
);
SWIFT_INLINE_BITFIELD(ReferenceOwnershipAttr, DeclAttribute,
NumReferenceOwnershipBits,
ownership : NumReferenceOwnershipBits
);
SWIFT_INLINE_BITFIELD(SpecializeAttr, DeclAttribute, 1+1,
exported : 1,
kind : 1
);
SWIFT_INLINE_BITFIELD(SynthesizedProtocolAttr, DeclAttribute,
NumKnownProtocolKindBits,
kind : NumKnownProtocolKindBits
);
} Bits;
DeclAttribute *Next = nullptr;
DeclAttribute(DeclAttrKind DK, SourceLoc AtLoc, SourceRange Range,
bool Implicit) : AttributeBase(AtLoc, Range) {
Bits.OpaqueBits = 0;
Bits.DeclAttribute.Kind = static_cast<unsigned>(DK);
Bits.DeclAttribute.Implicit = Implicit;
Bits.DeclAttribute.Invalid = false;
}
private:
// NOTE: We cannot use DeclKind due to layering. Even if we could, there is no
// guarantee that the first DeclKind starts at zero. This is only used to
// build "OnXYZ" flags.
enum class DeclKindIndex : unsigned {
#define DECL(Name, _) Name,
#define LAST_DECL(Name) Last_Decl = Name
#include "swift/AST/DeclNodes.def"
};
public:
enum DeclAttrOptions : uint64_t {
// There is one entry for each DeclKind, and some higher level buckets
// below. These are used in Attr.def to control which kinds of declarations
// an attribute can be attached to.
#define DECL(Name, _) On##Name = 1ull << unsigned(DeclKindIndex::Name),
#include "swift/AST/DeclNodes.def"
// Abstract class aggregations for use in Attr.def.
OnValue = 0
#define DECL(Name, _)
#define VALUE_DECL(Name, _) |On##Name
#include "swift/AST/DeclNodes.def"
,
OnNominalType = 0
#define DECL(Name, _)
#define NOMINAL_TYPE_DECL(Name, _) |On##Name
#include "swift/AST/DeclNodes.def"
,
OnConcreteNominalType = OnNominalType & ~OnProtocol,
OnGenericType = OnNominalType | OnTypeAlias,
OnAbstractFunction = 0
#define DECL(Name, _)
#define ABSTRACT_FUNCTION_DECL(Name, _) |On##Name
#include "swift/AST/DeclNodes.def"
,
OnOperator = 0
#define DECL(Name, _)
#define OPERATOR_DECL(Name, _) |On##Name
#include "swift/AST/DeclNodes.def"
,
OnAnyDecl = 0
#define DECL(Name, _) |On##Name
#include "swift/AST/DeclNodes.def"
,
/// True if multiple instances of this attribute are allowed on a single
/// declaration.
AllowMultipleAttributes = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 1),
/// True if this is a decl modifier - i.e., that it should not be spelled
/// with an @.
DeclModifier = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 2),
/// True if this is a long attribute that should be printed on its own line.
///
/// Currently has no effect on DeclModifier attributes.
LongAttribute = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 3),
/// True if this shouldn't be serialized.
NotSerialized = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 4),
/// True if this attribute is only valid when parsing a .sil file.
SILOnly = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 5),
/// The attribute should be reported by parser as unknown.
RejectByParser = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 6),
/// Whether client code cannot use the attribute.
UserInaccessible = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 7),
/// Whether adding this attribute can break API
APIBreakingToAdd = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 8),
/// Whether removing this attribute can break API
APIBreakingToRemove = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 9),
/// Whether adding this attribute can break ABI
ABIBreakingToAdd = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 10),
/// Whether removing this attribute can break ABI
ABIBreakingToRemove = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 11),
/// The opposite of APIBreakingToAdd
APIStableToAdd = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 12),
/// The opposite of APIBreakingToRemove
APIStableToRemove = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 13),
/// The opposite of ABIBreakingToAdd
ABIStableToAdd = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 14),
/// The opposite of ABIBreakingToRemove
ABIStableToRemove = 1ull << (unsigned(DeclKindIndex::Last_Decl) + 15),
};
LLVM_READNONE
static uint64_t getOptions(DeclAttrKind DK);
uint64_t getOptions() const {
return getOptions(getKind());
}
/// Prints this attribute (if applicable), returning `true` if anything was
/// printed.
bool printImpl(ASTPrinter &Printer, const PrintOptions &Options,
const Decl *D = nullptr) const;
public:
DeclAttrKind getKind() const {
return static_cast<DeclAttrKind>(Bits.DeclAttribute.Kind);
}
/// Whether this attribute was implicitly added.
bool isImplicit() const { return Bits.DeclAttribute.Implicit; }
/// Set whether this attribute was implicitly added.
void setImplicit(bool Implicit = true) {
Bits.DeclAttribute.Implicit = Implicit;
}
/// Returns true if this attribute was find to be invalid in some way by
/// semantic analysis. In that case, the attribute should not be considered,
/// the attribute node should be only used to retrieve source information.
bool isInvalid() const { return Bits.DeclAttribute.Invalid; }
void setInvalid() { Bits.DeclAttribute.Invalid = true; }
bool isValid() const { return !isInvalid(); }
/// Returns the address of the next pointer field.
/// Used for object deserialization.
DeclAttribute **getMutableNext() {
return &Next;
}
/// Print the attribute to the provided ASTPrinter.
void print(ASTPrinter &Printer, const PrintOptions &Options,
const Decl *D = nullptr) const;
/// Print the attribute to the provided stream.
void print(llvm::raw_ostream &OS, const Decl *D = nullptr) const;
/// Returns true if this attribute can appear on the specified decl. This is
/// controlled by the flags in Attr.def.
bool canAppearOnDecl(const Decl *D) const {
return canAttributeAppearOnDecl(getKind(), D);
}
LLVM_READONLY
static bool canAttributeAppearOnDecl(DeclAttrKind DK, const Decl *D);
/// Returns true if multiple instances of an attribute kind
/// can appear on a declaration.
static bool allowMultipleAttributes(DeclAttrKind DK) {
return getOptions(DK) & AllowMultipleAttributes;
}
bool isLongAttribute() const {
return isLongAttribute(getKind());
}
static bool isLongAttribute(DeclAttrKind DK) {
return getOptions(DK) & LongAttribute;
}
static bool shouldBeRejectedByParser(DeclAttrKind DK) {
return getOptions(DK) & RejectByParser;
}
static bool isSilOnly(DeclAttrKind DK) {
return getOptions(DK) & SILOnly;
}
static bool isUserInaccessible(DeclAttrKind DK) {
return getOptions(DK) & UserInaccessible;
}
static bool isAddingBreakingABI(DeclAttrKind DK) {
return getOptions(DK) & ABIBreakingToAdd;
}
#define DECL_ATTR(_, CLASS, OPTIONS, ...) \
static constexpr bool isOptionSetFor##CLASS(DeclAttrOptions Bit) { \
return (OPTIONS) & Bit; \
}
#include "swift/AST/Attr.def"
static bool isAddingBreakingAPI(DeclAttrKind DK) {
return getOptions(DK) & APIBreakingToAdd;
}
static bool isRemovingBreakingABI(DeclAttrKind DK) {
return getOptions(DK) & ABIBreakingToRemove;
}
static bool isRemovingBreakingAPI(DeclAttrKind DK) {
return getOptions(DK) & APIBreakingToRemove;
}
bool isDeclModifier() const {
return isDeclModifier(getKind());
}
static bool isDeclModifier(DeclAttrKind DK) {
return getOptions(DK) & DeclModifier;
}
static bool isOnParam(DeclAttrKind DK) {
return getOptions(DK) & OnParam;
}
static bool isOnFunc(DeclAttrKind DK) {
return getOptions(DK) & OnFunc;
}
static bool isOnClass(DeclAttrKind DK) {
return getOptions(DK) & OnClass;
}
static bool isNotSerialized(DeclAttrKind DK) {
return getOptions(DK) & NotSerialized;
}
bool isNotSerialized() const {
return isNotSerialized(getKind());
}
LLVM_READNONE
static bool canAttributeAppearOnDeclKind(DeclAttrKind DAK, DeclKind DK);
/// Returns the source name of the attribute, without the @ or any arguments.
StringRef getAttrName() const;
/// Given a name like "inline", return the decl attribute ID that corresponds
/// to it. Note that this is a many-to-one mapping, and that the identifier
/// passed in may only be the first portion of the attribute (e.g. in the case
/// of the 'unowned(unsafe)' attribute, the string passed in is 'unowned'.
///
/// Also note that this recognizes both attributes like '@inline' (with no @)
/// and decl modifiers like 'final'. This returns DAK_Count on failure.
///
static DeclAttrKind getAttrKindFromString(StringRef Str);
};
/// Describes a "simple" declaration attribute that carries no data.
template<DeclAttrKind Kind>
class SimpleDeclAttr : public DeclAttribute {
public:
SimpleDeclAttr(bool IsImplicit)
: DeclAttribute(Kind, SourceLoc(), SourceLoc(), IsImplicit) {}
SimpleDeclAttr(SourceLoc AtLoc, SourceLoc NameLoc)
: DeclAttribute(Kind, AtLoc,
SourceRange(AtLoc.isValid() ? AtLoc : NameLoc, NameLoc),
/*Implicit=*/false) { }
SimpleDeclAttr(SourceLoc NameLoc)
: DeclAttribute(Kind, SourceLoc(), SourceRange(NameLoc, NameLoc),
/*Implicit=*/false) { }
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == Kind;
}
};
// Declare typedefs for all of the simple declaration attributes.
#define SIMPLE_DECL_ATTR(_, CLASS, ...) \
typedef SimpleDeclAttr<DAK_##CLASS> CLASS##Attr;
#include "swift/AST/Attr.def"
/// Defines the @_silgen_name attribute.
class SILGenNameAttr : public DeclAttribute {
public:
SILGenNameAttr(StringRef Name, SourceLoc AtLoc, SourceRange Range, bool Implicit)
: DeclAttribute(DAK_SILGenName, AtLoc, Range, Implicit),
Name(Name) {}
SILGenNameAttr(StringRef Name, bool Implicit)
: SILGenNameAttr(Name, SourceLoc(), SourceRange(), /*Implicit=*/true) {}
/// The symbol name.
const StringRef Name;
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_SILGenName;
}
};
/// Defines the @_cdecl attribute.
class CDeclAttr : public DeclAttribute {
public:
CDeclAttr(StringRef Name, SourceLoc AtLoc, SourceRange Range, bool Implicit)
: DeclAttribute(DAK_CDecl, AtLoc, Range, Implicit),
Name(Name) {}
CDeclAttr(StringRef Name, bool Implicit)
: CDeclAttr(Name, SourceLoc(), SourceRange(), /*Implicit=*/true) {}
/// The symbol name.
const StringRef Name;
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_CDecl;
}
};
/// Defines the @_semantics attribute.
class SemanticsAttr : public DeclAttribute {
public:
SemanticsAttr(StringRef Value, SourceLoc AtLoc, SourceRange Range,
bool Implicit)
: DeclAttribute(DAK_Semantics, AtLoc, Range, Implicit),
Value(Value) {}
SemanticsAttr(StringRef Value, bool Implicit)
: SemanticsAttr(Value, SourceLoc(), SourceRange(), /*Implicit=*/true) {}
/// The semantics tag value.
const StringRef Value;
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_Semantics;
}
};
/// Defines the @_alignment attribute.
class AlignmentAttr : public DeclAttribute {
public:
AlignmentAttr(unsigned Value, SourceLoc AtLoc, SourceRange Range,
bool Implicit)
: DeclAttribute(DAK_Alignment, AtLoc, Range, Implicit) {
Bits.AlignmentAttr.Value = Value;
}
unsigned getValue() const { return Bits.AlignmentAttr.Value; }
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_Alignment;
}
};
/// Defines the @_swift_native_objc_runtime_base attribute.
///
/// This attribute indicates a class that should be treated semantically
/// as a native Swift root class, but which inherits a specific Objective-C
/// class at runtime. For most classes this is the runtime's "SwiftObject"
/// root class. The compiler does not need to know about the class; it's the
/// build system's responsibility to link against the ObjC code that implements
/// the root class, and the ObjC implementation's responsibility to ensure
/// instances begin with a Swift-refcounting-compatible object header and
/// override all the necessary NSObject refcounting methods.
class SwiftNativeObjCRuntimeBaseAttr : public DeclAttribute {
public:
SwiftNativeObjCRuntimeBaseAttr(Identifier BaseClassName,
SourceLoc AtLoc, SourceRange Range,
bool Implicit)
: DeclAttribute(DAK_SwiftNativeObjCRuntimeBase, AtLoc, Range, Implicit),
BaseClassName(BaseClassName) {}
// The base class's name.
const Identifier BaseClassName;
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_SwiftNativeObjCRuntimeBase;
}
};
/// Defines the @_implicitly_synthesizes_nested_requirement attribute.
class ImplicitlySynthesizesNestedRequirementAttr : public DeclAttribute {
public:
ImplicitlySynthesizesNestedRequirementAttr(StringRef Value, SourceLoc AtLoc,
SourceRange Range)
: DeclAttribute(DAK_ImplicitlySynthesizesNestedRequirement,
AtLoc, Range, /*Implicit*/false),
Value(Value) {}
/// The name of the phantom requirement.
const StringRef Value;
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_ImplicitlySynthesizesNestedRequirement;
}
};
/// Determine the result of comparing an availability attribute to a specific
/// platform or language version.
enum class AvailableVersionComparison {
/// The entity is guaranteed to be available.
Available,
/// The entity is never available.
Unavailable,
/// The entity might be unavailable at runtime, because it was introduced
/// after the requested minimum platform version.
PotentiallyUnavailable,
/// The entity has been obsoleted.
Obsoleted,
};
/// Describes the platform-agnostic availability of a declaration.
enum class PlatformAgnosticAvailabilityKind {
/// The associated availability attribute is not platform-agnostic.
None,
/// The declaration is deprecated, but can still be used.
Deprecated,
/// The declaration is unavailable in Swift, specifically
UnavailableInSwift,
/// The declaration is available in some but not all versions
/// of Swift, as specified by the VersionTuple members.
SwiftVersionSpecific,
/// The declaration is available in some but not all versions
/// of SwiftPM's PackageDescription library, as specified by
/// the VersionTuple members.
PackageDescriptionVersionSpecific,
/// The declaration is unavailable for other reasons.
Unavailable,
};
/// Defines the @available attribute.
class AvailableAttr : public DeclAttribute {
public:
#define INIT_VER_TUPLE(X)\
X(X.empty() ? Optional<llvm::VersionTuple>() : X)
AvailableAttr(SourceLoc AtLoc, SourceRange Range,
PlatformKind Platform,
StringRef Message, StringRef Rename,
const llvm::VersionTuple &Introduced,
SourceRange IntroducedRange,
const llvm::VersionTuple &Deprecated,
SourceRange DeprecatedRange,
const llvm::VersionTuple &Obsoleted,
SourceRange ObsoletedRange,
PlatformAgnosticAvailabilityKind PlatformAgnostic,
bool Implicit)
: DeclAttribute(DAK_Available, AtLoc, Range, Implicit),
Message(Message), Rename(Rename),
INIT_VER_TUPLE(Introduced), IntroducedRange(IntroducedRange),
INIT_VER_TUPLE(Deprecated), DeprecatedRange(DeprecatedRange),
INIT_VER_TUPLE(Obsoleted), ObsoletedRange(ObsoletedRange),
PlatformAgnostic(PlatformAgnostic),
Platform(Platform)
{}
#undef INIT_VER_TUPLE
/// The optional message.
const StringRef Message;
/// An optional replacement string to emit in a fixit. This allows simple
/// declaration renames to be applied by Xcode.
///
/// This should take the form of an operator, identifier, or full function
/// name, optionally with a prefixed type, similar to the syntax used for
/// the `NS_SWIFT_NAME` annotation in Objective-C.
const StringRef Rename;
/// Indicates when the symbol was introduced.
const Optional<llvm::VersionTuple> Introduced;
/// Indicates where the Introduced version was specified.
const SourceRange IntroducedRange;
/// Indicates when the symbol was deprecated.
const Optional<llvm::VersionTuple> Deprecated;
/// Indicates where the Deprecated version was specified.
const SourceRange DeprecatedRange;
/// Indicates when the symbol was obsoleted.
const Optional<llvm::VersionTuple> Obsoleted;
/// Indicates where the Obsoleted version was specified.
const SourceRange ObsoletedRange;
/// Indicates if the declaration has platform-agnostic availability.
const PlatformAgnosticAvailabilityKind PlatformAgnostic;
/// The platform of the availability.
const PlatformKind Platform;
/// Whether this is a language-version-specific entity.
bool isLanguageVersionSpecific() const;
/// Whether this is a PackageDescription version specific entity.
bool isPackageDescriptionVersionSpecific() const;
/// Whether this is an unconditionally unavailable entity.
bool isUnconditionallyUnavailable() const;
/// Whether this is an unconditionally deprecated entity.
bool isUnconditionallyDeprecated() const;
/// Returns the platform-agnostic availability.
PlatformAgnosticAvailabilityKind getPlatformAgnosticAvailability() const {
return PlatformAgnostic;
}
/// Determine if a given declaration should be considered unavailable given
/// the current settings.
///
/// \returns The attribute responsible for making the declaration unavailable.
static const AvailableAttr *isUnavailable(const Decl *D);
/// Returns true if the availability applies to a specific
/// platform.
bool hasPlatform() const {
return Platform != PlatformKind::none;
}
/// Returns the string for the platform of the attribute.
StringRef platformString() const {
return swift::platformString(Platform);
}
/// Returns the human-readable string for the platform of the attribute.
StringRef prettyPlatformString() const {
return swift::prettyPlatformString(Platform);
}
/// Returns true if this attribute is active given the current platform.
bool isActivePlatform(const ASTContext &ctx) const;
/// Returns the active version from the AST context corresponding to
/// the available kind. For example, this will return the effective language
/// version for swift version-specific availability kind, PackageDescription
/// version for PackageDescription version-specific availability.
llvm::VersionTuple getActiveVersion(const ASTContext &ctx) const;
/// Compare this attribute's version information against the platform or
/// language version (assuming the this attribute pertains to the active
/// platform).
AvailableVersionComparison getVersionAvailability(const ASTContext &ctx) const;
/// Create an AvailableAttr that indicates specific availability
/// for all platforms.
static AvailableAttr *
createPlatformAgnostic(ASTContext &C, StringRef Message, StringRef Rename = "",
PlatformAgnosticAvailabilityKind Reason
= PlatformAgnosticAvailabilityKind::Unavailable,
llvm::VersionTuple Obsoleted
= llvm::VersionTuple());
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_Available;
}
};
/// Indicates that the given declaration is visible to Objective-C.
class ObjCAttr final : public DeclAttribute,
private llvm::TrailingObjects<ObjCAttr, SourceLoc> {
friend TrailingObjects;
/// The Objective-C name associated with this entity, stored in its opaque
/// representation so that we can use null as an indicator for "no name".
void *NameData;
/// Create an implicit @objc attribute with the given (optional) name.
explicit ObjCAttr(Optional<ObjCSelector> name, bool implicitName)
: DeclAttribute(DAK_ObjC, SourceLoc(), SourceRange(), /*Implicit=*/true),
NameData(nullptr)
{
Bits.ObjCAttr.HasTrailingLocationInfo = false;
Bits.ObjCAttr.ImplicitName = implicitName;
Bits.ObjCAttr.Swift3Inferred = false;
if (name) {
NameData = name->getOpaqueValue();
}
}
/// Create an @objc attribute written in the source.
ObjCAttr(SourceLoc atLoc, SourceRange baseRange, Optional<ObjCSelector> name,
SourceRange parenRange, ArrayRef<SourceLoc> nameLocs);
/// Determine whether this attribute has trailing location information.
bool hasTrailingLocationInfo() const {
return Bits.ObjCAttr.HasTrailingLocationInfo;
}
/// Retrieve the trailing location information.
MutableArrayRef<SourceLoc> getTrailingLocations() {
assert(hasTrailingLocationInfo() && "No trailing location information");
unsigned length = 2;
if (auto name = getName())
length += name->getNumSelectorPieces();
return {getTrailingObjects<SourceLoc>(), length};
}
/// Retrieve the trailing location information.
ArrayRef<SourceLoc> getTrailingLocations() const {
assert(hasTrailingLocationInfo() && "No trailing location information");
unsigned length = 2;
if (auto name = getName())
length += name->getNumSelectorPieces();
return {getTrailingObjects<SourceLoc>(), length};
}
public:
/// Create implicit ObjC attribute with a given (optional) name.
static ObjCAttr *create(ASTContext &Ctx, Optional<ObjCSelector> name,
bool implicitName);
/// Create an unnamed Objective-C attribute, i.e., @objc.
static ObjCAttr *createUnnamed(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc ObjCLoc);
static ObjCAttr *createUnnamedImplicit(ASTContext &Ctx);
/// Create a nullary Objective-C attribute, which has a single name
/// with no colon following it.
///
/// Note that a nullary Objective-C attribute may represent either a
/// selector for a zero-parameter function or some other Objective-C
/// entity, such as a class or protocol.
static ObjCAttr *createNullary(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc ObjCLoc, SourceLoc LParenLoc,
SourceLoc NameLoc, Identifier Name,
SourceLoc RParenLoc);
/// Create an implicit nullary Objective-C attribute, which has a
/// single name with no colon following it.
///
/// Note that a nullary Objective-C attribute may represent either a
/// selector for a zero-parameter function or some other Objective-C
/// entity, such as a class or protocol.
static ObjCAttr *createNullary(ASTContext &Ctx, Identifier Name,
bool isNameImplicit);
/// Create a "selector" Objective-C attribute, which has some number
/// of identifiers followed by colons.
static ObjCAttr *createSelector(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc ObjCLoc, SourceLoc LParenLoc,
ArrayRef<SourceLoc> NameLocs,
ArrayRef<Identifier> Names,
SourceLoc RParenLoc);
/// Create an implicit "selector" Objective-C attribute, which has
/// some number of identifiers followed by colons.
static ObjCAttr *createSelector(ASTContext &Ctx, ArrayRef<Identifier> Names,
bool isNameImplicit);
/// Determine whether this attribute has a name associated with it.
bool hasName() const { return NameData != nullptr; }
/// Retrieve the name of this entity, if specified.
Optional<ObjCSelector> getName() const {
if (!hasName())
return None;
return ObjCSelector::getFromOpaqueValue(NameData);
}
/// Determine whether the name associated with this attribute was
/// implicit.
bool isNameImplicit() const { return Bits.ObjCAttr.ImplicitName; }
/// Set the name of this entity.
void setName(ObjCSelector name, bool implicit) {
// If we already have a name and we have location information, make sure
// drop the location information rather than allowing it to corrupt our
// state
if (hasTrailingLocationInfo() &&
(!hasName() ||
getName()->getNumSelectorPieces() < name.getNumSelectorPieces())) {
Bits.ObjCAttr.HasTrailingLocationInfo = false;
}
NameData = name.getOpaqueValue();
Bits.ObjCAttr.ImplicitName = implicit;
}
/// Determine whether this attribute was inferred based on Swift 3's
/// deprecated @objc inference rules.
bool isSwift3Inferred() const {
return Bits.ObjCAttr.Swift3Inferred;
}