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
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{parse_quote, ItemTrait, Result, TraitItem};

/// When added to a trait declaration, generates the impls required to use that trait in queries.
///
/// # Poor use cases
///
/// You should avoid using trait queries for very simple cases that can be solved with more direct solutions.
///
/// One naive use would be querying for a trait that looks something like:
///
/// ```
/// trait Person {
///     fn name(&self) -> &str;
/// }
/// ```
///
/// A far better way of expressing this would be to store the name in a separate component
/// and query for that directly, making `Person` a simple marker component.
///
/// Trait queries are often the most *obvious* solution to a problem, but not always the best one.
/// For examples of strong real-world use-cases, check out the RFC for trait queries in `bevy`:
/// https://github.com/bevyengine/rfcs/pull/39.
///
/// # Note
///
/// This will add the trait bound `'static` to the trait and all of its type parameters.
///
/// You may opt out of this by using the form `#[queryable(no_bounds)]`,
/// but you will have to add the bounds yourself to make it compile.
#[proc_macro_attribute]
pub fn queryable(attr: TokenStream, item: TokenStream) -> TokenStream {
    impl_trait_query(attr, item)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

fn impl_trait_query(arg: TokenStream, item: TokenStream) -> Result<TokenStream2> {
    syn::custom_keyword!(no_bounds);
    let no_bounds: Option<no_bounds> = syn::parse(arg).map_err(|e| {
        syn::Error::new(
            e.span(),
            "Valid forms are: `#[queryable]` and `#[queryable(no_bounds)]`",
        )
    })?;

    let mut trait_definition = syn::parse::<ItemTrait>(item)?;
    let trait_name = trait_definition.ident.clone();

    // Add `'static` bounds, unless the user asked us not to.
    if !no_bounds.is_some() {
        trait_definition.supertraits.push(parse_quote!('static));

        for param in &mut trait_definition.generics.params {
            // Make sure the parameters to the trait are `'static`.
            if let syn::GenericParam::Type(param) = param {
                param.bounds.push(parse_quote!('static));
            }
        }

        for item in &mut trait_definition.items {
            // Make sure all associated types are `'static`.
            if let TraitItem::Type(assoc) = item {
                assoc.bounds.push(parse_quote!('static));
            }
        }
    }

    let mut impl_generics_list = vec![];
    let mut trait_generics_list = vec![];
    let where_clause = trait_definition.generics.where_clause.clone();

    for param in &trait_definition.generics.params {
        impl_generics_list.push(param.clone());
        match param {
            syn::GenericParam::Type(param) => {
                let ident = &param.ident;
                trait_generics_list.push(quote! { #ident });
            }
            syn::GenericParam::Lifetime(param) => {
                let ident = &param.lifetime;
                trait_generics_list.push(quote! { #ident });
            }
            syn::GenericParam::Const(param) => {
                let ident = &param.ident;
                trait_generics_list.push(quote! { #ident });
            }
        }
    }

    // Add generics for unbounded associated types.
    for item in &trait_definition.items {
        if let TraitItem::Type(assoc) = item {
            if !assoc.generics.params.is_empty() {
                return Err(syn::Error::new(
                    assoc.ident.span(),
                    "Generic associated types are not supported in trait queries",
                ));
            }
            let ident = &assoc.ident;
            let lower_ident = format_ident!("__{ident}");
            let bound = &assoc.bounds;
            impl_generics_list.push(parse_quote! { #lower_ident: #bound });
            trait_generics_list.push(quote! { #ident = #lower_ident });
        }
    }

    let impl_generics = quote! { <#( #impl_generics_list ,)*> };
    let trait_generics = quote! { <#( #trait_generics_list ,)*> };

    let trait_object = quote! { dyn #trait_name #trait_generics };

    let my_crate = proc_macro_crate::crate_name("bevy-trait-query").unwrap();
    let my_crate = match my_crate {
        proc_macro_crate::FoundCrate::Itself => quote! { bevy_trait_query },
        proc_macro_crate::FoundCrate::Name(x) => {
            let ident = quote::format_ident!("{x}");
            quote! { #ident }
        }
    };

    let imports = quote! { #my_crate::imports };

    let trait_query = quote! { #my_crate::TraitQuery };

    let mut marker_impl_generics_list = impl_generics_list.clone();
    marker_impl_generics_list
        .push(parse_quote!(__Component: #trait_name #trait_generics + #imports::Component));
    let marker_impl_generics = quote! { <#( #marker_impl_generics_list ,)*> };

    let marker_impl_code = quote! {
        impl #impl_generics #trait_query for #trait_object #where_clause {}

        impl #marker_impl_generics #my_crate::TraitQueryMarker::<#trait_object> for (__Component,)
        #where_clause
        {
            type Covered = __Component;
            fn cast(ptr: *mut u8) -> *mut #trait_object {
                ptr as *mut __Component as *mut _
            }
        }
    };

    let mut impl_generics_with_lifetime = impl_generics_list.clone();
    impl_generics_with_lifetime.insert(0, parse_quote!('__a));
    let impl_generics_with_lifetime = quote! { <#( #impl_generics_with_lifetime ,)*> };

    let trait_object_query_code = quote! {
        unsafe impl #impl_generics #imports::QueryData for &#trait_object
        #where_clause
        {
            type ReadOnly = Self;
        }
        unsafe impl #impl_generics #imports::ReadOnlyQueryData for &#trait_object
        #where_clause
        {}

        unsafe impl #impl_generics_with_lifetime #imports::WorldQuery for &'__a #trait_object
        #where_clause
        {
            type Item<'__w> = #my_crate::ReadTraits<'__w, #trait_object>;
            type Fetch<'__w> = <#my_crate::All<&'__a #trait_object> as #imports::WorldQuery>::Fetch<'__w>;
            type State = #my_crate::TraitQueryState<#trait_object>;

            #[inline]
            unsafe fn init_fetch<'w>(
                world: #imports::UnsafeWorldCell<'w>,
                state: &Self::State,
                last_run: #imports::Tick,
                this_run: #imports::Tick,
            ) -> Self::Fetch<'w> {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::init_fetch(
                    world,
                    state,
                    last_run,
                    this_run,
                )
            }

            #[inline]
            fn shrink<'wlong: 'wshort, 'wshort>(
                item: Self::Item<'wlong>,
            ) -> Self::Item<'wshort> {
                item
            }

            const IS_DENSE: bool = <#my_crate::All<&#trait_object> as #imports::WorldQuery>::IS_DENSE;

            #[inline]
            unsafe fn set_archetype<'w>(
                fetch: &mut Self::Fetch<'w>,
                state: &Self::State,
                archetype: &'w #imports::Archetype,
                tables: &'w #imports::Table,
            ) {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::set_archetype(
                    fetch, state, archetype, tables,
                );
            }

            #[inline]
            unsafe fn set_table<'w>(
                fetch: &mut Self::Fetch<'w>,
                state: &Self::State,
                table: &'w #imports::Table,
            ) {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::set_table(fetch, state, table);
            }

            #[inline]
            unsafe fn fetch<'w>(
                fetch: &mut Self::Fetch<'w>,
                entity: #imports::Entity,
                table_row: #imports::TableRow,
            ) -> Self::Item<'w> {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::fetch(
                    fetch,
                    entity,
                    table_row,
                )
            }

            #[inline]
            fn update_component_access(
                state: &Self::State,
                access: &mut #imports::FilteredAccess<#imports::ComponentId>,
            ) {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::update_component_access(
                    state, access,
                );
            }

            #[inline]
            fn init_state(world: &mut #imports::World) -> Self::State {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::init_state(world)
            }

            #[inline]
            fn get_state(world: &#imports::World) -> Option<Self::State> {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::get_state(world)
            }

            #[inline]
            fn matches_component_set(
                state: &Self::State,
                set_contains_id: &impl Fn(#imports::ComponentId) -> bool,
            ) -> bool {
                <#my_crate::All<&#trait_object> as #imports::WorldQuery>::matches_component_set(state, set_contains_id)
            }
        }

        unsafe impl #impl_generics_with_lifetime #imports::QueryData for &'__a mut #trait_object
        #where_clause
        {
            type ReadOnly = &'__a #trait_object;
        }

        unsafe impl #impl_generics_with_lifetime #imports::WorldQuery for &'__a mut #trait_object
        #where_clause
        {
            type Item<'__w> = #my_crate::WriteTraits<'__w, #trait_object>;
            type Fetch<'__w> = <#my_crate::All<&'__a #trait_object> as #imports::WorldQuery>::Fetch<'__w>;
            type State = #my_crate::TraitQueryState<#trait_object>;

            #[inline]
            unsafe fn init_fetch<'w>(
                world: #imports::UnsafeWorldCell<'w>,
                state: &Self::State,
                last_run: #imports::Tick,
                this_run: #imports::Tick,
            ) -> Self::Fetch<'w> {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::init_fetch(
                    world,
                    state,
                    last_run,
                    this_run,
                )
            }

            #[inline]
            fn shrink<'wlong: 'wshort, 'wshort>(
                item: Self::Item<'wlong>,
            ) -> Self::Item<'wshort> {
                item
            }

            const IS_DENSE: bool = <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::IS_DENSE;

            #[inline]
            unsafe fn set_archetype<'w>(
                fetch: &mut Self::Fetch<'w>,
                state: &Self::State,
                archetype: &'w #imports::Archetype,
                table: &'w #imports::Table,
            ) {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::set_archetype(
                    fetch, state, archetype, table,
                );
            }

            #[inline]
            unsafe fn set_table<'w>(
                fetch: &mut Self::Fetch<'w>,
                state: &Self::State,
                table: &'w #imports::Table,
            ) {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::set_table(fetch, state, table);
            }

            #[inline]
            unsafe fn fetch<'w>(
                fetch: &mut Self::Fetch<'w>,
                entity: #imports::Entity,
                table_row: #imports::TableRow,
            ) -> Self::Item<'w> {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::fetch(
                    fetch,
                    entity,
                    table_row,
                )
            }

            #[inline]
            fn update_component_access(
                state: &Self::State,
                access: &mut #imports::FilteredAccess<#imports::ComponentId>,
            ) {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::update_component_access(
                    state, access,
                );
            }

            #[inline]
            fn init_state(world: &mut #imports::World) -> Self::State {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::init_state(world)
            }

            #[inline]
            fn get_state(world: &#imports::World) -> Option<Self::State> {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::get_state(world)
            }

            #[inline]
            fn matches_component_set(
                state: &Self::State,
                set_contains_id: &impl Fn(#imports::ComponentId) -> bool,
            ) -> bool {
                <#my_crate::All<&mut #trait_object> as #imports::WorldQuery>::matches_component_set(state, set_contains_id)
            }
        }
    };

    Ok(quote! {
        #trait_definition

        #marker_impl_code

        #trait_object_query_code
    })
}