bevy_pretty_nice_input_derive 0.4.3

Procedural macros for bevy_pretty_nice_input
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
use std::collections::HashSet;

use proc_macro::TokenStream;
use quote::{ToTokens, quote};
use syn::parse::{Parse, ParseStream};
use syn::{Token, parse_quote};

use crate::input::{Bindings, Conditions};

pub fn input_transition_impl(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as InputTransition);
    match input.transition {
        Transition::Uni {
            action,
            from,
            to,
            arrow,
        } => {
            let half = InputTransitionHalf {
                action,
                from,
                to: to.inclusions,
                arrow,
                bindings: input.bindings,
                conditions: input.conditions,
            };

            match input_transition(half) {
                Ok(expr) => expr.into_token_stream().into(),
                Err(err) => err.to_compile_error().into(),
            }
        }
        Transition::Bi {
            left_action,
            left,
            right_action,
            right,
        } => {
            if !input.conditions.conditions.is_empty() {
                return syn::Error::new_spanned(
                    input.conditions.to_token_stream(),
                    "Conditions are not supported for bidirectional transitions (`<=>`)",
                )
                .to_compile_error()
                .into();
            }

            let left_half = InputTransitionHalf {
                action: left_action,
                from: right.clone(),
                to: left.inclusions.clone(),
                arrow: ObserverArrow::Left,
                bindings: input.bindings.clone(),
                conditions: input.conditions.clone(),
            };
            let left_expr = match input_transition(left_half) {
                Ok(expr) => expr,
                Err(err) => return err.to_compile_error().into(),
            };

            let right_half = InputTransitionHalf {
                action: right_action,
                from: left,
                to: right.inclusions,
                arrow: ObserverArrow::Right,
                bindings: input.bindings,
                conditions: input.conditions,
            };
            let right_expr = match input_transition(right_half) {
                Ok(expr) => expr,
                Err(err) => return err.to_compile_error().into(),
            };

            quote! {
                (
                    #right_expr,
                    #left_expr
                )
            }
            .into_token_stream()
            .into()
        }
    }
}

fn input_transition(mut input: InputTransitionHalf) -> syn::Result<syn::Expr> {
    input
        .conditions
        .conditions
        .insert(0, build_filter(&input.from.query_filter()));

    let observers = build_observers(
        input.action.action(),
        &input.remove_bundle(),
        &input.insert_bundle(),
        &input.arrow,
    )?;

    Ok(build_output(
        &input.action,
        &input.bindings,
        &input.conditions,
        &observers,
    ))
}

fn build_output(
    action: &TransitionFromAction,
    bindings: &Bindings,
    conditions: &Conditions,
    observers: &[syn::Expr],
) -> syn::Expr {
    let inner: syn::Expr = parse_quote! {
        (
            ::bevy_pretty_nice_input::input!(
                #action,
                #bindings,
                #conditions,
            ),
            #( #observers ),*
        )
    };
    match action {
        TransitionFromAction::Specified(_) => inner,
        TransitionFromAction::Generated(_) => {
            parse_quote! {
                {
                    #[derive(::bevy_pretty_nice_input::Action)]
                    struct #action;

                    #inner
                }
            }
        }
    }
}

fn build_filter(from: &syn::Type) -> syn::Expr {
    parse_quote! {
        ::bevy_pretty_nice_input::InvalidatingFilter::< #from >::default()
    }
}

fn build_observers(
    action: &syn::Type,
    remove: &syn::Type,
    insert: &syn::Type,
    arrow: &ObserverArrow,
) -> syn::Result<Vec<syn::Expr>> {
    let transition: syn::Expr = match arrow {
        ObserverArrow::Left => parse_quote! { ::bevy_pretty_nice_input::transition_off },
        ObserverArrow::Right => parse_quote! { ::bevy_pretty_nice_input::transition_on },
    };

    Ok(vec![parse_quote! {
        ::bevy_pretty_nice_input::bundles::observe(#transition::<#action, #remove, #insert>)
    }])
}

#[derive(Clone)]
enum ObserverArrow {
    Left,
    Right,
}

#[derive(Clone)]
enum TransitionFromAction {
    Specified(syn::Type),
    Generated(syn::Type),
}

impl TransitionFromAction {
    fn action(&self) -> &syn::Type {
        match self {
            TransitionFromAction::Specified(t) => t,
            TransitionFromAction::Generated(t) => t,
        }
    }
}

impl ToTokens for TransitionFromAction {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        self.action().to_tokens(tokens);
    }
}

