MagicStateMachines 0.1.1

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
#[cfg(not(feature = "tracing"))]
use crate::StateCopy;
#[cfg(feature = "decompose")]
use crate::{DecomposedData, DecomposedState, RecomposeError};
use crate::{Initial, StateClone, StateMachineImpl, Transition};
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
#[cfg(feature = "tracing")]
use core::panic::Location;
use core::pin::Pin;

/// A directly owned runtime implementation `T` whose compile-time state is `S`.
///
/// Without the `tracing` feature, the state marker has no runtime storage and
/// `StateOwned<T, S>` has the same size and alignment as `T`.
/// With `tracing`, the wrapper also stores a `Vec<TraceEntry>` containing the
/// transition history for this value.
///
/// `StateOwned` is the simplest storage representation. Generic implementation
/// methods usually use [`State<SOwned, T, S>`](crate::State) instead, because
/// the same method can then work for owned, boxed, pinned, shared-guard, and
/// discriminated storage. `StateOwned<T, S>` remains useful when you want the
/// direct transparent wrapper explicitly.
///
/// The state marker `S` is compile-time authority, not runtime data. A
/// transition consumes one state token and returns another:
///
/// ```ignore
/// use magicstatemachines::{StateOwned, transition};
/// use test_def::states::{Connected, Disconnected};
///
/// let disconnected: StateOwned<Connection, Disconnected> =
///     StateOwned::new(Connection::new("localhost:8080"));
/// let connected: StateOwned<Connection, Connected> = transition!(disconnected);
/// ```
///
/// When `tracing` is enabled, the same transition appends a diagnostic record.
/// The trace is historical only; it is not consulted to decide which methods
/// are callable. The compiler-enforced state remains the `S` type parameter.
///
/// ```ignore
/// let connected = transition!(disconnected);
/// let entry = &connected.trace()[0];
///
/// assert!(entry.from().type_name().ends_with("::Disconnected"));
/// assert!(entry.to().type_name().ends_with("::Connected"));
/// ```
///
/// ```ignore
/// use magicstatemachines::{State, StateOwned, SOwned, transition};
/// use test_def::states::{Connected, Disconnected};
///
/// let disconnected: StateOwned<Connection, Disconnected> =
///     StateOwned::new(Connection::new("localhost:8080"));
///
/// // Generic APIs usually spell the same owned state like this:
/// let disconnected: State<SOwned, Connection, Disconnected> =
///     State::new(Connection::new("localhost:8080"));
/// // State-specific methods are implemented on `Connection` with arbitrary
/// // self types, so they can accept this generic owned state directly.
/// let connected: State<SOwned, Connection, Connected> =
///     connection_method_that_connects(disconnected);
/// ```
///
/// State tokens are linear and shared ownership is not valid state storage:
///
/// ```compile_fail
/// use std::rc::Rc;
/// use magicstatemachines::{Initial, StateMachineImpl, StateOwned};
///
/// struct Machine;
/// struct Ready;
/// struct Runtime;
/// struct Token;
///
/// impl Initial<Ready> for Machine {}
/// impl StateMachineImpl for Runtime {
///     type Standin = Machine;
///     type Impl = Self;
///     type TransitionToken = Token;
/// }
///
/// let _: StateOwned<Rc<Runtime>, Ready> = StateOwned::new(Rc::new(Runtime));
/// ```
#[cfg_attr(not(feature = "tracing"), repr(transparent))]
pub struct StateOwned<T, S> {
    pub(crate) value: T,
    pub(crate) state: PhantomData<fn() -> S>,
    #[cfg(feature = "tracing")]
    pub(crate) trace: Vec<crate::TraceEntry>,
}

/// Owned state whose runtime value is pinned by an arbitrary pinning pointer.
///
/// This is the direct owned alias for `StateOwned<Pin<P>, S>`. In generic
/// state-machine methods prefer [`State`](crate::State) plus a storage backend
/// such as [`SPinBox`](crate::SPinBox), because that keeps the same method
/// usable for owned, boxed, pinned, and guard-backed states.
pub type SPin<T, S> = StateOwned<Pin<T>, S>;

/// A one-shot callable that completes a state transition.
#[doc(hidden)]
pub struct TransitionCall<T, From, To> {
    state: StateOwned<T, From>,
    #[cfg(feature = "tracing")]
    callsite: &'static Location<'static>,
    to: PhantomData<fn() -> To>,
}

