-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckConcurrency.cpp
7671 lines (6558 loc) · 279 KB
/
TypeCheckConcurrency.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
//===--- TypeCheckConcurrency.cpp - Concurrency ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 type checking support for Swift's concurrency model.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckConcurrency.h"
#include "MiscDiagnostics.h"
#include "TypeCheckDistributed.h"
#include "TypeCheckInvertible.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AvailabilityInference.h"
#include "swift/AST/Concurrency.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DistributedDecl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Strings.h"
using namespace swift;
static ActorIsolation getOverriddenIsolationFor(const ValueDecl *value);
/// Determine whether it makes sense to infer an attribute in the given
/// context.
static bool shouldInferAttributeInContext(const DeclContext *dc) {
if (auto *file = dyn_cast<FileUnit>(dc->getModuleScopeContext())) {
switch (file->getKind()) {
case FileUnitKind::Source:
// Check what kind of source file we have.
if (auto sourceFile = dc->getParentSourceFile()) {
switch (sourceFile->Kind) {
case SourceFileKind::Interface:
// Interfaces have explicitly called-out Sendable conformances.
return false;
case SourceFileKind::DefaultArgument:
case SourceFileKind::Library:
case SourceFileKind::MacroExpansion:
case SourceFileKind::Main:
case SourceFileKind::SIL:
return true;
}
}
break;
case FileUnitKind::Builtin:
case FileUnitKind::SerializedAST:
case FileUnitKind::Synthesized:
return false;
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
return true;
}
return true;
}
return false;
}
void swift::addAsyncNotes(AbstractFunctionDecl const* func) {
assert(func);
if (!isa<DestructorDecl>(func) && !isa<AccessorDecl>(func)) {
auto note =
func->diagnose(diag::note_add_async_to_function, func);
if (func->hasThrows()) {
auto replacement = func->getAttrs().hasAttribute<RethrowsAttr>()
? "async rethrows"
: "async throws";
note.fixItReplace(SourceRange(func->getThrowsLoc()), replacement);
} else if (func->getParameters()->getRParenLoc().isValid()) {
note.fixItInsert(func->getParameters()->getRParenLoc().getAdvancedLoc(1),
" async");
}
}
}
static bool requiresFlowIsolation(ActorIsolation typeIso,
ConstructorDecl const *ctor) {
assert(ctor->isDesignatedInit());
auto ctorIso = getActorIsolation(const_cast<ConstructorDecl *>(ctor));
// Regardless of async-ness, a mismatch in isolation means we need to be
// flow-sensitive.
if (typeIso != ctorIso)
return true;
// Otherwise, if it's an actor instance, then it depends on async-ness.
switch (typeIso.getKind()) {
case ActorIsolation::GlobalActor:
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
return false;
// TODO: We probably want constructors to always be truly non-isolated.
case ActorIsolation::CallerIsolationInheriting:
llvm_unreachable("constructor cannot have nonisolated implicit actor "
"instance isolation");
case ActorIsolation::Erased:
llvm_unreachable("constructor cannot have erased isolation");
case ActorIsolation::ActorInstance:
return !(ctor->hasAsync()); // need flow-isolation for non-async.
};
}
bool swift::usesFlowSensitiveIsolation(AbstractFunctionDecl const *fn) {
if (!fn)
return false;
// Only designated constructors or nonisolated destructors use this kind of
// isolation.
if (auto const* ctor = dyn_cast<ConstructorDecl>(fn)) {
if (!ctor->isDesignatedInit())
return false;
} else if (auto const *dtor = dyn_cast<DestructorDecl>(fn)) {
if (getActorIsolation(const_cast<DestructorDecl *>(dtor))
.isActorIsolated()) {
return false;
}
} else {
return false;
}
auto *dc = fn->getDeclContext();
if (!dc)
return false;
// Must be part of a nominal type.
auto *nominal = dc->getSelfNominalTypeDecl();
if (!nominal)
return false;
// If it's part of an actor type, then its deinit and some of its inits use
// flow-isolation.
if (nominal->isAnyActor()) {
if (isa<DestructorDecl>(fn))
return true;
// construct an isolation corresponding to the type.
auto actorTypeIso = ActorIsolation::forActorInstanceSelf(
const_cast<AbstractFunctionDecl *>(fn));
return requiresFlowIsolation(actorTypeIso, cast<ConstructorDecl>(fn));
}
// Otherwise, the type must be isolated to a global actor.
auto nominalIso = getActorIsolation(nominal);
if (!nominalIso.isGlobalActor())
return false;
// if it's a deinit, then it's flow-isolated.
if (isa<DestructorDecl>(fn))
return true;
return requiresFlowIsolation(nominalIso, cast<ConstructorDecl>(fn));
}
bool IsActorRequest::evaluate(
Evaluator &evaluator, NominalTypeDecl *nominal) const {
// Protocols are actors if they inherit from `Actor`.
if (auto protocol = dyn_cast<ProtocolDecl>(nominal)) {
auto &ctx = protocol->getASTContext();
auto *actorProtocol = ctx.getProtocol(KnownProtocolKind::Actor);
if (!actorProtocol)
return false;
return (protocol == actorProtocol ||
protocol->inheritsFrom(actorProtocol));
}
// Class declarations are actors if they were declared with "actor".
auto classDecl = dyn_cast<ClassDecl>(nominal);
if (!classDecl)
return false;
return classDecl->isExplicitActor();
}
bool IsDefaultActorRequest::evaluate(
Evaluator &evaluator, ClassDecl *classDecl, ModuleDecl *M,
ResilienceExpansion expansion) const {
// If the class isn't an actor, it's not a default actor.
if (!classDecl->isActor())
return false;
// Distributed actors were not able to have custom executors until Swift 5.9,
// so in order to avoid wrongly treating a resilient distributed actor from another
// module as not-default we need to handle this case explicitly.
if (classDecl->isDistributedActor()) {
ASTContext &ctx = classDecl->getASTContext();
auto customExecutorAvailability =
ctx.getConcurrencyDistributedActorWithCustomExecutorAvailability();
auto actorAvailability = TypeChecker::overApproximateAvailabilityAtLocation(
classDecl->getStartLoc(),
classDecl);
if (!actorAvailability.isContainedIn(customExecutorAvailability)) {
// Any 'distributed actor' declared with availability lower than the
// introduction of custom executors for distributed actors, must be treated as default actor,
// even if it were to declared the unowned executor property, as older compilers
// do not have the logic to handle that case.
return true;
}
}
// If the class is resilient from the perspective of the module
// module, it's not a default actor.
if (classDecl->isForeign() || classDecl->isResilient(M, expansion))
return false;
// Check whether the class has explicit custom-actor methods.
// If we synthesized the unownedExecutor property, we should've
// added a semantics attribute to it (if it was actually a default
// actor).
bool foundExecutorPropertyImpl = false;
bool isDefaultActor = false;
if (auto executorProperty = classDecl->getUnownedExecutorProperty()) {
foundExecutorPropertyImpl = true;
isDefaultActor = isDefaultActor ||
executorProperty->getAttrs().hasSemanticsAttr(SEMANTICS_DEFAULT_ACTOR);
}
// Only if we found one of the executor properties, do we return the status of default or not,
// based on the findings of the semantics attribute of that located property.
if (foundExecutorPropertyImpl) {
if (!isDefaultActor &&
classDecl->getASTContext().LangOpts.isConcurrencyModelTaskToThread() &&
!classDecl->isUnavailable()) {
classDecl->diagnose(
diag::concurrency_task_to_thread_model_custom_executor,
"task-to-thread concurrency model");
}
return isDefaultActor;
}
// Otherwise, we definitely are a default actor.
return true;
}
VarDecl *GlobalActorInstanceRequest::evaluate(
Evaluator &evaluator, NominalTypeDecl *nominal) const {
auto globalActorAttr = nominal->getAttrs().getAttribute<GlobalActorAttr>();
if (!globalActorAttr)
return nullptr;
// Ensure that the actor protocol has been loaded.
ASTContext &ctx = nominal->getASTContext();
auto actorProto = ctx.getProtocol(KnownProtocolKind::Actor);
if (!actorProto) {
nominal->diagnose(diag::concurrency_lib_missing, "Actor");
return nullptr;
}
// Non-final classes cannot be global actors.
if (auto classDecl = dyn_cast<ClassDecl>(nominal)) {
if (!classDecl->isSemanticallyFinal()) {
nominal->diagnose(diag::global_actor_non_final_class, nominal->getName())
.highlight(globalActorAttr->getRangeWithAt());
}
}
// Global actors have a static property "shared" that provides an actor
// instance. The value must be of Actor type, which is validated by
// conformance to the 'GlobalActor' protocol.
SmallVector<ValueDecl *, 4> decls;
nominal->lookupQualified(
nominal, DeclNameRef(ctx.Id_shared),
nominal->getLoc(), NL_QualifiedDefault, decls);
for (auto decl : decls) {
auto var = dyn_cast<VarDecl>(decl);
if (!var)
continue;
if (var->getDeclContext() == nominal && var->isStatic())
return var;
}
return nullptr;
}
std::optional<std::pair<CustomAttr *, NominalTypeDecl *>>
swift::checkGlobalActorAttributes(SourceLoc loc, DeclContext *dc,
ArrayRef<CustomAttr *> attrs) {
ASTContext &ctx = dc->getASTContext();
CustomAttr *globalActorAttr = nullptr;
NominalTypeDecl *globalActorNominal = nullptr;
for (auto attr : attrs) {
// Figure out which nominal declaration this custom attribute refers to.
auto *nominal = evaluateOrDefault(ctx.evaluator,
CustomAttrNominalRequest{attr, dc},
nullptr);
if (!nominal)
continue;
// We are only interested in global actor types.
if (!nominal->isGlobalActor())
continue;
// Only a single global actor can be applied to a given entity.
if (globalActorAttr) {
ctx.Diags.diagnose(
loc, diag::multiple_global_actors, globalActorNominal->getName(),
nominal->getName());
continue;
}
globalActorAttr = const_cast<CustomAttr *>(attr);
globalActorNominal = nominal;
}
if (!globalActorAttr)
return std::nullopt;
return std::make_pair(globalActorAttr, globalActorNominal);
}
std::optional<std::pair<CustomAttr *, NominalTypeDecl *>>
GlobalActorAttributeRequest::evaluate(
Evaluator &evaluator,
llvm::PointerUnion<Decl *, ClosureExpr *> subject) const {
DeclContext *dc = nullptr;
DeclAttributes *declAttrs = nullptr;
SourceLoc loc;
if (auto decl = subject.dyn_cast<Decl *>()) {
dc = decl->getDeclContext();
declAttrs = &decl->getAttrs();
// HACK: `getLoc`, when querying the attr from a serialized decl,
// depending on deserialization order, may launch into arbitrary
// type-checking when querying interface types of such decls. Which,
// in turn, may do things like query (to print) USRs. This ends up being
// prone to request evaluator cycles.
//
// Because this only applies to serialized decls, we can be confident
// that they already went through this type-checking as primaries, so,
// for now, to avoid cycles, we simply ignore the locs on serialized decls
// only.
// This is a workaround for rdar://79563942
loc = decl->getLoc(/* SerializedOK */ false);
} else {
auto closure = subject.get<ClosureExpr *>();
dc = closure;
declAttrs = &closure->getAttrs();
loc = closure->getLoc();
}
// Collect the attributes.
SmallVector<CustomAttr *, 2> attrs;
for (auto attr : declAttrs->getAttributes<CustomAttr>()) {
auto mutableAttr = const_cast<CustomAttr *>(attr);
attrs.push_back(mutableAttr);
}
// Look for a global actor attribute.
auto result = checkGlobalActorAttributes(loc, dc, attrs);
if (!result)
return std::nullopt;
// Closures can always have a global actor attached.
if (subject.is<ClosureExpr *>()) {
return result;
}
// Check that a global actor attribute makes sense on this kind of
// declaration.
auto decl = subject.get<Decl *>();
// no further checking required if it's from a serialized module.
if (decl->getDeclContext()->getParentSourceFile() == nullptr)
return result;
auto isStoredInstancePropertyOfStruct = [](VarDecl *var) {
if (var->isStatic() || !var->isOrdinaryStoredProperty())
return false;
auto *nominal = var->getDeclContext()->getSelfNominalTypeDecl();
return isa_and_nonnull<StructDecl>(nominal) &&
!isWrappedValueOfPropWrapper(var);
};
auto globalActorAttr = result->first;
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
// Nominal types are okay...
if (auto classDecl = dyn_cast<ClassDecl>(nominal)){
if (classDecl->isActor()) {
// ... except for actors.
nominal->diagnose(diag::global_actor_on_actor_class, nominal->getName())
.highlight(globalActorAttr->getRangeWithAt());
return std::nullopt;
}
}
} else if (auto storage = dyn_cast<AbstractStorageDecl>(decl)) {
// Subscripts and properties are fine...
if (auto var = dyn_cast<VarDecl>(storage)) {
// ... but not if it's an async-context top-level global
if (var->isTopLevelGlobal() &&
(var->getDeclContext()->isAsyncContext() ||
var->getASTContext().LangOpts.StrictConcurrencyLevel >=
StrictConcurrency::Complete)) {
var->diagnose(diag::global_actor_top_level_var)
.highlight(globalActorAttr->getRangeWithAt());
return std::nullopt;
}
// ... and not if it's local property
if (var->getDeclContext()->isLocalContext()) {
var->diagnose(diag::global_actor_on_local_variable, var->getName())
.highlight(globalActorAttr->getRangeWithAt());
return std::nullopt;
}
}
} else if (isa<ExtensionDecl>(decl)) {
// Extensions are okay.
} else if (isa<ConstructorDecl>(decl) || isa<FuncDecl>(decl) ||
isa<DestructorDecl>(decl)) {
// None of the accessors/addressors besides a getter are allowed
// to have a global actor attribute.
if (auto *accessor = dyn_cast<AccessorDecl>(decl)) {
if (!accessor->isGetter()) {
decl->diagnose(diag::global_actor_disallowed,
decl->getDescriptiveKind())
.warnUntilSwiftVersion(6)
.fixItRemove(globalActorAttr->getRangeWithAt());
auto &ctx = decl->getASTContext();
auto *storage = accessor->getStorage();
// Let's suggest to move the attribute to the storage if
// this is an accessor/addressor of a property of subscript.
if (storage->getDeclContext()->isTypeContext()) {
auto canMoveAttr = [&]() {
// If enclosing declaration has a global actor,
// skip the suggestion.
if (storage->getGlobalActorAttr())
return false;
// Global actor attribute cannot be applied to
// an instance stored property of a struct.
if (auto *var = dyn_cast<VarDecl>(storage)) {
return !isStoredInstancePropertyOfStruct(var);
}
return true;
};
if (canMoveAttr()) {
decl->diagnose(diag::move_global_actor_attr_to_storage_decl,
storage)
.fixItInsert(
storage->getAttributeInsertionLoc(/*forModifier=*/false),
llvm::Twine("@", result->second->getNameStr()).str());
}
}
// In Swift 6, once the diag above is an error, it is disallowed.
if (ctx.isSwiftVersionAtLeast(6))
return std::nullopt;
}
}
// Functions are okay.
} else {
// Everything else is disallowed.
decl->diagnose(diag::global_actor_disallowed, decl->getDescriptiveKind());
return std::nullopt;
}
return result;
}
Type swift::getExplicitGlobalActor(ClosureExpr *closure) {
// Look at the explicit attribute.
auto globalActorAttr =
evaluateOrDefault(closure->getASTContext().evaluator,
GlobalActorAttributeRequest{closure}, std::nullopt);
if (!globalActorAttr)
return Type();
Type globalActor = evaluateOrDefault(
closure->getASTContext().evaluator,
CustomAttrTypeRequest{
globalActorAttr->first, closure, CustomAttrTypeKind::GlobalActor},
Type());
if (!globalActor || globalActor->hasError())
return Type();
return globalActor;
}
/// A 'let' declaration is safe across actors if it is either
/// nonisolated or it is accessed from within the same module.
static bool varIsSafeAcrossActors(const ModuleDecl *fromModule, VarDecl *var,
const ActorIsolation &varIsolation,
std::optional<ReferencedActor> actorInstance,
ActorReferenceResult::Options &options) {
bool accessWithinModule =
(fromModule == var->getDeclContext()->getParentModule());
if (varIsolation.getKind() == ActorIsolation::NonisolatedUnsafe)
return true;
if (!var->isLet()) {
// A mutable storage of a value type accessed from within the module is
// okay.
if (dyn_cast_or_null<StructDecl>(var->getDeclContext()->getAsDecl()) &&
!var->isStatic() && var->hasStorage() &&
var->getTypeInContext()->isSendableType()) {
if (accessWithinModule || varIsolation.isNonisolated())
return true;
}
// Otherwise, must be immutable.
return false;
}
switch (varIsolation) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
// if nonisolated, it's OK
return true;
case ActorIsolation::CallerIsolationInheriting:
return false;
case ActorIsolation::Erased:
llvm_unreachable("variable cannot have erased isolation");
case ActorIsolation::ActorInstance:
case ActorIsolation::GlobalActor:
// If it's explicitly 'nonisolated', it's okay.
if (var->getAttrs().hasAttribute<NonisolatedAttr>())
return true;
// Static 'let's are initialized upon first access, so they cannot be
// synchronously accessed across actors.
if (var->isGlobalStorage() && var->isLazilyInitializedGlobal()) {
// Compiler versions <= 5.9 accepted this code, so downgrade to a
// warning prior to Swift 6.
options = ActorReferenceResult::Flags::Preconcurrency;
return false;
}
// If it's distributed, but known to be local, it's ok
// TODO: Check if this can be obtained from the isolation, without a need for separate argument
if (actorInstance && actorInstance->isKnownToBeLocal()) {
return true;
}
// If it's distributed, generally variable access is not okay...
if (auto nominalParent = var->getDeclContext()->getSelfNominalTypeDecl()) {
if (nominalParent->isDistributedActor())
return false;
}
// If the type is not 'Sendable', it's unsafe
if (!var->getTypeInContext()->isSendableType()) {
// Compiler versions <= 5.10 treated this variable as nonisolated,
// so downgrade async access errors in the effects checker to
// warnings prior to Swift 6.
if (accessWithinModule)
options = ActorReferenceResult::Flags::Preconcurrency;
return false;
}
// If it's actor-isolated but in the same module, then it's OK too.
return accessWithinModule;
}
}
bool swift::isLetAccessibleAnywhere(const ModuleDecl *fromModule,
VarDecl *let,
ActorReferenceResult::Options &options) {
auto isolation = getActorIsolation(let);
return varIsSafeAcrossActors(fromModule, let, isolation, std::nullopt, options);
}
bool swift::isLetAccessibleAnywhere(const ModuleDecl *fromModule,
VarDecl *let) {
ActorReferenceResult::Options options = std::nullopt;
return isLetAccessibleAnywhere(fromModule, let, options);
}
namespace {
/// Describes the important parts of a partial apply thunk.
struct PartialApplyThunkInfo {
Expr *base;
Expr *fn;
bool isEscaping;
};
}
/// Try to decompose a call that might be an invocation of a partial apply
/// thunk.
static std::optional<PartialApplyThunkInfo>
decomposePartialApplyThunk(ApplyExpr *apply, Expr *parent) {
// Check for a call to the outer closure in the thunk.
auto outerAutoclosure = dyn_cast<AutoClosureExpr>(apply->getFn());
if (!outerAutoclosure || outerAutoclosure->getThunkKind() !=
AutoClosureExpr::Kind::DoubleCurryThunk)
return std::nullopt;
auto *unarySelfArg = apply->getArgs()->getUnlabeledUnaryExpr();
assert(unarySelfArg &&
"Double curry should start with a unary (Self) -> ... arg");
auto memberFn = outerAutoclosure->getUnwrappedCurryThunkExpr();
if (!memberFn)
return std::nullopt;
// Determine whether the partial apply thunk was immediately converted to
// noescape.
bool isEscaping = true;
if (auto conversion = dyn_cast_or_null<FunctionConversionExpr>(parent)) {
auto fnType = conversion->getType()->getAs<FunctionType>();
isEscaping = fnType && !fnType->isNoEscape();
}
return PartialApplyThunkInfo{unarySelfArg, memberFn, isEscaping};
}
/// Find the immediate member reference in the given expression.
static std::optional<std::pair<ConcreteDeclRef, SourceLoc>>
findReference(Expr *expr) {
// Look through a function conversion.
if (auto fnConv = dyn_cast<FunctionConversionExpr>(expr))
expr = fnConv->getSubExpr();
if (auto declRef = dyn_cast<DeclRefExpr>(expr))
return std::make_pair(declRef->getDeclRef(), declRef->getLoc());
if (auto otherCtor = dyn_cast<OtherConstructorDeclRefExpr>(expr)) {
return std::make_pair(otherCtor->getDeclRef(), otherCtor->getLoc());
}
Expr *inner = expr->getValueProvidingExpr();
if (inner != expr)
return findReference(inner);
return std::nullopt;
}
/// Return true if the callee of an ApplyExpr is async
///
/// Note that this must be called after the implicitlyAsync flag has been set,
/// or implicitly async calls will not return the correct value.
static bool isAsyncCall(
llvm::PointerUnion<ApplyExpr *, LookupExpr *> call) {
if (auto *apply = call.dyn_cast<ApplyExpr *>()) {
if (apply->isImplicitlyAsync())
return true;
// Effectively the same as doing a
// `cast_or_null<FunctionType>(call->getFn()->getType())`, check the
// result of that and then checking `isAsync` if it's defined.
Type funcTypeType = apply->getFn()->getType();
if (!funcTypeType)
return false;
AnyFunctionType *funcType = funcTypeType->getAs<AnyFunctionType>();
if (!funcType)
return false;
return funcType->isAsync();
}
auto *lookup = call.get<LookupExpr *>();
if (lookup->isImplicitlyAsync())
return true;
return isAsyncDecl(lookup->getDecl());
}
/// Determine whether we should diagnose data races within the current context.
///
/// By default, we do this only in code that makes use of concurrency
/// features.
static bool shouldDiagnoseExistingDataRaces(const DeclContext *dc);
/// Returns true if this closure acts as an inference boundary in the AST. An
/// inference boundary is an expression in the AST where we newly infer
/// isolation different from our parent decl context.
///
/// Examples:
///
/// 1. a @Sendable closure.
/// 2. a closure literal passed to a sending parameter.
///
/// NOTE: This does not mean that it has nonisolated isolation since for
/// instance one could define an @MainActor closure in a nonisolated
/// function. That @MainActor closure would act as an Isolation Inference
/// Boundary.
///
/// \param canInheritActorContext Whether or not the closure is allowed to
/// inherit the isolation of the enclosing context. If this is \c true ,
/// the closure is not considered an isolation inference boundary if the
/// \c @_inheritActorContext attribute is applied to the closure. This
/// attribute is inferred from a parameter declaration for closure arguments,
/// and it's set on the closure in CSApply.
static bool
isIsolationInferenceBoundaryClosure(const AbstractClosureExpr *closure,
bool canInheritActorContext) {
if (auto *ce = dyn_cast<ClosureExpr>(closure)) {
// If the closure can inherit the isolation of the enclosing context,
// it is not an actor isolation inference boundary.
if (canInheritActorContext && ce->inheritsActorContext())
return false;
if (ce->isPassedToSendingParameter())
return true;
}
// An autoclosure for an async let acts as a boundary. It is non-Sendable
// regardless of its context.
if (auto *autoclosure = dyn_cast<AutoClosureExpr>(closure)) {
if (autoclosure->getThunkKind() == AutoClosureExpr::Kind::AsyncLet)
return true;
}
return closure->isSendable();
}
/// Add Fix-It text for the given nominal type to adopt Sendable.
static void addSendableFixIt(
const NominalTypeDecl *nominal, InFlightDiagnostic &diag, bool unchecked) {
if (nominal->getInherited().empty()) {
SourceLoc fixItLoc = nominal->getBraces().Start;
diag.fixItInsert(fixItLoc,
unchecked ? ": @unchecked Sendable" : ": Sendable");
} else {
auto fixItLoc = nominal->getInherited().getEndLoc();
diag.fixItInsertAfter(fixItLoc,
unchecked ? ", @unchecked Sendable" : ", Sendable");
}
}
/// Add Fix-It text for the given generic param declaration type to adopt
/// Sendable.
static void addSendableFixIt(const GenericTypeParamDecl *genericArgument,
InFlightDiagnostic &diag, bool unchecked) {
if (genericArgument->getInherited().empty()) {
auto fixItLoc = genericArgument->getLoc();
diag.fixItInsertAfter(fixItLoc,
unchecked ? ": @unchecked Sendable" : ": Sendable");
} else {
auto fixItLoc = genericArgument->getInherited().getEndLoc();
diag.fixItInsertAfter(fixItLoc,
unchecked ? ", @unchecked Sendable" : ", Sendable");
}
}
static bool shouldDiagnoseExistingDataRaces(const DeclContext *dc) {
return contextRequiresStrictConcurrencyChecking(dc, [](const AbstractClosureExpr *) {
return Type();
},
[](const ClosureExpr *closure) {
return closure->isIsolatedByPreconcurrency();
});
}
bool SendableCheckContext::warnInMinimalChecking() const {
if (preconcurrencyContext)
return false;
if (!conformanceCheck)
return false;
switch (*conformanceCheck) {
case SendableCheck::Explicit:
return true;
case SendableCheck::ImpliedByStandardProtocol:
case SendableCheck::Implicit:
case SendableCheck::ImplicitForExternallyVisible:
return false;
}
}
DiagnosticBehavior SendableCheckContext::defaultDiagnosticBehavior() const {
// If we're not supposed to diagnose existing data races from this context,
// ignore the diagnostic entirely.
if (!warnInMinimalChecking() &&
!shouldDiagnoseExistingDataRaces(fromDC))
return DiagnosticBehavior::Ignore;
return DiagnosticBehavior::Warning;
}
DiagnosticBehavior
SendableCheckContext::implicitSendableDiagnosticBehavior() const {
switch (fromDC->getASTContext().LangOpts.StrictConcurrencyLevel) {
case StrictConcurrency::Targeted:
// Limited checking only diagnoses implicit Sendable within contexts that
// have adopted concurrency.
if (shouldDiagnoseExistingDataRaces(fromDC))
return DiagnosticBehavior::Warning;
LLVM_FALLTHROUGH;
case StrictConcurrency::Minimal:
if (warnInMinimalChecking())
return DiagnosticBehavior::Warning;
return DiagnosticBehavior::Ignore;
case StrictConcurrency::Complete:
return defaultDiagnosticBehavior();
}
}
/// Determine the diagnostic behavior for a Sendable reference to the given
/// nominal type.
DiagnosticBehavior SendableCheckContext::diagnosticBehavior(
NominalTypeDecl *nominal) const {
// If we're in a preconcurrency context, don't override the default behavior
// based on explicit conformances. For example, a @preconcurrency @Sendable
// closure should not warn about an explicitly unavailable Sendable
// conformance in minimal checking.
if (preconcurrencyContext)
return defaultDiagnosticBehavior();
if (hasExplicitSendableConformance(nominal))
return DiagnosticBehavior::Warning;
DiagnosticBehavior defaultBehavior = implicitSendableDiagnosticBehavior();
// If we are checking an implicit Sendable conformance, don't suppress
// diagnostics for declarations in the same module. We want them to make
// enclosing inferred types non-Sendable.
if (defaultBehavior == DiagnosticBehavior::Ignore &&
nominal->getParentSourceFile() &&
conformanceCheck && isImplicitSendableCheck(*conformanceCheck))
return DiagnosticBehavior::Warning;
return defaultBehavior;
}
std::optional<DiagnosticBehavior>
SendableCheckContext::preconcurrencyBehavior(
Decl *decl,
bool ignoreExplicitConformance) const {
if (!decl)
return std::nullopt;
if (auto *nominal = dyn_cast<NominalTypeDecl>(decl)) {
return getConcurrencyDiagnosticBehaviorLimit(nominal, fromDC,
ignoreExplicitConformance);
}
return std::nullopt;
}
static bool shouldDiagnosePreconcurrencyImports(SourceFile &sf) {
switch (sf.Kind) {
case SourceFileKind::Interface:
case SourceFileKind::SIL:
return false;
case SourceFileKind::DefaultArgument:
case SourceFileKind::Library:
case SourceFileKind::Main:
case SourceFileKind::MacroExpansion:
return true;
}
}
bool swift::diagnoseSendabilityErrorBasedOn(
NominalTypeDecl *nominal, SendableCheckContext fromContext,
llvm::function_ref<bool(DiagnosticBehavior)> diagnose) {
auto behavior = DiagnosticBehavior::Unspecified;
if (nominal) {
behavior = fromContext.diagnosticBehavior(nominal);
} else {
behavior = fromContext.implicitSendableDiagnosticBehavior();
}
bool wasSuppressed = diagnose(behavior);
SourceFile *sourceFile = fromContext.fromDC->getParentSourceFile();
if (sourceFile && shouldDiagnosePreconcurrencyImports(*sourceFile)) {
bool emittedDiagnostics =
behavior != DiagnosticBehavior::Ignore && !wasSuppressed;
// When the type is explicitly Sendable *or* explicitly non-Sendable, we
// assume it has been audited and `@preconcurrency` is not recommended even
// though it would actually affect the diagnostic.
bool nominalIsImportedAndHasImplicitSendability =
nominal &&
nominal->getParentModule() != fromContext.fromDC->getParentModule() &&
!hasExplicitSendableConformance(nominal);
if (emittedDiagnostics && nominalIsImportedAndHasImplicitSendability) {
// This type was imported from another module; try to find the
// corresponding import.
std::optional<AttributedImport<swift::ImportedModule>> import =
nominal->findImport(fromContext.fromDC);
// If we found the import that makes this nominal type visible, remark
// that it can be @preconcurrency import.
// Only emit this remark once per source file, because it can happen a
// lot.
if (import && !import->options.contains(ImportFlags::Preconcurrency) &&
import->importLoc.isValid() && sourceFile &&
!sourceFile->hasImportUsedPreconcurrency(*import)) {
SourceLoc importLoc = import->importLoc;
ASTContext &ctx = nominal->getASTContext();
ctx.Diags
.diagnose(importLoc, diag::add_predates_concurrency_import,
ctx.LangOpts.isSwiftVersionAtLeast(6),
nominal->getParentModule()->getName())
.fixItInsert(importLoc, "@preconcurrency ");
sourceFile->setImportUsedPreconcurrency(*import);
}
}
}
return behavior == DiagnosticBehavior::Unspecified && !wasSuppressed;
}
void swift::diagnoseUnnecessaryPreconcurrencyImports(SourceFile &sf) {
if (!shouldDiagnosePreconcurrencyImports(sf))
return;
ASTContext &ctx = sf.getASTContext();
if (ctx.TypeCheckerOpts.SkipFunctionBodies != FunctionBodySkipping::None)
return;
for (const auto &import : sf.getImports()) {
if (import.options.contains(ImportFlags::Preconcurrency) &&
import.importLoc.isValid() &&
!sf.hasImportUsedPreconcurrency(import)) {
ctx.Diags.diagnose(
import.importLoc, diag::remove_predates_concurrency_import,
import.module.importedModule->getName())
.fixItRemove(import.preconcurrencyRange);
}
}
}
/// Produce a diagnostic for a single instance of a non-Sendable type where
/// a Sendable type is required.
static bool diagnoseSingleNonSendableType(
Type type, SendableCheckContext fromContext,
Type inDerivedConformance, SourceLoc loc,
llvm::function_ref<bool(Type, DiagnosticBehavior)> diagnose) {
if (type->hasError())
return false;
auto module = fromContext.fromDC->getParentModule();
auto nominal = type->getAnyNominal();
auto &ctx = module->getASTContext();
return diagnoseSendabilityErrorBasedOn(nominal, fromContext,
[&](DiagnosticBehavior behavior) {
bool wasSuppressed = diagnose(type, behavior);
// Don't emit the following notes if we didn't have any diagnostics to
// attach them to.
if (wasSuppressed || behavior == DiagnosticBehavior::Ignore)
return true;
if (inDerivedConformance) {
ctx.Diags.diagnose(loc, diag::in_derived_conformance,
inDerivedConformance);
}
if (type->is<FunctionType>()) {