Skip to content

Commit 968e64c

Browse files
committed
Add a proposal to allow nonisolated to prevent global actor inference.
1 parent 066c747 commit 968e64c

File tree

1 file changed

+291
-0
lines changed

1 file changed

+291
-0
lines changed
Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
# Allow `nonisolated` to prevent global actor inference
2+
3+
* Proposal: [SE-NNNN](NNNN-nonisolated-for-global-actor-cutoff.md)
4+
* Authors: [Sima Nerush](https://github.com/simanerush), [Holly Borla](https://github.com/hborla)
5+
* Review Manager: TBD
6+
* Status: **Implemented**
7+
* Implementation: [swiftlang/swift#76395](https://github.com/swiftlang/swift/pull/76395)
8+
* Review: ([pitch](https://forums.swift.org/t/pitch-allow-nonisolated-to-prevent-global-actor-inference/74502))
9+
10+
## Introduction
11+
12+
This proposal allows annotating a set of declarations with `nonisolated` to prevent global actor inference.
13+
14+
## Motivation
15+
16+
Global actor inference has a number of different inference sources. For example, a global actor may be inferred on a type that conforms to a protocol because the protocol is annotated with a global actor attribute:
17+
18+
```swift
19+
@MainActor
20+
protocol GloballyIsolated {}
21+
22+
struct S: GloballyIsolated {} // implicitly globally-isolated
23+
```
24+
25+
In the above code, the struct `S` is inferring the global actor isolation from the explicitly globally-isolated protocol `GloballyIsolated` which it conforms to. While this code is straightforward, the conformance list can quickly get long, and global actor isolation can be inferred through a chain of protocol refinements or superclasses. It can become difficult for a programmer to understand where the global isolation is being inferred from on a given type.
26+
27+
While it is safe for a type with nonisolated methods to conform to a protocol marked with a global actor attribute, sometimes the programmer may want their type to be nonisolated. However, it is challenging to stop global actor inference from happening altogether. Programmers can annotate individual functions with the `nonisolated` keyword, but there is no straightforward way to prevent global actor inference on a type.
28+
29+
Currently, there are two common ways a programmer can “cut-off” the global actor inference from happening on a type when inference comes from a conformance. The first way is to conform to a protocol that causes global isolation to be inferred in an extension, and then marking all of its required properties and methods as `nonisolated`:
30+
31+
```swift
32+
@MainActor
33+
protocol P {
34+
var x: Int { get }
35+
}
36+
37+
struct S {}
38+
39+
extension S: P {
40+
nonisolated var x: Int {
41+
get { 1 }
42+
}
43+
nonisolated func test() {
44+
print(x)
45+
}
46+
}
47+
```
48+
49+
In the above code, `S` can still conform to the globally-isolated protocol `P` without inferring the isolation, but this comes at a cost of the programmer having to manually annotate each protocol requirement with `nonisolated`.
50+
51+
However, the above method would not work for cutting off the global isolation inference on a protocol itself. There is a very nonobvious workaround: when the compiler is inferring global actor isolation, if there are multiple inference sources with conflicting global actors, no global actor is inferred. This is demonstrated by the following example:
52+
53+
```swift
54+
class FakeExecutor: FakeGlobalActor {
55+
static let shared: FakeExecutor = .init()
56+
57+
func enqueue(_ job: consuming ExecutorJob) {
58+
fatalError()
59+
}
60+
}
61+
62+
@globalActor
63+
public actor FakeGlobalActor: Sendable {
64+
public static var shared = FakeGlobalActor()
65+
66+
private init() {}
67+
public nonisolated var unownedExecutor: UnownedSerialExecutor {
68+
FakeGlobalActor.shared.asUnownedSerialExecutor()
69+
}
70+
}
71+
72+
@MainActor
73+
protocol GloballyIsolated {}
74+
75+
@FakeGlobalActor
76+
protocol RemoveGlobalActor
77+
78+
protocol RefinedProtocol: GloballyIsolated, RemoveGlobalActor {} // 'RefinedProtocol' is non-isolated
79+
```
80+
81+
In the above code, the programmer creates a new protocol that is isolated to an actor that nominally is isolated to the global actor. This means that the protocol declaration `RefinedProtocol` refining the `RemoveGlobalActor` protocol will result in a conflicting global actor isolation, one from `GloballyIsolated` that’s isolated to `@MainActor`, and another one from `RemoveGlobalActor` that’s isolated to the `@FakeGlobalActor`. This results in the overall declaration having no global actor isolation, while still refining the protocols it conformed to.
82+
83+
84+
## Proposed solution
85+
86+
We propose to allow explicitly writing `nonisolated` on all type and protocol declarations for opting out of the global isolation inference:
87+
88+
```swift
89+
nonisolated struct S: GloballyIsolated, NonIsolatedProto {} // 'S' won't inherit isolation from 'GloballyIsolated' protocol
90+
```
91+
92+
In the above code, the programmer cuts off the global actor inference coming from the `GloballyIsolated` protocol for the struct `S`. Now, the workaround where the programmer had to write an additional protocol with global actor isolation is no longer needed.
93+
94+
```swift
95+
nonisolated protocol P: GloballyIsolated {} // 'P' won't inherit isolation of 'GloballyIsolated' protocol
96+
```
97+
98+
And in the above code, the protocol `P` refines the `GloballyIsolated` protocol. Because `nonisolated` is applied to it, the global actor isolation coming from the `GloballyIsolated` protocol will not be inferred for protocol `P`.
99+
100+
## Detailed design
101+
102+
Today, there are a number of places where `nonisolated` can be written, as proposed in [SE-0313: Improved control over actor isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0313-actor-isolation-control.md#non-isolated-declarations):
103+
104+
* Functions
105+
* Stored properties of classes that are `let` and `Sendable`
106+
107+
Additionally, under [SE-0434: Usability of global-actor-isolated types](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0434-global-actor-isolated-types-usability.md), `nonisolated` is allowed to be written on mutable `Sendable` storage of globally-isolated value types.
108+
109+
In this proposal, we expand the above rules by allowing annotating the declarations listed below with `nonisolated`.
110+
111+
### 1. Protocols
112+
113+
This proposal allows `nonisolated` attribute to be applied on protocol declarations:
114+
115+
```swift
116+
nonisolated protocol Refined: GloballyIsolated {}
117+
118+
struct A: Refined {
119+
var x: NonSendable
120+
nonisolated func printX() {
121+
print(x) // okay, 'x' is non-isolated
122+
}
123+
}
124+
```
125+
126+
In the above code, the protocol `Refined` is refining the `GloballyIsolated` protocol, but is declared non-isolated. This means that the `Refined` still has the same requirements as `GloballyIsolated`, but they are not isolated. Therefore, a struct `A` conforming to it is also non-isolated, which allows the programmer for more flexibility when implementing the requirements of a protocol.
127+
128+
### 2. Extensions
129+
130+
This proposal allows for `nonisolated` attribute to be applied on extension declarations:
131+
132+
```swift
133+
nonisolated extension GloballyIsolated {
134+
var x: NonSendable { .init() }
135+
func implicitlyNonisolated() {}
136+
}
137+
138+
struct C: GloballyIsolated {
139+
nonisolated func explicitlyNonisolated() {
140+
let _ = x // okay
141+
implicitlyNonisolated() // okay
142+
}
143+
}
144+
```
145+
146+
In the code above, the `nonisolated` attribute is applied to an extension declaration for a `GloballyIsolated` protocol. When applied to an extension, `nonisolated` applies to all of its members. In this case, `implicitlyNonisolated` method and the computed property `x` are both nonisolated, and therefore are able to be accessed from a nonisolated context in the body of `explicitlyNonisolated` method of a globally-isolated struct `C`.
147+
148+
### 3. Stored properties of non-`Sendable` types
149+
150+
Currently, any stored property of a non-`Sendable` type is implicitly treated as non-isolated. This proposal allows for spelling of this behavior:
151+
152+
```swift
153+
class MyClass {
154+
nonisolated var x: NonSendable = NonSendable() // okay
155+
}
156+
```
157+
158+
Because `MyClass` is does not conform to `Sendable`, the compiler guarantees mutually exclusive access to references of `MyClass` instance. `nonisolated` on methods and properties of non-`Sendable` types can be safely called from any isolation domain because the base instance can only be accessed by one isolation domain at a time.
159+
160+
### 4. Mutable `Sendable` storage of `Sendable` value types
161+
162+
For global-actor-isolated value types, [SE-0434: Usability of global-actor-isolated types](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0434-global-actor-isolated-types-usability.md) allows accessing `var` stored properties with `Sendable` type from within the module as `nonisolated`. This proposal extends this rule to **all** `Sendable` value types:
163+
164+
```swift
165+
struct S {
166+
nonisolated var x: Int // okay
167+
}
168+
```
169+
170+
In the above code, the value type `S` is implicitly `Sendable` because its storage `x` is of `Sendable` type `Int`. When `Sendable` value types are passed between isolation domains, each isolation domain has an independent copy of the value. Accessing stored properties of a value type from across isolation domains is safe as long as the stored property type is also `Sendable`. Even if the stored property is a `var`, assigning to the property will not risk a data race, because the assignment cannot have effects on copies in other isolation domains. Therefore, synchronized access to `x` in the example above is safe.
171+
172+
### 5. Classes, structs, and enums
173+
174+
Finally, we propose allowing writing `nonisolated` on class, struct and enum declarations:
175+
176+
```swift
177+
nonisolated class K: GloballyIsolated {
178+
var x: NonSendable
179+
init(x: NonSendable) {
180+
self.x = x // okay, 'x' is non-isolated
181+
}
182+
}
183+
184+
nonisolated struct S: GloballyIsolated {
185+
var x: NonSendable
186+
init(x: NonSendable) {
187+
self.x = x // okay, 'x' is non-isolated
188+
}
189+
}
190+
191+
nonisolated enum E: GloballyIsolated {
192+
func implicitlyNonisolated() {}
193+
init() {}
194+
}
195+
196+
struct TestEnum {
197+
nonisolated func call() {
198+
E().implicitlyNonisolated() // okay
199+
}
200+
}
201+
```
202+
203+
In all the above declarations, the `nonisolated` attribute propagates to all of their members, therefore making them accessible from a non-isolated context.
204+
205+
Importantly, types nested inside of explicitly `nonisolated` declarations still infer actor isolation from their own conformance lists:
206+
207+
```swift
208+
nonisolated struct S: GloballyIsolated {
209+
var value: NotSendable // 'value' is not isolated
210+
struct Nested: GloballyIsolated {} // 'Nested' is still @MainActor-isolated
211+
}
212+
```
213+
214+
The above behavior is semantically consistent with the existing rules around global isolation inference for members of a type:
215+
216+
```swift
217+
@MainActor struct S {
218+
var value: NotSendable // globally-isolated
219+
struct Nested {} // 'Nested' is not @MainActor-isolated
220+
}
221+
```
222+
223+
### Restrictions
224+
225+
Additionally, we propose the following set of rules for when the `nonisolated` attribute **cannot** be applied:
226+
227+
* Along with some other isolation such as a global actor or an isolated parameter:
228+
229+
```swift
230+
@MainActor
231+
nonisolated struct Conflict {} // error: 'struct 'Conflict' has multiple actor-isolation attributes ('nonisolated' and 'MainActor')'
232+
```
233+
234+
* On a property of a `Sendable` type when the type of the property does not conform to `Sendable`:
235+
236+
```swift
237+
@MainActor
238+
struct InvalidStruct /* implicitly Sendable */ {
239+
nonisolated let test: NonSendable // error: 'nonisolated' can not be applied to variable with non-'Sendable' type 'NonSendable
240+
}
241+
```
242+
243+
* On a property of a `Sendable` class when the property is a var:
244+
245+
```swift
246+
@MainActor
247+
final class InvalidClass /* implicitly Sendable */ {
248+
nonisolated var test: Int = 1 // error: 'nonisolated' cannot be applied to mutable stored properties
249+
}
250+
```
251+
252+
## Source compatibility
253+
254+
None, this is an additive change to the concurrency model.
255+
256+
## ABI compatibility
257+
258+
None, this proposal does not affect any existing inference rules of the concurrency model.
259+
260+
## Implications on adoption
261+
262+
Consider the following code:
263+
264+
```swift
265+
class C: GloballyIsolated {}
266+
```
267+
268+
`C` currently has an implicit conformance to `Sendable` based on `@MainActor`-inference. Let’s consider what happens when `nonisolated` is adopted for `C`:
269+
270+
```swift
271+
nonisolated class C: GloballyIsolated
272+
```
273+
274+
Now, `C` is no longer implicitly `Sendable`, since the global actor inference is cut off. This can break source compatibility for clients who have relied on the `Sendable` capability of `C`.
275+
276+
## Alternatives considered
277+
278+
### Allowing `nonisolated` on individual types and protocols in the conformance list
279+
280+
Allowing `nonisolated` on individual types and protocols in the conformance list would allow the programmer to opt-out of the global isolation inference from just one or more protocols or types:
281+
282+
```swift
283+
@MyActor
284+
protocol MyActorIsolated {}
285+
286+
struct S: nonisolated GloballyIsolated, MyActorIsolated {} // 'S' is isolated to 'MyActor'
287+
```
288+
289+
In the above code, by selectively applying `nonisolated`, the programmer is able to avoid global actor inference happening from just one of these protocols, meaning the struct `S` can retain isolation, in this case, to `MyActor`.
290+
291+
However, this approach is too cumbersome — the programmer is always able to explicitly specify isolation they want on the type. It also becomes harder to opt-out from any inference from happening, as in the extreme case, the `nonisolated` keyword would have to be applied to every single type or protocol in the conformance list.

0 commit comments

Comments
 (0)