{"id":13671760,"url":"https://github.com/mdeloof/statig","last_synced_at":"2025-04-27T18:31:39.768Z","repository":{"id":38264195,"uuid":"398071324","full_name":"mdeloof/statig","owner":"mdeloof","description":"Hierarchical state machines for designing event-driven systems","archived":false,"fork":false,"pushed_at":"2025-03-29T11:06:08.000Z","size":321,"stargazers_count":640,"open_issues_count":16,"forks_count":25,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-03-29T11:32:25.891Z","etag":null,"topics":["embedded","finite-state-machine","fsm","hierarchical-state-machine","hsm","no-std","rust","state-machine","statechart"],"latest_commit_sha":null,"homepage":"https://crates.io/crates/statig","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mdeloof.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-08-19T20:51:31.000Z","updated_at":"2025-03-29T10:52:08.000Z","dependencies_parsed_at":"2023-12-22T12:24:30.047Z","dependency_job_id":"ec27a8ff-b06e-4e87-a618-044bdf950263","html_url":"https://github.com/mdeloof/statig","commit_stats":{"total_commits":134,"total_committers":5,"mean_commits":26.8,"dds":0.09701492537313428,"last_synced_commit":"4cb00ce305713e30b690a790d79463c3bd75649e"},"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mdeloof%2Fstatig","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mdeloof%2Fstatig/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mdeloof%2Fstatig/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mdeloof%2Fstatig/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mdeloof","download_url":"https://codeload.github.com/mdeloof/statig/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251187269,"owners_count":21549613,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["embedded","finite-state-machine","fsm","hierarchical-state-machine","hsm","no-std","rust","state-machine","statechart"],"created_at":"2024-08-02T09:01:17.966Z","updated_at":"2025-04-27T18:31:39.748Z","avatar_url":"https://github.com/mdeloof.png","language":"Rust","funding_links":[],"categories":["Rust"],"sub_categories":[],"readme":"# statig\n\n[![Current crates.io version](https://img.shields.io/crates/v/statig.svg)](https://crates.io/crates/statig)\n[![Documentation](https://docs.rs/statig/badge.svg)](https://docs.rs/statig)\n[![Rust version](https://img.shields.io/badge/Rust-1.65.0-blue)](https://releases.rs/docs/released/1.65.0)\n[![CI](https://github.com/mdeloof/statig/actions/workflows/ci.yml/badge.svg)](https://github.com/mdeloof/statig/actions/workflows/ci.yml)\n\n\nHierarchical state machines for designing event-driven systems.\n\n**Features**\n\n- Hierachical state machines\n- State-local storage\n- Compatible with `#![no_std]`, state machines are defined in ROM and no heap memory allocations.\n- (Optional) macro's for reducing boilerplate.\n- Support for generics.\n- Support for async actions and handlers (only on `std`).\n\n---\n\n**Overview**\n\n- [Statig in action](#statig-in-action)\n- [Concepts](#concepts)\n    - [States](#states)\n    - [Superstates](#superstates)\n    - [Actions](#actions)\n    - [Shared storage](#shared-storage)\n    - [State-local storage](#state-local-storage)\n    - [Context](#context)\n    - [Introspection](#introspection)\n    - [Async](#async)\n- [Implementation](#implementation)\n- [FAQ](#faq)\n- [Credits](#credits)\n\n---\n\n## Statig in action\n\nA simple blinky state machine:\n\n```text\n┌─────────────────────────┐\n│         Blinking        │◀─────────┐\n│    ┌───────────────┐    │          │\n│ ┌─▶│     LedOn     │──┐ │  ┌───────────────┐\n│ │  └───────────────┘  │ │  │  NotBlinking  │\n│ │  ┌───────────────┐  │ │  └───────────────┘\n│ └──│     LedOff    │◀─┘ │          ▲\n│    └───────────────┘    │──────────┘\n└─────────────────────────┘\n```\n\n```rust\n#[derive(Default)]\npub struct Blinky;\n\npub enum Event {\n    TimerElapsed,\n    ButtonPressed\n}\n\n#[state_machine(initial = \"State::led_on()\")]\nimpl Blinky {\n    #[state(superstate = \"blinking\")]\n    fn led_on(event: \u0026Event) -\u003e Response\u003cState\u003e {\n        match event {\n            Event::TimerElapsed =\u003e Transition(State::led_off()),\n            _ =\u003e Super\n        }\n    }\n\n    #[state(superstate = \"blinking\")]\n    fn led_off(event: \u0026Event) -\u003e Response\u003cState\u003e {\n        match event {\n            Event::TimerElapsed =\u003e Transition(State::led_on()),\n            _ =\u003e Super\n        }\n    }\n\n    #[superstate]\n    fn blinking(event: \u0026Event) -\u003e Response\u003cState\u003e {\n        match event {\n            Event::ButtonPressed =\u003e Transition(State::not_blinking()),\n            _ =\u003e Super\n        }\n    }\n\n    #[state]\n    fn not_blinking(event: \u0026Event) -\u003e Response\u003cState\u003e {\n        match event {\n            Event::ButtonPressed =\u003e Transition(State::led_on()),\n            _ =\u003e Super\n        }\n    }\n}\n\nfn main() {\n    let mut state_machine = Blinky::default().state_machine();\n\n    state_machine.handle(\u0026Event::TimerElapsed);\n    state_machine.handle(\u0026Event::ButtonPressed);\n}\n```\n\n(See the [`macro/blinky`](examples/macro/blinky/src/main.rs) example for the full code with comments. Or see [`no_macro/blinky`](examples/no_macro/blinky/src/main.rs) for a version without using macro's).\n\n\n---\n\n## Concepts\n\n### States\n\nStates are defined by writing methods inside the `impl` block and adding the `#[state]` attribute to them. When an event is submitted to the state machine, the method associated with the current state will be called to process it. By default this event is mapped to the `event` argument of the method.\n\n```rust\n#[state]\nfn led_on(event: \u0026Event) -\u003e Response\u003cState\u003e {\n    Transition(State::led_off())\n}\n```\n\nEvery state must return a `Response`. A `Response` can be one of three things:\n\n- `Handled`: The event has been handled.\n- `Transition`: Transition to another state.\n- `Super`: Defer the event to the parent superstate.\n\n### Superstates\n\nSuperstates allow you to create a hierarchy of states. States can defer an event to their superstate by returning the `Super` response.\n\n```rust\n#[state(superstate = \"blinking\")]\nfn led_on(event: \u0026Event) -\u003e Response\u003cState\u003e {\n    match event {\n        Event::TimerElapsed =\u003e Transition(State::led_off()),\n        Event::ButtonPressed =\u003e Super\n    }\n}\n\n#[superstate]\nfn blinking(event: \u0026Event) -\u003e Response\u003cState\u003e {\n    match event {\n        Event::ButtonPressed =\u003e Transition(State::not_blinking()),\n        _ =\u003e Super\n    }\n}\n```\n\nSuperstates can themselves also have superstates.\n\n### Actions\n\nActions run when entering or leaving states during a transition.\n\n```rust\n#[state(entry_action = \"enter_led_on\", exit_action = \"exit_led_on\")]\nfn led_on(event: \u0026Event) -\u003e Response\u003cState\u003e {\n    Transition(State::led_off())\n}\n\n#[action]\nfn enter_led_on() {\n    println!(\"Entered on\");\n}\n\n#[action]\nfn exit_led_on() {\n    println!(\"Exited on\");\n}\n```\n\n### Shared storage\n\nIf the type on which your state machine is implemented has any fields, you can access them inside all states, superstates or actions.\n\n```rust\n#[state]\nfn led_on(\u0026mut self, event: \u0026Event) -\u003e Response\u003cState\u003e {\n    match event {\n        Event::TimerElapsed =\u003e {\n            self.led = false;\n            Transition(State::led_off())\n        }\n        _ =\u003e Super\n    }\n}\n```\n\nOr alternatively, set `led` inside the entry action.\n\n```rust\n#[action]\nfn enter_led_off(\u0026mut self) {\n    self.led = false;\n}\n```\n\n### State-local storage\n\nSometimes you have data that only exists in a certain state. Instead of adding this data to the shared storage and potentially having to unwrap an `Option\u003cT\u003e`, you can add it as an input to your state handler.\n\n```rust\n#[state]\nfn led_on(counter: \u0026mut u32, event: \u0026Event) -\u003e Response\u003cState\u003e {\n    match event {\n        Event::TimerElapsed =\u003e {\n            *counter -= 1;\n            if *counter == 0 {\n                Transition(State::led_off())\n            } else {\n                Handled\n            }\n        }\n        Event::ButtonPressed =\u003e Transition(State::led_on(10))\n    }\n}\n```\n\n`counter` is only available in the `led_on` state but can also be accessed in its superstates and actions.\n\n### Context\n\nWhen state machines are used in a larger systems it can sometimes be necessary to pass in an external mutable context. By default this context is mapped to the `context` argument of the method.\n\n```rust\n#[state]\nfn led_on(context: \u0026mut Context, event: \u0026Event) -\u003e Response\u003cState\u003e {\n    match event {\n        Event::TimerElapsed =\u003e {\n            context.do_something();\n            Handled\n        }\n        _ =\u003e Super\n    }\n}\n```\n\nYou will then be required to use the `handle_with_context` method to submit events to the state machine.\n\n```rust\nstate_machine.handle_with_context(\u0026Event::TimerElapsed, \u0026mut context);\n```\n\n### Introspection\n\nFor logging purposes you can define various callbacks that will be called at specific points during state machine execution.\n\n- `before_dispatch` is called before an event is dispatched to a specific state or superstate.\n- `after_dispatch` is called after an event is dispatched to a specific state or superstate.\n- `before_transition` is called before a transition has occured.\n- `after_transition` is called after a transition has occured.\n\n```rust\n#[state_machine(\n    initial = \"State::on()\",\n    before_dispatch = \"Self::before_dispatch\",\n    after_dispatch = \"Self::after_dispatch\",\n    before_transition = \"Self::before_transition\",\n    after_transition = \"Self::after_transition\",\n    state(derive(Debug)),\n    superstate(derive(Debug))\n)]\nimpl Blinky {\n    ...\n}\n\nimpl Blinky {\n    fn before_dispatch(\u0026mut self, state: StateOrSuperstate\u003cBlinky\u003e, event: \u0026Event) {\n        println!(\"before dispatched `{:?}` to `{:?}`\", event, state);\n    }\n\n    fn after_dispatch(\u0026mut self, state: StateOrSuperstate\u003cBlinky\u003e, event: \u0026Event) {\n        println!(\"after dispatched `{:?}` to `{:?}`\", event, state);\n    }\n\n    fn before_transition(\u0026mut self, source: \u0026State, target: \u0026State) {\n        println!(\"before transitioned from `{:?}` to `{:?}`\", source, target);\n    }\n\n    fn after_transition(\u0026mut self, source: \u0026State, target: \u0026State) {\n        println!(\"after transitioned from `{:?}` to `{:?}`\", source, target);\n    }\n}\n```\n\n### Async\n\nAll handlers and actions can be made async. (This is only available on `std` for now and requires the `async` feature to be enabled).\n\n```rust\n#[state_machine(initial = \"State::led_on()\")]\nimpl Blinky {\n    #[state]\n    async fn led_on(event: \u0026Event) -\u003e Response\u003cState\u003e {\n        match event {\n            Event::TimerElapsed =\u003e Transition(State::led_off()),\n            _ =\u003e Super\n        }\n    }\n}\n```\n\nThe `#[state_machine]` macro will then automatically detect that async functions are being used\nand generate an async state machine.\n\n```rust\nasync fn main() {\n    let mut state_machine = Blinky::default().state_machine();\n\n    state_machine.handle(\u0026Event::TimerElapsed).await;\n    state_machine.handle(\u0026Event::ButtonPressed).await;\n}\n```\n\n---\n\n## Implementation\n\nA lot of the implementation details are dealt with by the `#[state_machine]` macro, but it's always valuable to understand what's happening behind the scenes. Furthermore, you'll see that the generated code is actually pretty straight-forward and could easily be written by hand, so if you prefer to avoid using macro's this is totally feasible.\n\nThe goal of `statig` is to represent a hierarchical state machine. Conceptually a hierarchical state machine can be thought of as a tree.\n\n```text\n                          ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐\n                                    Top\n                          └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘\n                                     │\n                        ┌────────────┴────────────┐\n                        │                         │\n             ┌─────────────────────┐   ╔═════════════════════╗\n             │      Blinking       │   ║     NotBlinking     ║\n             │─────────────────────│   ╚═════════════════════╝\n             │ counter: \u0026'a usize  │\n             └─────────────────────┘\n                        │\n           ┌────────────┴────────────┐\n           │                         │\n╔═════════════════════╗   ╔═════════════════════╗\n║        LedOn        ║   ║        LedOff       ║\n║─────────────────────║   ║─────────────────────║\n║ counter: usize      ║   ║ counter: usize      ║\n╚═════════════════════╝   ╚═════════════════════╝\n```\n\nNodes at the edge of the tree are called leaf-states and are represented by an `enum` in `statig`. If data only exists in a particular state we can give that state ownership of the data. This is referred to as 'state-local storage'. For example `counter` only exists in the `LedOn` and `LedOff` state.\n\n```rust\nenum State {\n    LedOn { counter: usize },\n    LedOff { counter: usize },\n    NotBlinking\n}\n```\n\nStates such as `Blinking` are called superstates. They define shared behavior of their child states. Superstates are also represented by an enum, but instead of owning their data, they borrow it from the underlying state.\n\n```rust\nenum Superstate\u003c'sub\u003e {\n    Blinking { counter: \u0026'sub usize }\n}\n```\n\nThe association between states and their handlers is then expressed in the `State` and `Superstate` traits with the `call_handler()` method.\n\n```rust\nimpl statig::State\u003cBlinky\u003e for State {\n    fn call_handler(\u0026mut self, blinky: \u0026mut Blinky, event: \u0026Event) -\u003e Response\u003cSelf\u003e {\n        match self {\n            State::LedOn { counter } =\u003e blinky.led_on(counter, event),\n            State::LedOff { counter } =\u003e blinky.led_off(counter, event),\n            State::NotBlinking =\u003e blinky.not_blinking(event)\n        }\n    }\n}\n\nimpl statig::Superstate\u003cBlinky\u003e for Superstate {\n    fn call_handler(\u0026mut self, blinky: \u0026mut Blinky, event: \u0026Event) -\u003e Response\u003cSelf\u003e {\n        match self {\n            Superstate::Blinking { counter } =\u003e blinky.blinking(counter, event),\n        }\n    }\n}\n```\n\nThe association between states and their actions is expressed in a similar fashion.\n\n```rust\nimpl statig::State\u003cBlinky\u003e for State {\n\n    ...\n\n    fn call_entry_action(\u0026mut self, blinky: \u0026mut Blinky) {\n        match self {\n            State::LedOn { counter } =\u003e blinky.enter_led_on(counter),\n            State::LedOff { counter } =\u003e blinky.enter_led_off(counter),\n            State::NotBlinking =\u003e blinky.enter_not_blinking()\n        }\n    }\n\n    fn call_exit_action(\u0026mut self, blinky: \u0026mut Blinky) {\n        match self {\n            State::LedOn { counter } =\u003e blinky.exit_led_on(counter),\n            State::LedOff { counter } =\u003e blinky.exit_led_off(counter),\n            State::NotBlinking =\u003e blinky.exit_not_blinking()\n        }\n    }\n}\n\nimpl statig::Superstate\u003cBlinky\u003e for Superstate {\n\n    ...\n\n    fn call_entry_action(\u0026mut self, blinky: \u0026mut Blinky) {\n        match self {\n            Superstate::Blinking { counter } =\u003e blinky.enter_blinking(counter),\n        }\n    }\n\n    fn call_exit_action(\u0026mut self, blinky: \u0026mut Blinky) {\n        match self {\n            Superstate::Blinking { counter } =\u003e blinky.exit_blinking(counter),\n        }\n    }\n}\n```\n\nThe tree structure of states and their superstates is expressed in the `superstate` method of the `State` and `Superstate` trait.\n\n```rust\nimpl statig::State\u003cBlinky\u003e for State {\n\n    ...\n\n    fn superstate(\u0026mut self) -\u003e Option\u003cSuperstate\u003c'_\u003e\u003e {\n        match self {\n            State::LedOn { counter } =\u003e Some(Superstate::Blinking { counter }),\n            State::LedOff { counter } =\u003e Some(Superstate::Blinking { counter }),\n            State::NotBlinking =\u003e None\n        }\n    }\n}\n\nimpl\u003c'sub\u003e statig::Superstate\u003cBlinky\u003e for Superstate\u003c'sub\u003e {\n\n    ...\n\n    fn superstate(\u0026mut self) -\u003e Option\u003cSuperstate\u003c'_\u003e\u003e {\n        match self {\n            Superstate::Blinking { .. } =\u003e None\n        }\n    }\n}\n```\n\nWhen an event arrives, `statig` will first dispatch it to the current leaf state. If this state returns a `Super` response, it will then be dispatched to that state's superstate, which in turn returns its own response. Every time an event is defered to a superstate, `statig` will traverse upwards in the graph until it reaches the `Top` state. This is an implicit superstate that will consider every event as handled.\n\nIn case the returned response is a `Transition`, `statig` will perform a transition sequence by traversing the graph from the current source state to the target state by taking the shortest possible path. When this path is going upwards from the source state, every state that is passed will have its **exit action** executed. And then similarly when going downward, every state that is passed will have its **entry action** executed.\n\nFor example when transitioning from the `LedOn` state to the `NotBlinking` state the transition sequence looks like this:\n\n1. Exit the `LedOn` state\n2. Exit the `Blinking` state\n3. Enter the `NotBlinking` state\n\nFor comparison, the transition from the `LedOn` state to the `LedOff` state looks like this:\n\n1. Exit the `LedOn` state\n2. Enter the `LedOff` state\n\nWe don't execute the exit or entry action of `Blinking` as this superstate is shared between the `LedOn` and `LedOff` state.\n\nEntry and exit actions also have access to state-local storage, but note that exit actions operate on state-local storage of the source state and that entry actions operate on the state-local storage of the target state.\n\nFor example changing the value of `counter` in the exit action of `LedOn` will have no effect on the value of `counter` in the `LedOff` state.\n\nFinally, the `StateMachine` trait is implemented on the type that will be used for the shared storage.\n\n```rust\nimpl IntoStateMachine for Blinky {\n    type State = State;\n\n    type Superstate\u003c'sub\u003e = Superstate\u003c'sub\u003e;\n\n    type Event\u003c'evt\u003e = Event;\n\n    type Context\u003c'ctx\u003e = Context;\n\n    const INITIAL: fn() -\u003e State = || State::off(10);\n}\n```\n\n---\n\n## FAQ\n\n### **What is this `#[state_machine]` proc-macro doing to my code? 🤨**\n\nShort answer: nothing. `#[state_machine]` simply parses the underlying `impl` block and derives some code based on its content and adds it to your source file. Your code will still be there, unchanged. In fact `#[state_machine]` could have been a derive macro, but at the moment Rust only allows derive macros to be used on enums and structs. If you'd like to see what the generated code looks like take a look at the test [with](./statig/tests/transition_macro.rs) and [without](./statig/tests/transition.rs) macros.\n\n### What advantage does this have over using the typestate pattern?\n\nI would say they serve a different purpose. The [typestate pattern](http://cliffle.com/blog/rust-typestate/) is very useful for designing an API as it is able to enforce the validity of operations at compile time by making each state a unique type. But `statig` is designed to model a dynamic system where events originate externally and the order of operations is determined at run time. More concretely, this means that the state machine is going to sit in a loop where events are read from a queue and submitted to the state machine using the `handle()` method. If we want to do the same with a state machine that uses the typestate pattern we'd have to use an enum to wrap all our different states and match events to operations on these states. This means extra boilerplate code for little advantage as the order of operations is unknown so it can't be checked at compile time. On the other hand `statig` gives you the ability to create a hierarchy of states which I find to be invaluable as state machines grow in complexity.\n\n---\n\n## Credits\n\nThe idea for this library came from reading the book [Practical UML Statecharts in C/C++](https://www.state-machine.com/doc/PSiCC2.pdf). I highly recommend it if you want to learn how to use state machines to design complex systems.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmdeloof%2Fstatig","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmdeloof%2Fstatig","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmdeloof%2Fstatig/lists"}