Skip to content

Commit 1824b7d

Browse files
committed
A "defer" block is global-actor-isolated if its context is.
Fixes rdar://80799233. (cherry picked from commit 5dc4fcf)
1 parent 73a3881 commit 1824b7d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

lib/Sema/TypeCheckConcurrency.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3126,6 +3126,26 @@ ActorIsolation ActorIsolationRequest::evaluate(
31263126
return inferred;
31273127
};
31283128

3129+
// If this is a "defer" function body, inherit the global actor isolation
3130+
// from its context.
3131+
if (auto func = dyn_cast<FuncDecl>(value)) {
3132+
if (func->isDeferBody()) {
3133+
switch (auto enclosingIsolation =
3134+
getActorIsolationOfContext(func->getDeclContext())) {
3135+
case ActorIsolation::ActorInstance:
3136+
case ActorIsolation::DistributedActorInstance:
3137+
case ActorIsolation::Independent:
3138+
case ActorIsolation::Unspecified:
3139+
// Do nothing.
3140+
break;
3141+
3142+
case ActorIsolation::GlobalActor:
3143+
case ActorIsolation::GlobalActorUnsafe:
3144+
return inferredIsolation(enclosingIsolation);
3145+
}
3146+
}
3147+
}
3148+
31293149
// If the declaration overrides another declaration, it must have the same
31303150
// actor isolation.
31313151
if (auto overriddenValue = value->getOverriddenDecl()) {

test/Concurrency/global_actor_inference.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,3 +552,17 @@ func acceptAsyncSendableClosureInheriting<T>(@_inheritActorContext _: @Sendable
552552
await onlyOnMainActor() // expected-warning{{no 'async' operations occur within 'await' expression}}
553553
}
554554
}
555+
556+
557+
// defer bodies inherit global actor-ness
558+
@MainActor
559+
var statefulThingy: Bool = false
560+
561+
@MainActor
562+
func useFooInADefer() -> String {
563+
defer {
564+
statefulThingy = true
565+
}
566+
567+
return "hello"
568+
}

0 commit comments

Comments
 (0)