-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckEffects.cpp
4922 lines (4151 loc) · 167 KB
/
TypeCheckEffects.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
//===--- TypeCheckEffects.cpp - Type Checking for Effects Coverage --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 semantic analysis to ensure that various effects (such
// as throwing and async) are properly handled.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "OpenedExistentials.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckEffects.h"
#include "TypeCheckUnsafe.h"
#include "swift/AST/ASTBridging.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Effects.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/UnsafeUse.h"
#include "swift/Basic/Assertions.h"
using namespace swift;
static bool hasFunctionParameterWithEffect(EffectKind kind, Type type) {
// Look through Optional types.
type = type->lookThroughAllOptionalTypes();
// Only consider function types with this effect.
if (auto fnType = type->getAs<AnyFunctionType>()) {
return fnType->hasEffect(kind);
}
// Look through tuples.
if (auto tuple = type->getAs<TupleType>()) {
for (auto eltType : tuple->getElementTypes()) {
if (hasFunctionParameterWithEffect(kind, eltType))
return true;
}
return false;
}
// Suppress diagnostics in the presence of errors.
if (type->hasError()) {
return true;
}
return false;
}
PolymorphicEffectRequirementList
PolymorphicEffectRequirementsRequest::evaluate(Evaluator &evaluator,
EffectKind kind,
ProtocolDecl *proto) const {
ASTContext &ctx = proto->getASTContext();
// only allow rethrowing requirements to be determined from marked protocols
if (!proto->hasPolymorphicEffect(kind)) {
return PolymorphicEffectRequirementList();
}
SmallVector<AbstractFunctionDecl *, 2> requirements;
SmallVector<std::pair<Type, ProtocolDecl *>, 2> conformances;
// check if immediate members of protocol are 'throws'
for (auto member : proto->getMembers()) {
auto fnDecl = dyn_cast<AbstractFunctionDecl>(member);
if (!fnDecl || !fnDecl->hasEffect(kind))
continue;
requirements.push_back(fnDecl);
}
// check associated conformances of associated types or inheritance
for (auto requirement : proto->getRequirementSignature().getRequirements()) {
if (requirement.getKind() != RequirementKind::Conformance)
continue;
auto *protoDecl = requirement.getProtocolDecl();
if (!protoDecl->hasPolymorphicEffect(kind))
continue;
conformances.emplace_back(requirement.getFirstType(), protoDecl);
}
return PolymorphicEffectRequirementList(ctx.AllocateCopy(requirements),
ctx.AllocateCopy(conformances));
}
/// Determine whether the given protocol inherits from either
/// AsyncIteratorProtocol or AsyncSequence.
static bool inheritsFromAsyncSequenceProtocol(ProtocolDecl *proto) {
// If it's exactly one of these, shortcut.
if (proto->isSpecificProtocol(KnownProtocolKind::AsyncIteratorProtocol) ||
proto->isSpecificProtocol(KnownProtocolKind::AsyncSequence))
return false;
auto &ctx = proto->getASTContext();
if (auto iter = ctx.getProtocol(KnownProtocolKind::AsyncIteratorProtocol))
if (proto->inheritsFrom(iter))
return true;
if (auto seq = ctx.getProtocol(KnownProtocolKind::AsyncSequence))
if (proto->inheritsFrom(seq))
return true;
return false;
}
PolymorphicEffectKind
PolymorphicEffectKindRequest::evaluate(Evaluator &evaluator,
EffectKind kind,
AbstractFunctionDecl *decl) const {
if (!decl->hasEffect(kind))
return PolymorphicEffectKind::None;
if (!decl->hasPolymorphicEffect(kind)) {
if (auto proto = dyn_cast<ProtocolDecl>(decl->getDeclContext())) {
if (proto->hasPolymorphicEffect(kind))
return PolymorphicEffectKind::ByConformance;
}
return PolymorphicEffectKind::Always;
}
for (auto req : decl->getGenericSignature().getRequirements()) {
if (req.getKind() == RequirementKind::Conformance) {
auto proto = req.getProtocolDecl();
if (proto->hasPolymorphicEffect(kind)) {
// @rethrows protocols that inherit from AsyncIteratorProtocol or
// AsyncSequence should be categorized like AsyncIteratorProtocol or
// AsyncSequence.
if (kind == EffectKind::Throws &&
inheritsFromAsyncSequenceProtocol(proto))
return PolymorphicEffectKind::AsyncSequenceRethrows;
return PolymorphicEffectKind::ByConformance;
}
// Specifically recognize functions that are rethrows and would
// have been ByConformance polymorphic when AsyncIteratorProtocol
// and AsyncSequence were rethrowing protocols.
if (kind == EffectKind::Throws &&
(proto->isSpecificProtocol(
KnownProtocolKind::AsyncIteratorProtocol) ||
proto->isSpecificProtocol(KnownProtocolKind::AsyncSequence))) {
// FIXME: We should diagnose that this function should use typed
// throws instead.
return PolymorphicEffectKind::AsyncSequenceRethrows;
}
}
}
for (auto param : *decl->getParameters()) {
auto interfaceTy = param->getInterfaceType();
if (hasFunctionParameterWithEffect(kind, interfaceTy)) {
return PolymorphicEffectKind::ByClosure;
}
}
return PolymorphicEffectKind::Invalid;
}
static bool classifyWitness(ModuleDecl *module,
ProtocolConformance *conformance,
AbstractFunctionDecl *req,
EffectKind kind) {
auto declRef = conformance->getWitnessDeclRef(req);
if (!declRef) {
// Invalid conformance.
return true;
}
auto witnessDecl = dyn_cast<AbstractFunctionDecl>(declRef.getDecl());
if (!witnessDecl) {
// Enum element constructors do not have effects.
assert(isa<EnumElementDecl>(declRef.getDecl()));
return false;
}
switch (witnessDecl->getPolymorphicEffectKind(kind)) {
case PolymorphicEffectKind::None:
// Witness doesn't have this effect at all, so it contributes nothing.
return false;
case PolymorphicEffectKind::AsyncSequenceRethrows: {
// Witnesses that can only be polymorphic due to an
// AsyncSequence/AsyncIteratorProtocol conformance don't contribute
// anything; the thrown error result is captured by the Failure
// type.
return false;
}
case PolymorphicEffectKind::ByConformance: {
// Witness has the effect if the concrete type's conformances
// recursively have the effect.
auto substitutions = conformance->getSubstitutionMap();
for (auto conformanceRef : substitutions.getConformances()) {
if (conformanceRef.hasEffect(kind)) {
return true;
}
}
return false;
}
case PolymorphicEffectKind::ByClosure:
// Witness only has the effect if a closure argument has the effect,
// so it contributes nothing to the conformance`s effect.
return false;
case PolymorphicEffectKind::Always:
// Witness always has the effect.
// If the witness's thrown type is explicitly specified as a type
// parameter, then check whether the substituted type is `Never`.
if (kind == EffectKind::Throws) {
if (Type thrownError = witnessDecl->getThrownInterfaceType()) {
if (thrownError->hasTypeParameter())
thrownError = thrownError.subst(declRef.getSubstitutions());
if (thrownError->isNever())
return false;
}
}
return true;
case PolymorphicEffectKind::Invalid:
// If something was invalid, just assume it has the effect.
return true;
}
}
bool ConformanceHasEffectRequest::evaluate(
Evaluator &evaluator, EffectKind kind,
ProtocolConformance *conformance) const {
auto *module = conformance->getDeclContext()->getParentModule();
llvm::SmallDenseSet<ProtocolConformance *, 2> visited;
SmallVector<ProtocolConformance *, 2> worklist;
worklist.push_back(conformance);
while (!worklist.empty()) {
auto *current = worklist.back();
worklist.pop_back();
if (!visited.insert(current).second)
continue;
auto protoDecl = current->getProtocol();
auto list = protoDecl->getPolymorphicEffectRequirements(kind);
for (auto req : list.getRequirements()) {
if (classifyWitness(module, current, req, kind))
return true;
}
// For @unsafe, check if the conformance is labeled as unsafe.
if (kind == EffectKind::Unsafe) {
auto rootConf = current->getRootConformance();
if (auto normalConf = dyn_cast<NormalProtocolConformance>(rootConf)) {
if (normalConf->getExplicitSafety() == ExplicitSafety::Unsafe)
return true;
}
}
for (auto pair : list.getConformances()) {
auto assocConf =
current->getAssociatedConformance(
pair.first, pair.second);
if (!assocConf.isConcrete())
return kind != EffectKind::Unsafe;
worklist.push_back(assocConf.getConcrete());
}
}
return false;
}
/// \returns the getter decl iff its a prop/subscript with an effectful 'get'
static ConcreteDeclRef getEffectfulGetOnlyAccessor(ConcreteDeclRef cdr) {
if (!cdr)
return nullptr;
if (auto storageDecl = dyn_cast<AbstractStorageDecl>(cdr.getDecl())) {
if (auto getAccessor = storageDecl->getEffectfulGetAccessor())
return ConcreteDeclRef(getAccessor, cdr.getSubstitutions());
}
return nullptr;
}
/// Determine whether this is the "Never" type that's used to indicate that the
/// function never throws.
static bool isNeverThrownError(Type type) {
if (!type)
return true;
return type->isNever();
}
namespace {
/// A function reference.
class AbstractFunction {
public:
enum Kind : uint8_t {
Opaque, Function, Closure, Parameter,
};
private:
union {
AbstractFunctionDecl *TheFunction;
AbstractClosureExpr *TheClosure;
ParamDecl *TheParameter;
Expr *TheExpr;
};
Kind TheKind;
PolymorphicEffectKind RethrowsKind = PolymorphicEffectKind::None;
PolymorphicEffectKind ReasyncKind = PolymorphicEffectKind::None;
SubstitutionMap Substitutions;
public:
explicit AbstractFunction(Kind kind, Expr *fn)
: TheKind(kind) {
TheExpr = fn;
}
explicit AbstractFunction(AbstractFunctionDecl *fn, SubstitutionMap subs)
: TheKind(Kind::Function),
RethrowsKind(fn->getPolymorphicEffectKind(EffectKind::Throws)),
ReasyncKind(fn->getPolymorphicEffectKind(EffectKind::Async)),
Substitutions(subs) {
TheFunction = fn;
}
explicit AbstractFunction(AbstractClosureExpr *closure)
: TheKind(Kind::Closure) {
TheClosure = closure;
}
explicit AbstractFunction(ParamDecl *parameter, SubstitutionMap subs)
: TheKind(Kind::Parameter), Substitutions(subs) {
TheParameter = parameter;
}
Kind getKind() const { return TheKind; }
PolymorphicEffectKind getPolymorphicEffectKind(EffectKind kind) const {
switch (kind) {
case EffectKind::Throws: return RethrowsKind;
case EffectKind::Async: return ReasyncKind;
case EffectKind::Unsafe: return swift::PolymorphicEffectKind::None;
}
llvm_unreachable("Bad effect kind");
}
Type getType() const {
switch (getKind()) {
case Kind::Opaque: return getOpaqueFunction()->getType();
case Kind::Function: {
auto *AFD = getFunction();
if (AFD->hasImplicitSelfDecl())
return AFD->getMethodInterfaceType();
return AFD->getInterfaceType();
}
case Kind::Closure: return getClosure()->getType();
case Kind::Parameter: return getParameter()->getInterfaceType();
}
llvm_unreachable("bad kind");
}
/// Retrieve the interface type for a parameter based on an index into the
/// substituted parameter type. This
Type getOrigParamInterfaceType(unsigned substIndex) const {
switch (getKind()) {
case Kind::Opaque:
case Kind::Closure:
case Kind::Parameter:
return getType()->castTo<AnyFunctionType>()->getParams()[substIndex]
.getParameterType();
case Kind::Function: {
auto params = getParameterList(static_cast<ValueDecl *>(getFunction()));
auto origIndex = params->getOrigParamIndex(getSubstitutions(), substIndex);
return params->get(origIndex)->getInterfaceType();
}
}
}
bool isAutoClosure() const {
if (getKind() == Kind::Closure)
return isa<AutoClosureExpr>(getClosure());
return false;
}
AbstractFunctionDecl *getFunction() const {
assert(getKind() == Kind::Function);
return TheFunction;
}
AbstractClosureExpr *getClosure() const {
assert(getKind() == Kind::Closure);
return TheClosure;
}
ParamDecl *getParameter() const {
assert(getKind() == Kind::Parameter);
return TheParameter;
}
Expr *getOpaqueFunction() const {
assert(getKind() == Kind::Opaque);
return TheExpr;
}
SubstitutionMap getSubstitutions() const {
return Substitutions;
}
static AbstractFunction getAppliedFn(ApplyExpr *apply) {
Expr *fn = apply->getFn()->getValueProvidingExpr();
if (auto *selfCall = dyn_cast<SelfApplyExpr>(fn))
fn = selfCall->getFn()->getValueProvidingExpr();
return decomposeFunction(fn);
}
bool isPreconcurrency() const {
switch (getKind()) {
case Kind::Closure: {
auto *closure = dyn_cast<ClosureExpr>(getClosure());
return closure && closure->isIsolatedByPreconcurrency();
}
case Kind::Function:
return getActorIsolation(getFunction()).preconcurrency();
case Kind::Opaque:
case Kind::Parameter:
return false;
}
}
static AbstractFunction decomposeFunction(Expr *fn) {
assert(fn->getValueProvidingExpr() == fn);
while (true) {
// Look through Optional unwraps.
if (auto conversion = dyn_cast<ForceValueExpr>(fn)) {
fn = conversion->getSubExpr()->getValueProvidingExpr();
} else if (auto conversion = dyn_cast<BindOptionalExpr>(fn)) {
fn = conversion->getSubExpr()->getValueProvidingExpr();
// Look through optional injections.
} else if (auto injection = dyn_cast<InjectIntoOptionalExpr>(fn)) {
fn = injection->getSubExpr()->getValueProvidingExpr();
// Look through function conversions.
} else if (auto conversion = dyn_cast<FunctionConversionExpr>(fn)) {
fn = conversion->getSubExpr()->getValueProvidingExpr();
// Look through base-ignored qualified references (Module.methodName).
} else if (auto baseIgnored = dyn_cast<DotSyntaxBaseIgnoredExpr>(fn)) {
fn = baseIgnored->getRHS();
// Look through closure capture lists.
} else if (auto captureList = dyn_cast<CaptureListExpr>(fn)) {
fn = captureList->getClosureBody();
// Look through optional evaluations.
} else if (auto optionalEval = dyn_cast<OptionalEvaluationExpr>(fn)) {
fn = optionalEval->getSubExpr()->getValueProvidingExpr();
// Look through actor isolation erasures.
} else if (auto actorIsolationErasure =
dyn_cast<ActorIsolationErasureExpr>(fn)) {
fn = actorIsolationErasure->getSubExpr()->getValueProvidingExpr();
} else {
break;
}
}
// Constructor delegation.
if (auto otherCtorDeclRef = dyn_cast<OtherConstructorDeclRefExpr>(fn)) {
return AbstractFunction(otherCtorDeclRef->getDecl(),
otherCtorDeclRef->getDeclRef().getSubstitutions());
}
// Normal function references.
if (auto DRE = dyn_cast<DeclRefExpr>(fn)) {
ValueDecl *decl = DRE->getDecl();
if (auto fn = dyn_cast<AbstractFunctionDecl>(decl)) {
return AbstractFunction(fn, DRE->getDeclRef().getSubstitutions());
} else if (auto param = dyn_cast<ParamDecl>(decl)) {
SubstitutionMap subs;
if (auto genericEnv = param->getDeclContext()->getGenericEnvironmentOfContext())
subs = genericEnv->getForwardingSubstitutionMap();
return AbstractFunction(param, subs);
}
// Closures.
} else if (auto closure = dyn_cast<AbstractClosureExpr>(fn)) {
return AbstractFunction(closure);
}
// Everything else is opaque.
return AbstractFunction(Kind::Opaque, fn);
}
};
enum ShouldRecurse_t : bool {
ShouldNotRecurse = false, ShouldRecurse = true
};
/// A CRTP ASTWalker implementation that looks for interesting
/// nodes for effects handling.
template <class Impl>
class EffectsHandlingWalker : public ASTWalker {
Impl &asImpl() { return *static_cast<Impl*>(this); }
public:
LazyInitializerWalking getLazyInitializerWalkingBehavior() override {
return LazyInitializerWalking::InAccessor;
}
/// Only look at the expansions for effects checking.
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkAction walkToDeclPre(Decl *D) override {
ShouldRecurse_t recurse = ShouldRecurse;
// Skip the implementations of all local declarations... except
// PBD. We should really just have a PatternBindingStmt.
if (auto patternBinding = dyn_cast<PatternBindingDecl>(D)) {
if (patternBinding->isAsyncLet())
recurse = asImpl().checkAsyncLet(patternBinding);
} else if (isa<MacroExpansionDecl>(D)) {
recurse = ShouldRecurse;
} else {
recurse = ShouldNotRecurse;
}
return Action::VisitNodeIf(bool(recurse));
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
visitExprPre(E);
ShouldRecurse_t recurse = ShouldRecurse;
if (isa<ErrorExpr>(E)) {
asImpl().flagInvalidCode();
} else if (auto closure = dyn_cast<ClosureExpr>(E)) {
recurse = asImpl().checkClosure(closure);
} else if (auto autoclosure = dyn_cast<AutoClosureExpr>(E)) {
recurse = asImpl().checkAutoClosure(autoclosure);
} else if (auto awaitExpr = dyn_cast<AwaitExpr>(E)) {
recurse = asImpl().checkAwait(awaitExpr);
} else if (auto unsafeExpr = dyn_cast<UnsafeExpr>(E)) {
recurse = asImpl().checkUnsafe(unsafeExpr);
} else if (auto tryExpr = dyn_cast<TryExpr>(E)) {
recurse = asImpl().checkTry(tryExpr);
} else if (auto forceTryExpr = dyn_cast<ForceTryExpr>(E)) {
recurse = asImpl().checkForceTry(forceTryExpr);
} else if (auto optionalTryExpr = dyn_cast<OptionalTryExpr>(E)) {
recurse = asImpl().checkOptionalTry(optionalTryExpr);
} else if (auto apply = dyn_cast<ApplyExpr>(E)) {
recurse = asImpl().checkApply(apply);
} else if (auto lookup = dyn_cast<LookupExpr>(E)) {
recurse = asImpl().checkLookup(lookup);
} else if (auto declRef = dyn_cast<DeclRefExpr>(E)) {
recurse = asImpl().checkDeclRef(declRef,
declRef->getDeclRef(),
declRef->getLoc(),
/*isEvaluated=*/true,
declRef->isImplicitlyAsync().has_value(),
declRef->isImplicitlyThrows());
} else if (auto interpolated = dyn_cast<InterpolatedStringLiteralExpr>(E)) {
recurse = asImpl().checkInterpolatedStringLiteral(interpolated);
} else if (isa<MacroExpansionExpr>(E)) {
recurse = ShouldRecurse;
} else if (auto *SVE = dyn_cast<SingleValueStmtExpr>(E)) {
recurse = asImpl().checkSingleValueStmtExpr(SVE);
} else if (auto *UTO = dyn_cast<UnderlyingToOpaqueExpr>(E)) {
recurse = asImpl().checkWithSubstitutionMap(E, UTO->substitutions);
} else if (auto *EE = dyn_cast<ErasureExpr>(E)) {
recurse = asImpl().checkWithConformances(E, EE->getConformances());
} else if (auto *OCD = dyn_cast<OtherConstructorDeclRefExpr>(E)) {
recurse = asImpl().checkDeclRef(OCD, OCD->getDeclRef(), OCD->getLoc(),
/*isEvaluated=*/true,
/*isImplicitlyAsync=*/false,
/*isImplicitlyThrows=*/false);
} else if (auto *ME = dyn_cast<MacroExpansionExpr>(E)) {
recurse = asImpl().checkDeclRef(ME, ME->getMacroRef(), ME->getLoc(),
/*isEvaluated=*/false,
/*isImplicitlyAsync=*/false,
/*isImplicitlyThrows=*/false);
} else if (auto *LE = dyn_cast<LiteralExpr>(E)) {
recurse = asImpl().checkDeclRef(LE, LE->getInitializer(), LE->getLoc(),
/*isEvaluated=*/false,
/*isImplicitlyAsync=*/false,
/*isImplicitlyThrows=*/false);
} else if (auto *CE = dyn_cast<CollectionExpr>(E)) {
recurse = asImpl().checkDeclRef(CE, CE->getInitializer(), CE->getLoc(),
/*isEvaluated=*/false,
/*isImplicitlyAsync=*/false,
/*isImplicitlyThrows=*/false);
} else if (auto ECE = dyn_cast<ExplicitCastExpr>(E)) {
recurse = asImpl().checkType(E, ECE->getCastTypeRepr(), ECE->getCastType());
} else if (auto TE = dyn_cast<TypeExpr>(E)) {
if (!TE->isImplicit()) {
recurse = asImpl().checkType(TE, TE->getTypeRepr(), TE->getInstanceType());
}
} else if (auto KPE = dyn_cast<KeyPathExpr>(E)) {
for (auto &component : KPE->getComponents()) {
switch (component.getKind()) {
case KeyPathExpr::Component::Kind::Member:
case KeyPathExpr::Component::Kind::Subscript: {
(void)asImpl().checkDeclRef(KPE, component.getDeclRef(),
component.getLoc(),
/*isEvaluated=*/false,
/*isImplicitlyAsync=*/false,
/*isImplicitlyThrows=*/false);
break;
}
case KeyPathExpr::Component::Kind::TupleElement:
case KeyPathExpr::Component::Kind::Invalid:
case KeyPathExpr::Component::Kind::UnresolvedMember:
case KeyPathExpr::Component::Kind::UnresolvedSubscript:
case KeyPathExpr::Component::Kind::UnresolvedApply:
case KeyPathExpr::Component::Kind::Apply:
case KeyPathExpr::Component::Kind::OptionalChain:
case KeyPathExpr::Component::Kind::OptionalWrap:
case KeyPathExpr::Component::Kind::OptionalForce:
case KeyPathExpr::Component::Kind::Identity:
case KeyPathExpr::Component::Kind::DictionaryKey:
case KeyPathExpr::Component::Kind::CodeCompletion:
break;
}
}
} else if (auto TE = dyn_cast<MakeTemporarilyEscapableExpr>(E)) {
recurse = asImpl().checkTemporarilyEscapable(TE);
}
// Error handling validation (via checkTopLevelEffects) happens after
// type checking. If an unchecked expression is still around, the code was
// invalid.
#define UNCHECKED_EXPR(KIND, BASE) \
else if (isa<KIND##Expr>(E)) return Action::Stop();
#include "swift/AST/ExprNodes.def"
return Action::VisitNodeIf(bool(recurse), E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
ShouldRecurse_t recurse = ShouldRecurse;
if (auto doCatch = dyn_cast<DoCatchStmt>(S)) {
recurse = asImpl().checkDoCatch(doCatch);
} else if (auto thr = dyn_cast<ThrowStmt>(S)) {
recurse = asImpl().checkThrow(thr);
} else if (auto forEach = dyn_cast<ForEachStmt>(S)) {
recurse = asImpl().checkForEach(forEach);
}
if (!recurse)
return Action::SkipNode(S);
return Action::Continue(S);
}
ShouldRecurse_t checkDoCatch(DoCatchStmt *S) {
auto bodyResult = (S->isSyntacticallyExhaustive()
? asImpl().checkExhaustiveDoBody(S)
: asImpl().checkNonExhaustiveDoBody(S));
for (auto clause : S->getCatches()) {
asImpl().checkCatch(clause, bodyResult);
}
return ShouldNotRecurse;
}
ShouldRecurse_t checkForEach(ForEachStmt *S) {
return ShouldRecurse;
}
void visitExprPre(Expr *expr) { asImpl().visitExprPre(expr); }
};
/// A potential reason why something might have an effect.
class PotentialEffectReason {
public:
enum class Kind : uint8_t {
/// The function calls an unconditionally throws/async function.
Apply,
/// The function is rethrows/reasync, and it was passed an explicit
/// argument that was not rethrows/reasync-only in this context.
ByClosure,
/// The function is rethrows/reasync, and it was passed a default
/// argument that was not rethrows/reasync-only in this context.
ByDefaultClosure,
/// The function is rethrows/reasync, and it was called with
/// a throwing conformance as one of its generic arguments.
ByConformance,
/// The initializer of an 'async let' can throw.
AsyncLet,
/// The function accesses an unconditionally throws/async property.
PropertyAccess,
SubscriptAccess
};
static StringRef kindToString(Kind k) {
switch (k) {
case Kind::Apply:
return "Apply";
case Kind::PropertyAccess:
return "PropertyAccess";
case Kind::SubscriptAccess:
return "SubscriptAccess";
case Kind::ByClosure:
return "ByClosure";
case Kind::ByDefaultClosure:
return "ByDefaultClosure";
case Kind::ByConformance:
return "ByConformance";
case Kind::AsyncLet:
return "AsyncLet";
}
}
private:
Expr *TheExpression;
Kind TheKind;
explicit PotentialEffectReason(Kind kind) : TheKind(kind) {}
public:
static PotentialEffectReason forApply() {
return PotentialEffectReason(Kind::Apply);
}
static PotentialEffectReason forPropertyAccess() {
return PotentialEffectReason(Kind::PropertyAccess);
}
static PotentialEffectReason forSubscriptAccess() {
return PotentialEffectReason(Kind::SubscriptAccess);
}
static PotentialEffectReason forClosure(Expr *E) {
PotentialEffectReason result(Kind::ByClosure);
result.TheExpression = E;
return result;
}
static PotentialEffectReason forDefaultClosure() {
return PotentialEffectReason(Kind::ByDefaultClosure);
}
static PotentialEffectReason forConformance() {
return PotentialEffectReason(Kind::ByConformance);
}
static PotentialEffectReason forAsyncLet() {
return PotentialEffectReason(Kind::AsyncLet);
}
Kind getKind() const { return TheKind; }
bool hasPolymorphicEffect() const {
return (getKind() == Kind::ByClosure ||
getKind() == Kind::ByDefaultClosure ||
getKind() == Kind::ByConformance);
}
/// If this was built with forRethrowsArgument, return the expression.
Expr *getArgument() const {
assert(getKind() == Kind::ByClosure);
return TheExpression;
}
};
enum class ConditionalEffectKind {
/// The call/function can't have this effect.
None,
/// The call/function can only have this effect if one of the parameters
/// or conformances in the current context can throw.
Conditional,
/// The call/function can have this effect.
Always,
};
static void simple_display(llvm::raw_ostream &out, ConditionalEffectKind kind) {
out << "ConditionalEffectKind::";
switch(kind) {
case ConditionalEffectKind::None: out << "None"; return;
case ConditionalEffectKind::Conditional: out << "Conditional"; return;
case ConditionalEffectKind::Always: out << "Always"; return;
}
llvm_unreachable("Bad conditional effect kind");
}
/// Remove the type erasure to an existential error, to extract the
/// underlying error.
static Expr *removeErasureToExistentialError(Expr *expr) {
Type type = expr->getType();
if (!type)
return expr;
ASTContext &ctx = type->getASTContext();
if (!ctx.LangOpts.hasFeature(Feature::FullTypedThrows))
return expr;
// Look for an outer erasure expression.
if (auto erasure = dyn_cast<ErasureExpr>(expr)) {
if (type->isEqual(ctx.getErrorExistentialType()))
return erasure->getSubExpr();
}
return expr;
}
}
bool swift::isRethrowLikeTypedThrows(AbstractFunctionDecl *func) {
// This notion is only for compatibility in Swift 5 and is disabled
// when FullTypedThrows is enabled.
ASTContext &ctx = func->getASTContext();
if (ctx.LangOpts.hasFeature(Feature::FullTypedThrows))
return false;
// It must have a thrown error type...
auto thrownError = func->getThrownInterfaceType();
if (!thrownError)
return false;
/// ... that is a generic parameter type (call it E)
auto thrownErrorGP = thrownError->getAs<GenericTypeParamType>();
if (!thrownErrorGP)
return false;
/// ... of the generic function.
auto genericParams = func->getGenericParams();
if (!genericParams ||
thrownErrorGP->getDepth() !=
genericParams->getParams().front()->getDepth())
return false;
// E: Error must be the only conformance requirement on the generic parameter.
auto genericSig = func->getGenericSignature();
if (!genericSig)
return false;
auto requiredProtocols = genericSig->getRequiredProtocols(thrownErrorGP);
if (requiredProtocols.size() != 1 ||
requiredProtocols[0]->getKnownProtocolKind() != KnownProtocolKind::Error)
return false;
// Any parameters that are of throwing function type must also throw 'E'.
for (auto param : *func->getParameters()) {
auto paramTy = param->getInterfaceType();
if (auto paramFuncTy = paramTy->getAs<AnyFunctionType>()) {
if (auto paramThrownErrorTy = paramFuncTy->getEffectiveThrownErrorType())
if (!(*paramThrownErrorTy)->isEqual(thrownError))
return false;
}
}
return true;
}
namespace {
/// Determine whether the given rethrows context is only allowed to be
/// rethrowing because of the historically-rethrowing behavior of
/// AsyncSequence and AsyncIteratorProtocol.
static bool isRethrowingDueToAsyncSequence(DeclContext *rethrowsDC) {
auto rethrowsFunc = dyn_cast<AbstractFunctionDecl>(rethrowsDC);
if (!rethrowsFunc)
return false;
if (rethrowsFunc->getPolymorphicEffectKind(EffectKind::Throws) !=
PolymorphicEffectKind::AsyncSequenceRethrows)
return false;
return true;
}
/// Type-erase the opened archetypes in the given type, if there is one.
static Type typeEraseOpenedArchetypes(Type type) {
if (!type || !type->hasOpenedExistential())
return type;
GenericEnvironment *env = nullptr;
type.visit([&](Type type) {
if (auto opened = dyn_cast<ExistentialArchetypeType>(type.getPointer())) {
env = opened->getGenericEnvironment();
}
});
if (!env)
return type;
return typeEraseOpenedArchetypesFromEnvironment(type, env);
}
/// A type expressing the result of classifying whether a call or function
/// throws or is async.
class Classification {
bool IsInvalid = false; // The AST is malformed. Don't diagnose.
bool downgradeToWarning = false;
// Throwing
ConditionalEffectKind ThrowKind = ConditionalEffectKind::None;
std::optional<PotentialEffectReason> ThrowReason;
Type ThrownError;
// Async
ConditionalEffectKind AsyncKind = ConditionalEffectKind::None;
std::optional<PotentialEffectReason> AsyncReason;
// Unsafe
ConditionalEffectKind UnsafeKind = ConditionalEffectKind::None;
SmallVector<UnsafeUse, 2> UnsafeUses;
void print(raw_ostream &out) const {
out << "{ IsInvalid = " << IsInvalid
<< ", ThrowKind = ";
simple_display(out, ThrowKind);
out << ", ThrowReason = ";
if (!ThrowReason)
out << "nil";
else
out << PotentialEffectReason::kindToString(ThrowReason->getKind());
if (ThrownError)
out << ", ThrownError = " << ThrownError.getString();
out << ", AsyncKind = ";
simple_display(out, AsyncKind);
out << ", AsyncReason = ";
if (!AsyncReason)
out << "nil";
else
out << PotentialEffectReason::kindToString(AsyncReason->getKind());
out << ", UnsafeKind = ";
simple_display(out, UnsafeKind);
out << " }";
}
void recordUnsafeUse(const UnsafeUse &unsafeUse) {
UnsafeKind = ConditionalEffectKind::Always;
UnsafeUses.push_back(unsafeUse);
}
public:
Classification() {}
/// Whether this classification involves any effects.
bool hasAnyEffects() const {
return hasAsync() || hasThrows() || hasUnsafe();
}
explicit operator bool() const { return hasAnyEffects(); }
/// Whether there is an async effect.
bool hasAsync() const { return AsyncKind != ConditionalEffectKind::None; }
/// Whether there is a throws effect.
bool hasThrows() const { return ThrowKind != ConditionalEffectKind::None; }
/// Whether there is an unsafe effect.
bool hasUnsafe() const { return UnsafeKind != ConditionalEffectKind::None; }
/// Return a classification that only retains the async parts of the
/// given classification.
Classification onlyAsync() const {
Classification result(*this);
result.ThrowKind = ConditionalEffectKind::None;
result.ThrowReason = std::nullopt;
result.ThrownError = Type();
result.UnsafeKind = ConditionalEffectKind::None;
result.UnsafeUses.clear();
return result;
}
/// Return a classification that only retains the throwing parts of the
/// given classification.
Classification onlyThrowing(std::optional<PotentialEffectReason>