spire_enum_macros 1.2.0

Procedural macros distributed by the crate `spire_enum`.
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
use super::*;

pub fn run(input_stream: TokenStream1, enum_stream: TokenStream1) -> Result<TokenStream> {
    let table_attrs = parse_table_metas(input_stream)?;
    let input_enum = syn::parse::<Enum<SynMeta, SynMeta>>(enum_stream)?;
    let enum_def = input_enum.to_token_stream();

    let SaneEnum {
        ident: enum_ident,
        ty: enum_ty,
        variants,
    } = sanitize_enum(input_enum)?;

    let vis = Visibility::Public(Default::default());
    let lf = Lifetime::new("'_r", Span::call_site());
    let gen_t = Ident::new("Value", Span::call_site());

    let mod_ident = if let _Some(SettingModName {
        kw: _,
        eq_token: _,
        name,
    }) = table_attrs.mod_name
    {
        name
    } else {
        let mut enum_lower = enum_ident.to_string();
        enum_lower = enum_lower.to_case(Case::Snake);
        Ident::new(&format!("{enum_lower}_discriminant_table"), Span::call_site())
    };

    let table_ident = if let _Some(SettingTypeName {
        kw: _,
        eq_token: _,
        name,
    }) = table_attrs.ty_name
    {
        name
    } else {
        Ident::new(&format!("{enum_ident}DiscriminantTable"), Span::call_site())
    };

    let gen_params = quote! { <#gen_t> };
    let gen_args = &gen_params;
    let gen_lf_params = quote! { <#lf, #gen_t> };

    let table_ty = quote! { #table_ident::#gen_args };

    let fields = variants
        .iter()
        .map(
            |SaneVariant {
                 table_field_ident, ..
             }| table_field_ident,
        )
        .collect::<Vec<_>>();

    let var_cfgs = variants
        .iter()
        .map(|SaneVariant { cfg_attrs, .. }| cfg_attrs)
        .collect::<Vec<_>>();

    const MACRO_LINK: &str = "spire_enum_macros::discriminant_generic_table";
    const DOCS_INTRO: &str = "This type was generated by an invocation of the macro [`discriminant_generic_table`](spire_enum_macros::discriminant_generic_table).";

    let table_def = {
        let attrs = table_attrs.syn_metas;

        let docs = docs_tokens(format!(
            "{DOCS_INTRO}\n\n\
             A fixed-size collection that contains exactly one value of the generic [`{gen_t}`] for each variant of [`{enum_ident}`].\n\
             Values can be accessed by calling [`get({enum_ident})`]({table_ident}::get) or [`get_mut`]({table_ident}::get_mut).\n\
             For a full list of all methods generated for this type, see the [macro]({MACRO_LINK}) documentation.\n\n\
             This type does not allocate heap memory(can be used in `no_std`), though no such guarantee is provided to the generic [`{gen_t}`]."
        ));

        quote! {
            #docs
            #(#[#attrs])*
            #vis struct #table_ident #gen_params {
                #(
                    #var_cfgs
                    pub #fields: #gen_t
                ),*
            }
        }
    };

    let var_idents = variants.iter().map(|var| &var.ident).collect::<Vec<_>>();

    let len_ident = {
        let table_upper = table_ident.to_string().to_case(Case::Constant);
        Ident::new(&format!("{}_LEN", table_upper), Span::call_site())
    };

    let len_def = length_definition(&len_ident, var_cfgs.iter().cloned());

    let table_impls = {
        let docs_new = docs_tokens(format!(
            "Constructs a new instance of the type.\n\n\
			 Since this table guarantees that it contains exactly one value for each variant of [`{enum_ident}`],\
			 all variants' values must be initialized during construction."
        ));

        let from_fn_example = r###"
        ```rust
        use spire_enum_macros::discriminant_generic_table;
        
        #[discriminant_generic_table(ty_name = VolumeTable)]
        #[derive(Clone, Copy)]
        enum VolumeSetting {
            Main,
            Sfx,
            Music,
        }
        
        let default_values = VolumeTable::from_fn(
            |setting| { 
                match setting {
                    VolumeSetting::Main => 0.5,
                    VolumeSetting::Sfx => 1.0,
                    VolumeSetting::Music => 0.4,
                }
            }
        );
        
        assert_eq!(default_values[VolumeSetting::Main], 0.5);
        assert_eq!(default_values[VolumeSetting::Sfx], 1.0);
        assert_eq!(default_values[VolumeSetting::Music], 0.4);
        ```
        "###;

        let docs_from_fn = docs_tokens(format!(
            "Constructs a new instance of the type, invoking the closure `f` for every variant of [`{enum_ident}`].\n\n\
             # Example\n{from_fn_example}"
        ));

        let docs_into_iter = docs_tokens(format!(
            "Convert this table into an iterator that yields all values of the generic [`{gen_t}`], that were mapped to each variant of [`{enum_ident}`].\n\
			 - This iterator yields tuples of `({enum_ident}, {gen_t})`, where the first element represents the variant that the second element was associated with.\n\
			 - It is guaranteed that values will be yielded in the exact order they were declared in [`{enum_ident}`] (Top to bottom).\n\
             - The iterator returned does not allocate heap memory, it is merely a fixed-size array with length known at compile time."
        ));

        let docs_iter = docs_tokens(format!(
            "Iterates through references of all values of the generic [`{gen_t}`], that are mapped to each variant of [`{enum_ident}`].\n\
             - This iterator yields tuples of `({enum_ident}, &{gen_t})`, where the first element represents the variant that the second element is associated with.\n\
             - It is guaranteed that values will be yielded in the exact order they were declared in [`{enum_ident}`] (Top to bottom).\n\
             - The iterator returned does not allocate heap memory, it is merely a fixed-size array with length known at compile time."
        ));

        let docs_iter_mut = docs_tokens(format!(
            "Iterates through mutable references of all values of the generic [`{gen_t}`], that are mapped to each variant of [`{enum_ident}`].\n\
             - This iterator yields tuples of `({enum_ident}, &mut {gen_t})`, where the first element represents the variant that the second element is associated with.\n\
             - It is guaranteed that values will be yielded in the exact order they were declared in [`{enum_ident}`] (Top to bottom).\n\
             - The iterator returned does not allocate heap memory, it is merely a fixed-size array with length known at compile time."
        ));

        quote! {
            #[allow(clippy::too_many_arguments)]
            #[allow(unused)]
            impl #gen_params #table_ty {
                #docs_new
                pub const fn new(
                    #(
                        #var_cfgs
                        #fields: #gen_t
                    ),*
                ) -> Self {
                    Self {
                        #(
                            #var_cfgs
                            #fields
                        ),*
                    }
                }

                #[doc = "Constructs a new instance of the type, populating every variant's value with the parameter `__val`"]
                pub fn filled_with(__val: #gen_t) -> Self where #gen_t: Clone {
                    Self {
                        #(
                            #var_cfgs
                            #fields: __val.clone()
                        ),*
                    }
                }

                #docs_from_fn
                pub fn from_fn(mut f: impl FnMut(#enum_ty) -> #gen_t) -> Self {
                    Self {
                        #(
                            #var_cfgs
                            #fields: f(#enum_ty::#var_idents)
                        ),*
                    }
                }

                #[doc = "Returns a reference to the value associated with the variant `var` that is always present in this table.\n\n\
                This method will never panic, it is guaranteed at compile time that the table contains the value associated with `var`."]
                pub const fn get(&self, var: #enum_ty) -> & #gen_t {
                    match var {
                        #(
                            #var_cfgs
                            #enum_ty::#var_idents {..} => &self.#fields
                        ),*
                    }
                }

                #[doc = "Returns a mutable reference to the value associated with the variant `var` that is always present in this table.\n\n\
                This method will never panic, it is guaranteed at compile time that the table contains the value associated with `var`."]
                pub const fn get_mut(&mut self, var: #enum_ty) -> &mut #gen_t {
                    match var {
                        #(
                            #var_cfgs
                            #enum_ty::#var_idents {..} => &mut self.#fields
                        ),*
                    }
                }

                #[doc = "Replaces the field associated with the variant `var`, with the contents of `value`.\n\n\
                         This is shorthand for `*self.get_mut(var) = value;`.\n\
                         This is provided merely as \"sugar\" for those who aren't \
                         very familiar with dereferencing."]
                pub fn set(&mut self, var: #enum_ty, value: #gen_t) {
                    *self.get_mut(var) = value;
                }

                #[allow(clippy::needless_lifetimes)]
                #docs_iter
                pub fn iter<#lf>(&#lf self) -> ::core::array::IntoIter<(#enum_ty, &#lf #gen_t), #len_ident> {
                    [
                        #(
                            #var_cfgs
                            (#enum_ty::#var_idents, &self.#fields)
                        ),*
                    ].into_iter()
                }

                #[allow(clippy::needless_lifetimes)]
                #docs_iter_mut
                pub fn iter_mut<#lf>(&#lf mut self) -> ::core::array::IntoIter<(#enum_ty, &#lf mut #gen_t), #len_ident> {
                    [
                        #(
                            #var_cfgs
                            (#enum_ty::#var_idents, &mut self.#fields)
                        ),*
                    ].into_iter()
                }
            }

            impl #gen_params ::core::iter::IntoIterator for #table_ty {
                type Item = (#enum_ty, #gen_t);
                type IntoIter = ::core::array::IntoIter<(#enum_ty, #gen_t), #len_ident>;

                #docs_into_iter
                fn into_iter(self) -> Self::IntoIter {
                    [
                        #(
                            #var_cfgs
                            (#enum_ty::#var_idents, self.#fields)
                        ),*
                    ].into_iter()
                }
            }

            impl #gen_lf_params ::core::iter::IntoIterator for &#lf #table_ty {
                type Item = (#enum_ty, &#lf #gen_t);
                type IntoIter = ::core::array::IntoIter<Self::Item, #len_ident>;

                #[doc = "See [`iter`](Self::iter)"]
                fn into_iter(self) -> Self::IntoIter { self.iter() }
            }

            impl #gen_lf_params ::core::iter::IntoIterator for &#lf mut #table_ty {
                type Item = (#enum_ty, &#lf mut #gen_t);
                type IntoIter = ::core::array::IntoIter<Self::Item, #len_ident>;

                #[doc = "See [`iter_mut`](Self::iter_mut)"]
                fn into_iter(self) -> Self::IntoIter { self.iter_mut() }
            }

            impl #gen_params ::core::ops::Index<#enum_ty> for #table_ty {
                type Output = #gen_t;

                #[doc = "See [`get`](Self::get)"]
                fn index(&self, index: #enum_ty) -> &Self::Output {
                    self.get(index)
                }
            }

            impl #gen_params ::core::ops::IndexMut<#enum_ty> for #table_ty {
                #[doc = "See [`get_mut`](Self::get_mut)"]
                fn index_mut(&mut self, index: #enum_ty) -> &mut Self::Output {
                    self.get_mut(index)
                }
            }
        }
    };

    let from_const_fn_macro = {
        let macro_ident = {
            let mut str = table_ident.to_string();
            str = str.to_case(Case::Snake);
            Ident::new(&format!("{str}_from_const_fn"), Span::call_site())
        };

        quote! {
            #[allow(unused_macros)]
            macro_rules! #macro_ident {
                ( | $var: ident | $( -> $ret: ty )? $closure: block ) => {{
                    #table_ident {
                        #(
                            #var_cfgs
                            #fields: {
                                let $var = #enum_ty::#var_idents;
                                $closure
                            }
                        ),*
                    }
                }};

                ( |_| $( -> $ret: ty )? $closure: block ) => {{
                    #table_ident {
                        #(
                            #var_cfgs
                            #fields: $closure
                        ),*
                    }
                }};
            }
        }
    };

    Ok(quote! {
        #enum_def

        #[allow(unused_imports)]
        pub(crate) use #mod_ident::#table_ident;

        #[allow(unused_imports)]
        mod #mod_ident {
            use super::*;

            #len_def
            #table_def
            #table_impls
            #from_const_fn_macro
        }
    })
}

