essm 0.3.0

extremely simple state machine
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
# ESSM: Extremely Simple State Machines

A compile-time typestate state machine library for Rust. States are distinct types,
transitions are trait implementations. To make states reasonable lean external managed data
can be threaded through state transitions by providing a reference to a generic context.

## Design philosophy

ESSM provides **safe state transitions** via the typestate pattern. It does NOT provide
a runtime state machine wrapper, event dispatch, or async drivers; those are the user's
domain. ESSM handles one thing: making sure you can only transition between states that
have a defined path, and that the transition hooks (invariants, guards, entry/exit checks)
execute in the correct order.

Being extremely simple applies to being the usage which is intended to be very ergonomic and safe
(wrong use is a compile error). As well as its implementation which may be surprisingly minimal.

## Intended scope

ESSM is designed for **small-to-medium sized state machines**.  Each transition pair requires
a separate trait implementation, this is the cost of compile-time type safety.

## Getting started

Add `essm` to your `Cargo.toml`, then import everything:

```rust
# #[allow(clippy::wildcard_imports)]
use essm::*;
```

This brings in [`State`], [`Transition`], [`TransitionResult`], [`TransitionInfallible`],
[`ErrorState`], [`FailedAt`], [`Primordial`], [`Terminated`], [`Infallible`],
[`InitialState`], [`InitialStateInfallible`], [`TerminalState`],
[`TerminalStateInfallible`], and all other public types in one line.

## Quick example

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
#[derive(Debug)]
struct Idle;
impl State for Idle {}

#[derive(Debug)]
struct Running;
impl State for Running {}

// Define allowed transitions
impl Transition<Running> for Idle {
    fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running> {
        Ok(Running)
    }
}

impl Transition<Idle> for Running {
    fn change(self, _ctx: &dyn Any) -> TransitionResult<Running, Idle> {
        Ok(Idle)
    }
}

let idle = Idle;
let running: Running = idle.transition();
let idle: Idle = running.transition();
```

## Bootstrap and termination

ESSM provides an optional bootstrap pattern via predefined [`Primordial`] and [`Terminated`]
pseudo states.  These make creation and destruction symetric with state transitions. Every
lifecycle event uses the same [`Transition`] pipeline.

### Creating initial states

Implement `Transition<YourState>` for [`Primordial`] to define how your first
state is created, the [`InitialState`]/[`InitialStateInfallible`] traits are automatically
implemented for any transition from `Primordial`. They define convenient constructors:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;

#[derive(Debug)]
struct Red;
impl State for Red {}

impl Transition<Red> for Primordial {
    fn change(self, _: &dyn Any) -> TransitionResult<Primordial, Red> {
        Ok(Red)
    }
}

/// This is calling InitialStateInfallible::new()
let red = Red::new();
```

### Terminating the machine

Implement `Transition<Terminated>` for the final state, then call `.terminate()`:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug)]
# struct Red;
# impl State for Red {}
# impl Transition<Red> for Primordial {
#     fn change(self, _: &dyn Any) -> TransitionResult<Primordial, Red> { Ok(Red) }
# }
# let red = Red::new();

impl Transition<Terminated> for Red {
    fn change(self, _: &dyn Any) -> TransitionResult<Red, Terminated> {
        Ok(Terminated)
    }
}

// this is calling TerminalStateInfallible::terminate()
red.terminate();
```

### Primordial and Terminated are optional

You are not required to use [`Primordial`] or [`Terminated`]. States can be
constructed directly (e.g., `let idle = Idle;`) and destroyed by simply letting
them go out of scope. This is perfectly valid and often simpler for small
state machines or ZST states.

**However**, when bypassing [`Primordial`] and [`Terminated`], you are responsible maintaining
the lifecycle contracts manually by calling the respective hooks:

- `state.enter(&ctx)` — after constructing a state
- `state.invariant()` — for validating a state
- `state.leave(&ctx)` — before destroying a state

The [`InitialState`] and [`TerminalState`] traits automate this for you.

## Data-carrying states

When a state carries data, you can move that data to the next state in `change()`:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
struct Parsing { buf: Vec<u8>, pos: usize }
impl State for Parsing {}

struct Ready { buf: Vec<u8> }
impl State for Ready {}

impl Transition<Ready> for Parsing {
    fn change(self, _ctx: &dyn Any) -> TransitionResult<Parsing, Ready> {
        Ok(Ready { buf: self.buf })
    }
}
```

### `impl Drop` on state types

