MagicStateMachines 0.1.2

Ergonomic typestate wrappers for compiler-enforced state machines with separable contracts
Documentation
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
mod guard;
mod storage;
#[cfg(feature = "alloc")]
mod weak;

use crate::{
    Initial, RuntimeStateMarker, SOwned, State, StateMachineImpl, StateMarker,
    StateRuntimeMarkerFor, StateTrait, state_trait,
};
#[cfg(feature = "alloc")]
use alloc::rc::Rc;
#[cfg(feature = "alloc")]
use alloc::sync::Arc;
use core::marker::PhantomData;

pub use guard::{
    SharedBorrowState, StateMut, StateMutTransitionCall, StateRef, StorageStateMut,
    StorageStateRef, transition_mut,
};
#[cfg(feature = "std")]
pub use storage::{MutexStorage, RwLockStorage};
pub use storage::{
    RefCellStorage, SharedStateError, SharedStorage, SharedStorageView, SharedValue,
    WrongStateError,
};
#[cfg(feature = "alloc")]
pub use weak::{WeakSArc, WeakSRc, WeakSRcRefCell};
#[cfg(feature = "std")]
pub use weak::{WeakSArcMutex, WeakSArcRwLock};

/// Direct erased-state storage without a runtime borrow checker.
///
/// `DynState<T>` owns `T` together with an erased runtime state marker. Unlike
/// [`SRcRefCell`], it is not an aliasing container and does not perform
/// dynamic borrow checks. Immutable views require `&self`; mutable views require
/// `&mut self`, so Rust's ordinary borrowing rules provide exclusivity.
///
/// This is useful when code needs a runtime-erased state boundary but does not
/// need shared ownership or interior mutability. Borrowing checks the erased
/// state marker, then returns the same `StorageStateRef`/`StorageStateMut`
/// based views used by the shared container APIs.
pub struct DynState<T> {
    value: SharedValue<T>,
}

/// Storage marker used by [`DynState`] views.
pub struct DynStorage;

impl SharedStorageView for DynStorage {
    type Storage<T> = SharedValue<T>;
    type ReadGuard<'a, T>
        = &'a SharedValue<T>
    where
        T: 'a;
    type WriteGuard<'a, T>
        = &'a mut SharedValue<T>
    where
        T: 'a;
}

impl<T> DynState<T>
where
    T: StateMachineImpl,
{
    /// Creates direct erased-state storage from a runtime value in an initial state.
    #[must_use]
    pub fn new<State>(value: T) -> Self
    where
        T::Standin: Initial<State>,
        State: crate::ConcreteStateTrait,
    {
        Self {
            value: SharedValue {
                state: state_trait::erased_state::<State>(),
                value,
            },
        }
    }

    /// Moves an owned state token into direct erased-state storage.
    #[must_use]
    pub fn from_state<StateMarker>(state: State<SOwned, T, StateMarker>) -> Self
    where
        StateMarker: crate::ConcreteStateTrait,
    {
        Self {
            value: SharedValue {
                state: state_trait::erased_state::<StateMarker>(),
                value: state.inner.value,
            },
        }
    }

    /// Borrows a read-only typed view if the erased state matches.
    pub fn borrow<RequestedState>(
        &self,
    ) -> Result<
        SRefView<'_, DynStorage, T, RuntimeStateMarker<RequestedState>>,
        SharedStateError<core::convert::Infallible>,
    >
    where
        RequestedState:
            StateTrait + StateMarker + StateRuntimeMarkerFor<<RequestedState as StateMarker>::Kind>,
        RuntimeStateMarker<RequestedState>: SharedBorrowState,
    {
        StateRef::from_guard(&self.value).map(State::from_inner)
    }

    /// Borrows a mutable typed view if the erased state matches.
    ///
    /// The returned guard commits its final state back into this `DynState`
    /// when dropped. No runtime borrow checker is involved because creating the
    /// guard requires `&mut self`.
    pub fn borrow_mut<RequestedState>(
        &mut self,
    ) -> Result<
        SMutView<'_, DynStorage, T, RuntimeStateMarker<RequestedState>>,
        SharedStateError<core::convert::Infallible>,
    >
    where
        RequestedState:
            StateTrait + StateMarker + StateRuntimeMarkerFor<<RequestedState as StateMarker>::Kind>,
        RuntimeStateMarker<RequestedState>: SharedBorrowState,
    {
        StateMut::from_guard(&mut self.value).map(State::from_inner)
    }
}

