bevy_utils_proc_macros/
lib.rs

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
// FIXME(15321): solve CI failures, then replace with `#![expect()]`.
#![allow(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

use proc_macro::TokenStream;
use proc_macro2::{Span as Span2, TokenStream as TokenStream2};
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input,
    spanned::Spanned as _,
    token::Comma,
    Attribute, Error, Ident, LitInt, LitStr, Result,
};
struct AllTuples {
    fake_variadic: bool,
    macro_ident: Ident,
    start: usize,
    end: usize,
    idents: Vec<Ident>,
}

impl Parse for AllTuples {
    fn parse(input: ParseStream) -> Result<Self> {
        let fake_variadic = input.call(parse_fake_variadic_attr)?;
        let macro_ident = input.parse::<Ident>()?;
        input.parse::<Comma>()?;
        let start = input.parse::<LitInt>()?.base10_parse()?;
        input.parse::<Comma>()?;
        let end = input.parse::<LitInt>()?.base10_parse()?;
        input.parse::<Comma>()?;
        let mut idents = vec![input.parse::<Ident>()?];
        while input.parse::<Comma>().is_ok() {
            idents.push(input.parse::<Ident>()?);
        }

        if start > 1 && fake_variadic {
            return Err(Error::new(
                input.span(),
                "#[doc(fake_variadic)] only works when the tuple with length one is included",
            ));
        }

        Ok(AllTuples {
            fake_variadic,
            macro_ident,
            start,
            end,
            idents,
        })
    }
}

/// Helper macro to generate tuple pyramids. Useful to generate scaffolding to work around Rust
/// lacking variadics. Invoking `all_tuples!(impl_foo, start, end, P, Q, ..)`
/// invokes `impl_foo` providing ident tuples through arity `start..=end`.
/// If you require the length of the tuple, see [`all_tuples_with_size!`].
///
/// # Examples
///
/// ## Single parameter
///
/// ```
/// # use core::marker::PhantomData;
/// # use bevy_utils_proc_macros::all_tuples;
/// #
/// struct Foo<T> {
///     // ..
/// #    _phantom: PhantomData<T>
/// }
///
/// trait WrappedInFoo {
///     type Tup;
/// }
///
/// macro_rules! impl_wrapped_in_foo {
///     ($($T:ident),*) => {
///         impl<$($T),*> WrappedInFoo for ($($T,)*) {
///             type Tup = ($(Foo<$T>,)*);
///         }
///     };
/// }
///
/// all_tuples!(impl_wrapped_in_foo, 0, 15, T);
/// // impl_wrapped_in_foo!();
/// // impl_wrapped_in_foo!(T0);
/// // impl_wrapped_in_foo!(T0, T1);
/// // ..
/// // impl_wrapped_in_foo!(T0 .. T14);
/// ```
///
/// # Multiple parameters
///
/// ```
/// # use bevy_utils_proc_macros::all_tuples;
/// #
/// trait Append {
///     type Out<Item>;
///     fn append<Item>(tup: Self, item: Item) -> Self::Out<Item>;
/// }
///
/// impl Append for () {
///     type Out<Item> = (Item,);
///     fn append<Item>(_: Self, item: Item) -> Self::Out<Item> {
///         (item,)
///     }
/// }
///
/// macro_rules! impl_append {
///     ($(($P:ident, $p:ident)),*) => {
///         impl<$($P),*> Append for ($($P,)*) {
///             type Out<Item> = ($($P),*, Item);
///             fn append<Item>(($($p,)*): Self, item: Item) -> Self::Out<Item> {
///                 ($($p),*, item)
///             }
///         }
///     }
/// }
///
/// all_tuples!(impl_append, 1, 15, P, p);
/// // impl_append!((P0, p0));
/// // impl_append!((P0, p0), (P1, p1));
/// // impl_append!((P0, p0), (P1, p1), (P2, p2));
/// // ..
/// // impl_append!((P0, p0) .. (P14, p14));
/// ```
///
/// **`#[doc(fake_variadic)]`**
///
/// To improve the readability of your docs when implementing a trait for
/// tuples or fn pointers of varying length you can use the rustdoc-internal `fake_variadic` marker.
/// All your impls are collapsed and shown as a single `impl Trait for (F₁, F₂, …, Fₙ)`.
///
/// The `all_tuples!` macro does most of the work for you, the only change to your implementation macro
/// is that you have to accept attributes using `$(#[$meta:meta])*`.
///
/// Since this feature requires a nightly compiler, it's only enabled on docs.rs by default.
/// Add the following to your lib.rs if not already present:
///
/// ```
/// // `rustdoc_internals` is needed for `#[doc(fake_variadics)]`
/// #![allow(internal_features)]
/// #![cfg_attr(any(docsrs, docsrs_dep), feature(rustdoc_internals))]
/// ```
///
/// ```
/// # use bevy_utils_proc_macros::all_tuples;
/// #
/// trait Variadic {}
///
/// impl Variadic for () {}
///
/// macro_rules! impl_variadic {
///     ($(#[$meta:meta])* $(($P:ident, $p:ident)),*) => {
///         $(#[$meta])*
///         impl<$($P),*> Variadic for ($($P,)*) {}
///     }
/// }
///
/// all_tuples!(#[doc(fake_variadic)] impl_variadic, 1, 15, P, p);
/// ```
#[proc_macro]
pub fn all_tuples(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as AllTuples);
    let len = 1 + input.end - input.start;
    let mut ident_tuples = Vec::with_capacity(len);
    for i in 0..=len {
        let idents = input
            .idents
            .iter()
            .map(|ident| format_ident!("{}{}", ident, i));
        ident_tuples.push(to_ident_tuple(idents, input.idents.len()));
    }

    let macro_ident = &input.macro_ident;
    let invocations = (input.start..=input.end).map(|i| {
        let ident_tuples = choose_ident_tuples(&input, &ident_tuples, i);
        let attrs = if input.fake_variadic {
            fake_variadic_attrs(len, i)
        } else {
            TokenStream2::default()
        };
        quote! {
            #macro_ident!(#attrs #ident_tuples);
        }
    });
    TokenStream::from(quote! {
        #(
            #invocations
        )*
    })
}

