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:
#
use *;
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
#
# use *;
;
;
// Define allowed transitions
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:
#
# use *;
;
/// This is calling InitialStateInfallible::new()
let red = new;
Terminating the machine
Implement Transition<Terminated> for the final state, then call .terminate():
#
# use *;
#
# ;
#
#
# let red = new;
// 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 statestate.invariant()— for validating a statestate.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():
#
# use *;
impl Drop on state types
Rust forbids partial moves out of Drop-implementing types (E0509), but
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():
# use *;
#
#
#
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, 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:
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() for the zero-argument convenience path (context is ()).
Use try_transition_with() to pass a context that threads
through the entire pipeline; hooks can use it.
#
# use *;
# ;
# ;
#
let idle = Idle;
let running: Running = idle.transition;
With a user-defined context — set the Transition's Ctx type:
#
# use *;
# ;
# ;
#
let idle = Idle;
let ctx = MyCtx ;
let running: Running = idle.transition_with;
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:
#
# use *;
;
;
// Recover from any `ErrorState<MyError, ..>` back to Idle
let idle = Idle;
let working: Working = idle.try_transition.unwrap;
// Transition fails -- but the error IS a state
match working.try_transition
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 defines a
VendError enum to signal insufficient credit:
#
# use *;
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:
#
# use *;
;
;
// Recovery: ErrorState → HasCredit, restoring the original state
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
Errortypes 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.
Statebeing non generic, its methods returning bool. Somehow the transition then needs to synthesize aErroron failures. - I started a declarative macro DSL for easy state transitions like:
With generics and error types this becoming pretty complicated. We need to reevaluate if this should be done as proc macro (using unsynn).essm!{ state A; state B; initial A; transition A->B; terminal B; }
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.