/// Shared state using an explicit, replaceable storage backend.
///
/// `SharedState` is the runtime boundary for this library. Owned state tokens
/// carry their current state only in the type system. Shared containers such
/// as `Rc<RefCell<_>>`, `Arc<Mutex<_>>`, and `Arc<RwLock<_>>` need one
/// authoritative runtime marker because aliases can request typed views at
/// different times.
///
/// A borrow checks that runtime marker first. After the check succeeds, the
/// returned value is again a statically typed `State` view, so ordinary
/// read-only state-machine methods regain compile-time guarantees:
///
/// ```ignore
/// use magicstatemachines::{SArcMutex, transition};
/// use test_def::{Online, states::{Connected, Disconnected}};
///
/// let shared = SArcMutex::<Connection>::new::<Disconnected>(
///     Connection::new("localhost:8080"),
/// );
///
/// {
///     let disconnected = shared.borrow_mut::<Disconnected>()?;
///     let connected = transition!(disconnected);
///     drop(connected); // commits `Connected` back to the shared container.
/// }
///
/// let connected = shared.borrow::<Connected>()?;
/// let online = shared.borrow::<Online>()?;
/// ```
///
/// The storage backend is an explicit type parameter. The built-in aliases
/// cover the common cases:
///
/// - [`SRcRefCell<T>`] for single-threaded shared mutable state;
/// - [`SArcMutex<T>`] for shared state protected by `std::sync::Mutex`;
/// - [`SArcRwLock<T>`] for shared state protected by `std::sync::RwLock`;
/// - [`SRc<Storage, T>`] and [`SArc<Storage, T>`] when you provide a custom
///   [`SharedStorage`] implementation.
///
/// Union markers can be borrowed, but cannot be stored as the committed runtime state:
///
/// ```compile_fail
/// use magicstatemachines::{SArcMutex, StateMachineDefinition, StateMachineImpl, States};
///
/// struct Machine;
/// struct Standin;
///
/// States! {
///     A;
///     B;
/// }
///
/// StateMachineDefinition! {
///     for Standin;
///
///     pub Initial: A;
///     transition A => B();
///     union Any: A | B;
/// }
///
/// StateMachineImpl! {
///     Machine: Standin;
///
///     transition A => B();
/// }
///
/// let _state = SArcMutex::<Machine>::new::<Any>(Machine);
/// ```
pub struct SharedState<P, S, T>
where
    S: SharedStorage,
{
    pub(super) storage: P,
    pub(super) backend: PhantomData<fn() -> S>,
    pub(super) value: PhantomData<fn() -> T>,
}

impl<P: Clone, S: SharedStorage, T> Clone for SharedState<P, S, T> {
    fn clone(&self) -> Self {
        Self {
            storage: self.storage.clone(),
            backend: PhantomData,
            value: PhantomData,
        }
    }
}