struct SaneEnum {
    ident: Ident,
    ty: Type,
    variants: Vec<SaneVariant>,
}

struct SaneVariant {
    cfg_attrs: Any<Attribute<CfgMeta>>,
    ident: Ident,
    table_field_ident: Ident,
}

fn sanitize_enum(input: Enum<SynMeta, SynMeta>) -> Result<SaneEnum> {
    let Enum {
        attrs: _,
        vis: _,
        enum_token: _,
        ident,
        generics,
        where_clause,
        variants,
    } = input;

    let generics = sanitize_generics(generics, where_clause)?;
    let ty = new_ty_maybe_generic(&ident, &generics);

    let variants = variants
        .into_inner()
        .inner
        .into_iter()
        .map(|Var { attrs, ident, fields, discriminant: _ }| {
            const HELP: &str =
                "A discriminant table can only be generated if all variants are units (have zero fields).";

            let cfg_attrs = parse_cfg_attrs(attrs);

            match fields {
                VarFields::Named(named) => {
                    if named.is_empty() {
                        Ok(SaneVariant {
                            cfg_attrs,
                            table_field_ident: var_to_field_ident(&ident),
                            ident,
                        })
                    } else {
                        bail!(named => HELP)
                    }
                }
                VarFields::Unnamed(unnamed) => {
                    if unnamed.is_empty() {
                        Ok(SaneVariant {
                            cfg_attrs,
                            table_field_ident: var_to_field_ident(&ident),
                            ident,
                        })
                    } else {
                        bail!(unnamed => HELP)
                    }
                }
                VarFields::Unit => Ok(SaneVariant {
                    cfg_attrs,
                    table_field_ident: var_to_field_ident(&ident),
                    ident,
                }),
            }
        })
        .try_collect()?;

    Ok(SaneEnum {
        ident,
        variants,
        ty,
    })
}