/// Helper macro to generate tuple pyramids with their length. Useful to generate scaffolding to
/// work around Rust lacking variadics. Invoking `all_tuples_with_size!(impl_foo, start, end, P, Q, ..)`
/// invokes `impl_foo` providing ident tuples through arity `start..=end` preceded by their length.
/// If you don't require the length of the tuple, see [`all_tuples!`].
///
/// # Examples
///
/// ## Single parameter
///
/// ```
/// # use core::marker::PhantomData;
/// # use bevy_utils_proc_macros::all_tuples_with_size;
/// #
/// struct Foo<T> {
///     // ..
/// #    _phantom: PhantomData<T>
/// }
///
/// trait WrappedInFoo {
///     type Tup;
///     const LENGTH: usize;
/// }
///
/// macro_rules! impl_wrapped_in_foo {
///     ($N:expr, $($T:ident),*) => {
///         impl<$($T),*> WrappedInFoo for ($($T,)*) {
///             type Tup = ($(Foo<$T>,)*);
///             const LENGTH: usize = $N;
///         }
///     };
/// }
///
/// all_tuples_with_size!(impl_wrapped_in_foo, 0, 15, T);
/// // impl_wrapped_in_foo!(0);
/// // impl_wrapped_in_foo!(1, T0);
/// // impl_wrapped_in_foo!(2, T0, T1);
/// // ..
/// // impl_wrapped_in_foo!(15, T0 .. T14);
/// ```
///
/// ## Multiple parameters
///
/// ```
/// # use bevy_utils_proc_macros::all_tuples_with_size;
/// #
/// trait Append {
///     type Out<Item>;
///     fn append<Item>(tup: Self, item: Item) -> Self::Out<Item>;
/// }
///
/// impl Append for () {
///     type Out<Item> = (Item,);
///     fn append<Item>(_: Self, item: Item) -> Self::Out<Item> {
///         (item,)
///     }
/// }
///
/// macro_rules! impl_append {
///     ($N:expr, $(($P:ident, $p:ident)),*) => {
///         impl<$($P),*> Append for ($($P,)*) {
///             type Out<Item> = ($($P),*, Item);
///             fn append<Item>(($($p,)*): Self, item: Item) -> Self::Out<Item> {
///                 ($($p),*, item)
///             }
///         }
///     }
/// }
///
/// all_tuples_with_size!(impl_append, 1, 15, P, p);
/// // impl_append!(1, (P0, p0));
/// // impl_append!(2, (P0, p0), (P1, p1));
/// // impl_append!(3, (P0, p0), (P1, p1), (P2, p2));
/// // ..
/// // impl_append!(15, (P0, p0) .. (P14, p14));
/// ```
///
/// **`#[doc(fake_variadic)]`**
///
/// To improve the readability of your docs when implementing a trait for
/// tuples or fn pointers of varying length you can use the rustdoc-internal `fake_variadic` marker.
/// All your impls are collapsed and shown as a single `impl Trait for (F₁, F₂, …, Fₙ)`.
///
/// The `all_tuples!` macro does most of the work for you, the only change to your implementation macro
/// is that you have to accept attributes using `$(#[$meta:meta])*`.
///
/// Since this feature requires a nightly compiler, it's only enabled on docs.rs by default.
/// Add the following to your lib.rs if not already present:
///
/// ```
/// // `rustdoc_internals` is needed for `#[doc(fake_variadics)]`
/// #![allow(internal_features)]
/// #![cfg_attr(any(docsrs, docsrs_dep), feature(rustdoc_internals))]
/// ```
///
/// ```
/// # use bevy_utils_proc_macros::all_tuples_with_size;
/// #
/// trait Variadic {}
///
/// impl Variadic for () {}
///
/// macro_rules! impl_variadic {
///     ($N:expr, $(#[$meta:meta])* $(($P:ident, $p:ident)),*) => {
///         $(#[$meta])*
///         impl<$($P),*> Variadic for ($($P,)*) {}
///     }
/// }
///
/// all_tuples_with_size!(#[doc(fake_variadic)] impl_variadic, 1, 15, P, p);
/// ```
#[proc_macro]
pub fn all_tuples_with_size(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as AllTuples);
    let len = 1 + input.end - input.start;
    let mut ident_tuples = Vec::with_capacity(len);
    for i in 0..=len {
        let idents = input
            .idents
            .iter()
            .map(|ident| format_ident!("{}{}", ident, i));
        ident_tuples.push(to_ident_tuple(idents, input.idents.len()));
    }
    let macro_ident = &input.macro_ident;
    let invocations = (input.start..=input.end).map(|i| {
        let ident_tuples = choose_ident_tuples(&input, &ident_tuples, i);
        let attrs = if input.fake_variadic {
            fake_variadic_attrs(len, i)
        } else {
            TokenStream2::default()
        };
        quote! {
            #macro_ident!(#i, #attrs #ident_tuples);
        }
    });
    TokenStream::from(quote! {
        #(
            #invocations
        )*
    })
}