struct InputTransition {
    transition: Transition,
    bindings: Bindings,
    conditions: Conditions,
}

struct InputTransitionHalf {
    action: TransitionFromAction,
    from: TransitionFrom,
    to: Vec<syn::Type>,
    arrow: ObserverArrow,
    bindings: Bindings,
    conditions: Conditions,
}

impl InputTransitionHalf {
    fn remove_bundle(&self) -> syn::Type {
        let mut remove = self.from.inclusions.iter().cloned().collect::<HashSet<_>>();
        for inc in &self.to {
            remove.remove(inc);
        }
        let mut remove = remove.into_iter().collect::<Vec<_>>();
        remove.sort_by_key(|t| t.to_token_stream().to_string());
        parse_quote! { ( #( #remove ,)* ) }
    }

    fn insert_bundle(&self) -> syn::Type {
        let mut insert = self.to.iter().cloned().collect::<HashSet<_>>();
        for inc in &self.from.inclusions {
            insert.remove(inc);
        }
        let mut insert = insert.into_iter().collect::<Vec<_>>();
        insert.sort_by_key(|t| t.to_token_stream().to_string());
        parse_quote! { ( #( #insert ,)* ) }
    }
}

impl Parse for InputTransition {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let transition = input.parse::<Transition>()?;
        input.parse::<Token![,]>()?;
        let bindings = input.parse::<Bindings>()?;
        let conditions = if input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
            let conditions = input.parse::<Conditions>().unwrap_or_default();
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
            conditions
        } else {
            Conditions::default()
        };

        Ok(InputTransition {
            transition,
            bindings,
            conditions,
        })
    }
}

#[derive(Clone)]
struct TransitionFrom {
    action: Option<syn::Type>,
    inclusions: Vec<syn::Type>,
    exclusions: Vec<syn::Type>,
}

impl TransitionFrom {
    fn query_filter(&self) -> syn::Type {
        let inclusions = &self.inclusions;
        let exclusions = &self.exclusions;
        parse_quote! { ( #( ::bevy::prelude::With<#inclusions> ,)* #( ::bevy::prelude::Without<#exclusions> ,)* ) }
    }

    fn action(
        &self,
        left: &TransitionFrom,
        arrow: &ObserverArrow,
        right: &TransitionFrom,
    ) -> syn::Result<TransitionFromAction> {
        if let Some(action) = &self.action {
            Ok(TransitionFromAction::Specified(action.clone()))
        } else {
            let generated = generated_action(left, arrow, right)?;
            Ok(TransitionFromAction::Generated(generated))
        }
    }
}

fn generated_action(
    left: &TransitionFrom,
    arrow: &ObserverArrow,
    right: &TransitionFrom,
) -> syn::Result<syn::Type> {
    fn sanitize(s: &str) -> String {
        s.chars()
            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
            .collect()
    }

    fn type_to_ident_part(ty: &syn::Type) -> String {
        sanitize(&ty.to_token_stream().to_string())
    }

    let mut left_parts = vec![];
    for inc in left.inclusions.iter() {
        left_parts.push(type_to_ident_part(inc));
    }
    for exc in left.exclusions.iter() {
        left_parts.push(format!("Not{}", type_to_ident_part(exc)));
    }
    if left_parts.is_empty() {
        left_parts.push("None".to_string());
    }
    let left = left_parts.join("_");

    let mut right_parts = vec![];
    for inc in right.inclusions.iter() {
        right_parts.push(type_to_ident_part(inc));
    }
    for exc in right.exclusions.iter() {
        right_parts.push(format!("Not{}", type_to_ident_part(exc)));
    }
    if right_parts.is_empty() {
        right_parts.push("None".to_string());
    }
    let right = right_parts.join("_");

    let arrow = match arrow {
        ObserverArrow::Left => "From",
        ObserverArrow::Right => "To",
    };

    syn::parse_str(&format!("Transition_{}_{}_{}", left, arrow, right))
}

impl Parse for TransitionFrom {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let action = if input.peek(syn::token::Paren) {
            None
        } else {
            Some(input.parse::<syn::Type>()?)
        };

        let content;
        syn::parenthesized!(content in input);

        let types = content.parse_terminated(TransitionType::parse, Token![,])?;
        let mut inclusions = vec![];
        let mut exclusions = vec![];
        for ty in types {
            match ty {
                TransitionType::Inclusion(t) => inclusions.push(t),
                TransitionType::Exclusion(t) => exclusions.push(t),
            }
        }
        inclusions.sort_by_key(|t| t.to_token_stream().to_string());
        exclusions.sort_by_key(|t| t.to_token_stream().to_string());

        Ok(TransitionFrom {
            action,
            inclusions,
            exclusions,
        })
    }
}

impl ToTokens for TransitionFrom {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let inclusions = &self.inclusions;
        let exclusions = &self.exclusions;
        tokens.extend(quote! {
            ( #( #inclusions ,)* #( ! #exclusions ,)* )
        });
    }
}

#[derive(Clone)]
enum TransitionType {
    Inclusion(syn::Type),
    Exclusion(syn::Type),
}

impl Parse for TransitionType {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.peek(Token![!]) {
            input.parse::<Token![!]>()?;
            let ty = input.parse::<syn::Type>()?;
            Ok(TransitionType::Exclusion(ty))
        } else {
            let ty = input.parse::<syn::Type>()?;
            Ok(TransitionType::Inclusion(ty))
        }
    }
}

impl ToTokens for TransitionType {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            TransitionType::Inclusion(ty) => {
                ty.to_tokens(tokens);
            }
            TransitionType::Exclusion(ty) => {
                tokens.extend(quote! { ! #ty });
            }
        }
    }
}

#[derive(Clone, PartialEq, Debug)]
enum TransitionArrow {
    Left,
    Right,
    Both,
}

impl Parse for TransitionArrow {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.peek(Token![<]) && input.peek2(Token![=]) && input.peek3(Token![>]) {
            input.parse::<Token![<]>()?;
            input.parse::<Token![=]>()?;
            input.parse::<Token![>]>()?;
            Ok(TransitionArrow::Both)
        } else if input.peek(Token![<]) && input.peek2(Token![=]) {
            input.parse::<Token![<]>()?;
            input.parse::<Token![=]>()?;
            Ok(TransitionArrow::Left)
        } else if input.peek(Token![=]) && input.peek2(Token![>]) {
            input.parse::<Token![=]>()?;
            input.parse::<Token![>]>()?;
            Ok(TransitionArrow::Right)
        } else {
            Err(input.error("Expected one of `<=`, `=>`, or `<=>`"))
        }
    }
}

impl ToTokens for TransitionArrow {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            TransitionArrow::Left => {
                tokens.extend(quote! { <= });
            }
            TransitionArrow::Both => {
                tokens.extend(quote! { <=> });
            }
            TransitionArrow::Right => {
                tokens.extend(quote! { => });
            }
        }
    }
}

#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
enum Transition {
    Uni {
        action: TransitionFromAction,
        from: TransitionFrom,
        to: TransitionFrom,
        arrow: ObserverArrow,
    },
    Bi {
        left_action: TransitionFromAction,
        left: TransitionFrom,
        right_action: TransitionFromAction,
        right: TransitionFrom,
    },
}

impl Parse for Transition {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let left = input.parse::<TransitionFrom>()?;
        let arrow = input.parse::<TransitionArrow>()?;
        let right = input.parse::<TransitionFrom>()?;

        match arrow {
            TransitionArrow::Left => Ok(Transition::Uni {
                action: left.action(&left, &ObserverArrow::Left, &right)?,
                from: right,
                to: left,
                arrow: ObserverArrow::Left,
            }),
            TransitionArrow::Right => Ok(Transition::Uni {
                action: right.action(&left, &ObserverArrow::Right, &right)?,
                from: left,
                to: right,
                arrow: ObserverArrow::Right,
            }),
            TransitionArrow::Both => Ok(Transition::Bi {
                left_action: left.action(&left, &ObserverArrow::Left, &right)?,
                right_action: right.action(&left, &ObserverArrow::Right, &right)?,
                left,
                right,
            }),
        }
    }
}