Std. Fsm
(Cure Standard Library v0.37.2)
View Source
The structured finite-state-machine (fsm) macro surface and typed
gen_statem transition helpers.
Provides both the structured fsm and transition-table fsm ... with ...
syntax families, compile-time graph validation (reachability, duplicates,
and deadlock checks), the checked FsmAction return type, and pure
transition-table dispatch helpers.
Examples
use Std.Fsm
let table = [transition(:locked, :coin, :unlocked), transition(:unlocked, :push, :locked)]
first_state(table) # => :locked
dispatch_atom(table, :locked, :coin, 0) # => %[:next_state, :unlocked, 0]
next(:unlocked, 1) # => Next(:unlocked, 1)
Summary
Types
Checked callback result for the preferred typed FSM surface. Constructors
are ordinary Cure values; action_to_beam is the single private-shape
lowering point to the tuple vocabulary required by gen_statem.
Functions
Lower a typed FsmAction value into the raw gen_statem return tuple (BeamTerm).
Insert value into values if it is not already present.
Append an EventSpec to found if its constructor key is not already present.
Add an optional state name syntax node to found if present and not yet recorded.
Append a syntax node to found if its constructor key is not already present.
Return true if every atom in values is present in catalogue.
Return true if value appears in the atom list values.
Extract variable match patterns for each captured event parameter.
Extract the type syntax of each captured event parameter.
Return true if any non-terminal state has no outgoing edge in edges.
Return true if an unguarded edge with matching from and event exists in edges.
Project parsed transition definitions into compact GraphEdge values for validation.
Return true if state has at least one matching explicit or wildcard outgoing edge.
Return true if found contains an EventSpec with constructor key expected.
Return true if values contains a syntax node with constructor key expected.
Expand the structured fsm family into a gen_statem module.
Expand a compact transition-table fsm <name> with <data> definition after
validating event payloads, initial/terminal states, reachability, and deadlocks.
Look up (state, event) in a generic transition table and return
%[:next_state, next, data], staying in state when no row matches.
Exact encoder for atom-labelled transition tables.
Keeping it separate lets the ordinary dispatch algebra remain generic.
Return true if any two unguarded edges share the same source state and event.
Emit a gen_statem module for an atom-state structured fsm definition.
Emit a complete gen_statem module for a validated compact transition table,
including State, Event, TransitionInfo, decide/3, responds?/2,
handle_event/4, and typed start/send helpers.
Emit a gen_statem module for a typed-state structured fsm definition
whose decide/3 returns FsmAction(StateName, Data).
Build the constructor match pattern for an FSM event and its payload parameters.
Convert a list of EventSpec entries into payload-carrying enum variant declarations.
Perform one reachability expansion pass over edges, adding every target
state reachable from reachable (or via a wildcard edge).
Build responds?/2 match arms for transitions with an explicit source state.
Build decide/3 match arms for transitions with an explicit source state.
Look up an EventSpec by its constructor-key atom.
Return the first non-wildcard source state found in transitions.
Compatibility helper for the original atom-labelled transition-table
macro. Typed callers use first_state_or, whose fallback has the same
state type as the table.
Return the source state of the first transition row, or fallback when
transitions is empty.
Normalize each arm of an FSM :pattern_match body into a checked block in
ordinary source-level syntax.
Normalize a single :match_arm body by wrapping it in a :block node.
Construct the rewritten :match_arm node with its body wrapped in a block.
Map fsm_handler_arm across a list of FSM match arms.
Rewrite a :pattern_match node by normalizing every FSM event arm.
Construct a Keep(data) action that remains in the current state with updated data.
Construct a Next(state, data) action that transitions to state with data.
Return true when an Option holds Some(_), and false for None().
Unwrap an optional event payload parameter list, defaulting to [].
Extract the constructor-key atom from an optional syntax node.
Compare two lists of captured payload parameter syntax nodes for matching arity and parameter type identifiers.
At most |states| monotone passes are needed to saturate a finite graph. Recursing on the shrinking catalogue is visibly structural to the totality checker, unlike a conventional BFS whose work queue can grow.
Build a single responds?/2 match arm returning true for (state_pattern, event).
Compare two optional atoms for structural equality.
Choose the initial state: an explicit initial clause if present, or the
first explicit transition source state otherwise.
Construct a Stop(reason, data) action that terminates the state machine.
Turn a state name syntax node into a nullary constructor call expression.
Extract the :constructor_key atom attribute from a syntax node, if present.
Extract constructor-key atoms from a list of syntax nodes, skipping nodes without one.
Extract the string identifier from a Leaf syntax node, if present.
Constructor keys include arity (:Opened/0) for duplicate checking.
Public graph metadata instead preserves the identifier the author wrote.
Convert a list of state name syntax nodes into nullary enum variant declarations.
A transition row is ordinary data. The macro surface above expands rows to this checked ADT so users can compose, inspect, and transform tables with normal Cure functions.
Build a single decide/3 match arm (guarded when edge.when is present)
returning Next(target, updated_data).
Compile the table as one linear tuple match. Explicit rows are emitted before wildcard rows, which gives them precedence through ordinary pattern ordering. The previous nested state/event decision duplicated its complete fallback twice per row; moderately sized FSMs therefore produced an exponential Syntax value and exhausted computed-macro normalization.
Collect the deduplicated list of EventSpec entries referenced by transitions.
Emit the graph as ordinary generated data. Tooling and tests can inspect
exactly the rows which drive decide/3, without keeping a second table in
host code. Wildcard rows have a distinct constructor so callers cannot
accidentally mistake them for a concrete source state.
responds?/2 shares the same ordered patterns as decide/3. It answers
whether the compiled graph has a row for a state/event shape; guards are
deliberately not evaluated because they may depend on transition data.
Collect the deduplicated list of state syntax nodes referenced by transitions.
Unwrap an optional transition update expression, defaulting to data.
Validate a compact transition graph for unknown initial/terminal states, duplicate unguarded transitions, unreachable states, and deadlocks.
Verify that every occurrence of the same event name declares identical
payload parameter types, returning Some(:fsm_inconsistent_event_payload) on mismatch.
Build responds?/2 match arms for wildcard (*) transitions.
Build decide/3 match arms for wildcard (*) transitions.
Types
type AtomTransition
enum EventSpec
EventSpec
enum FsmAction
Keep
Next
Stop
Checked callback result for the preferred typed FSM surface. Constructors
are ordinary Cure values; action_to_beam is the single private-shape
lowering point to the tuple vocabulary required by gen_statem.
enum GraphEdge
GraphEdge
enum Transition
Row
Functions
fn action_to_beam(action: FsmAction(s, d)) -> BeamTerm
Lower a typed FsmAction value into the raw gen_statem return tuple (BeamTerm).
fn add_atom(value: Atom, values: List(Atom)) -> List(Atom)
Insert value into values if it is not already present.
fn add_event(event: Syntax, payload: List(Syntax), found: List(EventSpec)) -> List(EventSpec)
Append an EventSpec to found if its constructor key is not already present.
fn add_optional_syntax_name(value: Option(Syntax), found: List(Syntax)) -> List(Syntax)
Add an optional state name syntax node to found if present and not yet recorded.
fn add_syntax_name(value: Syntax, found: List(Syntax)) -> List(Syntax)
Append a syntax node to found if its constructor key is not already present.
fn all_atoms_in(values: List(Atom), catalogue: List(Atom)) -> Bool
Return true if every atom in values is present in catalogue.
fn atom_in(value: Atom, values: List(Atom)) -> Bool
Return true if value appears in the atom list values.
fn captured_parameter_patterns(parameters: List(Syntax)) -> List(Syntax)
Extract variable match patterns for each captured event parameter.
fn captured_parameter_types(parameters: List(Syntax)) -> List(Syntax)
Extract the type syntax of each captured event parameter.
fn compact_deadlock(states: List(Atom), terminals: List(Atom), edges: List(GraphEdge)) -> Bool
Return true if any non-terminal state has no outgoing edge in edges.
fn compact_edge_in(from: Option(Atom), event: Atom, edges: List(GraphEdge)) -> Bool
Return true if an unguarded edge with matching from and event exists in edges.
fn compact_edges(transitions: List(TransitionDefinitionSyntax)) -> List(GraphEdge)
Project parsed transition definitions into compact GraphEdge values for validation.
fn compact_outgoing(state: Atom, edges: List(GraphEdge)) -> Bool
Return true if state has at least one matching explicit or wildcard outgoing edge.
fn contains_event(values: List(EventSpec), expected: Atom) -> Bool
Return true if found contains an EventSpec with constructor key expected.
fn contains_syntax_name(values: List(Syntax), expected: Atom) -> Bool
Return true if values contains a syntax node with constructor key expected.
fn derive_fsm_family(name: ModuleNameSyntax, definition: FsmDefinitionSyntax) -> Syntax
Expand the structured fsm family into a gen_statem module.
The event type is a companion of the machine, so it is declared INSIDE the
generated module as Event -- the same place the transition-table emitter
puts its State/Event/Data. Declaring it beside the machine instead
would bind a name nobody wrote into the enclosing scope, and two sibling
modules each holding an fsm would collide on it.
fn derive_transition_table(name: ModuleNameSyntax, data: TypeSyntax, definition: TransitionTableDefinitionSyntax) -> Syntax
Expand a compact transition-table fsm <name> with <data> definition after
validating event payloads, initial/terminal states, reachability, and deadlocks.
fn dispatch(s: Type, e: Type, transitions: List(Transition(s, e)), state: s, event: e, data: a) -> Tuple(Atom, s, a)
Look up (state, event) in a generic transition table and return
%[:next_state, next, data], staying in state when no row matches.
fn dispatch_atom(transitions: List(Transition(Atom, Atom)), state: Atom, event: Atom, data: a) -> Tuple(Atom, Atom, a)
Exact encoder for atom-labelled transition tables.
Keeping it separate lets the ordinary dispatch algebra remain generic.
fn duplicate_compact_edge(edges: List(GraphEdge)) -> Bool
Return true if any two unguarded edges share the same source state and event.
fn emit_fsm_parts(name_syntax: Syntax, state_type: Syntax, event_declarations: List(Syntax), event_body: Syntax) -> Syntax
Emit a gen_statem module for an atom-state structured fsm definition.
fn emit_transition_table(name: Syntax, data: Syntax, initial: Syntax, states: List(Syntax), events: List(EventSpec), transitions: List(TransitionDefinitionSyntax)) -> Syntax
Emit a complete gen_statem module for a validated compact transition table,
including State, Event, TransitionInfo, decide/3, responds?/2,
handle_event/4, and typed start/send helpers.
fn emit_typed_fsm_parts(name_syntax: Syntax, data_type: Syntax, state_name_type: Syntax, initial_state: Syntax, event_declarations: List(Syntax), event_body: Syntax) -> Syntax
Emit a gen_statem module for a typed-state structured fsm definition
whose decide/3 returns FsmAction(StateName, Data).
fn event_pattern(event: Syntax, parameters: List(Syntax)) -> Syntax
Build the constructor match pattern for an FSM event and its payload parameters.
fn event_variants(values: List(EventSpec)) -> List(Syntax)
Convert a list of EventSpec entries into payload-carrying enum variant declarations.
fn exit_reason_atom(reason: ExitReason) -> Atom
fn expand_reachable(edges: List(GraphEdge), reachable: List(Atom)) -> List(Atom)
Perform one reachability expansion pass over edges, adding every target
state reachable from reachable (or via a wildcard edge).
fn explicit_response_arms(transitions: List(TransitionDefinitionSyntax)) -> List(Syntax)
Build responds?/2 match arms for transitions with an explicit source state.
fn explicit_transition_arms(transitions: List(TransitionDefinitionSyntax)) -> List(Syntax)
Build decide/3 match arms for transitions with an explicit source state.
fn find_event(values: List(EventSpec), expected: Atom) -> Option(EventSpec)
Look up an EventSpec by its constructor-key atom.
fn first_explicit_source(transitions: List(TransitionDefinitionSyntax)) -> Option(Syntax)
Return the first non-wildcard source state found in transitions.
fn first_state(transitions: List(Transition(Atom, Atom))) -> Atom
Compatibility helper for the original atom-labelled transition-table
macro. Typed callers use first_state_or, whose fallback has the same
state type as the table.
fn first_state_or(s: Type, e: Type, transitions: List(Transition(s, e)), fallback: s) -> s
Return the source state of the first transition row, or fallback when
transitions is empty.
fn fsm_handler(body: Syntax) -> Syntax
Normalize each arm of an FSM :pattern_match body into a checked block in
ordinary source-level syntax.
fn fsm_handler_arm(arm: Syntax) -> Syntax
Normalize a single :match_arm body by wrapping it in a :block node.
fn fsm_handler_arm_node(values: List(Attr), children: List(Syntax)) -> Syntax
Construct the rewritten :match_arm node with its body wrapped in a block.
fn fsm_handler_arms(arms: List(Syntax)) -> List(Syntax)
Map fsm_handler_arm across a list of FSM match arms.
fn fsm_handler_node(values: List(Attr), children: List(Syntax)) -> Syntax
Rewrite a :pattern_match node by normalizing every FSM event arm.
fn keep(s: Type, data: d) -> FsmAction(s, d)
Construct a Keep(data) action that remains in the current state with updated data.
fn next(state: s, data: d) -> FsmAction(s, d)
Construct a Next(state, data) action that transitions to state with data.
fn option_present(a: Type, value: Option(a)) -> Bool
Return true when an Option holds Some(_), and false for None().
fn optional_payload(payload: Option(List(Syntax))) -> List(Syntax)
Unwrap an optional event payload parameter list, defaulting to [].
fn optional_syntax_key(value: Option(Syntax)) -> Option(Atom)
Extract the constructor-key atom from an optional syntax node.
fn payload_types_equal(left: List(Syntax), right: List(Syntax)) -> Bool
Compare two lists of captured payload parameter syntax nodes for matching arity and parameter type identifiers.
fn reachable_atoms(fuel: List(Atom), reachable: List(Atom), edges: List(GraphEdge)) -> List(Atom)
At most |states| monotone passes are needed to saturate a finite graph. Recursing on the shrinking catalogue is visibly structural to the totality checker, unlike a conventional BFS whose work queue can grow.
fn response_arm(edge: TransitionDefinitionSyntax, state_pattern: Syntax) -> Syntax
Build a single responds?/2 match arm returning true for (state_pattern, event).
fn same_optional_atom(left: Option(Atom), right: Option(Atom)) -> Bool
Compare two optional atoms for structural equality.
fn select_initial(explicit: Option(Syntax), transitions: List(TransitionDefinitionSyntax)) -> Option(Syntax)
Choose the initial state: an explicit initial clause if present, or the
first explicit transition source state otherwise.
fn stop(s: Type, reason: ExitReason, data: d) -> FsmAction(s, d)
Construct a Stop(reason, data) action that terminates the state machine.
fn syntax_constructor(value: Syntax) -> Syntax
Turn a state name syntax node into a nullary constructor call expression.
fn syntax_key(value: Syntax) -> Option(Atom)
Extract the :constructor_key atom attribute from a syntax node, if present.
fn syntax_keys(values: List(Syntax)) -> List(Atom)
Extract constructor-key atoms from a list of syntax nodes, skipping nodes without one.
fn syntax_name(value: Syntax) -> Option(String)
Extract the string identifier from a Leaf syntax node, if present.
fn syntax_name_atom(value: Syntax) -> Option(Atom)
Constructor keys include arity (:Opened/0) for duplicate checking.
Public graph metadata instead preserves the identifier the author wrote.
fn syntax_variants(values: List(Syntax)) -> List(Syntax)
Convert a list of state name syntax nodes into nullary enum variant declarations.
fn transition(s: Type, e: Type, from: s, event: e, to: s) -> Transition(s, e)
A transition row is ordinary data. The macro surface above expands rows to this checked ADT so users can compose, inspect, and transform tables with normal Cure functions.
fn transition_arm(edge: TransitionDefinitionSyntax, state_pattern: Syntax) -> Syntax
Build a single decide/3 match arm (guarded when edge.when is present)
returning Next(target, updated_data).
fn transition_decision(transitions: List(TransitionDefinitionSyntax)) -> Syntax
Compile the table as one linear tuple match. Explicit rows are emitted before wildcard rows, which gives them precedence through ordinary pattern ordering. The previous nested state/event decision duplicated its complete fallback twice per row; moderately sized FSMs therefore produced an exponential Syntax value and exhausted computed-macro normalization.
fn transition_events(transitions: List(TransitionDefinitionSyntax), found: List(EventSpec)) -> List(EventSpec)
Collect the deduplicated list of EventSpec entries referenced by transitions.
fn transition_metadata(transitions: List(TransitionDefinitionSyntax)) -> List(Syntax)
Emit the graph as ordinary generated data. Tooling and tests can inspect
exactly the rows which drive decide/3, without keeping a second table in
host code. Wildcard rows have a distinct constructor so callers cannot
accidentally mistake them for a concrete source state.
fn transition_response_decision(transitions: List(TransitionDefinitionSyntax)) -> Syntax
responds?/2 shares the same ordered patterns as decide/3. It answers
whether the compiled graph has a row for a state/event shape; guards are
deliberately not evaluated because they may depend on transition data.
fn transition_states(transitions: List(TransitionDefinitionSyntax), found: List(Syntax)) -> List(Syntax)
Collect the deduplicated list of state syntax nodes referenced by transitions.
fn transition_update(update: Option(ExpressionSyntax)) -> Syntax
Unwrap an optional transition update expression, defaulting to data.
fn validate_compact_graph(initial: Syntax, states: List(Syntax), terminals: List(Syntax), transitions: List(TransitionDefinitionSyntax)) -> Option(Atom)
Validate a compact transition graph for unknown initial/terminal states, duplicate unguarded transitions, unreachable states, and deadlocks.
fn validate_event_payloads(transitions: List(TransitionDefinitionSyntax), found: List(EventSpec)) -> Option(Atom)
Verify that every occurrence of the same event name declares identical
payload parameter types, returning Some(:fsm_inconsistent_event_payload) on mismatch.
fn wildcard_response_arms(transitions: List(TransitionDefinitionSyntax)) -> List(Syntax)
Build responds?/2 match arms for wildcard (*) transitions.
fn wildcard_transition_arms(transitions: List(TransitionDefinitionSyntax)) -> List(Syntax)
Build decide/3 match arms for wildcard (*) transitions.