/// Parses the attribute `#[doc(fake_variadic)]`
fn parse_fake_variadic_attr(input: ParseStream) -> Result<bool> {
    let attribute = match input.call(Attribute::parse_outer)? {
        attributes if attributes.is_empty() => return Ok(false),
        attributes if attributes.len() == 1 => attributes[0].clone(),
        attributes => {
            return Err(Error::new(
                input.span(),
                format!("Expected exactly one attribute, got {}", attributes.len()),
            ))
        }
    };

    if attribute.path().is_ident("doc") {
        let nested = attribute.parse_args::<Ident>()?;
        if nested == "fake_variadic" {
            return Ok(true);
        }
    }

    Err(Error::new(
        attribute.meta.span(),
        "Unexpected attribute".to_string(),
    ))
}

fn choose_ident_tuples(input: &AllTuples, ident_tuples: &[TokenStream2], i: usize) -> TokenStream2 {
    // `rustdoc` uses the first ident to generate nice
    // idents with subscript numbers e.g. (F₁, F₂, …, Fₙ).
    // We don't want two numbers, so we use the
    // original, unnumbered idents for this case.
    if input.fake_variadic && i == 1 {
        let ident_tuple = to_ident_tuple(input.idents.iter().cloned(), input.idents.len());
        quote! { #ident_tuple }
    } else {
        let ident_tuples = &ident_tuples[..i];
        quote! { #(#ident_tuples),* }
    }
}

fn to_ident_tuple(idents: impl Iterator<Item = Ident>, len: usize) -> TokenStream2 {
    if len < 2 {
        quote! { #(#idents)* }
    } else {
        quote! { (#(#idents),*) }
    }
}

fn fake_variadic_attrs(len: usize, i: usize) -> TokenStream2 {
    let cfg = quote! { any(docsrs, docsrs_dep) };
    match i {
        // An empty tuple (i.e. the unit type) is still documented separately,
        // so no `#[doc(hidden)]` here.
        0 => TokenStream2::default(),
        // The `#[doc(fake_variadic)]` attr has to be on the first impl block.
        1 => {
            let doc = LitStr::new(
                &format!("This trait is implemented for tuples up to {len} items long."),
                Span2::call_site(),
            );
            quote! {
                #[cfg_attr(#cfg, doc(fake_variadic))]
                #[cfg_attr(#cfg, doc = #doc)]
            }
        }
        _ => quote! { #[cfg_attr(#cfg, doc(hidden))] },
    }
}