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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//! Provides the statemachine!() macro.
//!
//! # Examples
//!
//! ```
//! use statemachine_macro::*;
//!
//! statemachine! {
//!     #[derive(Default)]
//!     pub struct Foo {
//!         pub allow_x: bool
//!     }
//!
//!     enum FooState consumes [char, i32] from Start accepts [Done];
//!
//!     Start => {
//!         @enter => {
//!             println!("Entering Start!");
//!         },
//!         @leave => {
//!             println!("Leaving Start!");
//!         },
//!         @loop => {
//!             println!("Looping inside Start!");
//!         },
//!         char match 'a' => {
//!             println!("Got 'a'... Going to 'Done'!");
//!             Done
//!         },
//!         char match 'b' => {
//!             println!("Got 'b'... allowing 'x'!");
//!             self.allow_x = true;
//!             Start
//!         },
//!         char match 'x' => if self.allow_x {
//!             println!("Got authorized 'x'.");
//!             Done
//!         },
//!         char match 'x' => if !self.allow_x {
//!             println!("Got unauthorized 'x'.");
//!             Error
//!         },
//!         i32 match 42 => {
//!             println!("It is the answer!");
//!             Error
//!         },
//!         i32 match val => {
//!             println!("Got {}", val);
//!             Error
//!         },
//!         _ => Error
//!     },
//!
//!     Error => {
//!         _ => Error
//!     },
//!
//!     Done => {
//!         _ => Error
//!     }
//! }
//!
//! let mut foo: Foo = Default::default();
//! foo.consume('a');
//! assert!(foo.is_accepting());
//! assert!(!foo.allow_x);
//! foo.reset(FooState::Start);
//!
//! foo.consume('b');
//! assert!(!foo.is_accepting());
//! assert!(foo.allow_x);
//! foo.consume('x');
//! assert!(foo.is_accepting());
//! ```

mod model;
mod util;

use proc_macro;
use quote::ToTokens;
use syn::{parse_macro_input, parse_quote};

