mdeloof / statig

Hierarchical state machines for designing event-driven systems
https://crates.io/crates/statig
MIT License
560 stars 18 forks source link

Is it possible to split state machines across files? #16

Closed v-morlock closed 6 months ago

v-morlock commented 7 months ago

Hi,

I really love the idea and your implementation and was wondering if it's currently possible to define states for a single state machine across multiple files, by having multiple 'impl' blocks? I tried different approaches but couldn't find a working solution. Or is that something that would be feasible and that you would maybe consider implementing?

Thanks! Valentin

mdeloof commented 7 months ago

Hi Valentin

Thank you for your interest! It's currently not possible to define states in multiple files when using the #[state_machine] macro. I think the only way I could make something like that work is with build.rs but I'm not sure if I could make it robust enough and it's not something I'm currently planning to do. If you want to define your states in multiple files you will have to either not use the macro and implement the required traits manually like in the no_macro examples or you could do something like this I think:

Use the #[state_machine"] macro inside one file where you define all your states and then inside each method, just call another method defined in another file.

// my_state_machine.rs

#[state_machine(intial = "State::foo()")]
impl MyStateMachine {
    #[state]
    fn foo(&mut self, event: &Event) -> Response<State> {
        self.state_foo(event)
    }
}

And then write your full state logic inside another file.

// state_foo.rs

use crate::my_state_machine::{MyStateMachine, State};

impl MyStateMachine {
    fn state_foo(&mut self, event: &Event) -> Response<State> {
        todo!("write your full logic here")
    }
}

Hopefully one of these options is a viable solution for you?