gecs_macros 0.3.0

Procedural macros for the gecs crate.
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
use std::collections::HashMap;

use convert_case::{Case, Casing};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, quote_spanned};

use crate::data::{DataArchetype, DataWorld};
use crate::parse::{ParseQueryFind, ParseQueryIter, ParseQueryParam, ParseQueryParamType};

// NOTE: We should avoid using panics to express errors in queries when generating.
// Doing so will attribute the error to the ecs_world! declaration (due to the redirect
// macro) rather than to the query macro itself. Always use an Err result where possible.

#[derive(Clone, Copy, Debug)]
pub enum FetchMode {
    Mut,
    Borrow,
}

#[allow(non_snake_case)]
pub fn generate_query_find(mode: FetchMode, query: ParseQueryFind) -> syn::Result<TokenStream> {
    let world_data = DataWorld::from_base64(&query.world_data);
    let bound_params = bind_query_params(&world_data, &query.params)?;

    // NOTE: Beyond this point, query.params is only safe to use for information that
    // does not change depending on the type of the parameter (e.g. mutability). Anything
    // that might change after OneOf binding etc. must use the bound query params in
    // bound_params for the given archetype. Note that it's faster to use query.params
    // where available, since it avoids redundant computation for each archetype.

    // TODO PERF: We could avoid binding entirely if we know that the params have no OneOf.

    // Types
    let SelectInternalWorld = format_ident!("__SelectInternal{}", world_data.name);

    // Variables and fields
    let world = &query.world;
    let entity = &query.entity;
    let body = &query.body;
    let arg = query.params.iter().map(to_name).collect::<Vec<_>>();

    // We want this to be hygenic because it's declared above the closure.
    let resolved_entity = quote_spanned!(Span::mixed_site() => entity);

    // Keywords
    let maybe_mut = query.params.iter().map(to_maybe_mut).collect::<Vec<_>>();

    // Explicit return value on the query
    let ret = match &query.ret {
        Some(ret) => quote!(-> #ret),
        None => quote!(),
    };

    let mut queries = Vec::<TokenStream>::new();
    for archetype in world_data.archetypes {
        debug_assert!(archetype.build_data.is_none());

        if let Some(bound_params) = bound_params.get(&archetype.name) {
            // Types and traits
            let Archetype = format_ident!("{}", archetype.name);
            let ArchetypeRaw = format_ident!("{}Raw", archetype.name);
            let Type = bound_params
                .iter()
                .map(|p| to_type(p, &archetype))
                .collect::<Vec<_>>(); // Bind-dependent!

            #[rustfmt::skip]
            let get_archetype = match mode {
                FetchMode::Borrow => quote!(#world.archetype::<#Archetype>()),
                FetchMode::Mut => quote!(#world.archetype_mut::<#Archetype>()),
            };

            #[rustfmt::skip]
            let let_resolve = match mode {
                FetchMode::Borrow => quote!(
                    let Some(borrow) = archetype.begin_borrow(#resolved_entity)
                ),
                FetchMode::Mut => quote!(
                    let Some(view) = archetype.get_view_mut(#resolved_entity)
                ),
            };

            #[rustfmt::skip]
            let bind = match mode {
                FetchMode::Borrow => bound_params.iter().map(find_bind_borrow).collect::<Vec<_>>(),
                FetchMode::Mut => bound_params.iter().map(find_bind_mut).collect::<Vec<_>>(),
            };

            queries.push(quote!(
                #SelectInternalWorld::#Archetype(#resolved_entity) => {
                    // Alias the current archetype for use in the closure.
                    type MatchedArchetype = #Archetype;
                    // The closure needs to be made per-archetype because of OneOf types.
                    let mut closure = |#(#arg: &#maybe_mut #Type),*| #ret #body;

                    let archetype = #get_archetype;
                    let version = archetype.version();

                    if #let_resolve {
                        Some(closure(#(#bind),*))
                    } else {
                        None
                    }
                }
                #SelectInternalWorld::#ArchetypeRaw(#resolved_entity) => {
                    // Alias the current archetype for use in the closure.
                    type MatchedArchetype = #Archetype;
                    // The closure needs to be made per-archetype because of OneOf types.
                    let mut closure = |#(#arg: &#maybe_mut #Type),*| #ret #body;

                    let archetype = #get_archetype;
                    let version = archetype.version();

                    if #let_resolve {
                        Some(closure(#(#bind),*))
                    } else {
                        None
                    }
                }
            ));
        }
    }

    if queries.is_empty() {
        Err(syn::Error::new_spanned(
            world,
            "query matched no archetypes in world",
        ))
    } else {
        Ok(quote!(
            {
                match #SelectInternalWorld::from(#entity) {
                    #(#queries)*
                    _ => None,
                }
            }
        ))
    }
}

#[rustfmt::skip]
fn find_bind_mut(param: &ParseQueryParam) -> TokenStream {
    match &param.param_type {
        ParseQueryParamType::Component(ident) => { 
            let ident = to_snake_ident(ident); quote!(view.#ident)
        }
        ParseQueryParamType::Entity(_) => {
            quote!(view.entity)
        }
        ParseQueryParamType::EntityAny => {
            quote!(view.entity.into())
        }
        ParseQueryParamType::EntityWild => {
            quote!(view.entity)
        }
        ParseQueryParamType::EntityRaw(_) => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(view.index(), version))
        }
        ParseQueryParamType::EntityRawAny => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(view.index(), version).into())
        }
        ParseQueryParamType::EntityRawWild => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(view.index(), version))
        }
        ParseQueryParamType::OneOf(_) => {
            panic!("must unpack OneOf first")
        }
    }
}

