brisk-machine 0.3.0

Use of the brisk declarative engine to generate state machines.
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use std::collections::HashMap;

use brisk_it::{generator::Result, Required};
use convert_case::Casing;
use quote::ToTokens;

fn unknown_state(state: &syn::Ident) -> proc_macro2::TokenStream {
    return syn::Error::new(state.span(), format!("Unknown state {}", state.to_string()))
        .into_compile_error()
        .into();
}

fn snake_ident(id: &syn::Ident) -> syn::Ident {
    let id_str = id.to_string().to_case(convert_case::Case::Snake);
    syn::Ident::new(&id_str, id.span())
}

#[derive(Debug)]
enum TransitionInfo {
    ForwardTransition,
    SelfTransition {
        destination_state: syn::Ident,
        action: syn::Block,
    },
}

pub(crate) struct GenerationInfo {
    pub(crate) visibility: syn::Visibility,
    pub(crate) event_dispatcher: syn::Ident,
}

// pub(crate) struct StateGenerationInfo {
//     pub(crate) id_event: Option<syn::Ident>,
// }

pub(crate) struct GroupGenerationInfo<'a> {
    pub(crate) id_event: &'a Option<syn::Ident>,
    pub(crate) properties: &'a Option<proc_macro2::TokenStream>,
    pub(crate) event_dispatcher: &'a syn::Ident,
}

#[derive(Debug)]
pub(crate) struct ParsedStateGroup {
    id: syn::Ident,
    name: syn::Ident,
    first_state: syn::Ident,
    states: HashMap<syn::Ident, ParsedState>,
    /// name of the transition, State->Destination
    transitions: HashMap<syn::Ident, HashMap<syn::Ident, TransitionInfo>>,
}

impl ParsedStateGroup {
    /// Parse a Group
    pub(crate) fn parse(
        input: brisk_it::component::ComponentInput,
        manager: &brisk_it::generator::Manager,
    ) -> Result<ParsedStateGroup> {
        let name = input.id.required(&input.name, "id")?;
        let id = snake_ident(&name);
        let (first_state, states) = Self::parse_states(input.children, manager)?;
        let transitions = Self::parse_transitions(input.on_expressions, &states)?;

        Ok(ParsedStateGroup {
            id,
            name,
            first_state,
            states,
            transitions,
        })
    }
    /// Parse the states of a Group or State
    fn parse_states(
        children: Vec<brisk_it::component::ComponentInput>,
        manager: &brisk_it::generator::Manager,
    ) -> Result<(syn::Ident, HashMap<syn::Ident, ParsedState>)> {
        Ok((
            children
                .first()
                .as_ref()
                .ok_or(brisk_it::errors::impossible(proc_macro2::Span::call_site()))?
                .id
                .as_ref()
                .ok_or(brisk_it::errors::impossible(proc_macro2::Span::call_site()))?
                .to_owned(),
            children
                .into_iter()
                .map(|c| {
                    let s = ParsedState::parse(c, manager)?;
                    Ok((s.id.clone(), s))
                })
                .collect::<Result<_>>()?,
        ))
    }