Rust forbids partial moves out of `Drop`-implementing types (E0509), but
[`Transition::change`](Transition::change) consume `self` and may move data into the next
state. When you need to implement `Drop` for states, then the most universal workaround is
[`Option::take()`](Option::take):

```rust
# use essm::*;
#
#[derive(Debug)]
struct Parsing {
    buf: Option<Vec<u8>>,
    pos: usize,
}
impl State for Parsing {}

impl Drop for Parsing {
    fn drop(&mut self) {
        // Called after change() — buf is None if transition succeeded
    }
}

#[derive(Debug)]
struct Ready { buf: Vec<u8> }
impl State for Ready {}

impl Transition<Ready> for Parsing {
    fn change(mut self, _ctx: &dyn Any) -> TransitionResult<Parsing, Ready> {
        // take `buf` out of the option, leave `None` in self
        let buf = self.buf.take().unwrap();
        // self will be dropped at the end of this scope
        Ok(Ready { buf })
    }
}
#
# fn main() {
#     let parsing = Parsing { buf: Some(vec![1, 2, 3]), pos: 0 };
#     let ready: Ready = parsing.try_transition().unwrap();
#     assert_eq!(ready.buf, vec![1, 2, 3]);
#     // Drop ran on parsing (with buf: None)
# }
```

[`core::mem::take()`](core::mem::take) is an alternative for `T: Default` types
(no `Option` wrapper needed).

**External crates:** The `derive_destructure2` crate provides proc macros
(`#[derive(destructure)]`, `#[derive(remove_trait_impls)]`) that let you
destructure `Drop` types directly. The `drop-with-owned-fields` crate
offers a safe `ManuallyDrop` wrapper.

**Unsafe approach:** For zero-cost repackaging, wrap the `self` in
[`ManuallyDrop`](core::mem::ManuallyDrop), [`ptr::read`](core::ptr::read) each field, and
handle dropping of unused fields manually.

Prefer [`TerminalState`] for structured teardown or rely on Rust's automatic
drop for `Drop`-implementing fields (`Vec`, `String`, `Box`).

## Transition pipeline

Each `transition()` executes methods in a fixed order:

```text
1. self.invariant()                 : invariant check on source state integrity (no context)
2. self.leave(&ctx)                 : on-exit check
3. self.guard(&ctx)                 : pure predicate
4. let next = self.change(&ctx)     : produce next state
5. next.enter(&ctx)                 : on-entry check
6. next.invariant()                 : invariant check on target state integrity (no context)
```

All methods except for `change()` have no-op blanket implementations they only need to be
implemented when needed and are zero cost otherwise.

Call [`try_transition()`](Transition::try_transition) for the zero-argument convenience path (context is `()`).
Use [`try_transition_with()`](Transition::try_transition_with) to pass a context that threads
through the entire pipeline; hooks can use it.

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug, Default)] struct Idle; impl State for Idle {}
# #[derive(Debug, Default)] struct Running; impl State for Running {}
# impl Transition<Running> for Idle {
#     fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running> {
#         Ok(Running)
#     }
# }
let idle = Idle;
let running: Running = idle.transition();
```

With a user-defined context — set the Transition's `Ctx` type:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug, Default)] struct Idle; impl State for Idle {}
# #[derive(Debug, Default)] struct Running; impl State for Running {}
struct MyCtx { counter: u32 }
# impl Transition<Running> for Idle {
#     fn change(self, _: &dyn Any) -> TransitionResult<Idle, Running> {
#         Ok(Running)
#     }
# }
let idle = Idle;
let ctx = MyCtx { counter: 0 };
let running: Running = idle.transition_with(&ctx);
```

## Error recovery

In ESSM, errors **are** states. When a transition fails, it returns an
[`ErrorState`] which implements [`State`]. This means you can transition
FROM an error back to a valid state:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
#[derive(Debug)] enum MyError { Bad }
impl StateError for MyError {}

#[derive(Debug, Default)] struct Idle;
impl State for Idle {}

#[derive(Debug)] struct Working { should_fail: bool }
impl State for Working {}

#[derive(Debug)] struct Done;
impl State for Done {}

impl Transition<Working, MyError, Infallible> for Idle {
#     fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Working, MyError> {
#         Ok(Working { should_fail: false })
#     }
}
impl Transition<Done, MyError, Infallible> for Working {
#     fn change(self, _ctx: &dyn Any) -> TransitionResult<Working, Done, MyError> {
#         ErrorState::err_origin(MyError::Bad, self)
#     }
}

