-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckAvailability.cpp
4350 lines (3675 loc) · 159 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 "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.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/TypeRefinementContext.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Sema/IDETypeChecking.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
ExportContext::ExportContext(DeclContext *DC,
AvailabilityContext runningOSVersion,
FragileFunctionKind kind,
bool spi, bool exported, bool implicit, bool deprecated,
Optional<PlatformKind> unavailablePlatformKind)
: DC(DC), RunningOSVersion(runningOSVersion), FragileKind(kind) {
SPI = spi;
Exported = exported;
Implicit = implicit;
Deprecated = deprecated;
if (unavailablePlatformKind) {
Unavailable = 1;
Platform = unsigned(*unavailablePlatformKind);
} else {
Unavailable = 0;
Platform = 0;
}
Reason = unsigned(ExportabilityReason::General);
}
bool swift::isExported(const ValueDecl *VD) {
if (VD->getAttrs().hasAttribute<ImplementationOnlyAttr>())
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 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::TopLevelCodeDecl:
case DeclContextKind::SerializedLocal:
case DeclContextKind::Module:
case DeclContextKind::FileUnit:
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, bool *deprecated,
Optional<PlatformKind> *unavailablePlatformKind) {
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 (D->getAttrs().getDeprecated(Ctx))
*deprecated = true;
if (auto *A = D->getAttrs().getUnavailable(Ctx)) {
*unavailablePlatformKind = A->Platform;
}
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, deprecated,
unavailablePlatformKind);
}
}
}
ExportContext ExportContext::forDeclSignature(Decl *D) {
auto &Ctx = D->getASTContext();
auto *DC = D->getInnermostDeclContext();
auto fragileKind = DC->getFragileFunctionKind();
auto runningOSVersion =
(Ctx.LangOpts.DisableAvailabilityChecking
? AvailabilityContext::alwaysAvailable()
: TypeChecker::overApproximateAvailabilityAtLocation(D->getLoc(), DC));
bool spi = Ctx.LangOpts.LibraryLevel == LibraryLevel::SPI;
bool implicit = false;
bool deprecated = false;
Optional<PlatformKind> unavailablePlatformKind;
computeExportContextBits(Ctx, D, &spi, &implicit, &deprecated,
&unavailablePlatformKind);
forEachOuterDecl(D->getDeclContext(),
[&](Decl *D) {
computeExportContextBits(Ctx, D,
&spi, &implicit, &deprecated,
&unavailablePlatformKind);
});
bool exported = ::isExported(D);
return ExportContext(DC, runningOSVersion, fragileKind,
spi, exported, implicit, deprecated,
unavailablePlatformKind);
}
ExportContext ExportContext::forFunctionBody(DeclContext *DC, SourceLoc loc) {
auto &Ctx = DC->getASTContext();
auto fragileKind = DC->getFragileFunctionKind();
auto runningOSVersion =
(Ctx.LangOpts.DisableAvailabilityChecking
? AvailabilityContext::alwaysAvailable()
: TypeChecker::overApproximateAvailabilityAtLocation(loc, DC));
bool spi = Ctx.LangOpts.LibraryLevel == LibraryLevel::SPI;
bool implicit = false;
bool deprecated = false;
Optional<PlatformKind> unavailablePlatformKind;
forEachOuterDecl(DC,
[&](Decl *D) {
computeExportContextBits(Ctx, D,
&spi, &implicit, &deprecated,
&unavailablePlatformKind);
});
bool exported = false;
return ExportContext(DC, runningOSVersion, fragileKind,
spi, exported, implicit, deprecated,
unavailablePlatformKind);
}
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;
}
Optional<PlatformKind> ExportContext::getUnavailablePlatformKind() const {
if (Unavailable)
return PlatformKind(Platform);
return None;
}
bool ExportContext::mustOnlyReferenceExportedDecls() const {
return Exported || FragileKind.kind != FragileFunctionKind::None;
}
Optional<ExportabilityReason> ExportContext::getExportabilityReason() const {
if (Exported)
return ExportabilityReason(Reason);
return None;
}
/// Returns the first availability attribute on the declaration that is active
/// on the target platform.
static const AvailableAttr *getActiveAvailableAttribute(const Decl *D,
ASTContext &AC) {
for (auto Attr : D->getAttrs())
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (!AvAttr->isInvalid() && AvAttr->isActivePlatform(AC)) {
return AvAttr;
}
}
return nullptr;
}
/// Returns true if there is any availability attribute on the declaration
/// that is active on the target platform.
static bool hasActiveAvailableAttribute(Decl *D,
ASTContext &AC) {
return getActiveAvailableAttribute(D, AC);
}
static bool computeContainedByDeploymentTarget(TypeRefinementContext *TRC,
ASTContext &ctx) {
return TRC->getAvailabilityInfo()
.isContainedIn(AvailabilityContext::forDeploymentTarget(ctx));
}
/// Returns true if the reference or any of its parents is an
/// unconditional unavailable declaration for the same platform.
static bool isInsideCompatibleUnavailableDeclaration(
const Decl *D, const ExportContext &where, const AvailableAttr *attr) {
auto referencedPlatform = where.getUnavailablePlatformKind();
if (!referencedPlatform)
return false;
if (!attr->isUnconditionallyUnavailable()) {
return false;
}
// Refuse calling unavailable functions from unavailable code,
// but allow the use of types.
PlatformKind platform = attr->Platform;
if (platform == PlatformKind::none && !isa<TypeDecl>(D) &&
!isa<ExtensionDecl>(D)) {
return false;
}
return (*referencedPlatform == platform ||
inheritsAvailabilityFromPlatform(platform, *referencedPlatform));
}
namespace {
/// A class to walk the AST to build the type refinement context hierarchy.
class TypeRefinementContextBuilder : private ASTWalker {
ASTContext &Context;
/// Represents an entry in a stack of active type refinement contexts. The
/// stack is used to facilitate building the TRC's tree structure. A new TRC
/// is pushed onto this stack before visiting children whenever the current
/// AST node requires a new context and the TRC is then popped
/// post-visitation.
struct ContextInfo {
TypeRefinementContext *TRC;
/// 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;
/// Represents an entry in a stack of pending decl body type refinement
/// contexts. TRCs in this stack should be pushed onto \p ContextStack when
/// \p BodyStmt is encountered.
struct DeclBodyContextInfo {
TypeRefinementContext *TRC;
Decl *Decl;
Stmt *BodyStmt;
};
std::vector<DeclBodyContextInfo> DeclBodyContextStack;
/// A mapping from abstract storage declarations with accessors to
/// to the type refinement contexts for those declarations. We refer to
/// this map to determine the appropriate parent TRC to use when
/// walking the accessor function.
llvm::DenseMap<AbstractStorageDecl *, TypeRefinementContext *>
StorageContexts;
/// A mapping from pattern binding storage declarations to the type refinement
/// contexts for those declarations. We refer to this map to determine the
/// appropriate parent TRC to use when walking a var decl that belongs to a
/// pattern containing multiple vars.
llvm::DenseMap<PatternBindingDecl *, TypeRefinementContext *>
PatternBindingContexts;
TypeRefinementContext *getCurrentTRC() {
return ContextStack.back().TRC;
}
bool isCurrentTRCContainedByDeploymentTarget() {
return ContextStack.back().ContainedByDeploymentTarget;
}
void pushContext(TypeRefinementContext *TRC, ParentTy PopAfterNode) {
ContextInfo Info;
Info.TRC = TRC;
Info.ScopeNode = PopAfterNode;
if (!ContextStack.empty() && isCurrentTRCContainedByDeploymentTarget()) {
assert(computeContainedByDeploymentTarget(TRC, Context) &&
"incorrectly skipping computeContainedByDeploymentTarget()");
Info.ContainedByDeploymentTarget = true;
} else {
Info.ContainedByDeploymentTarget =
computeContainedByDeploymentTarget(TRC, Context);
}
ContextStack.push_back(Info);
}
void pushDeclBodyContext(TypeRefinementContext *TRC, Decl *D, Stmt *S) {
DeclBodyContextInfo Info;
Info.TRC = TRC;
Info.Decl = D;
Info.BodyStmt = S;
DeclBodyContextStack.push_back(Info);
}
const char *stackTraceAction() const {
return "building type refinement context for";
}
public:
TypeRefinementContextBuilder(TypeRefinementContext *TRC, ASTContext &Context)
: Context(Context) {
assert(TRC);
pushContext(TRC, ParentTy());
}
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:
PreWalkAction walkToDeclPre(Decl *D) override {
PrettyStackTraceDecl trace(stackTraceAction(), D);
// Adds in a parent TRC for decls which are syntactically nested but are not
// represented that way in the AST. (Particularly, AbstractStorageDecl
// parents for AccessorDecl children.)
if (auto ParentTRC = getEffectiveParentContextForDecl(D)) {
pushContext(ParentTRC, D);
}
// Adds in a TRC that covers the entire declaration.
if (auto DeclTRC = getNewContextForSignatureOfDecl(D)) {
pushContext(DeclTRC, D);
// Possibly use this as an effective parent context later.
recordEffectiveParentContext(D, DeclTRC);
}
// Create TRCs that cover only the body of the declaration.
buildContextsForBodyOfDecl(D);
return Action::Continue();
}
PostWalkAction walkToDeclPost(Decl *D) override {
while (ContextStack.back().ScopeNode.getAsDecl() == D) {
ContextStack.pop_back();
}
while (!DeclBodyContextStack.empty() &&
DeclBodyContextStack.back().Decl == D) {
DeclBodyContextStack.pop_back();
}
return Action::Continue();
}
TypeRefinementContext *getEffectiveParentContextForDecl(Decl *D) {
// FIXME: Can we assert that we won't walk parent decls later that should
// have been returned here?
if (auto *accessor = dyn_cast<AccessorDecl>(D)) {
// Use TRC of the storage rather the current TRC when walking this
// function.
auto it = StorageContexts.find(accessor->getStorage());
if (it != StorageContexts.end()) {
return it->second;
}
} else if (auto *VD = dyn_cast<VarDecl>(D)) {
// Use the TRC of the pattern binding decl as the parent for var decls.
if (auto *PBD = VD->getParentPatternBinding()) {
auto it = PatternBindingContexts.find(PBD);
if (it != PatternBindingContexts.end()) {
return it->second;
}
}
}
return nullptr;
}
/// If necessary, records a TRC so it can be returned by subsequent calls to
/// `getEffectiveParentContextForDecl()`.
void recordEffectiveParentContext(Decl *D, TypeRefinementContext *NewTRC) {
if (auto *StorageDecl = dyn_cast<AbstractStorageDecl>(D)) {
// Stash the TRC for the storage declaration to use as the parent of
// accessor decls later.
if (StorageDecl->hasParsedAccessors())
StorageContexts[StorageDecl] = NewTRC;
}
if (auto *VD = dyn_cast<VarDecl>(D)) {
// Stash the TRC for the var decl if its parent pattern binding decl has
// more than one entry so that the sibling var decls can reuse it.
if (auto *PBD = VD->getParentPatternBinding()) {
if (PBD->getNumPatternEntries() > 1)
PatternBindingContexts[PBD] = NewTRC;
}
}
}
/// Returns a new context to be introduced for the declaration, or nullptr
/// if no new context should be introduced.
TypeRefinementContext *getNewContextForSignatureOfDecl(Decl *D) {
if (!isa<ValueDecl>(D) && !isa<ExtensionDecl>(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;
// Ignore implicit declarations (mainly skips over `DeferStmt` functions).
if (D->isImplicit())
return nullptr;
// Skip introducing additional contexts for var decls past the first in a
// pattern. The context necessary for the pattern as a whole was already
// introduced if necessary by the first var decl.
if (auto *VD = dyn_cast<VarDecl>(D)) {
if (auto *PBD = VD->getParentPatternBinding())
if (VD != PBD->getAnchoringVarDecl(0))
return nullptr;
}
// Declarations with an explicit availability attribute always get a TRC.
if (hasActiveAvailableAttribute(D, Context)) {
AvailabilityContext DeclaredAvailability =
swift::AvailabilityInference::availableRange(D, Context);
return TypeRefinementContext::createForDecl(
Context, D, getCurrentTRC(),
getEffectiveAvailabilityForDeclSignature(D, DeclaredAvailability),
DeclaredAvailability, refinementSourceRangeForDecl(D));
}
// Declarations without explicit availability get a TRC 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.
AvailabilityContext CurrentAvailability =
getCurrentTRC()->getAvailabilityInfo();
AvailabilityContext EffectiveAvailability =
getEffectiveAvailabilityForDeclSignature(D, CurrentAvailability);
if (CurrentAvailability.isSupersetOf(EffectiveAvailability))
return TypeRefinementContext::createForDeclImplicit(
Context, D, getCurrentTRC(), EffectiveAvailability,
refinementSourceRangeForDecl(D));
return nullptr;
}
AvailabilityContext getEffectiveAvailabilityForDeclSignature(
Decl *D, const AvailabilityContext BaseAvailability) {
AvailabilityContext EffectiveAvailability = BaseAvailability;
// 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)) {
EffectiveAvailability.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.
EffectiveAvailability.unionWith(
AvailabilityContext::forDeploymentTarget(Context));
}
}
EffectiveAvailability.intersectWith(getCurrentTRC()->getAvailabilityInfo());
if (shouldConstrainSignatureToDeploymentTarget(D))
EffectiveAvailability.intersectWith(
AvailabilityContext::forDeploymentTarget(Context));
return EffectiveAvailability;
}
/// 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(Decl *D) {
if (isCurrentTRCContainedByDeploymentTarget())
return false;
// As a convenience, SPI decls and explicitly unavailable decls are
// constrained to the deployment target. There's not much benefit to
// checking these declarations at a lower availability version floor since
// neither can be used by API clients.
if (D->isSPI() || AvailableAttr::isUnavailable(D))
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 TRC
// 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());
if (auto *storageDecl = dyn_cast<AbstractStorageDecl>(D)) {
// Use the declaration's availability for the context when checking
// the bodies of its accessors.
SourceRange Range = storageDecl->getSourceRange();
// For a variable declaration (without accessors) we use the range of the
// containing pattern binding declaration to make sure that we include
// any type annotation in the type refinement context range. We also
// need to include any attached property wrappers.
if (auto *varDecl = dyn_cast<VarDecl>(storageDecl)) {
if (auto *PBD = varDecl->getParentPatternBinding())
Range = PBD->getSourceRange();
for (auto *propertyWrapper : varDecl->getAttachedPropertyWrappers()) {
Range.widen(propertyWrapper->getRange());
}
}
// 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 (storageDecl->hasParsedAccessors() && BracesRange.isValid()) {
Range.widen(BracesRange);
}
return Range;
}
return D->getSourceRange();
}
void buildContextsForBodyOfDecl(Decl *D) {
// Are we already constrained by the deployment target? If not, adding
// new contexts won't change availability.
if (isCurrentTRCContainedByDeploymentTarget())
return;
// A lambda that creates an implicit decl TRC specifying the deployment
// target for `range` in decl `D`.
auto createContext = [this](Decl *D, SourceRange range) {
AvailabilityContext Availability =
AvailabilityContext::forDeploymentTarget(Context);
Availability.intersectWith(getCurrentTRC()->getAvailabilityInfo());
return TypeRefinementContext::createForDeclImplicit(
Context, D, getCurrentTRC(), Availability, range);
};
// Top level code always uses the deployment target.
if (auto tlcd = dyn_cast<TopLevelCodeDecl>(D)) {
if (auto bodyStmt = tlcd->getBody()) {
pushDeclBodyContext(createContext(tlcd, tlcd->getSourceRange()), tlcd,
bodyStmt);
}
return;
}
// Function bodies use the deployment target if they are within the module's
// resilience domain.
if (auto afd = dyn_cast<AbstractFunctionDecl>(D)) {
if (!afd->isImplicit() &&
afd->getResilienceExpansion() != ResilienceExpansion::Minimal) {
if (auto body = afd->getBody(/*canSynthesize*/ false)) {
pushDeclBodyContext(createContext(afd, afd->getBodySourceRange()),
afd, body);
}
}
return;
}
// 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.
if (auto vd = dyn_cast<VarDecl>(D)) {
if (!vd->hasInitialValue() || vd->isInitExposedToClients())
return;
if (auto *pbd = vd->getParentPatternBinding()) {
int idx = pbd->getPatternEntryIndexForVarDecl(vd);
auto *initExpr = pbd->getInit(idx);
if (initExpr && !initExpr->isImplicit()) {
assert(initExpr->getSourceRange().isValid());
// Create a TRC for the init written in the source. The ASTWalker
// won't visit these expressions so instead of pushing these onto the
// stack we build them directly.
auto *initTRC = createContext(vd, initExpr->getSourceRange());
TypeRefinementContextBuilder(initTRC, Context).build(initExpr);
}
// 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
// TRC for the initializer expression.
//
// FIXME: Since we don't have an expression here, we can't build out its
// TRC. 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).
for (auto *wrapper : vd->getAttachedPropertyWrappers()) {
createContext(vd, wrapper->getRange());
}
}
return;
}
}
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::SkipChildren(S);
}
if (auto *RS = dyn_cast<GuardStmt>(S)) {
buildGuardStmtRefinementContext(RS);
return Action::SkipChildren(S);
}
if (auto *WS = dyn_cast<WhileStmt>(S)) {
buildWhileStmtRefinementContext(WS);
return Action::SkipChildren(S);
}
return Action::Continue(S);
}
PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override {
// If we have multiple guard statements in the same block
// then we may have multiple refinement contexts to pop
// after walking that block.
while (!ContextStack.empty() &&
ContextStack.back().ScopeNode.getAsStmt() == S) {
ContextStack.pop_back();
}
return Action::Continue(S);
}
/// Consumes the top TRC from \p DeclBodyContextStack and pushes it onto the
/// \p Context stack if the given \p Stmt is the matching body statement.
/// Returns \p true if a context was pushed.
bool consumeDeclBodyContextIfNecessary(Stmt *S) {
if (DeclBodyContextStack.empty())
return false;
auto Info = DeclBodyContextStack.back();
if (S != Info.BodyStmt)
return false;
pushContext(Info.TRC, Info.BodyStmt);
DeclBodyContextStack.pop_back();
return true;
}
/// Builds the type refinement hierarchy for the IfStmt if the guard
/// introduces a new refinement context for the Then branch.
/// There is no need for the caller to explicitly traverse the children
/// of this node.
void buildIfStmtRefinementContext(IfStmt *IS) {
Optional<AvailabilityContext> ThenRange;
Optional<AvailabilityContext> ElseRange;
std::tie(ThenRange, ElseRange) =
buildStmtConditionRefinementContext(IS->getCond());
if (ThenRange.hasValue()) {
// Create a new context for the Then branch and traverse it in that new
// context.
auto *ThenTRC =
TypeRefinementContext::createForIfStmtThen(Context, IS,
getCurrentTRC(),
ThenRange.getValue());
TypeRefinementContextBuilder(ThenTRC, Context).build(IS->getThenStmt());
} else {
build(IS->getThenStmt());
}
Stmt *ElseStmt = IS->getElseStmt();
if (!ElseStmt)
return;
// Refine the else branch if we're given a version range for that branch.
// For now, if present, this will only be the empty range, indicating
// that the branch is dead. We use it to suppress potential unavailability
// and deprecation diagnostics on code that definitely will not run with
// the current platform and minimum deployment target.
// If we add a more precise version range lattice (i.e., one that can
// support "<") we should create non-empty contexts for the Else branch.
if (ElseRange.hasValue()) {
// Create a new context for the Then branch and traverse it in that new
// context.
auto *ElseTRC =
TypeRefinementContext::createForIfStmtElse(Context, IS,
getCurrentTRC(),
ElseRange.getValue());
TypeRefinementContextBuilder(ElseTRC, Context).build(ElseStmt);
} else {
build(IS->getElseStmt());
}
}
/// Builds the type refinement hierarchy for the WhileStmt if the guard
/// introduces a new refinement context for the body branch.
/// There is no need for the caller to explicitly traverse the children
/// of this node.
void buildWhileStmtRefinementContext(WhileStmt *WS) {
Optional<AvailabilityContext> BodyRange =
buildStmtConditionRefinementContext(WS->getCond()).first;
if (BodyRange.hasValue()) {
// Create a new context for the body and traverse it in the new
// context.
auto *BodyTRC = TypeRefinementContext::createForWhileStmtBody(
Context, WS, getCurrentTRC(), BodyRange.getValue());
TypeRefinementContextBuilder(BodyTRC, Context).build(WS->getBody());
} else {
build(WS->getBody());
}
}
/// Builds the type refinement hierarchy for the GuardStmt and pushes
/// the fallthrough context onto the context stack so that subsequent
/// AST elements in the same scope are analyzed in the context of the
/// fallthrough TRC.
void buildGuardStmtRefinementContext(GuardStmt *GS) {
// 'guard' statements fall through if all of the
// guard conditions are true, so we refine the range after the require
// until the end of the enclosing block.
// if ... {
// guard available(...) else { return } <-- Refined range starts here
// ...
// } <-- Refined range ends here
//
// This is slightly tricky because, unlike our other control constructs,
// the refined region is not lexically contained inside the construct
// introducing the refinement context.
Optional<AvailabilityContext> FallthroughRange;
Optional<AvailabilityContext> ElseRange;
std::tie(FallthroughRange, ElseRange) =
buildStmtConditionRefinementContext(GS->getCond());
if (Stmt *ElseBody = GS->getBody()) {
if (ElseRange.hasValue()) {
auto *TrueTRC = TypeRefinementContext::createForGuardStmtElse(
Context, GS, getCurrentTRC(), ElseRange.getValue());
TypeRefinementContextBuilder(TrueTRC, Context).build(ElseBody);
} else {
build(ElseBody);
}
}
auto *ParentBrace = dyn_cast<BraceStmt>(Parent.getAsStmt());
assert(ParentBrace && "Expected parent of GuardStmt to be BraceStmt");
if (!FallthroughRange.hasValue())
return;
// Create a new context for the fallthrough.
auto *FallthroughTRC =
TypeRefinementContext::createForGuardStmtFallthrough(Context, GS,
ParentBrace, getCurrentTRC(), FallthroughRange.getValue());
pushContext(FallthroughTRC, ParentBrace);
}
/// Build the type refinement context for a StmtCondition and return a pair
/// of optional version ranges, the first for the true branch and the second
/// for the false branch. A value of None for a given branch indicates that
/// the branch does not introduce a new refinement.
std::pair<Optional<AvailabilityContext>, Optional<AvailabilityContext>>
buildStmtConditionRefinementContext(StmtCondition Cond) {
// Any refinement contexts introduced in the statement condition
// will end at the end of the last condition element.
StmtConditionElement LastElement = Cond.back();
// Keep track of how many nested refinement contexts we have pushed on
// the context stack so we can pop them when we're done building the
// context for the StmtCondition.
unsigned NestedCount = 0;
// Tracks the potential version range when the condition is false.
auto FalseFlow = AvailabilityContext::neverAvailable();
TypeRefinementContext *StartingTRC = getCurrentTRC();
// Tracks if we're refining for availability or unavailability.
Optional<bool> isUnavailability = None;
for (StmtConditionElement Element : Cond) {
TypeRefinementContext *CurrentTRC = getCurrentTRC();
AvailabilityContext CurrentInfo = CurrentTRC->getAvailabilityInfo();
AvailabilityContext CurrentExplicitInfo =
CurrentTRC->getExplicitAvailabilityInfo();
// If the element is not a condition, walk it in the current TRC.
if (Element.getKind() != StmtConditionElement::CK_Availability) {
// Assume any condition element that is not a #available() can
// potentially be false, so conservatively combine the version
// range of the current context with the accumulated false flow
// of all other conjuncts.
FalseFlow.unionWith(CurrentInfo);
Element.walk(*this);
continue;
}
// #available query: introduce a new refinement context for the statement
// condition elements following it.
auto *Query = Element.getAvailability();
if (isUnavailability == None) {
isUnavailability = Query->isUnavailability();
} else if (isUnavailability != Query->isUnavailability()) {
// Mixing availability with unavailability in the same statement will
// cause the false flow's version range to be ambiguous. Report it.
//
// Technically we can support this by not refining ambiguous flows,
// but there are currently no legitimate cases where one would have
// to mix availability with unavailability.