Skip to main content

bevy_registration_procedural_macros/
lib.rs

1use foldhash::HashMap;
2
3use proc_macro::TokenStream as StdTokenStream;
4use proc_macro2::{Span, TokenStream};
5use quote::quote;
6use syn::{
7    DeriveInput, Expr, Ident, ItemFn, Meta, Token, bracketed, parenthesized, parse::Parse,
8    parse_macro_input, punctuated::Punctuated, token,
9};
10
11/// Initiates events, resources, and reflected structs.
12/// Place above the derives.
13/// Example:
14/// ```
15/// #[init]
16/// #[derive(Resource, Default)]
17/// struct TestResource;
18///```
19#[proc_macro_attribute]
20pub fn init(_arguments: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
21    let input = item.clone();
22    // A tad dodgy, but when an attribute macro is on an item, it will have the same input as a derive macro.
23    let input = parse_macro_input!(input as DeriveInput);
24
25    let mut output: TokenStream = item.into();
26
27    let struct_ident = input.ident;
28
29    input.attrs.into_iter().for_each(|attribute| {
30        let Some(ident) = attribute.path().get_ident() else {
31            return;
32        };
33
34        if ident != "derive" {
35            return;
36        }
37
38        let Meta::List(derives) = attribute.meta else {
39            // Derive should always be a Meta::List so this won't ever return.
40            return;
41        };
42
43        let derives = derives.tokens.to_string();
44
45        if derives.contains("Resource") {
46            output.extend(quote! {
47                bevy_registration::app!(|app| {
48                    app.init_resource::<#struct_ident>();
49                });
50            });
51        }
52
53        if derives.contains("Event") {
54            output.extend(quote! {
55                bevy_registration::app!(|app| {
56                    app.add_event::<#struct_ident>();
57                });
58            });
59        }
60
61        if derives.contains("Reflect") {
62            output.extend(quote! {
63                bevy_registration::app!(|app| {
64                    app.register_type::<#struct_ident>();
65                });
66            });
67        }
68    });
69
70    output.into()
71}
72
73/// Annotates a system, and adds it to a schedule.
74/// It looks for the schedule in the crate root, so make sure it is accessible there.
75/// Example:
76/// ```
77/// #[system(Update)]
78/// fn some_system() {}
79///```
80/// To use it with [schedule!] you put :: between each path segment.
81/// Example:
82/// ```
83/// #[system(Update::Test)]
84/// fn some_system() {}
85/// ```
86#[proc_macro_attribute]
87pub fn system(arguments: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
88    let input = item.clone();
89    let input = parse_macro_input!(input as ItemFn);
90
91    let ident = input.sig.ident;
92
93    let mut output: TokenStream = item.into();
94
95    let schedule = Ident::new(
96        &arguments.to_string().replace(' ', "").replace("::", "_"),
97        Span::call_site(),
98    );
99
100    output.extend(quote! {
101        bevy_registration::app!(|app| {
102            app.add_systems(crate::#schedule, #ident);
103        });
104    });
105
106    output.into()
107}
108
109struct Schedule {
110    attributes: Vec<(Ident, Expr)>,
111    ident: Ident,
112    subschedules: Punctuated<Schedule, Token![,]>,
113}
114
115impl Schedule {
116    fn add_to_app(
117        &mut self,
118        define_structs: &mut TokenStream,
119        app: &mut TokenStream,
120        mut path: Vec<Ident>,
121    ) {
122        path.push(self.ident.clone());
123        let path_quote = quote! {#(#path)_*};
124
125        let attributes_template: HashMap<&str, Option<&Expr>> = ["run_every"]
126            .into_iter()
127            .map(|attribute| (attribute, None))
128            .collect();
129
130        let subschedules_attributes: Vec<HashMap<&str, Option<&Expr>>> = self
131            .subschedules
132            .iter()
133            .map(|schedule| {
134                let mut attributes = attributes_template.clone();
135                schedule.attributes.iter().for_each(|(ident, expr)| {
136                    let Some(attribute) = attributes.get_mut(ident.to_string().as_str()) else {
137                        define_structs.extend(
138                            syn::Error::new(ident.span(), "This attribute doesn't exist.")
139                                .into_compile_error(),
140                        );
141                        return;
142                    };
143
144                    if attribute.is_none() {
145                        *attribute = Some(expr);
146                    } else {
147                        define_structs.extend(
148                            syn::Error::new(ident.span(), "You have already used this attribute.")
149                                .into_compile_error(),
150                        );
151                    }
152                });
153
154                attributes
155            })
156            .collect();
157
158        let subschedules_idents = self.subschedules.iter().map(|schedule| &schedule.ident);
159
160        define_structs.extend(quote! {
161            #(
162                bevy_registration::paste! {
163                    #[derive(bevy::ecs::schedule::ScheduleLabel, Hash, Debug, Eq, PartialEq, Clone, Default)]
164                    pub struct [<#path_quote _ #subschedules_idents>];
165                }
166            )*
167        });
168
169        let subschedules_runners = self.subschedules.iter().zip(subschedules_attributes).map(|(schedule, attributes)| {
170            let ident = &schedule.ident;
171
172            if let Some(expr) = attributes.get("run_every").unwrap() {
173                quote! {
174                    |world: &mut bevy::prelude::World, mut time_passed: bevy::prelude::Local<std::time::Duration>| {
175                        *time_passed += world.resource::<bevy::time::Time>().delta();
176
177                        //warn_once!("TODO: The resource Time does not currently work in fixed timestep schedules.");
178                        let time = world.remove_resource::<bevy::time::Time>().unwrap();
179                        let mut fixed_time = bevy::time::Time::<bevy::prelude::Fixed>::from_duration(#expr).as_generic();
180                        fixed_time.advance_by(#expr);
181                        world.insert_resource(fixed_time);
182
183                        while *time_passed >= #expr {
184                            *time_passed -= #expr;
185                            let _ = world.try_run_schedule([<#path_quote _ #ident>]::default());
186                        }
187
188                        world.remove_resource::<bevy::time::Time>().unwrap();
189                        world.insert_resource(time);
190                    }
191                }
192            } else {
193                quote! {
194                    bevy_registration::try_run_schedule::<[<#path_quote _ #ident>]>
195                }
196            }
197        });
198
199        app.extend(quote! {
200            bevy_registration::paste! {
201                app.add_systems(
202                    [<#path_quote>],
203                    bevy::prelude::IntoSystemConfigs::chain((#(#subschedules_runners),*)),
204                );
205            }
206        });
207
208        self.subschedules.iter_mut().for_each(|schedule| {
209            if schedule.subschedules.is_empty() {
210                return;
211            }
212            schedule.add_to_app(define_structs, app, path.clone());
213        });
214    }
215}
216
217impl Parse for Schedule {
218    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
219        let mut attributes = vec![];
220
221        while input.peek(token::Bracket) {
222            let attribute;
223            bracketed!(attribute in input);
224
225            let ident = attribute.parse()?;
226
227            let expression;
228            parenthesized!(expression in attribute);
229
230            let expression = expression.parse()?;
231
232            attributes.push((ident, expression));
233        }
234
235        let ident = input.parse()?;
236
237        let subschedules = if input.peek(token::Paren) {
238            let subschedules;
239            parenthesized!(subschedules in input);
240
241            subschedules.parse_terminated(Self::parse, Token![,])?
242        } else {
243            Default::default()
244        };
245
246        Ok(Self {
247            attributes,
248            ident,
249            subschedules,
250        })
251    }
252}
253
254/// Creates a schedule hierarchy.
255/// Schedules in the heirarchy may have these attributes:
256/// * `run_every(Duration)` Runs the schedule every time the duration passes. May run the schedule multiple times.
257/// ## Example:
258/// ```
259/// schedule! {
260///     Update(
261///         [run_every(Duration::from_secs_f32(1.))]
262///         Test(
263///             First,
264///             Second,
265///             Third,
266///         ),
267///     )
268/// }
269///
270/// #[system(Update::Test::First)]
271/// fn first() {
272///     info!("1");
273/// }
274///
275/// #[system(Update::Test::Second)]
276/// fn second() {
277///     info!("2");
278/// }
279///
280/// #[system(Update::Test::Third)]
281/// fn third() {
282///     info!("3");
283/// }
284///
285/// #[system(Update::Test)]
286/// fn random() {
287///     info!("random");
288/// }
289/// ```
290/// Every 1 second, the Test schedule will run. First, Second, and Third always run in that order, with random being able to run at any point.
291#[proc_macro]
292pub fn schedule(input: StdTokenStream) -> StdTokenStream {
293    let mut input = parse_macro_input!(input as Schedule);
294
295    if !input.attributes.is_empty() {
296        return syn::Error::new(input.ident.span(), "Base schedule cannot have attributes.")
297            .into_compile_error()
298            .into();
299    }
300
301    let mut app = quote! {};
302    let mut define_structs = quote! {};
303
304    input.add_to_app(&mut define_structs, &mut app, vec![]);
305
306    quote! {
307        #define_structs
308
309        bevy_registration::app!(|app| {
310            #app
311        });
312    }
313    .into()
314}