#[rustfmt::skip]
fn find_bind_borrow(param: &ParseQueryParam) -> TokenStream {
    match &param.param_type {
        ParseQueryParamType::Component(ident) => {
            match param.is_mut { 
                true => quote!(&mut borrow.borrow_mut::<#ident>()),
                false => quote!(&borrow.borrow::<#ident>()),
            }
        }
        ParseQueryParamType::Entity(_) => {
            quote!(borrow.entity())
        }
        ParseQueryParamType::EntityAny => {
            quote!(borrow.entity().into())
        }
        ParseQueryParamType::EntityWild => {
            quote!(borrow.entity())
        }
        ParseQueryParamType::EntityRaw(_) => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(borrow.index(), version))
        }
        ParseQueryParamType::EntityRawAny => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(borrow.index(), version).into())
        }
        ParseQueryParamType::EntityRawWild => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(borrow.index(), version))
        }
        ParseQueryParamType::OneOf(_) => {
            panic!("must unpack OneOf first")
        }
    }
}

#[allow(non_snake_case)]
pub fn generate_query_iter(mode: FetchMode, query: ParseQueryIter) -> syn::Result<TokenStream> {
    let world_data = DataWorld::from_base64(&query.world_data);
    let bound_params = bind_query_params(&world_data, &query.params)?;

    // NOTE: Beyond this point, query.params is only safe to use for information that
    // does not change depending on the type of the parameter (e.g. mutability). Anything
    // that might change after OneOf binding etc. must use the bound query params in
    // bound_params for the given archetype. Note that it's faster to use query.params
    // where available, since it avoids redundant computation for each archetype.

    // TODO PERF: We could avoid binding entirely if we know that the params have no OneOf.

    // Variables and fields
    let world = &query.world;
    let body = &query.body;
    let arg = query.params.iter().map(to_name).collect::<Vec<_>>();

    // Special cases
    let maybe_mut = query.params.iter().map(to_maybe_mut).collect::<Vec<_>>();

    let mut queries = Vec::<TokenStream>::new();
    for archetype in world_data.archetypes {
        debug_assert!(archetype.build_data.is_none());

        if let Some(bound_params) = bound_params.get(&archetype.name) {
            // Types and traits
            let Archetype = format_ident!("{}", archetype.name);
            let Type = bound_params
                .iter()
                .map(|p| to_type(p, &archetype))
                .collect::<Vec<_>>(); // Bind-dependent!

            #[rustfmt::skip]
            let get_archetype = match mode {
                FetchMode::Borrow => quote!(#world.archetype::<#Archetype>()),
                FetchMode::Mut => quote!(#world.archetype_mut::<#Archetype>()),
            };

            #[rustfmt::skip]
            let get_slices = match mode {
                FetchMode::Borrow => quote!(()),
                FetchMode::Mut => quote!(archetype.get_all_slices_mut()),
            };

            #[rustfmt::skip]
            let bind = match mode {
                FetchMode::Borrow => bound_params.iter().map(iter_bind_borrow).collect::<Vec<_>>(),
                FetchMode::Mut => bound_params.iter().map(iter_bind_mut).collect::<Vec<_>>(),
            };

            queries.push(quote!(
                {
                    // Alias the current archetype for use in the closure
                    type MatchedArchetype = #Archetype;
                    // The closure needs to be made per-archetype because of OneOf types
                    let mut closure = |#(#arg: &#maybe_mut #Type),*| #body;

                    let archetype = #get_archetype;
                    let version = archetype.version();
                    let len = archetype.len();
                    let slices = #get_slices;

                    for idx in 0..len {
                        closure(#(#bind),*);
                    }
                }
            ));
        }
    }

    if queries.is_empty() {
        Err(syn::Error::new_spanned(
            world,
            "query matched no archetypes in world",
        ))
    } else {
        Ok(quote!(#(#queries)*))
    }
}

#[rustfmt::skip]
fn iter_bind_mut(param: &ParseQueryParam) -> TokenStream {
    match &param.param_type {
        ParseQueryParamType::Component(ident) => { 
            let ident = to_snake_ident(ident); 
            match param.is_mut { 
                true => quote!(&mut slices.#ident[idx]),
                false => quote!(&slices.#ident[idx]),
            }
        }
        ParseQueryParamType::Entity(_) => {
            quote!(&slices.entity[idx])
        }
        ParseQueryParamType::EntityAny => {
            quote!(&slices.entity[idx].into())
        }
        ParseQueryParamType::EntityWild => {
            quote!(&slices.entity[idx])
        }
        ParseQueryParamType::EntityRaw(_) => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(idx, version))
        }
        ParseQueryParamType::EntityRawAny => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(idx, version).into())
        }
        ParseQueryParamType::EntityRawWild => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(idx, version))
        }
        ParseQueryParamType::OneOf(_) => {
            panic!("must unpack OneOf first")
        }
    }
}

#[rustfmt::skip]
fn iter_bind_borrow(param: &ParseQueryParam) -> TokenStream {
    match &param.param_type {
        ParseQueryParamType::Component(ident) => {
            match param.is_mut { 
                true => quote!(&mut archetype.borrow_slice_mut::<#ident>()[idx]),
                false => quote!(&archetype.borrow_slice::<#ident>()[idx]),
            }
        }
        ParseQueryParamType::Entity(_) => {
            quote!(&archetype.get_slice_entities()[idx])
        }
        ParseQueryParamType::EntityAny => {
            quote!(&archetype.get_slice_entities()[idx].into())
        }
        ParseQueryParamType::EntityWild => {
            quote!(&archetype.get_slice_entities()[idx])
        }
        ParseQueryParamType::EntityRaw(_) => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(idx, version))
        }
        ParseQueryParamType::EntityRawAny => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(idx, version).into())
        }
        ParseQueryParamType::EntityRawWild => {
            quote!(&::gecs::__internal::new_entity_raw::<MatchedArchetype>(idx, version))
        }
        ParseQueryParamType::OneOf(_) => {
            panic!("must unpack OneOf first")
        }
    }
}