// Recover from any `ErrorState<MyError, ..>` back to Idle
impl<Origin, Next> Transition<Idle> for ErrorState<MyError, Origin, Next> {
    fn change(self, _ctx: &dyn Any) -> TransitionResult<Self, Idle> {
        Ok(Idle)
    }
}

let idle = Idle;
let working: Working = idle.try_transition().unwrap();

// Transition fails -- but the error IS a state
match working.try_transition() {
    Ok(done) => { /* success */ }
    Err(error_state) => {
        // Recover: transition from the error back to Idle
        let idle: Idle = error_state.try_transition().unwrap();
    }
}
```

On failure, `try_transition()` returns an [`ErrorState`] that carries both the
original error and a [`FailedAt`] wrapping the state that survived.
Use [`ErrorState::err_origin`], [`ErrorState::err_next`], or [`ErrorState::err`]
to construct errors from your `change()` implementation.

### Custom error types

You can define your own error types instead of using [`Infallible`]. For example,
the [vending machine example](examples/02_vending/main.rs) defines a
`VendError` enum to signal insufficient credit:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;
#[derive(Debug)]
enum VendError { NotEnoughCredit }
impl StateError for VendError {}
```

The `HasCredit → Dispensing` transition checks the credit balance and returns
`VendError::NotEnoughCredit` via [`ErrorState::err_origin`] if the balance is too low.
Because the origin state (`HasCredit`) is preserved in the [`ErrorState`], the caller
can recover by extracting it and continuing.

Custom errors should implement `StateError` which marks them convertible into itself.

### Recovery pattern

Since [`ErrorState`] implements [`State`], you can implement [`Transition`] _from_ an
[`ErrorState`] back to a valid state. Recovery can restore the original state via the
[`FailedAt::Origin`] (or [`FailedAt::Next`]) variant:

```rust
# #[allow(clippy::wildcard_imports)]
# use essm::*;

#[derive(Debug)] enum VendError { NotEnoughCredit }
impl StateError for VendError{}

#[derive(Debug)] struct HasCredit { amount: u32 }; impl State for HasCredit {}
#[derive(Debug)] struct Dispensing { item: &'static str, change: u32 }; impl State for Dispensing {}

// Recovery: ErrorState → HasCredit, restoring the original state
impl Transition<HasCredit> for ErrorState<VendError, HasCredit, Dispensing> {
    fn change(self, _ctx: &dyn Any) -> TransitionResult<Self, HasCredit> {
        match self.at {
            FailedAt::Origin(state) => Ok(state),  // restore original HasCredit
            _ => panic!("expected origin in recovery"),
        }
    }
}
```

This pattern lets you attempt a fallible transition, recover from failure by
restoring the original state, and retry with different inputs.

## Customizing transitions

The pipeline is defined by [`Transition`]'s default methods. Override the hooks, not the pipeline:

| Hook          | Trait        | Purpose                                     |
|---------------|--------------|---------------------------------------------|
| `invariant()` | `State`      | invariant check on state integrity          |
| `leave()`     | `State`      | On-exit check, immutable context            |
| `guard()`     | `Transition` | Pure predicate: is the transition allowed?  |
| `change()`    | `Transition` | Produce the next state from the current one |
| `enter()`     | `State`      | On-entry check, immutable context           |

## `no_std`

ESSM is `#![no_std]` by default.
Tests use `std` behind `#[cfg(test)]`.

## Status, Plans and Thoughts

This crate is still in development, significant/breaking changes may and will happen until
this note is removed.

* Since associated types can not have defaults we have to use generics, eventually this will
  become a breaking change where the `Error` types become associated types once defaults are
  stable.
* While the current way to have errors on states and transitions is universal, it can be less
  ergonomic to use. We need to think if we want to simplify this, eg. `State` being non
  generic, its methods returning bool. Somehow the transition then needs to synthesize a
  `Error` on failures.
* I started a declarative macro DSL for easy state transitions like:
  ```ignore
  essm!{
      state A;
      state B;
      initial A;
      transition A->B;
      terminal B;
  }
  ```
  With generics and error types this becoming pretty complicated. We need to reevaluate if
  this should be done as proc macro (using unsynn).

## LLM usage

- **Design and planning**: Completely human. Architecture decisions, API design, trait
  boundaries, and the transition pipeline are human-authored.
- **Implementation**: Hybrid. Core traits and library code are human-authored with LLM
  assistance for bootratapping. Eventually most llm code got rewritten manually
- **Contributions**: Will be judged by completeness and quality alone (test coverage,
  documentaton).
- **Documentation and examples**: Partially LLM-generated, human-reviewed. README,
  doctests, and example programs are drafted with LLM assistance and verified by
  human review.