impl<P, Backend, T> SharedState<P, Backend, T>
where
    Backend: SharedStorage,
    P: From<Backend::Storage<T>> + AsRef<Backend::Storage<T>>,
    T: StateMachineImpl,
{
    /// Creates shared state from a runtime value in an allowed initial state.
    ///
    /// `State` must be a concrete initial state declared by the definition
    /// crate. Union markers are intentionally rejected as committed storage
    /// states; they can be borrowed as views after a concrete state is stored.
    ///
    /// ```ignore
    /// let shared = SArcMutex::<Connection>::new::<Disconnected>(
    ///     Connection::new("localhost:8080"),
    /// );
    /// ```
    #[must_use]
    pub fn new<State>(value: T) -> Self
    where
        T::Standin: Initial<State>,
        State: crate::ConcreteStateTrait,
    {
        Self {
            storage: P::from(Backend::new(SharedValue {
                state: state_trait::erased_state::<State>(),
                value,
            })),
            backend: PhantomData,
            value: PhantomData,
        }
    }

    /// Moves an owned state token into shared storage without changing state.
    ///
    /// This is the shared-storage counterpart to putting an already-created
    /// [`State`] into `Rc`, `Arc`, or another container. The committed runtime
    /// marker is taken from the concrete state token.
    ///
    /// ```ignore
    /// let disconnected: State<SOwned, Connection, Disconnected> =
    ///     State::new(Connection::new("localhost:8080"));
    /// let shared = SArcMutex::<Connection>::from_state(disconnected);
    /// ```
    #[must_use]
    pub fn from_state<StateMarker>(state: State<SOwned, T, StateMarker>) -> Self
    where
        StateMarker: crate::ConcreteStateTrait,
    {
        Self {
            storage: P::from(Backend::new(SharedValue {
                state: state_trait::erased_state::<StateMarker>(),
                value: state.inner.value,
            })),
            backend: PhantomData,
            value: PhantomData,
        }
    }

    /// Borrows the runtime value if the committed state matches `RequestedState`.
    ///
    /// `RequestedState` may be a concrete state or a generated union marker.
    /// Concrete borrows require the exact committed state. Union borrows
    /// succeed when the committed concrete state is a member of that union.
    /// Errors distinguish "the container could not be borrowed/locked" from
    /// "the borrow succeeded but the state was wrong":
    ///
    /// ```ignore
    /// let connected = shared.borrow::<Connected>()?;
    /// let online = shared.borrow::<Online>()?;
    ///
    /// match shared.borrow::<Authenticated>() {
    ///     Err(magicstatemachines::SharedStateError::WrongState(error)) => {
    ///         eprintln!("{error}");
    ///     }
    ///     other => { /* storage errors and success are handled separately */ }
    /// }
    /// ```
    pub fn borrow<RequestedState>(
        &self,
    ) -> Result<
        SRefView<'_, Backend, T, RuntimeStateMarker<RequestedState>>,
        SharedStateError<Backend::ReadError<'_, T>>,
    >
    where
        RequestedState:
            StateTrait + StateMarker + StateRuntimeMarkerFor<<RequestedState as StateMarker>::Kind>,
        RuntimeStateMarker<RequestedState>: SharedBorrowState,
    {
        let guard = Backend::read(self.storage.as_ref()).map_err(SharedStateError::Storage)?;
        StateRef::from_guard(guard).map(State::from_inner)
    }

    /// Mutably borrows the runtime value and tracks the guard's final state.
    ///
    /// When the returned guard is dropped, the shared container is updated to
    /// the guard's pending state. This allows methods on `State<SMutView<...>>`
    /// to retain compile-time transition checks while the committed state is
    /// stored at runtime.
    ///
    /// ```ignore
    /// {
    ///     let connected = shared.borrow_mut::<Connected>()?;
    ///     let authenticated = transition!(connected, "alice".to_owned());
    ///     drop(authenticated); // commits `Authenticated`.
    /// }
    ///
    /// let authenticated = shared.borrow::<Authenticated>()?;
    /// ```
    pub fn borrow_mut<RequestedState>(
        &self,
    ) -> Result<
        SMutView<'_, Backend, T, RuntimeStateMarker<RequestedState>>,
        SharedStateError<Backend::WriteError<'_, T>>,
    >
    where
        RequestedState:
            StateTrait + StateMarker + StateRuntimeMarkerFor<<RequestedState as StateMarker>::Kind>,
        RuntimeStateMarker<RequestedState>: SharedBorrowState,
    {
        let guard = Backend::write(self.storage.as_ref()).map_err(SharedStateError::Storage)?;
        StateMut::from_guard(guard).map(State::from_inner)
    }
}

/// Shared state backed by `Rc<Storage::Storage<T>>`.
///
/// Use this alias when you want single-threaded aliasing but want to choose
/// the synchronization cell yourself. The first type parameter is the
/// [`SharedStorage`] backend, not the actual `Rc` payload:
///
/// ```ignore
/// use magicstatemachines::{RefCellStorage, SRc};
///
/// let shared: SRc<RefCellStorage, Connection> =
///     SRc::new::<Disconnected>(Connection::new("localhost:8080"));
/// ```
///
/// Most code should use [`SRcRefCell`] unless it is intentionally exercising a
/// custom backend.
#[cfg(feature = "alloc")]
pub type SRc<Storage, T> = SharedState<Rc<<Storage as SharedStorageView>::Storage<T>>, Storage, T>;
#[cfg(feature = "alloc")]
/// Shared state backed by `Arc<Storage::Storage<T>>`.
///
/// This is the thread-safe counterpart to [`SRc`]. It is useful when the
/// backend is selected by a public type alias or a generic parameter:
///
/// ```ignore
/// use magicstatemachines::{MutexStorage, SArc};
///
/// type SharedConnection = SArc<MutexStorage, Connection>;
///
/// let shared = SharedConnection::new::<Disconnected>(
///     Connection::new("localhost:8080"),
/// );
/// ```
///
/// Use [`SArcMutex`] or [`SArcRwLock`] for the built-in backends when no
/// custom storage choice is needed.
pub type SArc<Storage, T> =
    SharedState<Arc<<Storage as SharedStorageView>::Storage<T>>, Storage, T>;