fn to_name(param: &ParseQueryParam) -> TokenStream {
    let name = &param.name;
    quote!(#name)
}

#[rustfmt::skip]
fn to_type(param: &ParseQueryParam, archetype: &DataArchetype) -> TokenStream {
    let archetype_name = format_ident!("{}", archetype.name);
    match &param.param_type {
        ParseQueryParamType::Component(ident) => quote!(#ident),
        ParseQueryParamType::Entity(ident) => quote!(Entity<#ident>),
        ParseQueryParamType::EntityAny => quote!(EntityAny),
        ParseQueryParamType::EntityWild => quote!(Entity<#archetype_name>),
        ParseQueryParamType::EntityRaw(ident) => quote!(EntityRaw<#ident>),
        ParseQueryParamType::EntityRawAny => quote!(EntityRawAny),
        ParseQueryParamType::EntityRawWild => quote!(EntityRaw<#archetype_name>),
        ParseQueryParamType::OneOf(_) => panic!("must unpack OneOf first"),
    }
}

fn to_maybe_mut(param: &ParseQueryParam) -> TokenStream {
    match &param.is_mut {
        true => quote!(mut),
        false => quote!(),
    }
}

fn to_snake_ident(ident: &Ident) -> Ident {
    Ident::new(&to_snake_str(&ident.to_string()), ident.span())
}

fn to_snake_str(name: &String) -> String {
    name.from_case(Case::Pascal).to_case(Case::Snake)
}

fn bind_query_params(
    world_data: &DataWorld,
    params: &[ParseQueryParam],
) -> syn::Result<HashMap<String, Box<[ParseQueryParam]>>> {
    let mut result = HashMap::new();
    let mut bound = Vec::new();

    for archetype in world_data.archetypes.iter() {
        bound.clear();

        for param in params {
            match &param.param_type {
                ParseQueryParamType::EntityAny => {
                    bound.push(param.clone()); // Always matches
                }
                ParseQueryParamType::EntityRawAny => {
                    bound.push(param.clone()); // Always matches
                }
                ParseQueryParamType::EntityWild => {
                    bound.push(param.clone()); // Always matches
                }
                ParseQueryParamType::EntityRawWild => {
                    bound.push(param.clone()); // Always matches
                }
                ParseQueryParamType::Component(name) => {
                    if archetype.contains_component(name) {
                        bound.push(param.clone());
                    } else {
                        continue; // No need to check more
                    }
                }
                ParseQueryParamType::Entity(name) => {
                    if archetype.name == name.to_string() {
                        bound.push(param.clone());
                    } else {
                        continue; // No need to check more
                    }
                }
                ParseQueryParamType::EntityRaw(name) => {
                    if archetype.name == name.to_string() {
                        bound.push(param.clone());
                    } else {
                        continue; // No need to check more
                    }
                }
                ParseQueryParamType::OneOf(args) => {
                    if let Some(found) = bind_one_of(archetype, args)? {
                        // Convert this to a new Component type
                        bound.push(ParseQueryParam {
                            name: param.name.clone(),
                            is_mut: param.is_mut,
                            param_type: found,
                        });
                    } else {
                        continue; // No need to check more
                    }
                }
            }
        }

        // Did we remap everything?
        if bound.len() == params.len() {
            result.insert(archetype.name.clone(), bound.clone().into_boxed_slice());
        }
    }

    Ok(result)
}

fn bind_one_of(
    archetype: &DataArchetype, //.
    one_of_args: &[Ident],
) -> syn::Result<Option<ParseQueryParamType>> {
    let mut found: Option<Ident> = None;

    for arg in one_of_args.iter() {
        if archetype.contains_component(arg) {
            // An OneOf can only match one component in a given archetype
            if let Some(found) = found {
                return Err(syn::Error::new(
                    arg.span(),
                    format!(
                        "OneOf parameter is ambiguous for {}, matching both {} and {}",
                        archetype.name,
                        found.to_string(),
                        arg.to_string(),
                    ),
                ));
            }

            // We found at least one match for this archetype
            found = Some(arg.clone());
        }
    }

    // TODO: What about OneOf<Entity<A>, Entity<B>>?
    Ok(found.map(|ident| ParseQueryParamType::Component(ident)))
}