/// Creates a callable transition requiring the definition's arguments.
///
/// This low-level function requires the implementation's private transition
/// capability. It is mainly used by generated code and crate-internal tests.
/// Implementation methods should normally use
/// [`transition!`](macro@crate::transition), which expands to the private
/// helpers generated by [`StateMachineImpl!`](macro@crate::StateMachineImpl).
///
/// The returned [`TransitionCall`] is one-shot. Calling `.call(args)` checks
/// `args` against the declaration's [`Transition::F`] signature and then
/// retags the wrapper from `S` to `Next`. With `tracing`, the callsite captured
/// here is appended to the returned state's trace.
#[must_use]
#[track_caller]
pub fn transition<T, S, Next>(
    state: StateOwned<T, S>,
    _token: T::TransitionToken,
) -> TransitionCall<T, S, Next>
where
    T: StateMachineImpl,
    T::Standin: Transition<S, Next>,
{
    TransitionCall {
        state,
        #[cfg(feature = "tracing")]
        callsite: Location::caller(),
        to: PhantomData,
    }
}

#[cfg(not(feature = "tracing"))]
impl<T, From, To> TransitionCall<T, From, To>
where
    T: StateMachineImpl,
{
    #[doc(hidden)]
    pub fn call<Args>(self, _args: Args) -> StateOwned<T, To>
    where
        T::Standin: Transition<From, To>,
        <T::Standin as Transition<From, To>>::F: crate::TransitionSignature<Args>,
    {
        StateOwned {
            value: self.state.value,
            state: PhantomData,
        }
    }
}

#[cfg(feature = "tracing")]
impl<T, From, To> TransitionCall<T, From, To>
where
    T: StateMachineImpl,
{
    #[doc(hidden)]
    pub fn call<Args>(self, _args: Args) -> StateOwned<T, To>
    where
        T::Standin: Transition<From, To>,
        <T::Standin as Transition<From, To>>::F: crate::TransitionSignature<Args>,
        From: crate::StateTrait,
        To: crate::ConcreteStateTrait,
    {
        let mut trace = self.state.trace;
        trace.push(crate::TraceEntry::new::<From, To>(self.callsite));

        StateOwned {
            value: self.state.value,
            state: PhantomData,
            trace,
        }
    }
}

impl<T, S> StateOwned<T, S> {
    /// Separates the compile-time state token from the runtime data.
    ///
    /// This is a provenance API for temporarily splitting a valid typestate
    /// value into two opaque halves. The [`DecomposedState`] half carries the
    /// authority that the value was in state `S`; the [`DecomposedData`] half
    /// carries the runtime data `T`. Both halves contain the same generated UID,
    /// and [`StateOwned::recompose`] checks that UID before it recreates a
    /// usable `StateOwned<T, S>`.
    ///
    /// This is useful when state proof and runtime data need to pass through
    /// different layers, but neither layer should be able to manufacture a new
    /// valid state by itself. The state half cannot expose or mutate `T`, and
    /// the data half cannot recreate typestate authority without the matching
    /// state half.
    ///
    /// ```
    /// use magicstatemachines::{Initial, StateMachineImpl, StateOwned};
    ///
    /// struct Machine;
    /// struct Runtime {
    ///     value: u32,
    /// }
    /// struct Ready;
    /// struct Token;
    ///
    /// impl Initial<Ready> for Machine {}
    ///
    /// impl StateMachineImpl for Runtime {
    ///     type Standin = Machine;
    ///     type Impl = Self;
    ///     type TransitionToken = Token;
    /// }
    ///
    /// let ready: StateOwned<Runtime, Ready> = StateOwned::new(Runtime { value: 7 });
    /// let (state, data) = ready.decompose();
    ///
    /// // The halves can now move through different code paths. Only the
    /// // original matching pair can be recomposed into a valid state token.
    /// let ready = StateOwned::recompose(state, data).expect("matching decomposition");
    ///
    /// assert_eq!(ready.value, 7);
    /// ```
    ///
    /// This method is available only with `decompose`. The UID generator is
    /// selected separately: `decompose-rand` uses the stable `rand` dependency,
    /// while `decompose nightly-random` uses nightly `std::random` and does not
    /// need `rand`. If `tracing` is also enabled, the trace stays with the state
    /// half and is restored by recomposition.
    #[cfg(feature = "decompose")]
    #[must_use]
    pub fn decompose(self) -> (DecomposedState<S>, DecomposedData<T>) {
        let uid = decompose_uid();

        (
            DecomposedState {
                uid,
                state: PhantomData,
                #[cfg(feature = "tracing")]
                trace: self.trace,
            },
            DecomposedData {
                uid,
                value: self.value,
            },
        )
    }