    /// Parse the transitions of a Group or State
    fn parse_transitions(
        on_expressions: Vec<brisk_it::component::OnValue>,
        states: &HashMap<syn::Ident, ParsedState>,
    ) -> Result<HashMap<syn::Ident, HashMap<syn::Ident, TransitionInfo>>> {
        let mut map: HashMap<syn::Ident, HashMap<syn::Ident, TransitionInfo>> = on_expressions
            .into_iter()
            .map(|oe| {
                let transition_name = oe.name;
                let transition_infos = oe
                    .transition_definitions
                    .into_iter()
                    .map(|td| {
                        (
                            td.source_state,
                            TransitionInfo::SelfTransition {
                                destination_state: td.destination_state,
                                action: td.action,
                            },
                        )
                    })
                    .collect();
                (transition_name, transition_infos)
            })
            .collect();

        for (src_state_name, state) in states.iter() {
            for group in state.groups.iter() {
                for (transition_name, _) in group.transitions.iter() {
                    let s_ti = map.get_mut(transition_name);
                    match s_ti {
                        Some(v) => {
                            if let Some(ct) = v.get(src_state_name) {
                                match ct {
                                    TransitionInfo::ForwardTransition => {}
                                    TransitionInfo::SelfTransition { .. } => {
                                        return Err(syn::Error::new(transition_name.span(), format!("Transition {} for state {} is shadowed by a higher priority transition.", transition_name, src_state_name))
                                        .into_compile_error()
                                        .into());
                                    }
                                }
                            } else {
                                v.insert(
                                    src_state_name.to_owned(),
                                    TransitionInfo::ForwardTransition,
                                );
                            }
                        }
                        None => {
                            map.insert(
                                transition_name.to_owned(),
                                [(src_state_name.to_owned(), TransitionInfo::ForwardTransition)]
                                    .into(),
                            );
                        }
                    }
                }
            }
        }

        Ok(map)
    }

