-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckAvailability.cpp
4859 lines (4125 loc) · 177 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/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;
static const Decl *
concreteSyntaxDeclForAvailableAttribute(const Decl *AbstractSyntaxDecl);
/// 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);
}
bool swift::isExported(const ValueDecl *VD) {
if (VD->getAttrs().hasAttribute<ImplementationOnlyAttr>())
return false;
if (VD->isObjCMemberImplementation())
return false;
// Is this part of the module's API or ABI?
AccessScope accessScope =
VD->getFormalAccessScope(nullptr,
/*treatUsableFromInlineAsPublic*/true);
if (accessScope.isPublic())
return true;
// Is this a stored property in a @frozen struct or class?
if (auto *property = dyn_cast<VarDecl>(VD))
if (property->isLayoutExposedToClients())
return true;
return false;
}
static bool hasConformancesToPublicProtocols(const ExtensionDecl *ED) {
auto nominal = ED->getExtendedNominal();
if (!nominal)
return false;
// Extensions of protocols cannot introduce additional conformances.
if (isa<ProtocolDecl>(nominal))
return false;
auto protocols = ED->getLocalProtocols(ConformanceLookupKind::OnlyExplicit);
for (const ProtocolDecl *PD : protocols) {
AccessScope scope =
PD->getFormalAccessScope(/*useDC*/ nullptr,
/*treatUsableFromInlineAsPublic*/ true);
if (scope.isPublic())
return true;
}
return false;
}
bool swift::isExported(const ExtensionDecl *ED) {
// An extension can only be exported if it extends an exported type.
if (auto *NTD = ED->getExtendedNominal()) {
if (!isExported(NTD))
return false;
}
// If there are any exported members then the extension is exported.
for (const Decl *D : ED->getMembers()) {
if (isExported(D))
return true;
}
// If the extension declares a conformance to a public protocol then the
// extension is exported.
if (hasConformancesToPublicProtocols(ED))
return true;
return false;
}
bool swift::isExported(const Decl *D) {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
return isExported(VD);
}
if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
for (unsigned i = 0, e = PBD->getNumPatternEntries(); i < e; ++i) {
if (auto *VD = PBD->getAnchoringVarDecl(i))
return isExported(VD);
}
return false;
}
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
return isExported(ED);
}
return true;
}
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 = TypeChecker::availabilityAtLocation(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 = TypeChecker::availabilityAtLocation(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.
static bool hasActiveAvailableAttribute(const Decl *D, ASTContext &ctx) {
D = abstractSyntaxDeclForAvailableAttribute(D);
for (auto Attr : D->getSemanticAvailableAttrs()) {
if (Attr.isActive(ctx))
return true;
}
return false;
}
static bool computeContainedByDeploymentTarget(AvailabilityScope *scope,
ASTContext &ctx) {
return scope->getPlatformAvailabilityRange().isContainedIn(
AvailabilityRange::forDeploymentTarget(ctx));
}
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();
}
namespace {
/// A class to walk the AST to build the availability scope tree.
class AvailabilityScopeBuilder : private ASTWalker {
ASTContext &Context;
/// Represents an entry in a stack of active availability scopes. The stack is
/// used to facilitate building the availability scope tree structure. A new
/// scope is pushed onto this stack before visiting children whenever the
/// current AST node requires a new context and the scope is then popped
/// post-visitation.
struct ContextInfo {
AvailabilityScope *Scope;
/// The AST node. This node can be null (ParentTy()),
/// indicating that custom logic elsewhere will handle removing
/// the context when needed.
ParentTy ScopeNode;
bool ContainedByDeploymentTarget;
};
std::vector<ContextInfo> ContextStack;
llvm::SmallVector<const Decl *, 4> ConcreteDeclStack;
/// Represents an entry in a stack of pending decl body availability scopes.
/// Scopes in this stack should be pushed onto \p ContextStack when
/// \p BodyStmt is encountered.
struct DeclBodyContextInfo {
Decl *Decl;
llvm::DenseMap<ASTNode, AvailabilityScope *> BodyScopes;
};
std::vector<DeclBodyContextInfo> DeclBodyContextStack;
std::vector<const DeclContext *> DeclContextStack;
AvailabilityScope *getCurrentScope() {
return ContextStack.back().Scope;
}
const DeclContext *getCurrentDeclContext() const {
assert(!DeclContextStack.empty());
return DeclContextStack.back();
}
bool isCurrentScopeContainedByDeploymentTarget() {
return ContextStack.back().ContainedByDeploymentTarget;
}
const AvailabilityContext constrainCurrentAvailabilityWithPlatformRange(
const AvailabilityRange &platformRange) {
auto availability = getCurrentScope()->getAvailabilityContext();
availability.constrainWithPlatformRange(platformRange, Context);
return availability;
}
void pushContext(AvailabilityScope *Scope, ParentTy PopAfterNode) {
ContextInfo Info;
Info.Scope = Scope;
Info.ScopeNode = PopAfterNode;
if (!ContextStack.empty() && isCurrentScopeContainedByDeploymentTarget()) {
assert(computeContainedByDeploymentTarget(Scope, Context) &&
"incorrectly skipping computeContainedByDeploymentTarget()");
Info.ContainedByDeploymentTarget = true;
} else {
Info.ContainedByDeploymentTarget =
computeContainedByDeploymentTarget(Scope, Context);
}
ContextStack.push_back(Info);
}
void pushDeclBodyContext(
Decl *D, llvm::SmallVector<std::pair<ASTNode, AvailabilityScope *>, 4>
NodesAndScopes) {
DeclBodyContextInfo Info;
Info.Decl = D;
for (auto NodeAndScope : NodesAndScopes) {
Info.BodyScopes.insert(NodeAndScope);
}
DeclBodyContextStack.push_back(Info);
}
const char *stackTraceAction() const {
return "building availabiilty scope for";
}
friend class swift::ExpandChildAvailabilityScopesRequest;
public:
AvailabilityScopeBuilder(AvailabilityScope *Scope, ASTContext &Context)
: Context(Context) {
assert(Scope);
pushContext(Scope, ParentTy());
DeclContextStack.push_back(Scope->getIntroductionNode().getDeclContext());
}
void build(Decl *D) {
PrettyStackTraceDecl trace(stackTraceAction(), D);
unsigned StackHeight = ContextStack.size();
D->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
void build(Stmt *S) {
PrettyStackTraceStmt trace(Context, stackTraceAction(), S);
unsigned StackHeight = ContextStack.size();
S->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
void build(Expr *E) {
PrettyStackTraceExpr trace(Context, stackTraceAction(), E);
unsigned StackHeight = ContextStack.size();
E->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
private:
MacroWalking getMacroWalkingBehavior() const override {
// Expansion buffers will have their type availability scopes built lazily.
return MacroWalking::Arguments;
}
SequenceWalking getSequenceWalkingBehavior() const override {
// Since availability scopes may be built at arbitrary times, the builder
// may encounter ASTs where SequenceExprs still exist and have not been
// folded, or it may encounter folded SequenceExprs that have not been
// removed from the AST. When folded exprs are encountered, its important
// to avoid walking into the same AST nodes twice.
return SequenceWalking::OnlyWalkFirstOperatorWhenFolded;
}
/// Check whether this declaration is within a macro expansion buffer that
/// will have its own availability scope that will be lazily expanded.
bool isDeclInMacroExpansion(Decl *decl) const override {
// If it's not in a macro expansion relative to its context, it's not
// considered to be in a macro expansion.
if (!decl->isInMacroExpansionInContext())
return false;
auto module = decl->getDeclContext()->getParentModule();
auto *declFile = module->getSourceFileContainingLocation(decl->getLoc());
if (!declFile)
return false;
// Look for a parent context that implies that we are producing an
// availability scope for this expansion.
for (auto iter = ContextStack.rbegin(), endIter = ContextStack.rend();
iter != endIter; ++iter) {
const auto &context = *iter;
if (auto scope = context.Scope) {
// If the context is the same source file, don't treat it as an
// expansion.
auto introNode = scope->getIntroductionNode();
switch (scope->getReason()) {
case AvailabilityScope::Reason::Root:
if (auto contextFile = introNode.getAsSourceFile())
if (declFile == contextFile)
return false;
break;
case AvailabilityScope::Reason::Decl:
case AvailabilityScope::Reason::DeclImplicit:
// If the context is a declaration, check whether the declaration
// is in the same source file as this declaration.
if (auto contextDecl = introNode.getAsDecl()) {
if (decl == contextDecl)
return false;
auto contextModule =
contextDecl->getDeclContext()->getParentModule();
SourceLoc contextDeclLoc = contextDecl->getLoc();
auto contextDeclFile =
contextModule->getSourceFileContainingLocation(contextDeclLoc);
if (declFile == contextDeclFile)
return false;
}
break;
case AvailabilityScope::Reason::IfStmtThenBranch:
case AvailabilityScope::Reason::IfStmtElseBranch:
case AvailabilityScope::Reason::ConditionFollowingAvailabilityQuery:
case AvailabilityScope::Reason::GuardStmtFallthrough:
case AvailabilityScope::Reason::GuardStmtElseBranch:
case AvailabilityScope::Reason::WhileStmtBody:
// Nothing to check here.
break;
}
}
}
return true;
}
bool shouldSkipDecl(Decl *D) const {
// Only visit a node that has a corresponding concrete syntax node if we are
// already walking that concrete syntax node.
auto *concreteDecl = concreteSyntaxDeclForAvailableAttribute(D);
if (concreteDecl != D) {
if (ConcreteDeclStack.empty() || ConcreteDeclStack.back() != concreteDecl)
return true;
}
return false;
}
PreWalkAction walkToDeclPre(Decl *D) override {
PrettyStackTraceDecl trace(stackTraceAction(), D);
// Implicit decls don't have source locations so they cannot have a scope.
// However, some implicit nodes contain non-implicit nodes (e.g. defer
// blocks) so we must continue through them.
if (!D->isImplicit()) {
if (shouldSkipDecl(D))
return Action::SkipNode();
// The AST of this decl may not be ready to traverse yet if it hasn't been
// full typechecked. If that's the case, we leave a placeholder node in
// the tree to indicate that the subtree should be expanded lazily when it
// needs to be traversed.
if (buildLazyContextForDecl(D))
return Action::SkipNode();
// Adds in a scope that covers the entire declaration.
if (auto DeclScope = getNewContextForSignatureOfDecl(D)) {
pushContext(DeclScope, D);
}
// Create scopes that cover only the body of the declaration.
buildContextsForBodyOfDecl(D);
}
if (auto *DC = dyn_cast<DeclContext>(D)) {
DeclContextStack.push_back(DC);
}
// If this decl is the concrete syntax decl for some abstract syntax decl,
// push it onto the stack so that the abstract syntax decls may be visited.
auto *abstractDecl = abstractSyntaxDeclForAvailableAttribute(D);
if (abstractDecl != D) {
ConcreteDeclStack.push_back(D);
}
return Action::Continue();
}
PostWalkAction walkToDeclPost(Decl *D) override {
if (!ConcreteDeclStack.empty() && ConcreteDeclStack.back() == D) {
ConcreteDeclStack.pop_back();
}
if (auto *DC = dyn_cast<DeclContext>(D)) {
assert(DeclContextStack.back() == DC);
DeclContextStack.pop_back();
}
while (ContextStack.back().ScopeNode.getAsDecl() == D) {
ContextStack.pop_back();
}
while (!DeclBodyContextStack.empty() &&
DeclBodyContextStack.back().Decl == D) {
// All pending body scopes should have been consumed.
assert(DeclBodyContextStack.back().BodyScopes.empty());
DeclBodyContextStack.pop_back();
}
return Action::Continue();
}
bool shouldBuildLazyContextForDecl(Decl *D) {
// Skip functions that have unparsed bodies on an initial descent to avoid
// eagerly parsing bodies unnecessarily.
if (auto *afd = dyn_cast<AbstractFunctionDecl>(D)) {
if (afd->hasBody() && !afd->isBodySkipped() &&
!afd->getBody(/*canSynthesize=*/false))
return true;
}
// Pattern binding declarations may have attached property wrappers that
// get expanded from macros attached to the parent declaration. We must
// not eagerly expand the attached property wrappers to avoid request
// cycles.
if (isa<PatternBindingDecl>(D)) {
return true;
}
if (isa<ExtensionDecl>(D)) {
return true;
}
return false;
}
/// For declarations that were previously skipped prepare the AST before
/// building out scopes.
void prepareDeclForLazyExpansion(Decl *D) {
if (auto AFD = dyn_cast<AbstractFunctionDecl>(D)) {
(void)AFD->getBody(/*canSynthesize*/ true);
}
}
/// Constructs a placeholder scope that should be expanded later. This is
/// useful for postponing unnecessary work (and request triggers) when
/// initally building out the scope subtree under a declaration. Lazy nodes
/// constructed here will be expanded by ExpandChildAvailabilityScopesRequest.
/// Returns true if a node was created.
bool buildLazyContextForDecl(Decl *D) {
// Check whether the current scope is already a lazy placeholder. If it is,
// we should try to expand it rather than creating a new placeholder.
auto currentScope = getCurrentScope();
if (currentScope->getNeedsExpansion() && currentScope->getDeclOrNull() == D)
return false;
if (!shouldBuildLazyContextForDecl(D))
return false;
// If we've made it this far then we've identified a declaration that
// requires lazy expansion later.
auto lazyScope = AvailabilityScope::createForDeclImplicit(
Context, D, currentScope, currentScope->getAvailabilityContext(),
refinementSourceRangeForDecl(D));
lazyScope->setNeedsExpansion(true);
return true;
}
/// Returns a new context to be introduced for the declaration, or nullptr
/// if no new context should be introduced.
AvailabilityScope *getNewContextForSignatureOfDecl(Decl *D) {
if (!isa<ValueDecl>(D) &&
!isa<EnumCaseDecl>(D) &&
!isa<ExtensionDecl>(D) &&
!isa<MacroExpansionDecl>(D) &&
!isa<PatternBindingDecl>(D))
return nullptr;
// Only introduce for an AbstractStorageDecl if it is not local. We
// introduce for the non-local case because these may have getters and
// setters (and these may be synthesized, so they might not even exist yet).
if (isa<AbstractStorageDecl>(D) && D->getDeclContext()->isLocalContext())
return nullptr;
// Don't introduce for abstract syntax nodes that have separate concrete
// syntax nodes. The scope will be introduced for the concrete node instead.
if (concreteSyntaxDeclForAvailableAttribute(D) != D)
return nullptr;
// Declarations with explicit availability attributes always get a scope.
if (hasActiveAvailableAttribute(D, Context)) {
return AvailabilityScope::createForDecl(
Context, D, getCurrentScope(),
getEffectiveAvailabilityForDeclSignature(D),
refinementSourceRangeForDecl(D));
}
// Declarations without explicit availability attributes get a scope if they
// are effectively less available than the surrounding context. For example,
// an internal property in a public struct can be effectively less available
// than the containing struct decl because the internal property will only
// be accessed by code running at the deployment target or later.
auto CurrentAvailability = getCurrentScope()->getAvailabilityContext();
auto EffectiveAvailability = getEffectiveAvailabilityForDeclSignature(D);
if (CurrentAvailability != EffectiveAvailability)
return AvailabilityScope::createForDeclImplicit(
Context, D, getCurrentScope(), EffectiveAvailability,
refinementSourceRangeForDecl(D));
return nullptr;
}
const AvailabilityContext
getEffectiveAvailabilityForDeclSignature(const Decl *D) {
auto EffectiveIntroduction = AvailabilityRange::alwaysAvailable();
// Availability attributes are found abstract syntax decls.
D = abstractSyntaxDeclForAvailableAttribute(D);
// As a special case, extension decls are treated as effectively as
// available as the nominal type they extend, up to the deployment target.
// This rule is a convenience for library authors who have written
// extensions without specifying availabilty on the extension itself.
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
auto ET = ED->getExtendedType();
if (ET && !hasActiveAvailableAttribute(D, Context)) {
EffectiveIntroduction.intersectWith(
swift::AvailabilityInference::inferForType(ET));
// We want to require availability to be specified on extensions of
// types that would be potentially unavailable to the module containing
// the extension, so limit the effective availability to the deployment
// target.
EffectiveIntroduction.unionWith(
AvailabilityRange::forDeploymentTarget(Context));
}
}
if (shouldConstrainSignatureToDeploymentTarget(D))
EffectiveIntroduction.intersectWith(
AvailabilityRange::forDeploymentTarget(Context));
auto availability = getCurrentScope()->getAvailabilityContext();
availability.constrainWithDeclAndPlatformRange(D, EffectiveIntroduction);
return availability;
}
/// Checks whether the entire declaration, including its signature, should be
/// constrained to the deployment target. Generally public API declarations
/// are not constrained since they appear in the interface of the module and
/// may be consumed by clients with lower deployment targets, but there are
/// some exceptions.
bool shouldConstrainSignatureToDeploymentTarget(const Decl *D) {
if (isCurrentScopeContainedByDeploymentTarget())
return false;
// A declaration inside of a local context always inherits the availability
// of the parent.
if (D->getDeclContext()->isLocalContext())
return false;
// As a convenience, explicitly unavailable decls are constrained to the
// deployment target. There's not much benefit to checking these decls at a
// lower availability version floor since they can't be invoked by clients.
if (getCurrentScope()->getAvailabilityContext().isUnavailable() ||
D->isUnavailable())
return true;
// To remain compatible with a lot of existing SPIs that are declared
// without availability attributes, constrain them to the deployment target
// too.
if (D->isSPI())
return true;
return !::isExported(D);
}
/// Returns the source range which should be refined by declaration. This
/// provides a convenient place to specify the refined range when it is
/// different than the declaration's source range.
SourceRange refinementSourceRangeForDecl(Decl *D) {
// We require a valid range in order to be able to query for the scope
// corresponding to a given SourceLoc.
// If this assert fires, it means we have probably synthesized an implicit
// declaration without location information. The appropriate fix is
// probably to gin up a source range for the declaration when synthesizing
// it.
assert(D->getSourceRange().isValid());
auto &Context = D->getASTContext();
SourceRange Range;
if (auto *storageDecl = dyn_cast<AbstractStorageDecl>(D)) {
// Use the declaration's availability for the context when checking
// the bodies of its accessors.
Range = storageDecl->getSourceRange();
// HACK: For synthesized trivial accessors we may have not a valid
// location for the end of the braces, so in that case we will fall back
// to using the range for the storage declaration. The right fix here is
// to update AbstractStorageDecl::addTrivialAccessors() to take brace
// locations and have callers of that method provide appropriate source
// locations.
SourceRange BracesRange = storageDecl->getBracesRange();
if (BracesRange.isValid()) {
Range.widen(BracesRange);
}
} else {
Range = D->getSourceRangeIncludingAttrs();
}
Range.End = Lexer::getLocForEndOfToken(Context.SourceMgr, Range.End);
return Range;
}
/// Enumerate the AST nodes and their corresponding source ranges for
/// the body (or bodies) of the given declaration.
void enumerateBodyRanges(
Decl *decl,
llvm::function_ref<void(Decl *decl, ASTNode body, SourceRange)> acceptBody
) {
// Top level code always uses the deployment target.
if (auto tlcd = dyn_cast<TopLevelCodeDecl>(decl)) {
if (auto bodyStmt = tlcd->getBody()) {
acceptBody(tlcd, bodyStmt, refinementSourceRangeForDecl(tlcd));
}
return;
}
// For functions, provide the body source range.
if (auto afd = dyn_cast<AbstractFunctionDecl>(decl)) {
if (!afd->isImplicit()) {
if (auto body = afd->getBody(/*canSynthesize*/ false)) {
acceptBody(afd, body, afd->getBodySourceRange());
}
}
return;
}
// Pattern binding declarations have initial values that are their
// bodies.
if (auto *pbd = dyn_cast<PatternBindingDecl>(decl)) {
for (unsigned index : range(pbd->getNumPatternEntries())) {
auto var = pbd->getAnchoringVarDecl(index);
if (!var)
continue;
auto *initExpr = pbd->getInit(index);
if (initExpr && !initExpr->isImplicit()) {
assert(initExpr->getSourceRange().isValid());
// Create a scope for the init written in the source.
acceptBody(var, initExpr, initExpr->getSourceRange());
}
}
return;
}
}
// Creates an implicit decl scope specifying the deployment target for
// `range` in decl `D`.
AvailabilityScope *
createImplicitDeclContextForDeploymentTarget(Decl *D, SourceRange range) {
const AvailabilityContext Availability =
constrainCurrentAvailabilityWithPlatformRange(
AvailabilityRange::forDeploymentTarget(Context));
return AvailabilityScope::createForDeclImplicit(
Context, D, getCurrentScope(), Availability, range);
}
/// Determine whether the body of the given declaration has
/// deployment-target availability.
static bool bodyIsDeploymentTarget(Decl *decl) {
if (auto afd = dyn_cast<AbstractFunctionDecl>(decl)) {
return afd->getResilienceExpansion() != ResilienceExpansion::Minimal;
}
if (auto var = dyn_cast<VarDecl>(decl)) {
// Var decls may have associated pattern binding decls or property
// wrappers with init expressions. Those expressions need to be
// constrained to the deployment target unless they are exposed to
// clients.
return var->hasInitialValue() && !var->isInitExposedToClients();
}
return true;
}
void buildContextsForBodyOfDecl(Decl *D) {
// Are we already constrained by the deployment target and the declaration
// doesn't explicitly allow unsafe constructs in its definition, adding
// new contexts won't change availability.
if (isCurrentScopeContainedByDeploymentTarget())
return;
// Enumerate all of the body scopes to apply availability.
llvm::SmallVector<std::pair<ASTNode, AvailabilityScope *>, 4>
nodesAndScopes;
enumerateBodyRanges(D, [&](Decl *decl, ASTNode body, SourceRange range) {
auto availability = getCurrentScope()->getAvailabilityContext();
// Apply deployment-target availability if appropriate for this body.
if (!isCurrentScopeContainedByDeploymentTarget() &&
bodyIsDeploymentTarget(decl)) {
availability.constrainWithPlatformRange(
AvailabilityRange::forDeploymentTarget(Context), Context);
}
nodesAndScopes.push_back({
body,
AvailabilityScope::createForDeclImplicit(
Context, decl, getCurrentScope(), availability, range)
});
});
if (nodesAndScopes.size() > 0)
pushDeclBodyContext(D, nodesAndScopes);
if (!isCurrentScopeContainedByDeploymentTarget()) {
// Pattern binding declarations can have children corresponding to property
// wrappers, which we handle separately.
if (auto *pbd = dyn_cast<PatternBindingDecl>(D)) {
// Ideally any init expression would be returned by `getInit()` above.
// However, for property wrappers it doesn't get populated until
// typechecking completes (which is too late). Instead, we find the
// the property wrapper attribute and use its source range to create a
// scope for the initializer expression.
//
// FIXME: Since we don't have an expression here, we can't build out its
// scope. If the Expr that will eventually be created contains a closure
// expression, then it might have AST nodes that need to be refined. For
// example, property wrapper initializers that takes block arguments
// are not handled correctly because of this (rdar://77841331).
if (auto firstVar = pbd->getAnchoringVarDecl(0)) {
if (firstVar->hasInitialValue() &&
!firstVar->isInitExposedToClients()) {
for (auto *wrapper : firstVar->getAttachedPropertyWrappers()) {
createImplicitDeclContextForDeploymentTarget(firstVar,
wrapper->getRange());
}
}
}
}
}
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
PrettyStackTraceStmt trace(Context, stackTraceAction(), S);
if (consumeDeclBodyContextIfNecessary(S)) {
return Action::Continue(S);
}
if (auto *IS = dyn_cast<IfStmt>(S)) {
buildIfStmtRefinementContext(IS);
return Action::SkipNode(S);
}