    /// Recombines state and data produced by the same [`StateOwned::decompose`] call.
    ///
    /// Recomposition restores the exact same state type `S`. After it succeeds,
    /// the returned value can be used like any other `StateOwned<T, S>`: it
    /// dereferences to `T`, can keep transitioning according to the declared
    /// state-machine contract, and, with `tracing`, continues carrying the
    /// existing trace.
    ///
    /// A mismatched UID returns [`RecomposeError`]. The check is deliberately
    /// narrow: it does not inspect `T`, and it does not infer whether two
    /// runtime values happen to be equal. It only verifies that both opaque UID
    /// halves came from the same decomposition. The UID is non-cryptographic and
    /// exists to catch accidental or invalid recombination, not malicious input.
    ///
    /// ```
    /// use magicstatemachines::{Initial, StateMachineImpl, StateOwned};
    ///
    /// struct Machine;
    /// struct Runtime;
    /// struct Ready;
    /// struct Token;
    ///
    /// impl Initial<Ready> for Machine {}
    ///
    /// impl StateMachineImpl for Runtime {
    ///     type Standin = Machine;
    ///     type Impl = Self;
    ///     type TransitionToken = Token;
    /// }
    ///
    /// let ready: StateOwned<Runtime, Ready> = StateOwned::new(Runtime);
    /// let (state, data) = ready.decompose();
    /// let ready: StateOwned<Runtime, Ready> =
    ///     StateOwned::recompose(state, data).expect("matching decomposition");
    ///
    /// let _: StateOwned<Runtime, Ready> = ready;
    /// ```
    #[cfg(feature = "decompose")]
    pub fn recompose(
        state: DecomposedState<S>,
        data: DecomposedData<T>,
    ) -> Result<Self, RecomposeError> {
        if state.uid != data.uid {
            return Err(RecomposeError);
        }

        Ok(Self {
            value: data.value,
            state: PhantomData,
            #[cfg(feature = "tracing")]
            trace: state.trace,
        })
    }

    /// Recorded transitions in call order.
    ///
    /// Each entry stores the source state, destination state, and callsite
    /// captured by the transition wrapper. This is available only with the
    /// `tracing` feature and is intended for diagnostics, not for enforcing
    /// the state machine.
    ///
    /// Cloning a traced state clones the erased state markers in every entry.
    /// The public API of each entry stays the same whether erased markers are
    /// backed by `&'static dyn StateTrait` or by the `dynZST` feature.
    #[cfg(feature = "tracing")]
    #[must_use]
    pub fn trace(&self) -> &[crate::TraceEntry] {
        &self.trace
    }
}

#[cfg(all(feature = "decompose", feature = "nightly-random"))]
fn decompose_uid() -> u64 {
    std::random::random(..)
}

#[cfg(all(
    feature = "decompose",
    not(feature = "nightly-random"),
    feature = "decompose-rand"
))]
fn decompose_uid() -> u64 {
    use rand::TryRngCore;

    rand::rngs::OsRng
        .try_next_u64()
        .expect("OS random source failed while decomposing state")
}

#[cfg(all(
    feature = "decompose",
    not(feature = "nightly-random"),
    not(feature = "decompose-rand")
))]
compile_error!(
    "feature `decompose` requires a random backend: enable `nightly-random` or `decompose-rand`"
);

impl<T, S> StateOwned<T, S>
where
    T: StateMachineImpl,
    T::Standin: Initial<S>,
{
    /// Wraps an implementation in a state declared initial by its definition.
    ///
    /// This only compiles when `T::Standin: Initial<S>`. Use transition
    /// methods generated in the implementation module to reach every later
    /// state.
    #[must_use]
    pub const fn new(value: T) -> Self {
        Self {
            value,
            state: PhantomData,
            #[cfg(feature = "tracing")]
            trace: Vec::new(),
        }
    }
}

impl<T, S> Deref for StateOwned<T, S> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T, S> DerefMut for StateOwned<T, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

impl<T, S> Clone for StateOwned<T, S>
where
    T: Clone,
    S: StateClone,
{
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            state: PhantomData,
            #[cfg(feature = "tracing")]
            trace: self.trace.clone(),
        }
    }
}

#[cfg(not(feature = "tracing"))]
impl<T, S> Copy for StateOwned<T, S>
where
    T: Copy,
    S: StateClone + StateCopy,
{
}

impl<T: core::fmt::Debug, S> core::fmt::Debug for StateOwned<T, S> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.value.fmt(formatter)
    }
}

#[cfg(not(feature = "tracing"))]
pub(super) fn complete_transition<T, From, To>(
    state: StateOwned<T, From>,
    _callsite: super::TransitionCallsite,
) -> StateOwned<T, To> {
    StateOwned {
        value: state.value,
        state: PhantomData,
    }
}

#[cfg(feature = "tracing")]
pub(super) fn complete_transition<T, From, To>(
    state: StateOwned<T, From>,
    callsite: super::TransitionCallsite,
) -> StateOwned<T, To>
where
    From: crate::StateTrait,
    To: crate::ConcreteStateTrait,
{
    let mut trace = state.trace;
    trace.push(crate::TraceEntry::new::<From, To>(callsite));

    StateOwned {
        value: state.value,
        state: PhantomData,
        trace,
    }
}