@state
class S(MachineStateBase):
N: Param[int]
ctr: StateVar[int]
Param[T] marks a constant; StateVar[T] marks a mutable variable. The underlying Annotated[...] form is still accepted.
@action(init=True)
def init(c: Context[S]):
c.state.ctr = Val(0)
Initialisation action: sets all variables to starting values
@action(writes="*")
def step(c: Context[S]):
alts = iter(c.alternatives("up", "down"))
with next(alts): ... # up branch
with next(alts): ... # down branch
Step action: c.alternatives() declares mutually exclusive branches
c.state.x = Val(1)
Assign a variable (at most once per transition)
c.assume(condition)
Guard: prune this branch if condition is false
with c.one_of(S, "x") as x:
c.state.y = x
Non-deterministic choice from set S
(then_, else_) = c.split(condition)
Branch on a boolean condition
cached = c.cache(expr, name="cached")
Bind a reused symbolic subexpression to a fresh local name
c.state.pc[q] = Val(PC.CS)
c.state.req[p][q] = Val(0)
c.state.chan.val = d
Direct nested update — map entry, nested path, or record field (immediate)
s.x = c.old.y
s.y = c.old.x
Read the pre-state (unprimed x) with c.old: it ignores writes made so far, so this swaps correctly; s.x = s.y; s.y = s.x would not. c.old is read-only (including nested fields and entries), its reads count as the action's reads (Rule 2 still applies to @action calls), and init actions may read only parameters through it.
with c.state.editing() as upd:
upd.x = c.state.y
upd.y = c.state.x
Batch several interdependent nested updates into one assignment per field (reads see the pre-update state). To read old values, prefer c.old.
balances: StateVar[dict[str, int], UPSERT]
Mark a map field so keyed assignment inserts missing keys (insert-or-update)