Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-v3.1-terminus-thinking· DeepSeekHugging Face Arena Expert 5K

In rust. Is it possible to give a better error message when someone is using my…

  1. User

    In rust. Is it possible to give a better error message when someone is using my typestate pattern?

    I currently get this error: error[E0599]: no method named build found for struct StateMachineBuilder<_, &str, {integer}, Initial> in the current scope --> examples\cd_player_str.rs:9:10 | 8 | let mut cd_player = StateMachineBuilder::new( track, "Stopped") | _______________________- 9 | | .build(); | | -^^^^^ method not found in StateMachineBuilder<_, &str, {integer}, Initial> | |_______| | | = note: the method was found for - StateMachineBuilder<Event, State, Store, StateSelected> - StateMachineBuilder<Event, State, Store, TransitionStarted>

    When someone does this: let mut cd_player = StateMachineBuilder::new( track, "Stopped").build();

    For this library code:

    pub struct Transition<Event, State, Store> { event: Event, from_state: State, to_state: State, before_event: fn(&mut Store), after_event: fn(&mut Store), condition: fn(&Store) -> bool, }

    impl<Event, State, Store> Transition<Event, State, Store> { fn new(event: Event, from_state: State) -> Self where State: Copy, { Self { event, from_state, to_state: from_state, // Default to same state before_event: || {}, // Default to no-op after_event: || {}, // Default to no-op condition: |_| true, // Default to always true } } }

    pub struct StateMachine<Event, State, Store> { global_function_after_transition: fn(&mut Store, &State, &Event), transitions: Vec<Transition<Event, State, Store>>, pub state: State, pub store: Store, }

    impl<Event, State, Store> StateMachine<Event, State, Store> where State: Copy + PartialEq, Event: PartialEq, { #[allow(clippy::needless_pass_by_value)] pub fn trigger(&mut self, event: Event) { for transition in &mut self.transitions { if transition.event != event || self.state != transition.from_state { continue; }

            (transition.before_event)(&mut self.store);
    
            if (transition.condition)(&self.store) {
                (transition.after_event)(&mut self.store);
                self.state = transition.to_state;
                (self.global_function_after_transition)(&mut self.store, &self.state, &event);
                break;
            }
        }
    }
    

    }

    pub struct Initial; pub struct StateSelected; pub struct TransitionStarted;

    pub trait BuilderState {} impl BuilderState for Initial {} impl BuilderState for StateSelected {} impl BuilderState for TransitionStarted {}

    #[must_use] pub struct StateMachineBuilder<Event, State, Store, BuilderStateType: BuilderState> { state_machine: StateMachine<Event, State, Store>, current_state: State, _builder_state: std::marker::PhantomData, }

    impl<Event, State, Store> StateMachineBuilder<Event, State, Store, Initial> where State: Copy + PartialEq, Event: PartialEq, { pub fn new(data_store: Store, initial_state: State) -> Self { Self { state_machine: StateMachine { transitions: Vec::new(), state: initial_state, store: data_store, global_function_after_transition: |,,_| {}, }, current_state: initial_state, _builder_state: std::marker::PhantomData, } }

    pub fn set_global_action(
        mut self,
        global_action: fn(&mut Store, &State, &Event)
    ) -> Self {
        self.state_machine.global_function_after_transition = global_action;
        self
    }
    
    pub fn state(mut self, state: State) -> StateMachineBuilder<Event, State, Store, StateSelected> {
        self.current_state = state;
        StateMachineBuilder {
            state_machine: self.state_machine,
            current_state: state,
            _builder_state: std::marker::PhantomData,
        }
    }
    

    }

    impl<Event, State, Store> StateMachineBuilder<Event, State, Store, StateSelected> where State: Copy + PartialEq, Event: PartialEq, { pub fn state(mut self, state: State) -> Self { self.current_state = state; self }

    pub fn on(mut self, event: Event) -> StateMachineBuilder<Event, State, Store, TransitionStarted> {
        let transition = Transition::new(event, self.current_state);
        self.state_machine.transitions.push(transition);
        
        StateMachineBuilder {
            state_machine: self.state_machine,
            current_state: self.current_state,
            _builder_state: std::marker::PhantomData,
        }
    }
    
    pub fn build(self) -> StateMachine<Event, State, Store> {
        self.state_machine
    }
    

    }

    impl<Event, State, Store> StateMachineBuilder<Event, State, Store, TransitionStarted> where State: Copy + PartialEq, Event: PartialEq, { pub fn state(mut self, state: State) -> StateMachineBuilder<Event, State, Store, StateSelected> { self.current_state = state; StateMachineBuilder { state_machine: self.state_machine, current_state: state, _builder_state: std::marker::PhantomData, } }

    pub fn on(mut self, event: Event) -> Self {
        let transition = Transition::new(event, self.current_state);
        self.state_machine.transitions.push(transition);
        self
    }
    
    pub fn go_to(mut self, target: State) -> Self {
        let last_idx = self.state_machine.transitions.len() - 1;
        self.state_machine.transitions[last_idx].to_state = target;
        self
    }
    
    pub fn update(mut self, before_event: fn(&mut Store)) -> Self {
        let last_idx = self.state_machine.transitions.len() - 1;
        self.state_machine.transitions[last_idx].before_event = before_event;
        self
    }
    
    pub fn only_if(mut self, condition: fn(&Store) -> bool) -> Self {
        let last_idx = self.state_machine.transitions.len() - 1;
        self.state_machine.transitions[last_idx].condition = condition;
        self
    }
    
    pub fn then(mut self, after_event: fn(&mut Store)) -> Self {
        let last_idx = self.state_machine.transitions.len() - 1;
        self.state_machine.transitions[last_idx].after_event = after_event;
        self
    }
    
    pub fn build(self) -> StateMachine<Event, State, Store> {
        self.state_machine
    }
    

    }

  2. DeepSeek Assistant

    Yes! You can provide better error messages by using Rust's trait system to give more descriptive errors when methods are called in the wrong order. Here are a few approaches:

    Approach 1: Add helpful methods to the initial state

    Add a method to the Initial state that guides users toward the correct pattern:

    impl<Event, State, Store> StateMachineBuilder<Event, State, Store, Initial> 
    where
        State: Copy + PartialEq,
        Event: PartialEq,
    {
        // ... existing methods ...
    
        /// Guide users toward the correct pattern
        pub fn help(self) -> ! {
            panic!(
                "Cannot build state machine directly after creation.\n\
                You need to define at least one state and transition.\n\
                Example usage:\n\
                \n\
                StateMachineBuilder::new(store, initial_state)\n\
                    .state(some_state)\n\
                    .on(some_event)\n\
                    .go_to(target_state)\n\
                    .build()\n\
                \n\
                Or if you just want the initial state without transitions:\n\
                \n\
                StateMachineBuilder::new(store, initial_state)\n\
                    .state(initial_state)  // <- note this extra .state() call\n\
                    .build()\n"
            )
        }
    
        /// Alternative: return a Result with a helpful error
        pub fn try_build(self) -> Result<StateMachine<Event, State, Store>, &'static str> {
            Err(
                "Cannot build state machine directly after creation.\n\
                You need to define at least one state and transition.\n\
                Add .state(your_state) before .build()"
            )
        }
    }
    

    Approach 2: Use a custom trait with better error messages

    Create a trait that's only implemented for states that can be built:

    pub trait Buildable {}
    impl Buildable for StateSelected {}
    impl Buildable for TransitionStarted {}
    
    pub trait StateMachineBuild<Event, State, Store> {
        fn build(self) -> StateMachine<Event, State, Store>;
    }
    
    // Only implement build for buildable states
    impl<Event, State, Store> StateMachineBuild<Event, State, Store> 
        for StateMachineBuilder<Event, State, Store, StateSelected>
    {
        fn build(self) -> StateMachine<Event, State, Store> {
            self.state_machine
        }
    }
    
    impl<Event, State, Store> StateMachineBuild<Event, State, Store> 
        for StateMachineBuilder<Event, State, Store, TransitionStarted>
    {
        fn build(self) -> StateMachine<Event, State, Store> {
            self.state_machine
        }
    }
    
    // Add a method to the Initial state that provides guidance
    impl<Event, State, Store> StateMachineBuilder<Event, State, Store, Initial> {
        pub fn build(self) -> ! {
            panic!(
                "Invalid state machine build pattern!\n\n\
                You're trying to build immediately after creation, but you need to define states and transitions first.\n\
                \n\
                Correct usage examples:\n\
                \n\
                // With transitions:\n\
                StateMachineBuilder::new(store, initial_state)\n\
                    .state(\"Stopped\")\n\
                    .on(\"Play\")\n\
                    .go_to(\"Playing\")\n\
                    .build()\n\
                \n\
                // Without transitions (just initial state):\n\
                StateMachineBuilder::new(store, initial_state)\n\
                    .state(initial_state)  // ← This is required!\n\
                    .build()\n\
                \n\
                The .state() method transitions the builder to a state where .build() is allowed."
            )
        }
    }
    

    Approach 3: Use a type alias and documentation

    Create type aliases that make the intended usage clearer:

    // More descriptive type aliases
    pub type InitialBuilder<Event, State, Store> = StateMachineBuilder<Event, State, Store, Initial>;
    pub type ReadyToBuild<Event, State, Store> = StateMachineBuilder<Event, State, Store, StateSelected>;
    
    impl<Event, State, Store> InitialBuilder<Event, State, Store> {
        /// Transition to state definition phase
        pub fn state(self, state: State) -> ReadyToBuild<Event, State, Store> {
            // ... implementation ...
        }
        
        // Don't implement build() here at all - let the compiler error guide users
    }
    

    Approach 4: Comprehensive solution with macros (most user-friendly)

    For the best developer experience, you could create a macro that validates the pattern at compile time:

    #[macro_export]
    macro_rules! state_machine {
        ($store:expr, $initial_state:expr) => {
            StateMachineBuilder::new($store, $initial_state)
        };
        ($store:expr, $initial_state:expr, $($rest:tt)*) => {
            compile_error!(
                "Invalid state machine syntax!\n\n\
                Usage examples:\n\
                state_machine!(store, initial_state)\n\
                    .state(some_state)\n\
                    .on(some_event)\n\
                    .go_to(target_state)\n\
                    .build()\n\n\
                Or:\n\
                state_machine!(store, initial_state)\n\
                    .state(initial_state)\n\
                    .build()"
            )
        };
    }
    

    Recommended Approach

    I'd recommend Approach 2 as it provides the best balance of compile-time safety and helpful error messages. Users would call it like this:

    // This would panic with a helpful message:
    // let cd_player = StateMachineBuilder::new(track, "Stopped").build();
    
    // Correct usage:
    let cd_player = StateMachineBuilder::new(track, "Stopped")
        .state("Stopped")  // Transition to StateSelected
        .build();          // Now build is allowed
    
    // Or with transitions:
    let cd_player = StateMachineBuilder::new(track, "Stopped")
        .state("Stopped")
        .on("Play")
        .go_to("Playing")
        .build();
    

    The key insight is that by not implementing build() for the Initial state (or implementing it with a panic/error), you force users to call .state() first, which moves the builder to a state where build() is properly implemented.

    This approach maintains your type-state pattern while providing much better developer experience!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.