-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathAvailability.cpp
1085 lines (910 loc) · 39 KB
/
Availability.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
//===--- Availability.cpp - Swift Availability Structures -----------------===//
//
// 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 data structures for API availability.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/AvailabilityConstraint.h"
#include "swift/AST/AvailabilityContext.h"
#include "swift/AST/AvailabilityDomain.h"
#include "swift/AST/AvailabilityInference.h"
#include "swift/AST/AvailabilityRange.h"
#include "swift/AST/Decl.h"
// FIXME: [availability] Remove this when possible
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/PlatformKind.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Platform.h"
#include "swift/ClangImporter/ClangModule.h"
#include <map>
using namespace swift;
void VersionRange::Profile(llvm::FoldingSetNodeID &id) const {
id.AddBoolean(hasLowerEndpoint());
if (!hasLowerEndpoint()) {
id.AddBoolean(isAll());
return;
}
auto profileVersionComponent = [&id](std::optional<unsigned> component) {
id.AddBoolean(component.has_value());
if (component)
id.AddInteger(*component);
};
auto lowerEndpoint = getLowerEndpoint();
id.AddInteger(lowerEndpoint.getMajor());
profileVersionComponent(lowerEndpoint.getMinor());
profileVersionComponent(lowerEndpoint.getSubminor());
profileVersionComponent(lowerEndpoint.getBuild());
}
AvailabilityRange
AvailabilityRange::forDeploymentTarget(const ASTContext &Ctx) {
return AvailabilityRange(Ctx.LangOpts.getMinPlatformVersion());
}
AvailabilityRange AvailabilityRange::forInliningTarget(const ASTContext &Ctx) {
return AvailabilityRange(Ctx.LangOpts.MinimumInliningTargetVersion);
}
AvailabilityRange AvailabilityRange::forRuntimeTarget(const ASTContext &Ctx) {
return AvailabilityRange(Ctx.LangOpts.RuntimeVersion);
}
namespace {
/// The inferred availability required to access a group of declarations
/// on a single platform.
struct InferredAvailability {
AvailableAttr::Kind Kind = AvailableAttr::Kind::Default;
std::optional<llvm::VersionTuple> Introduced;
std::optional<llvm::VersionTuple> Deprecated;
std::optional<llvm::VersionTuple> Obsoleted;
StringRef Message;
StringRef Rename;
bool IsSPI = false;
};
/// The type of a function that merges two version tuples.
typedef const llvm::VersionTuple &(*MergeFunction)(
const llvm::VersionTuple &, const llvm::VersionTuple &);
} // end anonymous namespace
/// Apply a merge function to two optional versions, returning the result
/// in Inferred.
static bool
mergeIntoInferredVersion(const std::optional<llvm::VersionTuple> &Version,
std::optional<llvm::VersionTuple> &Inferred,
MergeFunction Merge) {
if (Version.has_value()) {
if (Inferred.has_value()) {
Inferred = Merge(Inferred.value(), Version.value());
return *Inferred == *Version;
} else {
Inferred = Version;
return true;
}
}
return false;
}
/// Merge an attribute's availability with an existing inferred availability
/// so that the new inferred availability is at least as available as
/// the attribute requires.
static void mergeWithInferredAvailability(SemanticAvailableAttr Attr,
InferredAvailability &Inferred) {
auto *ParsedAttr = Attr.getParsedAttr();
Inferred.Kind = static_cast<AvailableAttr::Kind>(
std::max(static_cast<unsigned>(Inferred.Kind),
static_cast<unsigned>(ParsedAttr->getKind())));
// The merge of two introduction versions is the maximum of the two versions.
if (mergeIntoInferredVersion(Attr.getIntroduced(), Inferred.Introduced,
std::max)) {
Inferred.IsSPI = Attr.isSPI();
}
// The merge of deprecated and obsoleted versions takes the minimum.
mergeIntoInferredVersion(Attr.getDeprecated(), Inferred.Deprecated, std::min);
mergeIntoInferredVersion(Attr.getObsoleted(), Inferred.Obsoleted, std::min);
if (Inferred.Message.empty() && !Attr.getMessage().empty())
Inferred.Message = Attr.getMessage();
if (Inferred.Rename.empty() && !Attr.getRename().empty())
Inferred.Rename = Attr.getRename();
}
/// Create an implicit availability attribute for the given domain
/// and with the inferred availability.
static AvailableAttr *createAvailableAttr(AvailabilityDomain Domain,
const InferredAvailability &Inferred,
ASTContext &Context) {
// If there is no information that would go into the availability attribute,
// don't create one.
if (Inferred.Kind == AvailableAttr::Kind::Default && !Inferred.Introduced &&
!Inferred.Deprecated && !Inferred.Obsoleted && Inferred.Message.empty() &&
Inferred.Rename.empty())
return nullptr;
llvm::VersionTuple Introduced =
Inferred.Introduced.value_or(llvm::VersionTuple());
llvm::VersionTuple Deprecated =
Inferred.Deprecated.value_or(llvm::VersionTuple());
llvm::VersionTuple Obsoleted =
Inferred.Obsoleted.value_or(llvm::VersionTuple());
return new (Context) AvailableAttr(
SourceLoc(), SourceRange(), Domain, SourceLoc(), Inferred.Kind,
Inferred.Message, Inferred.Rename, Introduced, SourceRange(), Deprecated,
SourceRange(), Obsoleted, SourceRange(), /*Implicit=*/true,
Inferred.IsSPI);
}
void AvailabilityInference::applyInferredAvailableAttrs(
Decl *ToDecl, ArrayRef<const Decl *> InferredFromDecls) {
auto &Context = ToDecl->getASTContext();
// Iterate over the declarations and infer required availability on
// a per-domain basis.
std::map<AvailabilityDomain, InferredAvailability,
StableAvailabilityDomainComparator>
Inferred;
for (const Decl *D : InferredFromDecls) {
llvm::SmallVector<SemanticAvailableAttr, 8> MergedAttrs;
do {
llvm::SmallVector<SemanticAvailableAttr, 8> PendingAttrs;
for (auto AvAttr : D->getSemanticAvailableAttrs()) {
// Skip an attribute from an outer declaration if it is for a platform
// that was already handled implicitly by an attribute from an inner
// declaration.
if (llvm::any_of(MergedAttrs,
[&AvAttr](SemanticAvailableAttr MergedAttr) {
return inheritsAvailabilityFromPlatform(
AvAttr.getPlatform(), MergedAttr.getPlatform());
}))
continue;
mergeWithInferredAvailability(AvAttr, Inferred[AvAttr.getDomain()]);
PendingAttrs.push_back(AvAttr);
}
MergedAttrs.append(PendingAttrs);
// Walk up the enclosing declaration hierarchy to make sure we aren't
// missing any inherited attributes.
D = AvailabilityInference::parentDeclForInferredAvailability(D);
} while (D);
}
DeclAttributes &Attrs = ToDecl->getAttrs();
// Create an availability attribute for each observed platform and add
// to ToDecl.
for (auto &Pair : Inferred) {
if (auto Attr = createAvailableAttr(Pair.first, Pair.second, Context))
Attrs.add(Attr);
}
}
/// Returns the decl that should be considered the parent decl of the given decl
/// when looking for inherited availability annotations.
const Decl *
AvailabilityInference::parentDeclForInferredAvailability(const Decl *D) {
if (auto *AD = dyn_cast<AccessorDecl>(D))
return AD->getStorage();
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
if (auto *NTD = ED->getExtendedNominal())
return NTD;
}
if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
if (PBD->getNumPatternEntries() < 1)
return nullptr;
return PBD->getAnchoringVarDecl(0);
}
if (auto *OTD = dyn_cast<OpaqueTypeDecl>(D))
return OTD->getNamingDecl();
// Clang decls may be inaccurately parented rdar://53956555
if (D->hasClangNode())
return nullptr;
// Availability is inherited from the enclosing context.
return D->getDeclContext()->getInnermostDeclarationDeclContext();
}
/// Returns true if the introduced version in \p newAttr should be used instead
/// of the introduced version in \p prevAttr when both are attached to the same
/// declaration and refer to the active platform.
static bool isBetterThan(const SemanticAvailableAttr &newAttr,
const std::optional<SemanticAvailableAttr> &prevAttr) {
// If there is no prevAttr, newAttr of course wins.
if (!prevAttr)
return true;
// If they belong to the same platform, the one that introduces later wins.
if (prevAttr->getPlatform() == newAttr.getPlatform())
return prevAttr->getIntroduced().value() < newAttr.getIntroduced().value();
// If the new attribute's platform inherits from the old one, it wins.
return inheritsAvailabilityFromPlatform(newAttr.getPlatform(),
prevAttr->getPlatform());
}
static const clang::DarwinSDKInfo::RelatedTargetVersionMapping *
getFallbackVersionMapping(const ASTContext &Ctx,
clang::DarwinSDKInfo::OSEnvPair Kind) {
auto *SDKInfo = Ctx.getDarwinSDKInfo();
if (SDKInfo)
return SDKInfo->getVersionMapping(Kind);
return Ctx.getAuxiliaryDarwinPlatformRemapInfo(Kind);
}
static std::optional<clang::VersionTuple>
getRemappedIntroducedVersionForFallbackPlatform(
const ASTContext &Ctx, const llvm::VersionTuple &Version) {
const auto *Mapping = getFallbackVersionMapping(
Ctx, clang::DarwinSDKInfo::OSEnvPair(
llvm::Triple::IOS, llvm::Triple::UnknownEnvironment,
llvm::Triple::XROS, llvm::Triple::UnknownEnvironment));
if (!Mapping)
return std::nullopt;
return Mapping->mapIntroducedAvailabilityVersion(Version);
}
static std::optional<clang::VersionTuple>
getRemappedDeprecatedObsoletedVersionForFallbackPlatform(
const ASTContext &Ctx, const llvm::VersionTuple &Version) {
const auto *Mapping = getFallbackVersionMapping(
Ctx, clang::DarwinSDKInfo::OSEnvPair(
llvm::Triple::IOS, llvm::Triple::UnknownEnvironment,
llvm::Triple::XROS, llvm::Triple::UnknownEnvironment));
if (!Mapping)
return std::nullopt;
return Mapping->mapDeprecatedObsoletedAvailabilityVersion(Version);
}
bool AvailabilityInference::updateIntroducedAvailabilityDomainForFallback(
const SemanticAvailableAttr &attr, const ASTContext &ctx,
AvailabilityDomain &domain, llvm::VersionTuple &platformVer) {
std::optional<llvm::VersionTuple> introducedVersion = attr.getIntroduced();
if (attr.getPlatform() == PlatformKind::iOS &&
introducedVersion.has_value() &&
isPlatformActive(PlatformKind::visionOS, ctx.LangOpts)) {
// We re-map the iOS introduced version to the corresponding visionOS version
auto potentiallyRemappedIntroducedVersion =
getRemappedIntroducedVersionForFallbackPlatform(ctx,
*introducedVersion);
if (potentiallyRemappedIntroducedVersion.has_value()) {
domain = AvailabilityDomain::forPlatform(PlatformKind::visionOS);
platformVer = potentiallyRemappedIntroducedVersion.value();
return true;
}
}
return false;
}
bool AvailabilityInference::updateDeprecatedAvailabilityDomainForFallback(
const SemanticAvailableAttr &attr, const ASTContext &ctx,
AvailabilityDomain &domain, llvm::VersionTuple &platformVer) {
std::optional<llvm::VersionTuple> deprecatedVersion = attr.getDeprecated();
if (attr.getPlatform() == PlatformKind::iOS &&
deprecatedVersion.has_value() &&
isPlatformActive(PlatformKind::visionOS, ctx.LangOpts)) {
// We re-map the iOS deprecated version to the corresponding visionOS version
auto potentiallyRemappedDeprecatedVersion =
getRemappedDeprecatedObsoletedVersionForFallbackPlatform(
ctx, *deprecatedVersion);
if (potentiallyRemappedDeprecatedVersion.has_value()) {
domain = AvailabilityDomain::forPlatform(PlatformKind::visionOS);
platformVer = potentiallyRemappedDeprecatedVersion.value();
return true;
}
}
return false;
}
bool AvailabilityInference::updateObsoletedAvailabilityDomainForFallback(
const SemanticAvailableAttr &attr, const ASTContext &ctx,
AvailabilityDomain &domain, llvm::VersionTuple &platformVer) {
std::optional<llvm::VersionTuple> obsoletedVersion = attr.getObsoleted();
if (attr.getPlatform() == PlatformKind::iOS && obsoletedVersion.has_value() &&
isPlatformActive(PlatformKind::visionOS, ctx.LangOpts)) {
// We re-map the iOS obsoleted version to the corresponding visionOS version
auto potentiallyRemappedObsoletedVersion =
getRemappedDeprecatedObsoletedVersionForFallbackPlatform(
ctx, *obsoletedVersion);
if (potentiallyRemappedObsoletedVersion.has_value()) {
domain = AvailabilityDomain::forPlatform(PlatformKind::visionOS);
platformVer = potentiallyRemappedObsoletedVersion.value();
return true;
}
}
return false;
}
void AvailabilityInference::updateAvailabilityDomainForFallback(
const SemanticAvailableAttr &attr, const ASTContext &Ctx,
AvailabilityDomain &domain) {
if (attr.getPlatform() == PlatformKind::iOS &&
isPlatformActive(PlatformKind::visionOS, Ctx.LangOpts)) {
domain = AvailabilityDomain::forPlatform(PlatformKind::visionOS);
}
}
bool AvailabilityInference::updateBeforeAvailabilityDomainForFallback(
const BackDeployedAttr *attr, const ASTContext &ctx,
AvailabilityDomain &domain, llvm::VersionTuple &platformVer) {
auto beforeVersion = attr->Version;
if (attr->Platform == PlatformKind::iOS &&
isPlatformActive(PlatformKind::visionOS, ctx.LangOpts)) {
// We re-map the iOS before version to the corresponding visionOS version
auto PotentiallyRemappedIntroducedVersion =
getRemappedIntroducedVersionForFallbackPlatform(ctx, beforeVersion);
if (PotentiallyRemappedIntroducedVersion.has_value()) {
domain = AvailabilityDomain::forPlatform(PlatformKind::visionOS);
platformVer = PotentiallyRemappedIntroducedVersion.value();
return true;
}
}
return false;
}
static std::optional<SemanticAvailableAttr>
getDeclAvailableAttrForPlatformIntroduction(const Decl *D) {
std::optional<SemanticAvailableAttr> bestAvailAttr;
D = abstractSyntaxDeclForAvailableAttribute(D);
for (auto attr : D->getSemanticAvailableAttrs(/*includingInactive=*/false)) {
if (!attr.isPlatformSpecific() || !attr.getIntroduced())
continue;
if (isBetterThan(attr, bestAvailAttr))
bestAvailAttr.emplace(attr);
}
return bestAvailAttr;
}
std::optional<AvailabilityRange>
AvailabilityInference::annotatedAvailableRange(const Decl *D) {
auto bestAvailAttr = D->getAvailableAttrForPlatformIntroduction();
if (!bestAvailAttr)
return std::nullopt;
return bestAvailAttr->getIntroducedRange(D->getASTContext());
}
bool Decl::isAvailableAsSPI() const {
return AvailabilityInference::isAvailableAsSPI(this);
}
SemanticAvailableAttributes
Decl::getSemanticAvailableAttrs(bool includeInactive) const {
return SemanticAvailableAttributes(getAttrs(), this, includeInactive);
}
std::optional<SemanticAvailableAttr>
Decl::getSemanticAvailableAttr(const AvailableAttr *attr) const {
return evaluateOrDefault(getASTContext().evaluator,
SemanticAvailableAttrRequest{attr, this},
std::nullopt);
}
std::optional<SemanticAvailableAttr>
Decl::getActiveAvailableAttrForCurrentPlatform() const {
std::optional<SemanticAvailableAttr> bestAttr;
for (auto attr : getSemanticAvailableAttrs(/*includingInactive=*/false)) {
if (!attr.isPlatformSpecific())
continue;
// We have an attribute that is active for the platform, but is it more
// specific than our current best?
if (!bestAttr || inheritsAvailabilityFromPlatform(
attr.getPlatform(), bestAttr->getPlatform())) {
bestAttr.emplace(attr);
}
}
return bestAttr;
}
std::optional<SemanticAvailableAttr> Decl::getDeprecatedAttr() const {
auto &ctx = getASTContext();
std::optional<SemanticAvailableAttr> result;
auto bestActive = getActiveAvailableAttrForCurrentPlatform();
for (auto attr : getSemanticAvailableAttrs(/*includingInactive=*/false)) {
if (attr.isPlatformSpecific() && (!bestActive || attr != bestActive))
continue;
// Unconditional deprecated.
if (attr.isUnconditionallyDeprecated())
return attr;
auto deprecatedRange = attr.getDeprecatedRange(ctx);
if (!deprecatedRange)
continue;
// We treat the declaration as deprecated if it is deprecated on
// all deployment targets.
auto deploymentRange = attr.getDomain().getDeploymentRange(ctx);
if (deploymentRange && deploymentRange->isContainedIn(*deprecatedRange))
result.emplace(attr);
}
return result;
}
std::optional<SemanticAvailableAttr> Decl::getSoftDeprecatedAttr() const {
auto &ctx = getASTContext();
std::optional<SemanticAvailableAttr> result;
auto bestActive = getActiveAvailableAttrForCurrentPlatform();
for (auto attr : getSemanticAvailableAttrs(/*includingInactive=*/false)) {
if (attr.isPlatformSpecific() && (!bestActive || attr != bestActive))
continue;
auto deprecatedRange = attr.getDeprecatedRange(ctx);
if (!deprecatedRange)
continue;
// We treat the declaration as soft-deprecated if it is deprecated in a
// future version.
auto deploymentRange = attr.getDomain().getDeploymentRange(ctx);
if (!deploymentRange || !deploymentRange->isContainedIn(*deprecatedRange))
result.emplace(attr);
}
return result;
}
std::optional<SemanticAvailableAttr> Decl::getNoAsyncAttr() const {
std::optional<SemanticAvailableAttr> bestAttr;
for (auto attr : getSemanticAvailableAttrs(/*includingInactive=*/false)) {
if (!attr.isNoAsync())
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.emplace(attr);
} else if (bestAttr && attr.isPlatformSpecific() &&
bestAttr->isPlatformSpecific() &&
inheritsAvailabilityFromPlatform(attr.getPlatform(),
bestAttr->getPlatform())) {
// if they both have a viable platform, use the better one
bestAttr.emplace(attr);
} else if (attr.isPlatformSpecific() && !bestAttr->isPlatformSpecific()) {
// Use the one more specific
bestAttr.emplace(attr);
}
}
return bestAttr;
}
bool Decl::isUnavailableInCurrentSwiftVersion() const {
llvm::VersionTuple vers = getASTContext().LangOpts.EffectiveLanguageVersion;
for (auto attr : getSemanticAvailableAttrs(/*includingInactive=*/false)) {
if (attr.isSwiftLanguageModeSpecific()) {
auto introduced = attr.getIntroduced();
if (introduced && *introduced > vers)
return true;
auto obsoleted = attr.getObsoleted();
if (obsoleted && *obsoleted <= vers)
return true;
}
}
return false;
}
std::optional<SemanticAvailableAttr> Decl::getUnavailableAttr() const {
auto context = AvailabilityContext::forDeploymentTarget(getASTContext());
if (auto constraint = getAvailabilityConstraintsForDecl(this, context)
.getPrimaryConstraint()) {
if (constraint->isUnavailable())
return constraint->getAttr();
}
return std::nullopt;
}
static llvm::SmallVector<AvailabilityDomain, 2>
availabilityDomainsForABICompatibility(const ASTContext &ctx) {
llvm::SmallVector<AvailabilityDomain, 2> domains;
// Regardless of target platform, binaries built for Embedded do not require
// compatibility.
if (ctx.LangOpts.hasFeature(Feature::Embedded))
return domains;
if (auto targetDomain = AvailabilityDomain::forTargetPlatform(ctx))
domains.push_back(targetDomain->getABICompatibilityDomain());
if (auto variantDomain = AvailabilityDomain::forTargetVariantPlatform(ctx))
domains.push_back(variantDomain->getABICompatibilityDomain());
return domains;
}
/// Returns true if \p decl is proven to be unavailable for all platforms that
/// external modules interacting with this module could target. A declaration
/// that is not proven to be unavailable in this way could be reachable at
/// runtime, even if it is unavailable to all code in this module.
static bool isUnavailableForAllABICompatiblePlatforms(const Decl *decl) {
// Don't trust unavailability on declarations from Clang modules.
if (isa<ClangModuleUnit>(decl->getDeclContext()->getModuleScopeContext()))
return false;
auto &ctx = decl->getASTContext();
llvm::SmallVector<AvailabilityDomain, 2> compatibilityDomains =
availabilityDomainsForABICompatibility(ctx);
llvm::SmallSet<AvailabilityDomain, 8> unavailableDescendantDomains;
llvm::SmallSet<AvailabilityDomain, 8> availableDescendantDomains;
// Build up the collection of relevant available and unavailable platform
// domains by looking at all the @available attributes. Along the way, we
// may find an attribute that makes the declaration universally unavailable
// in which case platform availability is irrelevant.
for (auto attr : decl->getSemanticAvailableAttrs(/*includeInactive=*/true)) {
auto domain = attr.getDomain();
bool isCompabilityDomainDescendant =
llvm::find_if(compatibilityDomains,
[&domain](AvailabilityDomain compatibilityDomain) {
return compatibilityDomain.contains(domain);
}) != compatibilityDomains.end();
if (isCompabilityDomainDescendant) {
// Record the whether the descendant domain is marked available
// or unavailable. Unavailability overrides availability.
if (attr.isUnconditionallyUnavailable()) {
availableDescendantDomains.erase(domain);
unavailableDescendantDomains.insert(domain);
} else if (!unavailableDescendantDomains.contains(domain)) {
availableDescendantDomains.insert(domain);
}
} else if (attr.isActive(ctx)) {
// The declaration is always unavailable if an active attribute from a
// domain outside the compatibility hierarchy indicates unavailability.
if (attr.isUnconditionallyUnavailable())
return true;
}
}
// If there aren't any compatibility domains to check and we didn't find any
// other active attributes that make the declaration unavailable, then it must
// be available.
if (compatibilityDomains.empty())
return false;
// Verify that the declaration has been marked unavailable in every
// compatibility domain.
for (auto compatibilityDomain : compatibilityDomains) {
if (!unavailableDescendantDomains.contains(compatibilityDomain))
return false;
}
// Verify that there aren't any explicitly available descendant domains.
if (availableDescendantDomains.size() > 0)
return false;
return true;
}
SemanticDeclAvailability
SemanticDeclAvailabilityRequest::evaluate(Evaluator &evaluator,
const Decl *decl) const {
auto inherited = SemanticDeclAvailability::PotentiallyAvailable;
if (auto *parent =
AvailabilityInference::parentDeclForInferredAvailability(decl)) {
inherited = evaluateOrDefault(
evaluator, SemanticDeclAvailabilityRequest{parent}, inherited);
}
if (inherited == SemanticDeclAvailability::CompletelyUnavailable ||
isUnavailableForAllABICompatiblePlatforms(decl))
return SemanticDeclAvailability::CompletelyUnavailable;
if (inherited == SemanticDeclAvailability::ConditionallyUnavailable ||
decl->isUnavailable())
return SemanticDeclAvailability::ConditionallyUnavailable;
return SemanticDeclAvailability::PotentiallyAvailable;
}
bool Decl::isSemanticallyUnavailable() const {
auto availability = evaluateOrDefault(
getASTContext().evaluator, SemanticDeclAvailabilityRequest{this},
SemanticDeclAvailability::PotentiallyAvailable);
return availability != SemanticDeclAvailability::PotentiallyAvailable;
}
bool Decl::isUnreachableAtRuntime() const {
auto availability = evaluateOrDefault(
getASTContext().evaluator, SemanticDeclAvailabilityRequest{this},
SemanticDeclAvailability::PotentiallyAvailable);
return availability == SemanticDeclAvailability::CompletelyUnavailable;
}
static UnavailableDeclOptimization
getEffectiveUnavailableDeclOptimization(ASTContext &ctx) {
if (ctx.LangOpts.UnavailableDeclOptimizationMode.has_value())
return *ctx.LangOpts.UnavailableDeclOptimizationMode;
return UnavailableDeclOptimization::None;
}
bool Decl::isAvailableDuringLowering() const {
// Unconditionally unavailable declarations should be skipped during lowering
// when -unavailable-decl-optimization=complete is specified.
if (getEffectiveUnavailableDeclOptimization(getASTContext()) !=
UnavailableDeclOptimization::Complete)
return true;
return !isUnreachableAtRuntime();
}
bool Decl::requiresUnavailableDeclABICompatibilityStubs() const {
// Code associated with unavailable declarations should trap at runtime if
// -unavailable-decl-optimization=stub is specified.
if (getEffectiveUnavailableDeclOptimization(getASTContext()) !=
UnavailableDeclOptimization::Stub)
return false;
return isUnreachableAtRuntime();
}
AvailabilityRange AvailabilityInference::annotatedAvailableRangeForAttr(
const Decl *D, const SpecializeAttr *attr, ASTContext &ctx) {
std::optional<SemanticAvailableAttr> bestAvailAttr;
for (auto *availAttr : attr->getAvailableAttrs()) {
auto semanticAttr = D->getSemanticAvailableAttr(availAttr);
if (!semanticAttr)
continue;
if (!semanticAttr->getIntroduced() || !semanticAttr->isActive(ctx) ||
!semanticAttr->isPlatformSpecific()) {
continue;
}
if (isBetterThan(*semanticAttr, bestAvailAttr))
bestAvailAttr.emplace(*semanticAttr);
}
if (bestAvailAttr)
return bestAvailAttr->getIntroducedRange(ctx).value_or(
AvailabilityRange::alwaysAvailable());
return AvailabilityRange::alwaysAvailable();
}
std::optional<SemanticAvailableAttr>
Decl::getAvailableAttrForPlatformIntroduction(bool checkExtension) const {
if (auto attr = getDeclAvailableAttrForPlatformIntroduction(this))
return attr;
// Unlike other declarations, extensions can be used without referring to them
// by name (they don't have one) in the source. For this reason, when checking
// the available range of a declaration we also need to check to see if it is
// immediately contained in an extension and use the extension's availability
// if the declaration does not have an explicit @available attribute
// itself. This check relies on the fact that we cannot have nested
// extensions.
if (!checkExtension)
return std::nullopt;
if (auto parent =
AvailabilityInference::parentDeclForInferredAvailability(this)) {
if (auto *ED = dyn_cast<ExtensionDecl>(parent)) {
if (auto attr = getDeclAvailableAttrForPlatformIntroduction(ED))
return attr;
}
}
return std::nullopt;
}
AvailabilityRange AvailabilityInference::availableRange(const Decl *D) {
// ALLANXXX
if (auto attr = D->getAvailableAttrForPlatformIntroduction())
return attr->getIntroducedRange(D->getASTContext())
.value_or(AvailabilityRange::alwaysAvailable());
return AvailabilityRange::alwaysAvailable();
}
bool AvailabilityInference::isAvailableAsSPI(const Decl *D) {
if (auto attr = D->getAvailableAttrForPlatformIntroduction())
return attr->isSPI();
return false;
}
std::optional<SemanticAvailableAttr>
SemanticAvailableAttrRequest::evaluate(swift::Evaluator &evaluator,
const AvailableAttr *attr,
const Decl *decl) const {
if (attr->getDomainOrIdentifier().isDomain())
return SemanticAvailableAttr(attr);
auto &ctx = decl->getASTContext();
auto &diags = ctx.Diags;
auto attrLoc = attr->getLocation();
auto domainLoc = attr->getDomainLoc();
auto declContext = decl->getInnermostDeclContext();
auto mutableAttr = const_cast<AvailableAttr *>(attr);
auto domain = mutableAttr->DomainOrIdentifier.resolveInDeclContext(
domainLoc, declContext);
if (!domain)
return std::nullopt;
auto checkVersion = [&](std::optional<llvm::VersionTuple> version,
SourceRange sourceRange) {
if (version && !VersionRange::isValidVersion(*version)) {
diags
.diagnose(attrLoc, diag::availability_unsupported_version_number,
*version)
.highlight(sourceRange);
return true;
}
return false;
};
if (checkVersion(attr->getRawIntroduced(), attr->IntroducedRange))
return std::nullopt;
if (checkVersion(attr->getRawDeprecated(), attr->DeprecatedRange))
return std::nullopt;
if (checkVersion(attr->getRawObsoleted(), attr->ObsoletedRange))
return std::nullopt;
bool hasIntroduced = attr->getRawIntroduced().has_value();
bool hasDeprecated = attr->getRawDeprecated().has_value();
auto hasObsoleted = attr->getRawObsoleted().has_value();
bool hasVersionSpec = (hasIntroduced || hasDeprecated || hasObsoleted);
if (!domain->isVersioned() && hasVersionSpec) {
SourceRange versionSourceRange;
if (hasIntroduced)
versionSourceRange = attr->IntroducedRange;
else if (hasDeprecated)
versionSourceRange = attr->DeprecatedRange;
else if (hasObsoleted)
versionSourceRange = attr->ObsoletedRange;
diags.diagnose(attrLoc, diag::availability_unexpected_version, *domain)
.limitBehaviorIf(domain->isUniversal(), DiagnosticBehavior::Warning)
.highlight(versionSourceRange);
return std::nullopt;
}
if (domain->isSwiftLanguage() || domain->isPackageDescription()) {
switch (attr->getKind()) {
case AvailableAttr::Kind::Deprecated:
diags.diagnose(attrLoc,
diag::attr_availability_expected_deprecated_version, attr,
*domain);
return std::nullopt;
case AvailableAttr::Kind::Unavailable:
diags.diagnose(attrLoc, diag::attr_availability_cannot_be_used_for_domain,
"unavailable", attr, *domain);
return std::nullopt;
case AvailableAttr::Kind::NoAsync:
diags.diagnose(attrLoc, diag::attr_availability_cannot_be_used_for_domain,
"noasync", attr, *domain);
return std::nullopt;
case AvailableAttr::Kind::Default:
break;
}
}
if (!hasVersionSpec && domain->isVersioned()) {
switch (attr->getKind()) {
case AvailableAttr::Kind::Default:
diags.diagnose(domainLoc, diag::attr_availability_expected_version_spec,
attr, *domain);
return std::nullopt;
case AvailableAttr::Kind::Deprecated:
case AvailableAttr::Kind::Unavailable:
case AvailableAttr::Kind::NoAsync:
break;
}
}
return SemanticAvailableAttr(attr);
}
std::optional<llvm::VersionTuple> SemanticAvailableAttr::getIntroduced() const {
if (auto version = attr->getRawIntroduced())
return canonicalizePlatformVersion(getPlatform(), *version);
return std::nullopt;
}
std::optional<AvailabilityRange>
SemanticAvailableAttr::getIntroducedRange(const ASTContext &Ctx) const {
DEBUG_ASSERT(getDomain().isActive(Ctx));
auto *attr = getParsedAttr();
if (!attr->getRawIntroduced().has_value()) {
// For versioned domains, an "introduced:" version is always required to
// indicate introduction.
if (getDomain().isVersioned())
return std::nullopt;
// For version-less domains, an attribute that does not indicate some other
// kind of unconditional availability constraint implicitly specifies that
// the decl is available in all versions of the domain.
switch (attr->getKind()) {
case AvailableAttr::Kind::Default:
return AvailabilityRange::alwaysAvailable();
case AvailableAttr::Kind::Deprecated:
case AvailableAttr::Kind::Unavailable:
case AvailableAttr::Kind::NoAsync:
return std::nullopt;
}
}
llvm::VersionTuple introducedVersion = getIntroduced().value();
AvailabilityDomain unusedDomain;
llvm::VersionTuple remappedVersion;
if (AvailabilityInference::updateIntroducedAvailabilityDomainForFallback(
*this, Ctx, unusedDomain, remappedVersion))
introducedVersion = remappedVersion;
return AvailabilityRange{introducedVersion};
}
std::optional<llvm::VersionTuple> SemanticAvailableAttr::getDeprecated() const {
if (auto version = attr->getRawDeprecated())
return canonicalizePlatformVersion(getPlatform(), *version);
return std::nullopt;
}
std::optional<AvailabilityRange>
SemanticAvailableAttr::getDeprecatedRange(const ASTContext &Ctx) const {
DEBUG_ASSERT(getDomain().isActive(Ctx));
auto *attr = getParsedAttr();
if (!attr->getRawDeprecated().has_value()) {
// Regardless of the whether the domain supports versions or not, an
// unconditional deprecation attribute indicates the decl is always
// deprecated.
if (isUnconditionallyDeprecated())
return AvailabilityRange::alwaysAvailable();
return std::nullopt;
}
llvm::VersionTuple deprecatedVersion = getDeprecated().value();
AvailabilityDomain unusedDomain;
llvm::VersionTuple remappedVersion;
if (AvailabilityInference::updateDeprecatedAvailabilityDomainForFallback(
*this, Ctx, unusedDomain, remappedVersion))
deprecatedVersion = remappedVersion;
return AvailabilityRange{deprecatedVersion};
}
std::optional<llvm::VersionTuple> SemanticAvailableAttr::getObsoleted() const {
if (auto version = attr->getRawObsoleted())
return canonicalizePlatformVersion(getPlatform(), *version);
return std::nullopt;
}
std::optional<AvailabilityRange>
SemanticAvailableAttr::getObsoletedRange(const ASTContext &Ctx) const {
DEBUG_ASSERT(getDomain().isActive(Ctx));
auto *attr = getParsedAttr();
// Obsoletion always requires a version.
if (!attr->getRawObsoleted().has_value())
return std::nullopt;
llvm::VersionTuple obsoletedVersion = getObsoleted().value();
AvailabilityDomain unusedDomain;
llvm::VersionTuple remappedVersion;
if (AvailabilityInference::updateObsoletedAvailabilityDomainForFallback(
*this, Ctx, unusedDomain, remappedVersion))
obsoletedVersion = remappedVersion;
return AvailabilityRange{obsoletedVersion};
}
namespace {
/// Infers the availability required to access a type.
class AvailabilityInferenceTypeWalker : public TypeWalker {
public:
AvailabilityRange AvailabilityInfo = AvailabilityRange::alwaysAvailable();
Action walkToTypePre(Type ty) override {
if (auto *nominalDecl = ty->getAnyNominal()) {
AvailabilityInfo.intersectWith(
AvailabilityInference::availableRange(nominalDecl));
}
return Action::Continue;
}
};
} // end anonymous namespace
AvailabilityRange AvailabilityInference::inferForType(Type t) {
AvailabilityInferenceTypeWalker walker;
t.walk(walker);
return walker.AvailabilityInfo;
}
AvailabilityRange ASTContext::getSwiftFutureAvailability() const {
auto target = LangOpts.Target;
auto getFutureAvailabilityRange = []() -> AvailabilityRange {
return AvailabilityRange(llvm::VersionTuple(99, 99, 0));
};
if (target.isMacOSX()) {
return getFutureAvailabilityRange();
} else if (target.isiOS()) {
return getFutureAvailabilityRange();
} else if (target.isWatchOS()) {
return getFutureAvailabilityRange();
} else if (target.isXROS()) {
return getFutureAvailabilityRange();
} else {
return AvailabilityRange::alwaysAvailable();
}
}
AvailabilityRange ASTContext::getSwiftAvailability(unsigned major,
unsigned minor) const {
auto target = LangOpts.Target;
// Deal with special cases for Swift 5.3 and lower
if (major == 5 && minor <= 3) {
if (target.getArchName() == "arm64e")