    /// Generate a group
    pub(crate) fn generate<'a>(
        &self,
        gen_info: &GenerationInfo,
        group_gen_info: GroupGenerationInfo<'a>,
    ) -> Result<proc_macro2::TokenStream> {
        let mut children = Vec::<proc_macro2::TokenStream>::new();
        let mut states = Vec::<proc_macro2::TokenStream>::new();
        let group_name = &self.name;

        for (_, state) in self.states.iter() {
            states.push(state.generate_enum_field()?);
            children.push(state.generate(gen_info)?);
        }

        // Prepare arguments to transition function
        let transition_fn_args = match group_gen_info.properties {
            Some(properties) => quote::quote! { , super_properties: &#properties },

            None => Default::default(),
        };
        // Generate transition functions. Which involves:
        // 1) Applying the potential transition to this state
        // 2) Forwarding it to a child
        // 3) ignore
        let mut transitions = Vec::<proc_macro2::TokenStream>::new();
        for (transition_name, src_to_transitions) in self.transitions.iter() {
            let mut transitions_matches = Vec::<proc_macro2::TokenStream>::new();

            for (src_state, transition) in src_to_transitions {
                let src_state_info = self
                    .states
                    .get(&src_state)
                    .ok_or_else(|| unknown_state(&src_state))?;

                let transition_call_fn_args = match src_state_info.properties {
                    Some(_) => quote::quote! { properties },
                    None => Default::default(),
                };

                let src_field_names = src_state_info.field_names();
                match transition {
                    TransitionInfo::ForwardTransition => {
                        let mut forwards = Vec::<proc_macro2::TokenStream>::new();
                        transitions.push(quote::quote!());
                        for group in src_state_info.groups.iter() {
                            if group.transitions.contains_key(&transition_name) {
                                let id = snake_ident(&group.id);
                                forwards.push(quote::quote! { #id.#transition_name(event_dispatcher, #transition_call_fn_args); });
                            }
                        }
                        transitions_matches.push(quote::quote! (
                            #group_name :: #src_state #src_field_names => {
                                #(#forwards)*
                            }
                        ));
                    }
                    TransitionInfo::SelfTransition {
                        destination_state,
                        action,
                    } => {
                        let dst_state_info = self
                            .states
                            .get(&destination_state)
                            .ok_or_else(|| unknown_state(&destination_state))?;

                        let prelude: proc_macro2::TokenStream;
                        let mut fields = Vec::<proc_macro2::TokenStream>::new();
                        for group in dst_state_info.groups.iter() {
                            let id = &group.id;
                            let name = &group.name;
                            if group_gen_info.properties.is_some() {
                                fields.push(quote::quote! { #id: #name::create(&properties), });
                            } else {
                                fields.push(quote::quote! { #id: #name::create(), });
                            }
                        }
                        if let Some(dst_properties_type) = &dst_state_info.properties {
                            if group_gen_info.properties.is_some() {
                                prelude = quote::quote! { let properties: #dst_properties_type = super_properties.into(); }
                            } else {
                                prelude = quote::quote! { let properties: #dst_properties_type = Default::default(); }
                            }
                            fields.push(quote::quote! { properties });
                        } else {
                            prelude = Default::default();
                        }
                        if fields.is_empty() {
                            transitions_matches.push(quote::quote! {
                                #group_name :: #src_state #src_field_names => {
                                    #action
                                    *self = #group_name :: #destination_state;
                                },
                            });
                        } else {
                            transitions_matches.push(quote::quote! {
                                #group_name :: #src_state #src_field_names => {
                                    #prelude
                                    #action
                                    *self = #group_name :: #destination_state { #(#fields)* };
                                },
                            });
                        }
                    }
                }
            }
            let event_dispatcher = &group_gen_info.event_dispatcher;
            transitions.push(quote::quote! {
                fn #transition_name(&mut self, event_dispatcher: &#event_dispatcher #transition_fn_args)
                {
                    #[allow(unused_variables, unused_braces)]
                    match self
                    {
                        #(#transitions_matches)*
                        _ => {}
                    }
                }
            });
        }
        let visibility = &gen_info.visibility;
        let id_transitions = group_gen_info.id_event.as_ref().unwrap_or(&group_name);

        // Create functions
        let first_state = &self.first_state;
        let first_state_info = self
            .states
            .get(first_state)
            .ok_or_else(|| unknown_state(&self.first_state))?;
        let (use_properties, initial_fields) = first_state_info.initialise_fields();
        let (create_function_args, create_function_prelude) = match group_gen_info.properties {
            Some(properties) => (
                quote::quote! { super_properties: &#properties },
                match use_properties {
                    true => quote::quote! { let properties = super_properties.into(); },
                    false => proc_macro2::TokenStream::new(),
                },
            ),
            None => (
                proc_macro2::TokenStream::new(),
                match first_state_info.properties {
                    Some(_) => quote::quote! { let properties = Default::default(); },
                    None => proc_macro2::TokenStream::new(),
                },
            ),
        };

        let create_function = quote::quote! {
            pub fn create(#create_function_args) -> Self
            {
                #create_function_prelude
                Self::#first_state {
                    #initial_fields
                }
            }
        };
        // Generate
        Ok(quote::quote! {
            #(#children)*
            #visibility enum #group_name {
                #(#states,)*
            }
            impl #group_name {
                #create_function
            }
            impl #id_transitions {
                #(#transitions)*
            }
        })
    }
}

#[derive(Debug)]
pub(crate) struct ParsedState {
    pub(crate) id: syn::Ident,
    // fields: Vec<syn::Ident>,
    groups: Vec<ParsedStateGroup>,
    pub(crate) properties: Option<proc_macro2::TokenStream>,
}

impl ParsedState {
    pub(crate) fn parse(
        input: brisk_it::component::ComponentInput,
        manager: &brisk_it::generator::Manager,
    ) -> Result<ParsedState> {
        let id = input.id.required(&input.name, "id")?;
        let mut groups: Vec<ParsedStateGroup> = Default::default();
        let mut properties: Option<proc_macro2::TokenStream> = None;

        for prop in input.properties.into_iter() {
            if prop.name == "properties" {
                properties = Some(prop.expr.into_token_stream());
            }
        }

        let state_child_count = input.children.iter().filter(|c| c.name == "State").count();
        let group_child_count = input.children.iter().filter(|c| c.name == "Group").count();
        if state_child_count != 0 && group_child_count != 0 {
            return Err(
                syn::Error::new(input.name.span(), "Cannot mix states and groups.")
                    .into_compile_error()
                    .into(),
            );
        }
        if state_child_count != 0 {
            let name = id.clone();
            let id = syn::Ident::new("state", input.name.span());
            let (first_state, states) = ParsedStateGroup::parse_states(input.children, manager)?;
            let transitions = ParsedStateGroup::parse_transitions(input.on_expressions, &states)?;

            let psg = ParsedStateGroup {
                id,
                name,
                first_state,
                states,
                transitions,
            };
            groups.push(psg);
        } else if group_child_count != 0 {
            groups = input
                .children
                .into_iter()
                .map(|c| ParsedStateGroup::parse(c, manager))
                .collect::<Result<_>>()?;
        }

        Ok(ParsedState {
            id,
            groups,
            properties,
        })
    }
    pub(crate) fn events(&self) -> Vec<syn::Ident> {
        self.groups
            .iter()
            .map(|x| x.transitions.keys())
            .flatten()
            .cloned()
            .collect()
    }
    pub(crate) fn generate(&self, gen_info: &GenerationInfo) -> Result<proc_macro2::TokenStream> {
        if self.groups.is_empty() {
            Ok(proc_macro2::TokenStream::new())
        } else {
            let mut children = Vec::<proc_macro2::TokenStream>::new();

            for group in self.groups.iter() {
                children.push(group.generate(
                    gen_info,
                    crate::state::GroupGenerationInfo {
                        id_event: &None,
                        properties: &self.properties,
                        event_dispatcher: &gen_info.event_dispatcher,
                    },
                )?);
            }

            Ok(quote::quote! {
                #(#children)*
            })
        }
    }
    fn initialise_fields(&self) -> (bool, proc_macro2::TokenStream) {
        let mut fields = Vec::<proc_macro2::TokenStream>::new();
        let (mut use_properties, states_init) = self.initialise_states(false);
        fields.push(states_init);
        if self.properties.is_some() {
            use_properties = true;
            fields.push(quote::quote! {  properties, });
        }
        (use_properties, quote::quote! { #(#fields)* })
    }
    pub(crate) fn initialise_states(&self, ref_cell: bool) -> (bool, proc_macro2::TokenStream) {
        let mut fields = Vec::<proc_macro2::TokenStream>::new();
        let mut use_properties = false;
        for group in self.groups.iter() {
            let id = &group.id;
            let name = &group.name;
            if ref_cell {
                if self.properties.is_some() {
                    use_properties = true;
                    fields.push(
                        quote::quote! { #id: std::cell::RefCell::new(#name::create(&properties)), },
                    );
                } else {
                    fields.push(quote::quote! { #id: std::cell::RefCell::new(#name::create()), });
                }
            } else {
                if self.properties.is_some() {
                    use_properties = true;
                    fields.push(quote::quote! { #id: #name::create(super_properties), });
                } else {
                    fields.push(quote::quote! { #id: #name::create(), });
                }
            }
        }
        (use_properties, quote::quote! { #(#fields)* })
    }
    fn generate_enum_field(&self) -> Result<proc_macro2::TokenStream> {
        let mut fields = Vec::<proc_macro2::TokenStream>::new();

        if let Some(properties) = &self.properties {
            fields.push(quote::quote! {
                properties: #properties,
            });
        }

        for group in self.groups.iter() {
            let id = &group.id;
            let name = &group.name;
            fields.push(quote::quote! { #id: #name, });
        }
        let id = &self.id;
        if fields.is_empty() {
            Ok(quote::quote! { #id })
        } else {
            Ok(quote::quote! { #id { #(#fields)* } })
        }
    }
    fn field_names(&self) -> proc_macro2::TokenStream {
        if self.properties.is_none() {
            if self.groups.is_empty() {
                proc_macro2::TokenStream::new()
            } else {
                let gn = self.groups.iter().map(|g| {
                    let id = snake_ident(&g.id);
                    quote::quote! { #id, }
                });
                quote::quote! { {#(#gn)*} }
            }
        } else {
            let gn = self.groups.iter().map(|g| {
                let id = snake_ident(&g.id);
                quote::quote! { #id, }
            });
            quote::quote! { {properties, #(#gn)*} }
        }
    }
}