#[cfg(feature = "alloc")]
/// Shared state backed by `Rc<RefCell<...>>`.
///
/// This is the default single-threaded shared-state container. It preserves
/// the native `RefCell` error behavior: borrowing mutably while an immutable
/// borrow is alive returns [`SharedStateError::Storage`] containing
/// `std::cell::BorrowMutError`; asking for a state that is not committed
/// returns [`SharedStateError::WrongState`].
pub type SRcRefCell<T> = SRc<RefCellStorage, T>;
#[cfg(feature = "std")]
/// Shared state backed by `Arc<Mutex<...>>`.
///
/// `borrow` and `borrow_mut` both acquire the mutex with `try_lock`, so a
/// concurrent borrow reports the standard `TryLockError` through
/// [`SharedStateError::Storage`] instead of blocking the caller.
pub type SArcMutex<T> = SArc<MutexStorage, T>;
#[cfg(feature = "std")]
/// Shared state backed by `Arc<RwLock<...>>`.
///
/// Immutable borrows use `try_read` and can coexist with other immutable
/// borrows. Mutable borrows use `try_write` and fail with the backend's
/// `TryLockError` while readers or another writer are alive.
pub type SArcRwLock<T> = SArc<RwLockStorage, T>;
/// Mutable-guard storage backend for [`RefCellStorage`].
///
/// This is the `Storage` parameter of a state returned by
/// [`SRcRefCell::borrow_mut`]. It is useful in signatures when a method wants
/// to specifically accept a `RefCell` guard rather than any [`crate::SMut`]
/// storage:
///
/// ```ignore
/// fn only_ref_cell_guard(
///     state: magicstatemachines::State<
///         magicstatemachines::SRefCell<'_>,
///         Connection,
///         Connected,
///     >,
/// ) {
///     drop(state);
/// }
/// ```
///
/// State-machine implementation methods usually prefer `S: SMut` so they also
/// work with owned, boxed, mutex, and custom storage.
pub type SRefCell<'a> = StorageStateMut<'a, RefCellStorage>;
#[cfg(feature = "std")]
/// Mutable-guard storage backend for [`MutexStorage`].
///
/// This is the concrete guard storage used by [`SArcMutex::borrow_mut`].
/// Prefer a generic `S: SMut` bound unless you intentionally need to restrict
/// a function to mutex-backed shared state.
pub type SMutex<'a> = StorageStateMut<'a, MutexStorage>;
#[cfg(feature = "std")]
/// Mutable-guard storage backend for [`RwLockStorage`].
///
/// This is the concrete guard storage used by [`SArcRwLock::borrow_mut`].
/// It represents an active write guard whose final typestate will be committed
/// back to the `RwLock` when the returned [`State`] is dropped.
pub type SRwLock<'a> = StorageStateMut<'a, RwLockStorage>;
/// State view held by a mutable guard from a shared storage backend.
///
/// The alias is mainly documentation for return types. For example,
/// `SArcMutex<T>::borrow_mut::<Connected>()` returns an
/// `SMutView<'_, MutexStorage, T, Connected>`. In user-facing methods, prefer
/// the shorter arbitrary-self receiver form:
///
/// ```ignore
/// fn authenticate<S>(
///     self: magicstatemachines::State<S, Self, Connected>,
///     user: String,
/// ) -> magicstatemachines::State<S, Self, Authenticated>
/// where
///     S: magicstatemachines::SMut,
/// {
///     magicstatemachines::transition!(self, user)
/// }
/// ```
pub type SMutView<'a, Backend, T, S> = State<StorageStateMut<'a, Backend>, T, S>;
/// State view held by an immutable guard from a shared storage backend.
///
/// This is the return type of [`SharedState::borrow`]. It implements [`SRef`](crate::SRef)
/// but not [`SMut`](crate::SMut), so it supports read-only arbitrary-self
/// receivers such as `self: &State<impl SRef, Self, impl InOnline>` while
/// preventing generated transitions from completing.
pub type SRefView<'a, Backend, T, S> = State<StorageStateRef<'a, Backend>, T, S>;