mdeloof / statig

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

Would be awesome to have an attribute that draws an ASCII picture of the resulting tree #11

Open matthewgapp opened 1 year ago

matthewgapp commented 1 year ago

Thinking something like

#[state_machine(visualize)]
impl MyStruct { ... } 

fn main() { 
  let mut state_machine = Blinky::default().uninitialized_state_machine().init();
  let ascii_visualization: String = state_machine.visualize();
  println!("{}", ascii_visualiztion);
}

Which would print something like

                          ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐             
                                    Top                       
                          └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘             
                                     │                        
                        ┌────────────┴────────────┐           
                        │                         │           
             ┌─────────────────────┐   ╔═════════════════════╗
             │      Blinking       │   ║     NotBlinking     ║
             │─────────────────────│   ╚═════════════════════╝
             │ counter: &'a usize  │                          
             └─────────────────────┘                          
                        │                                     
           ┌────────────┴────────────┐                        
           │                         │                        
╔═════════════════════╗   ╔═════════════════════╗             
║        LedOn        ║   ║        LedOff       ║             
║─────────────────────║   ║─────────────────────║             
║ counter: usize      ║   ║ counter: usize      ║             
╚═════════════════════╝   ╚═════════════════════╝
mdeloof commented 1 year ago

I definitely want to add some way to visualise the state machines, though I'm still thinking about the best way to go about it. The tree representation is a nice start and should be pretty easy to do, but it doesn't include the possible transitions in response to events. Because that logic is defined as Rust code it's almost impossible to derive that reliably, so I'm thinking of maybe adding a way to annotate your state machines to provide that information to the visualiser.

I've been considering something like this, though I'm still not completely happy with it.

#[state]
fn led_on(&mut self, event: &Event) -> Response<State> {
    match event {
        #[event(transition(led_off))]   
        Event::TimerElapsed => {
            self.led = false;
            Transition(State::led_off())
        }
        #[event(transition(not_blinking))]
        Event::ButtonPressed => Transition(State::not_blinking())
    }
}

So yeah, maybe I'll just start with tree and go from there.

sadilekivan commented 1 year ago

I'd love this feature too. I have been trying multiple state machine crates to enforce some safety between transitions with not too much boilerplate. typestate-rs crate has the ability to generate such flowcharts from the code. It uses macros to define which transitions are allowed with zero sized types and traits.

I find that statig is much more concise with defining which transitions occur together with any conditions or events that make them happen inside the function body. There could be something to define the transitions at compile time, but that adds complexity to the nice approach you have.

v-morlock commented 7 months ago

To solve the „retrieve transitions from code problem“, wouldn’t one solution be to add the possible target states for a certain state within the states macro above the function signature? I think that would be a bit more brief than adding a macro to each returned value.

One could even generate an Enum that has to be returned from the state instead of the „States“ enum thats containing all states. This of course wouldn’t prevent transitions from never happen but it would make sure that the generated graph contains all possible transitions. Something like:

#[state(target_states=[StateB, StateC])]
fn state_a(…) -> Response<StateAOut> {…}
andrew-otiv commented 5 days ago

Is there something that makes this hard to construct dynamically?

for each state... construct a state machine in that state for each event... If the transition succeeds, record the transition to the target state in a DAG from some graph libary, perhaps using the on_transition() callback

Then once you have that graph, use graph algorithms from the graph libarary to do visualization, reachability analysis, etc...

This would work for pure state machines that only transition in response to events, but since users can stick arbitrary logic in their event handler functions (including non-deterministic transitions), so maybe that's not a solution for everyone.

This is something I might be able to get budget to work on and upstream; we're considering using statig for a project at my work. Thanks!