/// Creates a state machine.
///
/// # The Statemachine Struct
///
/// The statemachine struct that is generated (the first item in the macro body) has methods with the following signatures.
///
/// ```
/// use statemachine_macro::*;
///
/// statemachine! {
///     struct Foo;
///     enum FooState consumes [char] from Start;
/// }
///
/// /*impl Foo {
///     /// Changes the statemachine to the given state.
///     fn reset(&mut self, state: FooState) { ... }
///
///     /// Returns true if the statemachine is in an accepting state.
///     fn is_accepting(&self) -> bool { ... }
///
///     /// Performs a transition for the given input symbol.
///     fn consume<T: ...>(&mut self, val: T) { ... }
/// }*/
/// ```
///
/// These methods are currently not provided as a trait implementation. This may change in a future major version.
///
/// # Examples
///
/// Basic consuming:
/// ```
/// use statemachine_macro::*;
///
/// statemachine! {
///     pub struct Foo;
///
///     enum FooState consumes [char] from Even accepts [Odd];
///
///     Even => {
///         _ => Odd
///     },
///
///     Odd => {
///         _ => Even
///     }
/// }
///
/// let mut foo = statemachine_new!(Foo{});
/// assert!(!foo.is_accepting());
/// foo.consume(' ');
/// assert!(foo.is_accepting());
/// foo.consume(' ');
/// assert!(!foo.is_accepting());
/// foo.consume(' ');
/// assert!(foo.is_accepting());
/// ```
///
/// Resetting the state machine:
/// ```
/// use statemachine_macro::*;
///
/// #[derive(Debug)]
/// struct Money;
///
/// statemachine! {
///     pub struct Foo;
///
///     enum FooState consumes [Money] from Unpaid accepts [Paid];
/// }
///
/// let mut foo = statemachine_new!(Foo{});
/// assert!(!foo.is_accepting());
/// foo.reset(FooState::Paid); // mwahahaha free real estate
/// assert!(foo.is_accepting());
/// ```
///
/// Advanced consuming with multiple types:
/// ```
/// use statemachine_macro::*;
///
/// statemachine! {
///     pub struct Foo {
///         cheater: bool
///     }
///
///     enum FooState consumes [u32, i32] from Even accepts [Odd];
///
///     Even => {
///         u32 match x => {
///             if x % 2 == 0 {
///                 Even
///             } else {
///                 Odd
///             }
///         },
///         i32 match v => if *v < 0 {
///             self.cheater = true;
///             Even
///         },
///         i32 match x => panic!("Hey! Are you trying to cheat?")
///     },
///
///     Odd => {
///         u32 match x => {
///             if x % 2 == 0 {
///                 Even
///             } else {
///                 Odd
///             }
///         },
///         i32 match v => if *v < 0 {
///             self.cheater = true;
///             Odd
///         },
///         i32 match x => panic!("Hey! Are you trying to cheat?")
///     }
/// }
///
/// let mut foo = statemachine_new!(Foo{ cheater: false });
/// assert!(!foo.cheater);
/// assert!(!foo.is_accepting());
/// foo.consume(5u32);
/// assert!(!foo.cheater);
/// assert!(foo.is_accepting());
/// foo.consume(4u32);
/// assert!(!foo.cheater);
/// assert!(!foo.is_accepting());
/// foo.consume(4u32);
/// assert!(!foo.cheater);
/// assert!(!foo.is_accepting());
/// foo.consume(-3i32);
/// assert!(foo.cheater);
/// assert!(!foo.is_accepting());
/// ```
///
/// # Syntax
///
/// The following is the syntax of the macro contents. The starting nonterminal is 'statemachine'.
///
/// ```txt
/// statemachine ::= struct-item state-description ( state-behaviors )?
///
/// state-description ::=
///     "enum" ident "consumes" "[" type ( "," type )* "]"
///                  ( "accepts" "[" ident ( "," ident )* "]" )? ";"
///
/// state-behaviors ::= state-behavior ( "," state-behavior )*
///
/// state-behavior ::= ident "=>" "{" ( state-transitions )? "}"
///
/// state-transitions ::= state-transition ( "," state-transition )*
///
/// state-transition ::= transition-trigger | transition-pattern | transition-catchall
///
/// transition-pattern ::= type "match" pattern "=>" ( transition-guard )? expr
///
/// transition-guard ::= "if" expr
///
/// transition-catchall ::= "_" "=>" expr
///
/// transition-trigger ::= "@" ( enter-trigger | leave-trigger | loop-trigger )
///
/// enter-trigger ::= "enter" "=>" expr
/// leave-trigger ::= "leave" "=>" expr
/// loop-trigger ::= "loop" "=>" expr
/// ```
#[proc_macro]
pub fn statemachine(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let statemachine = parse_macro_input!(input as model::StateMachine);
    statemachine.to_stream().into()
}

/// Creates a statemachine.
///
/// Because statemachines do some magic processing to the underlying struct, regular struct literals do not work. By wrapping your struct literals in `statemachine_new!`, you can circumvent this restriction.
///
/// Note that you can alternatively derive `Default` for your statemachine struct.
///
/// # Examples
///
/// Without `statemachine_new!`:
/// ```compile_fail
/// use statemachine_macro::*;
///
/// statemachine! {
///     struct Foo {
///         bar: i32
///     }
///
///     enum FooState consumes [char] from Start;
/// }
///
/// let _foo = Foo { bar: 3 };
/// ```
///
/// With `statemachine_new!`:
/// ```
/// use statemachine_macro::*;
///
/// statemachine! {
///     struct Foo {
///         bar: i32
///     }
///
///     enum FooState consumes [char] from Start;
/// }
///
/// let _foo = statemachine_new!(Foo { bar: 3 });
/// ```
///
/// By deriving `Default`:
/// ```
/// use statemachine_macro::*;
///
/// statemachine! {
///     #[derive(Default)]
///     struct Foo {
///         bar: i32
///     }
///
///     enum FooState consumes [char] from Start;
/// }
///
/// let _foo: Foo = Foo { bar: 3, ..Default::default() };
/// let _baz: Foo = Default::default();
/// ```
#[proc_macro]
pub fn statemachine_new(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let mut expr: syn::ExprStruct = syn::parse(input).expect("Note: Did you mean to use Foo{} for a statemachine Foo with no fields?");
    expr.fields.push(parse_quote! {
        _statemachine_state: Default::default()
    });
    expr.into_token_stream().into()
}