-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckAvailability.cpp
3531 lines (3000 loc) · 127 KB
/
TypeCheckAvailability.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
//===--- TypeCheckAvailability.cpp - Availability Diagnostics -------------===//
//
// 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 availability diagnostics.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckAvailability.h"
#include "MiscDiagnostics.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckObjC.h"
#include "TypeCheckType.h"
#include "TypeCheckUnsafe.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AvailabilityConstraint.h"
#include "swift/AST/AvailabilityDomain.h"
#include "swift/AST/AvailabilityInference.h"
#include "swift/AST/AvailabilityScope.h"
#include "swift/AST/AvailabilitySpec.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/DeclExportabilityVisitor.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeDeclFinder.h"
#include "swift/AST/UnsafeUse.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/ParseDeclName.h"
#include "swift/Sema/IDETypeChecking.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
/// Emit a diagnostic for references to declarations that have been
/// marked as unavailable, either through "unavailable" or "obsoleted:".
static bool diagnoseExplicitUnavailability(
SourceLoc loc, const AvailabilityConstraint &constraint,
const RootProtocolConformance *rootConf, const ExtensionDecl *ext,
const ExportContext &where,
bool warnIfConformanceUnavailablePreSwift6 = false,
bool preconcurrency = false);
/// Emit a diagnostic for references to declarations that have been
/// marked as unavailable, either through "unavailable" or "obsoleted:".
static bool diagnoseExplicitUnavailability(
const ValueDecl *D, SourceRange R, const AvailabilityConstraint &constraint,
const ExportContext &Where, DeclAvailabilityFlags Flags,
llvm::function_ref<void(InFlightDiagnostic &, StringRef)>
attachRenameFixIts);
static bool diagnoseSubstitutionMapAvailability(
SourceLoc loc, SubstitutionMap subs, const ExportContext &where,
Type depTy = Type(), Type replacementTy = Type(),
bool warnIfConformanceUnavailablePreSwift6 = false,
bool suppressParameterizationCheckForOptional = false,
bool preconcurrency = false);
/// Diagnose uses of unavailable declarations in types.
static bool
diagnoseTypeReprAvailability(const TypeRepr *T, const ExportContext &where,
DeclAvailabilityFlags flags = std::nullopt);
ExportContext::ExportContext(DeclContext *DC,
AvailabilityContext availability,
FragileFunctionKind kind,
llvm::SmallVectorImpl<UnsafeUse> *unsafeUses,
bool spi, bool exported,
bool implicit)
: DC(DC), Availability(availability), FragileKind(kind),
UnsafeUses(unsafeUses) {
SPI = spi;
Exported = exported;
Implicit = implicit;
Reason = unsigned(ExportabilityReason::General);
}
template<typename Fn>
static void forEachOuterDecl(DeclContext *DC, Fn fn) {
for (; !DC->isModuleScopeContext(); DC = DC->getParent()) {
switch (DC->getContextKind()) {
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::SerializedAbstractClosure:
case DeclContextKind::TopLevelCodeDecl:
case DeclContextKind::SerializedTopLevelCodeDecl:
case DeclContextKind::Package:
case DeclContextKind::Module:
case DeclContextKind::FileUnit:
case DeclContextKind::MacroDecl:
break;
case DeclContextKind::Initializer:
if (auto *PBI = dyn_cast<PatternBindingInitializer>(DC))
fn(PBI->getBinding());
else if (auto *I = dyn_cast<PropertyWrapperInitializer>(DC))
fn(I->getWrappedVar());
break;
case DeclContextKind::SubscriptDecl:
fn(cast<SubscriptDecl>(DC));
break;
case DeclContextKind::EnumElementDecl:
fn(cast<EnumElementDecl>(DC));
break;
case DeclContextKind::AbstractFunctionDecl:
fn(cast<AbstractFunctionDecl>(DC));
if (auto *AD = dyn_cast<AccessorDecl>(DC))
fn(AD->getStorage());
break;
case DeclContextKind::GenericTypeDecl:
fn(cast<GenericTypeDecl>(DC));
break;
case DeclContextKind::ExtensionDecl:
fn(cast<ExtensionDecl>(DC));
break;
}
}
}
static void computeExportContextBits(ASTContext &Ctx, Decl *D, bool *spi,
bool *implicit) {
if (D->isSPI() ||
D->isAvailableAsSPI())
*spi = true;
// Defer bodies are desugared to an implicit closure expression. We need to
// dilute the meaning of "implicit" to make sure we're still checking
// availability inside of defer statements.
const auto isDeferBody = isa<FuncDecl>(D) && cast<FuncDecl>(D)->isDeferBody();
if (D->isImplicit() && !isDeferBody)
*implicit = true;
if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
for (unsigned i = 0, e = PBD->getNumPatternEntries(); i < e; ++i) {
if (auto *VD = PBD->getAnchoringVarDecl(i))
computeExportContextBits(Ctx, VD, spi, implicit);
}
}
}
ExportContext ExportContext::forDeclSignature(Decl *D) {
auto &Ctx = D->getASTContext();
auto *DC = D->getInnermostDeclContext();
auto fragileKind = DC->getFragileFunctionKind();
auto loc = D->getLoc();
auto availabilityContext = AvailabilityContext::forLocation(loc, DC);
bool spi = Ctx.LangOpts.LibraryLevel == LibraryLevel::SPI;
bool implicit = false;
computeExportContextBits(Ctx, D, &spi, &implicit);
forEachOuterDecl(D->getDeclContext(), [&](Decl *D) {
computeExportContextBits(Ctx, D, &spi, &implicit);
});
bool exported = ::isExported(D);
return ExportContext(DC, availabilityContext, fragileKind, nullptr,
spi, exported, implicit);
}
ExportContext ExportContext::forFunctionBody(DeclContext *DC, SourceLoc loc) {
auto &Ctx = DC->getASTContext();
auto fragileKind = DC->getFragileFunctionKind();
auto availabilityContext = AvailabilityContext::forLocation(loc, DC);
bool spi = Ctx.LangOpts.LibraryLevel == LibraryLevel::SPI;
bool implicit = false;
forEachOuterDecl(
DC, [&](Decl *D) { computeExportContextBits(Ctx, D, &spi, &implicit); });
bool exported = false;
return ExportContext(DC, availabilityContext, fragileKind, nullptr,
spi, exported, implicit);
}
ExportContext ExportContext::forConformance(DeclContext *DC,
ProtocolDecl *proto) {
assert(isa<ExtensionDecl>(DC) || isa<NominalTypeDecl>(DC));
auto where = forDeclSignature(DC->getInnermostDeclarationDeclContext());
where.Exported &= proto->getFormalAccessScope(
DC, /*usableFromInlineAsPublic*/true).isPublic();
return where;
}
ExportContext ExportContext::withReason(ExportabilityReason reason) const {
auto copy = *this;
copy.Reason = unsigned(reason);
return copy;
}
ExportContext ExportContext::withExported(bool exported) const {
auto copy = *this;
copy.Exported = isExported() && exported;
return copy;
}
ExportContext ExportContext::withRefinedAvailability(
const AvailabilityRange &availability) const {
auto copy = *this;
copy.Availability.constrainWithPlatformRange(availability,
DC->getASTContext());
return copy;
}
bool ExportContext::mustOnlyReferenceExportedDecls() const {
return Exported || FragileKind.kind != FragileFunctionKind::None;
}
std::optional<ExportabilityReason>
ExportContext::getExportabilityReason() const {
if (Exported)
return ExportabilityReason(Reason);
return std::nullopt;
}
/// Returns true if there is any availability attribute on the declaration
/// that is active.
// FIXME: [availability] De-duplicate this with AvailabilityScopeBuilder.cpp.
static bool hasActiveAvailableAttribute(const Decl *D, ASTContext &ctx) {
D = D->getAbstractSyntaxDeclForAttributes();
for (auto Attr : D->getSemanticAvailableAttrs()) {
if (Attr.isActive(ctx))
return true;
}
return false;
}
static bool shouldAllowReferenceToUnavailableInSwiftDeclaration(
const Decl *D, const ExportContext &where) {
auto *DC = where.getDeclContext();
auto *SF = DC->getParentSourceFile();
// Unavailable-in-Swift declarations shouldn't be referenced directly in
// source. However, they can be referenced in implicit declarations that are
// printed in .swiftinterfaces.
if (!SF || SF->Kind != SourceFileKind::Interface)
return false;
if (auto constructor = dyn_cast_or_null<ConstructorDecl>(DC->getAsDecl())) {
// Designated initializers inherited from an Obj-C superclass may have
// parameters that are unavailable-in-Swift.
if (constructor->isObjC())
return true;
}
return false;
}
// Utility function to help determine if noasync diagnostics are still
// appropriate even if a `DeclContext` returns `false` from `isAsyncContext()`.
static bool shouldTreatDeclContextAsAsyncForDiagnostics(const DeclContext *DC) {
if (auto *D = DC->getAsDecl())
if (auto *FD = dyn_cast<FuncDecl>(D))
if (FD->isDeferBody())
// If this is a defer body, we should delegate to its parent.
return shouldTreatDeclContextAsAsyncForDiagnostics(DC->getParent());
return DC->isAsyncContext();
}
/// A class that walks the AST to find the innermost (i.e., deepest) node that
/// contains a target SourceRange and matches a particular criterion.
/// This class finds the innermost nodes of interest by walking
/// down the root until it has found the target range (in a Pre-visitor)
/// and then recording the innermost node on the way back up in the
/// Post-visitors. It does its best to not search unnecessary subtrees,
/// although this is complicated by the fact that not all nodes have
/// source range information.
class InnermostAncestorFinder : private ASTWalker {
public:
/// The type of a match predicate, which takes as input a node and its
/// parent and returns a bool indicating whether the node matches.
using MatchPredicate = std::function<bool(ASTNode, ASTWalker::ParentTy)>;
private:
const SourceRange TargetRange;
const SourceManager &SM;
const MatchPredicate Predicate;
bool FoundTarget = false;
std::optional<ASTNode> InnermostMatchingNode;
public:
InnermostAncestorFinder(SourceRange TargetRange, const SourceManager &SM,
ASTNode SearchNode, const MatchPredicate &Predicate)
: TargetRange(TargetRange), SM(SM), Predicate(Predicate) {
assert(TargetRange.isValid());
SearchNode.walk(*this);
}
/// Returns the innermost node containing the target range that matches
/// the predicate.
std::optional<ASTNode> getInnermostMatchingNode() {
return InnermostMatchingNode;
}
MacroWalking getMacroWalkingBehavior() const override {
// This is SourceRange based finder. 'SM.rangeContains()' fails anyway when
// crossing source buffers.
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
return getPreWalkActionFor(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
return getPreWalkActionFor(S);
}
PreWalkAction walkToDeclPre(Decl *D) override {
return getPreWalkActionFor(D).Action;
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
return getPreWalkActionFor(P);
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
return getPreWalkActionFor(T).Action;
}
/// Retrieve the pre-walk action for a given node, which determines whether
/// or not it should be walked into.
template <typename T>
PreWalkResult<T> getPreWalkActionFor(T Node) {
// When walking down the tree, we traverse until we have found a node
// inside the target range. Once we have found such a node, there is no
// need to traverse any deeper.
if (FoundTarget)
return Action::SkipNode(Node);
// If we haven't found our target yet and the node we are pre-visiting
// doesn't have a valid range, we still have to traverse it because its
// subtrees may have valid ranges.
auto Range = Node->getSourceRange();
if (Range.isInvalid())
return Action::Continue(Node);
// We have found our target if the range of the node we are visiting
// is contained in the range we are looking for.
FoundTarget = SM.rangeContains(TargetRange, Range);
if (FoundTarget) {
walkToNodePost(Node);
return Action::SkipNode(Node);
}
// Search the subtree if the target range is inside its range.
if (!SM.rangeContains(Range, TargetRange))
return Action::SkipNode(Node);
return Action::Continue(Node);
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
return walkToNodePost(E);
}
PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override {
return walkToNodePost(S);
}
PostWalkAction walkToDeclPost(Decl *D) override {
return walkToNodePost(D).Action;
}
/// Once we have found the target node, look for the innermost ancestor
/// matching our criteria on the way back up the spine of the tree.
template <typename T>
PostWalkResult<T> walkToNodePost(T Node) {
if (!InnermostMatchingNode.has_value() && Predicate(Node, Parent)) {
assert(Node->getSourceRange().isInvalid() ||
SM.rangeContains(Node->getSourceRange(), TargetRange));
InnermostMatchingNode = Node;
return Action::Stop();
}
return Action::Continue(Node);
}
};
/// Starting from SearchRoot, finds the innermost node containing ChildRange
/// for which Predicate returns true. Returns None if no such root is found.
static std::optional<ASTNode> findInnermostAncestor(
SourceRange ChildRange, const SourceManager &SM, ASTNode SearchRoot,
const InnermostAncestorFinder::MatchPredicate &Predicate) {
InnermostAncestorFinder Finder(ChildRange, SM, SearchRoot, Predicate);
return Finder.getInnermostMatchingNode();
}
/// Given a reference range and a declaration context containing the range,
/// attempt to find a declaration containing the reference. This may not
/// be the innermost declaration containing the range.
/// Returns null if no such declaration can be found.
static const Decl *findContainingDeclaration(SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
const SourceManager &SM) {
auto ContainsReferenceRange = [&](const Decl *D) -> bool {
if (ReferenceRange.isInvalid())
return false;
return SM.rangeContains(D->getSourceRange(), ReferenceRange);
};
if (const Decl *D = ReferenceDC->getInnermostDeclarationDeclContext()) {
// If we have an inner declaration context, see if we can narrow the search
// down to one of its members. This is important for properties, which don't
// count as DeclContexts of their own but which can still introduce
// availability.
if (auto *IDC = dyn_cast<IterableDeclContext>(D)) {
auto BestMember = llvm::find_if(IDC->getMembers(),
ContainsReferenceRange);
if (BestMember != IDC->getMembers().end())
return *BestMember;
}
return D;
}
// We couldn't find a suitable node by climbing the DeclContext hierarchy, so
// fall back to looking for a top-level declaration that contains the
// reference range. We will hit this case for top-level elements that do not
// themselves introduce DeclContexts, such as global variables. If we don't
// have a reference range, there is nothing we can do, so return null.
if (ReferenceRange.isInvalid())
return nullptr;
SourceFile *SF = ReferenceDC->getParentSourceFile();
if (!SF)
return nullptr;
auto BestTopLevelDecl = llvm::find_if(SF->getTopLevelDecls(),
ContainsReferenceRange);
if (BestTopLevelDecl != SF->getTopLevelDecls().end())
return *BestTopLevelDecl;
return nullptr;
}
/// Given a declaration, return a better related declaration for which
/// to suggest an @available fixit, or the original declaration
/// if no such related declaration exists.
static const Decl *relatedDeclForAvailabilityFixit(const Decl *D) {
if (auto *accessor = dyn_cast<AccessorDecl>(D)) {
// Suggest @available Fix-Its on property rather than individual
// accessors.
D = accessor->getStorage();
}
return D->getAbstractSyntaxDeclForAttributes();
}
/// Walk the DeclContext hierarchy starting from D to find a declaration
/// at the member level (i.e., declared in a type context) on which to provide
/// an @available() Fix-It.
static const Decl *ancestorMemberLevelDeclForAvailabilityFixit(const Decl *D) {
while (D) {
D = relatedDeclForAvailabilityFixit(D);
if (!D->isImplicit() && D->getDeclContext()->isTypeContext() &&
DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind::Available, D)) {
break;
}
D = cast_or_null<AbstractFunctionDecl>(
D->getDeclContext()->getInnermostMethodContext());
}
return D;
}
/// Returns true if the declaration is at the type level (either a nominal
/// type, an extension, or a global function) and can support an @available
/// attribute.
static bool isTypeLevelDeclForAvailabilityFixit(const Decl *D) {
if (!DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind::Available, D)) {
return false;
}
if (isa<ExtensionDecl>(D) || isa<NominalTypeDecl>(D)) {
return true;
}
bool IsModuleScopeContext = D->getDeclContext()->isModuleScopeContext();
// We consider global functions, type aliases, and macros to be "type level"
if (isa<FuncDecl>(D) || isa<MacroDecl>(D) || isa<TypeAliasDecl>(D)) {
return IsModuleScopeContext;
}
if (auto *VD = dyn_cast<VarDecl>(D)) {
if (!IsModuleScopeContext)
return false;
if (PatternBindingDecl *PBD = VD->getParentPatternBinding()) {
return PBD->getDeclContext()->isModuleScopeContext();
}
}
return false;
}
/// Walk the DeclContext hierarchy starting from D to find a declaration
/// at a member level (i.e., declared in a type context) on which to provide an
/// @available() Fix-It.
static const Decl *ancestorTypeLevelDeclForAvailabilityFixit(const Decl *D) {
assert(D);
D = relatedDeclForAvailabilityFixit(D);
while (D && !isTypeLevelDeclForAvailabilityFixit(D)) {
D = D->getDeclContext()->getInnermostDeclarationDeclContext();
}
return D;
}
/// Given the range of a reference to an unavailable symbol and the
/// declaration context containing the reference, make a best effort find up to
/// three locations for potential fixits.
///
/// \param FoundVersionCheckNode Returns a node that can be wrapped in a
/// if #available(...) { ... } version check to fix the unavailable reference,
/// or None if such a node cannot be found.
///
/// \param FoundMemberLevelDecl Returns member-level declaration (i.e., the
/// child of a type DeclContext) for which an @available attribute would
/// fix the unavailable reference.
///
/// \param FoundTypeLevelDecl returns a type-level declaration (a
/// a nominal type, an extension, or a global function) for which an
/// @available attribute would fix the unavailable reference.
static void findAvailabilityFixItNodes(
SourceRange ReferenceRange, const DeclContext *ReferenceDC,
const SourceManager &SM, std::optional<ASTNode> &FoundVersionCheckNode,
const Decl *&FoundMemberLevelDecl, const Decl *&FoundTypeLevelDecl) {
FoundVersionCheckNode = std::nullopt;
FoundMemberLevelDecl = nullptr;
FoundTypeLevelDecl = nullptr;
// Limit tree to search based on the DeclContext of the reference.
const Decl *DeclarationToSearch =
findContainingDeclaration(ReferenceRange, ReferenceDC, SM);
if (!DeclarationToSearch)
return;
// Const-cast to inject into ASTNode. This search will not modify
// the declaration.
ASTNode SearchRoot = const_cast<Decl *>(DeclarationToSearch);
// The node to wrap in if #available(...) { ... } is the innermost node in
// SearchRoot that (1) can be guarded with an if statement and (2)
// contains the ReferenceRange.
// We make no guarantee that the Fix-It, when applied, will result in
// semantically valid code -- but, at a minimum, it should parse. So,
// for example, we may suggest wrapping a variable declaration in a guard,
// which would not be valid if the variable is later used. The goal
// is discoverability of #os() (via the diagnostic and Fix-It) rather than
// magically fixing the code in all cases.
InnermostAncestorFinder::MatchPredicate IsGuardable =
[](ASTNode Node, ASTWalker::ParentTy Parent) {
if (Expr *ParentExpr = Parent.getAsExpr()) {
if (!isa<ClosureExpr>(ParentExpr))
return false;
} else if (auto *ParentStmt = Parent.getAsStmt()) {
if (!isa<BraceStmt>(ParentStmt)) {
return false;
}
} else {
return false;
}
return true;
};
FoundVersionCheckNode =
findInnermostAncestor(ReferenceRange, SM, SearchRoot, IsGuardable);
// Try to find declarations on which @available attributes can be added.
// The heuristics for finding these declarations are biased towards deeper
// nodes in the AST to limit the scope of suggested availability regions
// and provide a better IDE experience (it can get jumpy if Fix-It locations
// are far away from the error needing the Fix-It).
if (DeclarationToSearch) {
FoundMemberLevelDecl =
ancestorMemberLevelDeclForAvailabilityFixit(DeclarationToSearch);
FoundTypeLevelDecl =
ancestorTypeLevelDeclForAvailabilityFixit(DeclarationToSearch);
}
}
/// Emit a diagnostic note and Fix-It to add an @available attribute
/// on the given declaration for the given version range.
static void fixAvailabilityForDecl(
SourceRange ReferenceRange, const Decl *D, AvailabilityDomain Domain,
const AvailabilityRange &RequiredAvailability, ASTContext &Context) {
assert(D);
// Don't suggest adding an @available() to a declaration where we would
// emit a diagnostic saying it is not allowed.
if (TypeChecker::diagnosticIfDeclCannotBePotentiallyUnavailable(D).has_value())
return;
if (hasActiveAvailableAttribute(D, Context)) {
// For QoI, in future should emit a fixit to update the existing attribute.
return;
}
// For some declarations (variables, enum elements), the location in concrete
// syntax to suggest the Fix-It may differ from the declaration to which
// we attach availability attributes in the abstract syntax tree during
// parsing.
const Decl *ConcDecl = D->getConcreteSyntaxDeclForAttributes();
// To avoid exposing the pattern binding declaration to the user, get the
// descriptive kind from one of the VarDecls.
DescriptiveDeclKind KindForDiagnostic = ConcDecl->getDescriptiveKind();
if (KindForDiagnostic == DescriptiveDeclKind::PatternBinding) {
KindForDiagnostic = D->getDescriptiveKind();
}
SourceLoc InsertLoc =
ConcDecl->getAttributeInsertionLoc(/*forModifier=*/false);
if (InsertLoc.isInvalid())
return;
StringRef OriginalIndent =
Lexer::getIndentationForLine(Context.SourceMgr, InsertLoc);
D->diagnose(diag::availability_add_attribute, KindForDiagnostic)
.fixItInsert(InsertLoc, diag::insert_available_attr,
Domain.getNameForAttributePrinting(),
RequiredAvailability.getVersionString(), OriginalIndent);
}
/// In the special case of being in an existing, nontrivial availability scope
/// that's close but not quite narrow enough to satisfy requirements
/// (i.e. requirements are contained-in the existing scope but off by a subminor
/// version), emit a diagnostic and fixit that narrows the existing scope
/// condition to the required range.
static bool fixAvailabilityByNarrowingNearbyVersionCheck(
SourceRange ReferenceRange, const DeclContext *ReferenceDC,
AvailabilityDomain Domain, const AvailabilityRange &RequiredAvailability,
ASTContext &Context, InFlightDiagnostic &Err) {
// FIXME: [availability] Support fixing availability for non-platform domains
if (!Domain.isPlatform())
return false;
const AvailabilityScope *scope = nullptr;
(void)AvailabilityContext::forLocation(ReferenceRange.Start, ReferenceDC,
&scope);
if (!scope)
return false;
// FIXME: [availability] Support fixing availability for versionless domains.
auto ExplicitAvailability = scope->getExplicitAvailabilityRange();
if (ExplicitAvailability && !RequiredAvailability.isAlwaysAvailable() &&
scope->getReason() != AvailabilityScope::Reason::Root &&
RequiredAvailability.isContainedIn(*ExplicitAvailability)) {
// Only fix situations that are "nearby" versions, meaning
// disagreement on a minor-or-less version (subminor-or-less version for
// macOS 10.x.y).
auto RunningVers = ExplicitAvailability->getRawMinimumVersion();
auto RequiredVers = RequiredAvailability.getRawMinimumVersion();
auto Platform = targetPlatform(Context.LangOpts);
if (RunningVers.getMajor() != RequiredVers.getMajor())
return false;
if ((Platform == PlatformKind::macOS ||
Platform == PlatformKind::macOSApplicationExtension) &&
RunningVers.getMajor() == 10 &&
!(RunningVers.getMinor().has_value() &&
RequiredVers.getMinor().has_value() &&
RunningVers.getMinor().value() ==
RequiredVers.getMinor().value()))
return false;
auto FixRange = scope->getAvailabilityConditionVersionSourceRange(
AvailabilityDomain::forPlatform(Platform), RunningVers);
if (!FixRange.isValid())
return false;
// Have found a nontrivial availability scope-introducer to narrow.
Err.fixItReplace(FixRange, RequiredAvailability.getVersionString());
return true;
}
return false;
}
/// Emit a diagnostic note and Fix-It to add an if #available(...) { } guard
/// that checks for the given version range around the given node.
static void fixAvailabilityByAddingVersionCheck(
ASTNode NodeToWrap, const AvailabilityRange &RequiredAvailability,
SourceRange ReferenceRange, ASTContext &Context) {
// If this is an implicit variable that wraps an expression,
// let's point to it's initializer. For example, result builder
// transform captures expressions into implicit variables.
if (auto *PB =
dyn_cast_or_null<PatternBindingDecl>(NodeToWrap.dyn_cast<Decl *>())) {
if (PB->isImplicit() && PB->getSingleVar()) {
if (auto *init = PB->getInit(0))
NodeToWrap = init;
}
}
SourceRange RangeToWrap = NodeToWrap.getSourceRange();
if (RangeToWrap.isInvalid())
return;
SourceLoc ReplaceLocStart = RangeToWrap.Start;
StringRef ExtraIndent;
StringRef OriginalIndent = Lexer::getIndentationForLine(
Context.SourceMgr, ReplaceLocStart, &ExtraIndent);
std::string IfText;
{
llvm::raw_string_ostream Out(IfText);
SourceLoc ReplaceLocEnd =
Lexer::getLocForEndOfToken(Context.SourceMgr, RangeToWrap.End);
std::string GuardedText =
Context.SourceMgr.extractText(CharSourceRange(Context.SourceMgr,
ReplaceLocStart,
ReplaceLocEnd)).str();
std::string NewLine = "\n";
std::string NewLineReplacement = (NewLine + ExtraIndent).str();
// Indent the body of the Fix-It if. Because the body may be a compound
// statement, we may have to indent multiple lines.
size_t StartAt = 0;
while ((StartAt = GuardedText.find(NewLine, StartAt)) !=
std::string::npos) {
GuardedText.replace(StartAt, NewLine.length(), NewLineReplacement);
StartAt += NewLine.length();
}
PlatformKind Target = targetPlatform(Context.LangOpts);
// Runtime availability checks that specify app extension platforms don't
// work, so only suggest checks against the base platform.
if (auto TargetRemovingAppExtension =
basePlatformForExtensionPlatform(Target))
Target = *TargetRemovingAppExtension;
Out << "if #available(" << platformString(Target) << " "
<< RequiredAvailability.getVersionString() << ", *) {\n";
Out << OriginalIndent << ExtraIndent << GuardedText << "\n";
// We emit an empty fallback case with a comment to encourage the developer
// to think explicitly about whether fallback on earlier versions is needed.
Out << OriginalIndent << "} else {\n";
Out << OriginalIndent << ExtraIndent << "// Fallback on earlier versions\n";
Out << OriginalIndent << "}";
}
Context.Diags.diagnose(
ReferenceRange.Start, diag::availability_guard_with_version_check)
.fixItReplace(RangeToWrap, IfText);
}
/// Emit suggested Fix-Its for a reference with to an unavailable symbol
/// requiting the given OS version range.
static void fixAvailability(SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
AvailabilityDomain Domain,
const AvailabilityRange &RequiredAvailability,
ASTContext &Context) {
if (ReferenceRange.isInvalid())
return;
// FIXME: [availability] Support non-platform domains.
if (!Domain.isPlatform())
return;
std::optional<ASTNode> NodeToWrapInVersionCheck;
const Decl *FoundMemberDecl = nullptr;
const Decl *FoundTypeLevelDecl = nullptr;
findAvailabilityFixItNodes(ReferenceRange, ReferenceDC, Context.SourceMgr,
NodeToWrapInVersionCheck, FoundMemberDecl,
FoundTypeLevelDecl);
// Suggest wrapping in if #available(...) { ... } if possible.
if (NodeToWrapInVersionCheck.has_value()) {
fixAvailabilityByAddingVersionCheck(NodeToWrapInVersionCheck.value(),
RequiredAvailability, ReferenceRange,
Context);
}
// Suggest adding availability attributes.
if (FoundMemberDecl) {
fixAvailabilityForDecl(ReferenceRange, FoundMemberDecl, Domain,
RequiredAvailability, Context);
}
if (FoundTypeLevelDecl) {
fixAvailabilityForDecl(ReferenceRange, FoundTypeLevelDecl, Domain,
RequiredAvailability, Context);
}
}
static void diagnosePotentialUnavailability(
SourceRange ReferenceRange,
llvm::function_ref<InFlightDiagnostic(AvailabilityDomain,
AvailabilityRange)>
Diagnose,
const DeclContext *ReferenceDC, AvailabilityDomain Domain,
const AvailabilityRange &Availability) {
ASTContext &Context = ReferenceDC->getASTContext();
{
auto Err = Diagnose(Domain, Availability);
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(
ReferenceRange, ReferenceDC, Domain, Availability, Context, Err))
return;
}
fixAvailability(ReferenceRange, ReferenceDC, Domain, Availability, Context);
}
// FIXME: [availability] Should this take an AvailabilityContext instead of
// AvailabilityRange?
bool TypeChecker::checkAvailability(SourceRange ReferenceRange,
AvailabilityRange PlatformRange,
const DeclContext *ReferenceDC,
llvm::function_ref<InFlightDiagnostic(
AvailabilityDomain, AvailabilityRange)>
Diagnose) {
ASTContext &ctx = ReferenceDC->getASTContext();
if (ctx.LangOpts.DisableAvailabilityChecking)
return false;
auto domain = ctx.getTargetAvailabilityDomain();
if (domain.isUniversal())
return false;
auto availabilityAtLocation =
AvailabilityContext::forLocation(ReferenceRange.Start, ReferenceDC)
.getPlatformRange();
if (!availabilityAtLocation.isContainedIn(PlatformRange)) {
diagnosePotentialUnavailability(ReferenceRange, Diagnose, ReferenceDC,
domain, PlatformRange);
return true;
}
return false;
}
bool TypeChecker::checkAvailability(
SourceRange ReferenceRange, AvailabilityRange PlatformRange,
Diag<AvailabilityDomain, AvailabilityRange> Diag,
const DeclContext *ReferenceDC) {
auto &Diags = ReferenceDC->getASTContext().Diags;
return TypeChecker::checkAvailability(
ReferenceRange, PlatformRange, ReferenceDC,
[&](AvailabilityDomain domain, AvailabilityRange range) {
return Diags.diagnose(ReferenceRange.Start, Diag, domain, range);
});
}
void TypeChecker::checkConcurrencyAvailability(SourceRange ReferenceRange,
const DeclContext *ReferenceDC) {
checkAvailability(
ReferenceRange,
ReferenceDC->getASTContext().getBackDeployedConcurrencyAvailability(),
diag::availability_concurrency_only_version_newer, ReferenceDC);
}
static bool
requiresDeploymentTargetOrEarlier(AvailabilityDomain domain,
const AvailabilityRange &availability,
ASTContext &ctx) {
if (auto deploymentRange = domain.getDeploymentRange(ctx))
return deploymentRange->isContainedIn(availability);
return false;
}
/// Returns the diagnostic to emit for the potentially unavailable decl and sets
/// \p IsError accordingly.
static Diagnostic getPotentialUnavailabilityDiagnostic(
const ValueDecl *D, const DeclContext *ReferenceDC,
AvailabilityDomain Domain, const AvailabilityRange &Availability,
bool WarnBeforeDeploymentTarget, bool &IsError) {
ASTContext &Context = ReferenceDC->getASTContext();
if (requiresDeploymentTargetOrEarlier(Domain, Availability, Context)) {
// The required OS version is at or before the deployment target so this
// diagnostic should indicate that the decl could be unavailable to clients
// of the module containing the reference.
IsError = !WarnBeforeDeploymentTarget;
auto diag = Diagnostic(diag::availability_decl_only_in_for_clients, D,
Domain, Availability.hasMinimumVersion(),
Availability, ReferenceDC->getParentModule());
if (!IsError)
diag.setBehaviorLimit(DiagnosticBehavior::Warning);
return diag;
}
IsError = true;
return Diagnostic(diag::availability_decl_only_in, D, Domain,
Availability.hasMinimumVersion(), Availability);
}
// Emits a diagnostic for a reference to a declaration that is potentially
// unavailable at the given source location. Returns true if an error diagnostic
// was emitted.
static bool
diagnosePotentialUnavailability(const ValueDecl *D, SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
AvailabilityDomain Domain,
const AvailabilityRange &Availability,
bool WarnBeforeDeploymentTarget = false) {
ASTContext &Context = ReferenceDC->getASTContext();
if (Context.LangOpts.DisableAvailabilityChecking)
return false;
bool IsError;
{
auto Diag = Context.Diags.diagnose(
ReferenceRange.Start, getPotentialUnavailabilityDiagnostic(
D, ReferenceDC, Domain, Availability,
WarnBeforeDeploymentTarget, IsError));
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(
ReferenceRange, ReferenceDC, Domain, Availability, Context, Diag))
return IsError;
}
fixAvailability(ReferenceRange, ReferenceDC, Domain, Availability, Context);
return IsError;
}
/// Emits a diagnostic for a reference to a storage accessor that is
/// potentially unavailable.
static void diagnosePotentialAccessorUnavailability(
const AccessorDecl *Accessor, SourceRange ReferenceRange,
const DeclContext *ReferenceDC, AvailabilityDomain Domain,
const AvailabilityRange &Availability, bool ForInout) {
ASTContext &Context = ReferenceDC->getASTContext();
assert(Accessor->isGetterOrSetter());
auto &diag = ForInout ? diag::availability_inout_accessor_only_in
: diag::availability_decl_only_in;
{
auto Err =
Context.Diags.diagnose(ReferenceRange.Start, diag, Accessor,
Context.getTargetAvailabilityDomain(),
Availability.hasMinimumVersion(), Availability);
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(
ReferenceRange, ReferenceDC, Domain, Availability, Context, Err))
return;
}
fixAvailability(ReferenceRange, ReferenceDC, Domain, Availability, Context);
}