-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathAttr.cpp
3048 lines (2699 loc) · 111 KB
/
Attr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- Attr.cpp - Swift Language Attr ASTs ------------------------------===//
//
// 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 implements routines relating to declaration attributes.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Attr.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IndexSubset.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeRepr.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/QuotedString.h"
#include "swift/Strings.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
#define DECL_ATTR(_, Id, ...) \
static_assert(IsTriviallyDestructible<Id##Attr>::value, \
"Attrs are BumpPtrAllocated; the destructor is never called");
#include "swift/AST/DeclAttr.def"
static_assert(IsTriviallyDestructible<DeclAttributes>::value,
"DeclAttributes are BumpPtrAllocated; the d'tor is never called");
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIBreakingToAdd) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIStableToAdd), \
#Name " needs to specify either ABIBreakingToAdd or ABIStableToAdd");
#include "swift/AST/DeclAttr.def"
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIBreakingToRemove) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIStableToRemove), \
#Name " needs to specify either ABIBreakingToRemove or ABIStableToRemove");
#include "swift/AST/DeclAttr.def"
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIBreakingToAdd) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIStableToAdd), \
#Name " needs to specify either APIBreakingToAdd or APIStableToAdd");
#include "swift/AST/DeclAttr.def"
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIBreakingToRemove) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIStableToRemove), \
#Name " needs to specify either APIBreakingToRemove or APIStableToRemove");
#include "swift/AST/DeclAttr.def"
StringRef swift::getAccessLevelSpelling(AccessLevel value) {
switch (value) {
case AccessLevel::Private: return "private";
case AccessLevel::FilePrivate: return "fileprivate";
case AccessLevel::Internal: return "internal";
case AccessLevel::Package: return "package";
case AccessLevel::Public: return "public";
case AccessLevel::Open: return "open";
}
llvm_unreachable("Unhandled AccessLevel in switch.");
}
SourceLoc TypeAttribute::getStartLoc() const {
switch (getKind()) {
#define TYPE_ATTR(_, CLASS) \
case TypeAttrKind::CLASS: \
return static_cast<const CLASS##TypeAttr *>(this)->getStartLocImpl();
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("bad kind");
}
SourceLoc TypeAttribute::getEndLoc() const {
switch (getKind()) {
#define TYPE_ATTR(_, CLASS) \
case TypeAttrKind::CLASS: \
return static_cast<const CLASS##TypeAttr *>(this)->getEndLocImpl();
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("bad kind");
}
SourceRange TypeAttribute::getSourceRange() const {
switch (getKind()) {
#define TYPE_ATTR(_, CLASS) \
case TypeAttrKind::CLASS: { \
auto attr = static_cast<const CLASS##TypeAttr *>(this); \
return SourceRange(attr->getStartLocImpl(), attr->getEndLocImpl()); \
}
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("bad kind");
}
/// Given a name like "autoclosure", return the type attribute ID that
/// corresponds to it.
///
std::optional<TypeAttrKind>
TypeAttribute::getAttrKindFromString(StringRef Str) {
return llvm::StringSwitch<std::optional<TypeAttrKind>>(Str)
#define TYPE_ATTR(X, C) .Case(#X, TypeAttrKind::C)
#include "swift/AST/TypeAttr.def"
.Default(std::nullopt);
}
bool TypeAttribute::isSilOnly(TypeAttrKind TK) {
switch (TK) {
#define SIL_TYPE_ATTR(X, C) case TypeAttrKind::C:
#include "swift/AST/TypeAttr.def"
return true;
default:
return false;
}
}
/// Return the name (like "autoclosure") for an attribute ID.
const char *TypeAttribute::getAttrName(TypeAttrKind kind) {
switch (kind) {
#define TYPE_ATTR(X, C) \
case TypeAttrKind::C: \
return #X;
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("unknown type attribute kind");
}
bool TypeAttribute::isUserInaccessible(TypeAttrKind DK) {
// Currently we can base this off whether it is underscored or for SIL.
// TODO: We could introduce a similar options scheme to DECL_ATTR if we ever
// need a user-inaccessible non-underscored attribute.
switch (DK) {
// SIL attributes are always considered user-inaccessible.
#define SIL_TYPE_ATTR(SPELLING, C) \
case TypeAttrKind::C: \
return true;
// For non-SIL attributes, check whether the spelling is underscored.
#define TYPE_ATTR(SPELLING, C) \
case TypeAttrKind::C: \
return StringRef(#SPELLING).starts_with("_");
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("unhandled case in switch!");
}
TypeAttribute *TypeAttribute::createSimple(const ASTContext &context,
TypeAttrKind kind,
SourceLoc atLoc,
SourceLoc attrLoc) {
switch (kind) {
// The simple cases should all be doing the exact same thing, and we
// can reasonably hope that the optimizer will unify them so that this
// function doesn't actually need a switch.
#define TYPE_ATTR(SPELLING, CLASS) \
case TypeAttrKind::CLASS: \
llvm_unreachable("not a simple attribute");
#define SIMPLE_TYPE_ATTR(SPELLING, CLASS) \
case TypeAttrKind::CLASS: \
return new (context) CLASS##TypeAttr(atLoc, attrLoc);
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("bad type attribute kind");
}
void TypeAttribute::dump() const {
StreamPrinter P(llvm::errs());
PrintOptions PO = PrintOptions::printDeclarations();
print(P, PO);
}
void TypeAttribute::print(ASTPrinter &printer,
const PrintOptions &options) const {
switch (getKind()) {
#define TYPE_ATTR(_, CLASS)
#define SIMPLE_TYPE_ATTR(_, CLASS) case TypeAttrKind::CLASS:
#include "swift/AST/TypeAttr.def"
printer.printSimpleAttr(getAttrName(getKind()), /*needAt*/ true);
return;
#define TYPE_ATTR(_, CLASS) \
case TypeAttrKind::CLASS: \
return cast<CLASS##TypeAttr>(this)->printImpl(printer, options);
#define SIMPLE_TYPE_ATTR(_, C)
#include "swift/AST/TypeAttr.def"
}
llvm_unreachable("bad kind");
}
void DifferentiableTypeAttr::printImpl(ASTPrinter &printer,
const PrintOptions &options) const {
printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
printer.printAttrName("@differentiable");
switch (getDifferentiability()) {
case DifferentiabilityKind::Normal:
break;
case DifferentiabilityKind::Forward:
printer << "(_forward)";
break;
case DifferentiabilityKind::Reverse:
printer << "(reverse)";
break;
case DifferentiabilityKind::Linear:
printer << "(_linear)";
break;
case DifferentiabilityKind::NonDifferentiable:
llvm_unreachable("Unexpected case 'NonDifferentiable'");
}
printer << ' ';
printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
}
void ConventionTypeAttr::printImpl(ASTPrinter &printer,
const PrintOptions &options) const {
printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
printer.printAttrName("@convention");
printer << "(" << getConventionName();
if (auto protocol = getWitnessMethodProtocol()) {
printer << ": " << protocol;
} else if (auto clangType = getClangType()) {
printer << ", cType: " << QuotedString(*clangType);
}
printer << ")";
printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
}
void OpaqueReturnTypeOfTypeAttr::printImpl(ASTPrinter &printer,
const PrintOptions &options) const {
printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
printer.printAttrName("@_opaqueReturnTypeOf");
printer << "(" << QuotedString(getMangledName()) << ", " << getIndex() << ")";
printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
}
void OpenedTypeAttr::printImpl(ASTPrinter &printer,
const PrintOptions &options) const {
printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
printer.printAttrName("@opened");
printer << "(\"" << getUUID() << "\"";
if (auto constraintType = getConstraintType()) {
printer << ", ";
getConstraintType()->print(printer, options);
}
printer << ")";
printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
}
void PackElementTypeAttr::printImpl(ASTPrinter &printer,
const PrintOptions &options) const {
printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
printer.printAttrName("@pack_element");
printer << "(\"" << getUUID() << "\")";
printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
}
const char *IsolatedTypeAttr::getIsolationKindName(IsolationKind kind) {
switch (kind) {
case IsolationKind::Dynamic: return "any";
}
llvm_unreachable("bad kind");
}
void IsolatedTypeAttr::printImpl(ASTPrinter &printer,
const PrintOptions &options) const {
// Suppress the attribute if requested.
switch (getIsolationKind()) {
case IsolationKind::Dynamic:
if (options.SuppressIsolatedAny) return;
break;
}
printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
printer.printAttrName("@isolated");
printer << "(" << getIsolationKindName() << ")";
printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
}
/// 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'.
///
std::optional<DeclAttrKind>
DeclAttribute::getAttrKindFromString(StringRef Str) {
return llvm::StringSwitch<std::optional<DeclAttrKind>>(Str)
#define DECL_ATTR(X, CLASS, ...) .Case(#X, DeclAttrKind::CLASS)
#define DECL_ATTR_ALIAS(X, CLASS) .Case(#X, DeclAttrKind::CLASS)
#include "swift/AST/DeclAttr.def"
.Case(SPI_AVAILABLE_ATTRNAME, DeclAttrKind::Available)
.Default(std::nullopt);
}
DeclAttribute *DeclAttribute::createSimple(const ASTContext &context,
DeclAttrKind kind, SourceLoc atLoc,
SourceLoc attrLoc) {
switch (kind) {
// The simple cases should all be doing the exact same thing, and we
// can reasonably hope that the optimizer will unify them so that this
// function doesn't actually need a switch.
#define DECL_ATTR(SPELLING, CLASS, ...) \
case DeclAttrKind::CLASS: \
llvm_unreachable("not a simple attribute");
#define SIMPLE_DECL_ATTR(SPELLING, CLASS, ...) \
case DeclAttrKind::CLASS: \
return new (context) CLASS##Attr(atLoc, attrLoc);
#include "swift/AST/DeclAttr.def"
}
llvm_unreachable("bad decl attribute kind");
}
/// Returns true if this attribute can appear on the specified decl.
bool DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind DK, const Decl *D) {
if ((getOptions(DK) & OnAnyClangDecl) && D->hasClangNode())
return true;
return canAttributeAppearOnDeclKind(DK, D->getKind());
}
bool DeclAttribute::canAttributeAppearOnDeclKind(DeclAttrKind DAK, DeclKind DK) {
auto Options = getOptions(DAK);
switch (DK) {
#define DECL(Id, Parent) case DeclKind::Id: return (Options & On##Id) != 0;
#include "swift/AST/DeclNodes.def"
}
llvm_unreachable("bad DeclKind");
}
bool
DeclAttributes::isUnavailableInSwiftVersion(
const version::Version &effectiveVersion) const {
llvm::VersionTuple vers = effectiveVersion;
for (auto attr : *this) {
if (auto available = dyn_cast<AvailableAttr>(attr)) {
if (available->isInvalid())
continue;
if (available->getPlatformAgnosticAvailability() ==
PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) {
if (available->Introduced.has_value() &&
available->Introduced.value() > vers)
return true;
if (available->Obsoleted.has_value() &&
available->Obsoleted.value() <= vers)
return true;
}
}
}
return false;
}
const AvailableAttr *
DeclAttributes::findMostSpecificActivePlatform(const ASTContext &ctx,
bool ignoreAppExtensions) const {
const AvailableAttr *bestAttr = nullptr;
for (auto attr : *this) {
auto *avAttr = dyn_cast<AvailableAttr>(attr);
if (!avAttr)
continue;
if (avAttr->isInvalid())
continue;
if (!avAttr->hasPlatform())
continue;
if (!avAttr->isActivePlatform(ctx))
continue;
if (ignoreAppExtensions && isApplicationExtensionPlatform(avAttr->Platform))
continue;
// We have an attribute that is active for the platform, but
// is it more specific than our current best?
if (!bestAttr || inheritsAvailabilityFromPlatform(avAttr->Platform,
bestAttr->Platform)) {
bestAttr = avAttr;
}
}
return bestAttr;
}
const AvailableAttr *
DeclAttributes::getPotentiallyUnavailable(const ASTContext &ctx) const {
const AvailableAttr *potential = nullptr;
const AvailableAttr *conditional = nullptr;
for (auto Attr : *this)
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
// Definitely not available.
if (AvAttr->isUnconditionallyUnavailable())
return AvAttr;
switch (AvAttr->getVersionAvailability(ctx)) {
case AvailableVersionComparison::Available:
// Doesn't limit the introduced version.
break;
case AvailableVersionComparison::PotentiallyUnavailable:
// We'll return this if we don't see something that proves it's
// not available in this version.
potential = AvAttr;
break;
case AvailableVersionComparison::Unavailable:
case AvailableVersionComparison::Obsoleted:
conditional = AvAttr;
break;
}
}
if (conditional)
return conditional;
return potential;
}
const AvailableAttr *
DeclAttributes::getUnavailable(const ASTContext &ctx,
bool ignoreAppExtensions) const {
const AvailableAttr *conditional = nullptr;
const AvailableAttr *bestActive =
findMostSpecificActivePlatform(ctx, ignoreAppExtensions);
for (auto Attr : *this)
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
// If this is a platform-specific attribute and it isn't the most
// specific attribute for the current platform, we're done.
if (AvAttr->hasPlatform() &&
(!bestActive || AvAttr != bestActive))
continue;
// If this attribute doesn't apply to the active platform, we're done.
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
if (ignoreAppExtensions &&
isApplicationExtensionPlatform(AvAttr->Platform))
continue;
// Unconditional unavailable.
if (AvAttr->isUnconditionallyUnavailable())
return AvAttr;
switch (AvAttr->getVersionAvailability(ctx)) {
case AvailableVersionComparison::Available:
case AvailableVersionComparison::PotentiallyUnavailable:
break;
case AvailableVersionComparison::Obsoleted:
case AvailableVersionComparison::Unavailable:
conditional = AvAttr;
break;
}
}
return conditional;
}
const AvailableAttr *
DeclAttributes::getDeprecated(const ASTContext &ctx) const {
const AvailableAttr *conditional = nullptr;
const AvailableAttr *bestActive = findMostSpecificActivePlatform(ctx);
for (auto Attr : *this) {
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
if (AvAttr->hasPlatform() &&
(!bestActive || AvAttr != bestActive))
continue;
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
// Unconditional deprecated.
if (AvAttr->isUnconditionallyDeprecated())
return AvAttr;
std::optional<llvm::VersionTuple> DeprecatedVersion = AvAttr->Deprecated;
StringRef DeprecatedPlatform = AvAttr->prettyPlatformString();
llvm::VersionTuple RemappedDeprecatedVersion;
if (AvailabilityInference::updateDeprecatedPlatformForFallback(
AvAttr, ctx, DeprecatedPlatform, RemappedDeprecatedVersion))
DeprecatedVersion = RemappedDeprecatedVersion;
if (!DeprecatedVersion.has_value())
continue;
llvm::VersionTuple MinVersion = AvAttr->getActiveVersion(ctx);
// We treat the declaration as deprecated if it is deprecated on
// all deployment targets.
// Once availability checking is enabled by default, we should
// query the type refinement context hierarchy to determine
// whether a declaration is deprecated on all versions
// allowed by the context containing the reference.
if (DeprecatedVersion.value() <= MinVersion) {
conditional = AvAttr;
}
}
}
return conditional;
}
const AvailableAttr *
DeclAttributes::getSoftDeprecated(const ASTContext &ctx) const {
const AvailableAttr *conditional = nullptr;
const AvailableAttr *bestActive = findMostSpecificActivePlatform(ctx);
for (auto Attr : *this) {
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
if (AvAttr->hasPlatform() &&
(!bestActive || AvAttr != bestActive))
continue;
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
std::optional<llvm::VersionTuple> DeprecatedVersion = AvAttr->Deprecated;
if (!DeprecatedVersion.has_value())
continue;
llvm::VersionTuple ActiveVersion = AvAttr->getActiveVersion(ctx);
if (DeprecatedVersion.value() > ActiveVersion) {
conditional = AvAttr;
}
}
}
return conditional;
}
const AvailableAttr *DeclAttributes::getNoAsync(const ASTContext &ctx) const {
const AvailableAttr *bestAttr = nullptr;
for (const DeclAttribute *attr : *this) {
if (const AvailableAttr *avAttr = dyn_cast<AvailableAttr>(attr)) {
if (avAttr->isInvalid())
continue;
if (avAttr->getPlatformAgnosticAvailability() ==
PlatformAgnosticAvailabilityKind::NoAsync) {
// An API may only be unavailable on specific platforms.
// If it doesn't have a platform associated with it, then it's
// unavailable for all platforms, so we should include it. If it does
// have a platform and we are not that platform, then it doesn't apply
// to us.
const bool isGoodForPlatform =
(avAttr->hasPlatform() && avAttr->isActivePlatform(ctx)) ||
!avAttr->hasPlatform();
if (!isGoodForPlatform)
continue;
if (!bestAttr) {
// If there is no best attr selected
// and the attr either has an active platform, or doesn't have one at
// all, select it.
bestAttr = avAttr;
} else if (bestAttr && avAttr->hasPlatform() &&
bestAttr->hasPlatform() &&
inheritsAvailabilityFromPlatform(avAttr->Platform,
bestAttr->Platform)) {
// if they both have a viable platform, use the better one
bestAttr = avAttr;
} else if (avAttr->hasPlatform() && !bestAttr->hasPlatform()) {
// Use the one more specific
bestAttr = avAttr;
}
}
}
}
return bestAttr;
}
const BackDeployedAttr *
DeclAttributes::getBackDeployed(const ASTContext &ctx,
bool forTargetVariant) const {
const BackDeployedAttr *bestAttr = nullptr;
for (auto attr : *this) {
auto *backDeployedAttr = dyn_cast<BackDeployedAttr>(attr);
if (!backDeployedAttr)
continue;
if (backDeployedAttr->isInvalid() ||
!backDeployedAttr->isActivePlatform(ctx, forTargetVariant))
continue;
// We have an attribute that is active for the platform, but
// is it more specific than our current best?
if (!bestAttr || inheritsAvailabilityFromPlatform(
backDeployedAttr->Platform, bestAttr->Platform)) {
bestAttr = backDeployedAttr;
}
}
return bestAttr;
}
void DeclAttributes::dump(const Decl *D) const {
StreamPrinter P(llvm::errs());
PrintOptions PO = PrintOptions::printDeclarations();
print(P, PO, D);
}
/// Returns true if the attribute can be presented as a short form available
/// attribute (e.g., as @available(iOS 8.0, *). The presentation requires an
/// introduction version and does not support deprecation, obsoletion, or
/// messages.
LLVM_READONLY
static bool isShortAvailable(const DeclAttribute *DA) {
auto *AvailAttr = dyn_cast<AvailableAttr>(DA);
if (!AvailAttr)
return false;
if (AvailAttr->IsSPI)
return false;
if (!AvailAttr->Introduced.has_value())
return false;
if (AvailAttr->Deprecated.has_value())
return false;
if (AvailAttr->Obsoleted.has_value())
return false;
if (!AvailAttr->Message.empty())
return false;
if (!AvailAttr->Rename.empty())
return false;
switch (AvailAttr->PlatformAgnostic) {
case PlatformAgnosticAvailabilityKind::Deprecated:
case PlatformAgnosticAvailabilityKind::Unavailable:
case PlatformAgnosticAvailabilityKind::UnavailableInSwift:
case PlatformAgnosticAvailabilityKind::NoAsync:
return false;
case PlatformAgnosticAvailabilityKind::None:
case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:
case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:
return true;
}
return true;
}
/// Return true when another availability attribute implies the same availability as this
/// attribute and so printing the attribute can be skipped to de-clutter the declaration
/// when printing the short form.
/// For example, iOS availability implies macCatalyst availability so if attributes for
/// both are present and they have the same 'introduced' version, we can skip printing an
/// explicit availability for macCatalyst.
static bool isShortFormAvailabilityImpliedByOther(const AvailableAttr *Attr,
ArrayRef<const DeclAttribute *> Others) {
assert(isShortAvailable(Attr));
for (auto *DA : Others) {
auto *Other = cast<AvailableAttr>(DA);
if (Attr->Platform == Other->Platform)
continue;
if (!inheritsAvailabilityFromPlatform(Attr->Platform, Other->Platform))
continue;
if (Attr->Introduced == Other->Introduced)
return true;
}
return false;
}
/// Print the short-form @available() attribute for an array of long-form
/// AvailableAttrs that can be represented in the short form.
/// For example, for:
/// @available(OSX, introduced: 10.10)
/// @available(iOS, introduced: 8.0)
/// this will print:
/// @available(OSX 10.10, iOS 8.0, *)
static void printShortFormAvailable(ArrayRef<const DeclAttribute *> Attrs,
ASTPrinter &Printer,
const PrintOptions &Options,
bool forAtSpecialize = false) {
assert(!Attrs.empty());
if (!forAtSpecialize)
Printer << "@available(";
auto FirstAvail = cast<AvailableAttr>(Attrs.front());
if (Attrs.size() == 1 &&
FirstAvail->getPlatformAgnosticAvailability() !=
PlatformAgnosticAvailabilityKind::None) {
assert(FirstAvail->Introduced.has_value());
if (FirstAvail->isLanguageVersionSpecific()) {
Printer << "swift ";
} else {
assert(FirstAvail->isPackageDescriptionVersionSpecific());
Printer << "_PackageDescription ";
}
Printer << FirstAvail->Introduced.value().getAsString();
if (!forAtSpecialize)
Printer << ")";
} else {
for (auto *DA : Attrs) {
auto *AvailAttr = cast<AvailableAttr>(DA);
assert(AvailAttr->Introduced.has_value());
// Avoid omitting available attribute when we are printing module interface.
if (!Options.IsForSwiftInterface &&
isShortFormAvailabilityImpliedByOther(AvailAttr, Attrs))
continue;
Printer << platformString(AvailAttr->Platform) << " "
<< AvailAttr->Introduced.value().getAsString() << ", ";
}
Printer << "*";
if (!forAtSpecialize)
Printer << ")";
}
if (!forAtSpecialize)
Printer.printNewline();
}
static void printShortFormBackDeployed(ArrayRef<const DeclAttribute *> Attrs,
ASTPrinter &Printer,
const PrintOptions &Options) {
assert(!Attrs.empty());
Printer << "@backDeployed(before: ";
bool isFirst = true;
for (auto *DA : Attrs) {
if (!isFirst)
Printer << ", ";
auto *attr = cast<BackDeployedAttr>(DA);
Printer << platformString(attr->Platform) << " "
<< attr->Version.getAsString();
isFirst = false;
}
Printer << ")";
Printer.printNewline();
}
/// The kind of a parameter in a `wrt:` differentiation parameters clause:
/// either a differentiability parameter or a linearity parameter. Used for
/// printing `@differentiable`, `@derivative`, and `@transpose` attributes.
enum class DifferentiationParameterKind {
/// A differentiability parameter, printed by name.
/// Used for `@differentiable` and `@derivative` attribute.
Differentiability,
/// A linearity parameter, printed by index.
/// Used for `@transpose` attribute.
Linearity
};
/// Returns the differentiation parameters clause string for the given function,
/// parameter indices, parsed parameters, and differentiation parameter kind.
/// Use the parameter indices if specified; otherwise, use the parsed
/// parameters.
static std::string getDifferentiationParametersClauseString(
const AbstractFunctionDecl *function, IndexSubset *parameterIndices,
ArrayRef<ParsedAutoDiffParameter> parsedParams,
DifferentiationParameterKind parameterKind) {
assert(function);
bool isInstanceMethod = function->isInstanceMember();
bool isStaticMethod = function->isStatic();
std::string result;
llvm::raw_string_ostream printer(result);
// Use the parameter indices, if specified.
if (parameterIndices) {
auto parameters = parameterIndices->getBitVector();
auto parameterCount = parameters.count();
printer << "wrt: ";
if (parameterCount > 1)
printer << '(';
// Check if differentiating wrt `self`. If so, manually print it first.
bool isWrtSelf =
(isInstanceMethod ||
(isStaticMethod &&
parameterKind == DifferentiationParameterKind::Linearity)) &&
parameters.test(parameters.size() - 1);
if (isWrtSelf) {
parameters.reset(parameters.size() - 1);
printer << "self";
if (parameters.any())
printer << ", ";
}
// Print remaining differentiation parameters.
interleave(parameters.set_bits(), [&](unsigned index) {
switch (parameterKind) {
// Print differentiability parameters by name.
case DifferentiationParameterKind::Differentiability:
printer << function->getParameters()->get(index)->getName().str();
break;
// Print linearity parameters by index.
case DifferentiationParameterKind::Linearity:
printer << index;
break;
}
}, [&] { printer << ", "; });
if (parameterCount > 1)
printer << ')';
}
// Otherwise, use the parsed parameters.
else if (!parsedParams.empty()) {
printer << "wrt: ";
if (parsedParams.size() > 1)
printer << '(';
interleave(parsedParams, [&](const ParsedAutoDiffParameter ¶m) {
switch (param.getKind()) {
case ParsedAutoDiffParameter::Kind::Named:
printer << param.getName();
break;
case ParsedAutoDiffParameter::Kind::Self:
printer << "self";
break;
case ParsedAutoDiffParameter::Kind::Ordered:
auto *paramList = function->getParameters();
assert(param.getIndex() <= paramList->size() &&
"wrt parameter is out of range");
auto *funcParam = paramList->get(param.getIndex());
printer << funcParam->getNameStr();
break;
}
}, [&] { printer << ", "; });
if (parsedParams.size() > 1)
printer << ')';
}
return printer.str();
}
/// Print the arguments of the given `@differentiable` attribute.
/// - If `omitWrtClause` is true, omit printing the `wrt:` differentiation
/// parameters clause.
static void printDifferentiableAttrArguments(
const DifferentiableAttr *attr, ASTPrinter &printer,
const PrintOptions &Options, const Decl *D, bool omitWrtClause = false) {
// Create a temporary string for the attribute argument text.
std::string attrArgText;
llvm::raw_string_ostream stream(attrArgText);
// Print comma if not leading clause.
bool isLeadingClause = false;
auto printCommaIfNecessary = [&] {
if (isLeadingClause) {
isLeadingClause = false;
return;
}
stream << ", ";
};
// Print if the function is marked as linear.
switch (attr->getDifferentiabilityKind()) {
case DifferentiabilityKind::Normal:
isLeadingClause = true;
break;
case DifferentiabilityKind::Forward:
stream << "_forward";
break;
case DifferentiabilityKind::Reverse:
stream << "reverse";
break;
case DifferentiabilityKind::Linear:
stream << "_linear";
break;
case DifferentiabilityKind::NonDifferentiable:
llvm_unreachable("Impossible case `NonDifferentiable`");
}
// If the declaration is not available, there is not enough context to print
// the differentiability parameters or the 'where' clause, so just print the
// differentiability kind if applicable (when not `Normal`).
if (!D) {
if (attr->getDifferentiabilityKind() != DifferentiabilityKind::Normal) {
printer << '(' << stream.str() << ')';
}
return;
}
// Get original function.
auto *original = dyn_cast<AbstractFunctionDecl>(D);
// Handle stored/computed properties and subscript methods.
if (auto *asd = dyn_cast<AbstractStorageDecl>(D))
original = asd->getAccessor(AccessorKind::Get);
assert(original && "Must resolve original declaration");
// Print differentiation parameters clause, unless it is to be omitted.
if (!omitWrtClause) {
auto diffParamsString = getDifferentiationParametersClauseString(
original, attr->getParameterIndices(), attr->getParsedParameters(),
DifferentiationParameterKind::Differentiability);
// Check whether differentiation parameter clause is empty.
// Handles edge case where resolved parameter indices are unset and
// parsed parameters are empty. This case should never trigger for
// user-visible printing.
if (!diffParamsString.empty()) {
printCommaIfNecessary();
stream << diffParamsString;
}
}
// Print 'where' clause, if any.
// First, filter out requirements satisfied by the original function's
// generic signature. They should not be printed.
ArrayRef<Requirement> derivativeRequirements;
if (auto derivativeGenSig = attr->getDerivativeGenericSignature())
derivativeRequirements = derivativeGenSig.getRequirements();
auto requirementsToPrint =
llvm::make_filter_range(derivativeRequirements, [&](Requirement req) {
if (const auto &originalGenSig = original->getGenericSignature())
if (originalGenSig->isRequirementSatisfied(req))
return false;
return true;
});
if (!requirementsToPrint.empty()) {
if (!isLeadingClause)
stream << ' ';
stream << "where ";
interleave(requirementsToPrint, [&](Requirement req) {
if (const auto &originalGenSig = original->getGenericSignature())
if (originalGenSig->isRequirementSatisfied(req))
return;
req.print(stream, Options);
}, [&] {
stream << ", ";
});
}
// If the attribute argument text is empty, return. Do not print parentheses.
if (stream.str().empty())
return;
// Otherwise, print the attribute argument text enclosed in parentheses.
printer << '(' << stream.str() << ')';
}
void DeclAttributes::print(ASTPrinter &Printer, const PrintOptions &Options,
const Decl *D) const {
if (!DeclAttrs)
return;
SmallVector<const DeclAttribute *, 8> orderedAttributes(begin(), end());
print(Printer, Options, orderedAttributes, D);
}
void DeclAttributes::print(ASTPrinter &Printer, const PrintOptions &Options,
ArrayRef<const DeclAttribute *> FlattenedAttrs,
const Decl *D) {
using AttributeVector = SmallVector<const DeclAttribute *, 8>;
// Process attributes in passes.
AttributeVector shortAvailableAttributes;
const DeclAttribute *swiftVersionAvailableAttribute = nullptr;
const DeclAttribute *packageDescriptionVersionAvailableAttribute = nullptr;
AttributeVector backDeployedAttributes;
AttributeVector longAttributes;
AttributeVector attributes;
AttributeVector modifiers;
for (auto DA : llvm::reverse(FlattenedAttrs)) {
// Don't skip implicit custom attributes. Custom attributes like global