Finite state machines in rust; bendns fork to add types.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use crate::variant::Final;

use super::variant::Variant;
use proc_macro2::TokenStream;
use syn::{
    parse::{Error, Parse, ParseStream, Result},
    token::Bracket,
    *,
};
/// The output of a state transition
pub struct Output(Option<Final>);

impl Parse for Output {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.lookahead1().peek(Bracket) {
            let output_content;
            bracketed!(output_content in input);
            Ok(Self(Some(output_content.parse()?)))
        } else {
            Ok(Self(None))
        }
    }
}

impl From<Output> for Option<Final> {
    fn from(output: Output) -> Self {
        output.0
    }
}

/// Represents a part of state transition without the initial state. The `Parse`
/// trait is implemented for the compact form.
pub struct TransitionEntry {
    pub input_value: Variant,
    pub final_state: Final,
    pub output: Option<Final>,
}

impl Parse for TransitionEntry {
    fn parse(input: ParseStream) -> Result<Self> {
        let input_value = input.parse()?;
        input.parse::<Token![=>]>()?;
        let final_state = input.parse()?;
        let output = input.parse::<Output>()?.into();
        Ok(Self {
            input_value,
            final_state,
            output,
        })
    }
}

/// Parses the transition in any of the possible formats.
pub struct TransitionDef {
    pub initial_state: Variant,
    pub transitions: Vec<TransitionEntry>,
}

impl Parse for TransitionDef {
    fn parse(input: ParseStream) -> Result<Self> {
        let initial_state = input.parse()?;
        input.parse::<Token![=>]>()?;
        // Parse the transition in the simple format
        // InitialState => Input => ResultState
        let transitions = if !input.lookahead1().peek(token::Brace) {
            let input_value = input.parse()?;
            input.parse::<Token![=>]>()?;
            let final_state = input.parse()?;
            let output = input.parse::<Output>()?.into();

            vec![TransitionEntry {
                input_value,
                final_state,
                output,
            }]
        } else {
            // Parse the transition in the compact format
            // InitialState => {
            //     Input1 => State1,
            //     Input2 => State2 [Output]
            // }
            let entries_content;
            braced!(entries_content in input);

            let entries: Vec<_> = entries_content
                .parse_terminated(TransitionEntry::parse, Token![,])?
                .into_iter()
                .collect();
            if entries.is_empty() {
                return Err(Error::new_spanned(
                    initial_state,
                    "No transitions provided for a compact representation",
                ));
            }
            entries
        };
        Ok(Self {
            initial_state,
            transitions,
        })
    }
}

/// Parses the whole state machine definition in the following form (example):
///
/// ```rust,ignore
/// state_machine! {
///     CircuitBreaker(Closed)
///
///     Closed(Unsuccessful) => Open [SetupTimer],
///     Open(TimerTriggered) => HalfOpen,
///     HalfOpen => {
///         Successful => Closed,
///         Unsuccessful => Open [SetupTimer]
///     }
/// }
/// ```
pub struct StateMachineDef {
    pub doc: Vec<Attribute>,
    /// The visibility modifier (applies to all generated items)
    pub visibility: Visibility,
    pub state_name: ImplementationRequired,
    pub input_name: ImplementationRequired,
    pub output_name: ImplementationRequired,
    pub transitions: Vec<TransitionDef>,
    pub attributes: Vec<Attribute>,
}

pub enum ImplementationRequired {
    Yes(Ident),
    No(Path),
}

impl ImplementationRequired {
    pub fn tokenize(&self, f: impl Fn(&Ident) -> TokenStream) -> TokenStream {
        match self {
            ImplementationRequired::Yes(ident) => f(ident),
            ImplementationRequired::No(_) => TokenStream::default(),
        }
    }
    pub fn path(self) -> Path {
        match self {
            ImplementationRequired::Yes(ident) => ident.into(),
            ImplementationRequired::No(path) => path,
        }
    }
}

impl Parse for StateMachineDef {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut doc = Vec::new();
        let attributes = Attribute::parse_outer(input)?
            .into_iter()
            .filter_map(|attribute| {
                if attribute.path().is_ident("doc") {
                    doc.push(attribute);
                    None
                } else {
                    Some(attribute)
                }
            })
            .collect();

        let visibility = input.parse()?;
        let i = || {
            input
                .parse::<Ident>()
                .map(ImplementationRequired::Yes)
                .or_else(|_| input.parse::<Path>().map(ImplementationRequired::No))
        };
        let state_name = i()?;
        input.parse::<Token![=>]>()?;
        let input_name = i()?;
        input.parse::<Token![=>]>()?;
        let output_name = i()?;

        let transitions = input
            .parse_terminated(TransitionDef::parse, Token![,])?
            .into_iter()
            .collect();

        Ok(Self {
            doc,
            visibility,
            state_name,
            input_name,
            output_name,
            transitions,
            attributes,
        })
    }
}