bare_err_tree_proc/
fields.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5 */
6
7use quote::format_ident;
8use syn::{punctuated::Punctuated, token::Comma, Field, Fields, Ident, Meta, Visibility};
9
10/// Dig out the struct/enum name.
11pub fn name_attribute(args: &Punctuated<Meta, Comma>) -> Option<&proc_macro2::Ident> {
12    args.iter().find_map(|arg| arg.path().get_ident())
13}
14
15#[derive(Debug)]
16pub struct FieldsStrip {
17    pub bounds: Punctuated<Field, Comma>,
18    pub idents: Vec<Ident>,
19}
20
21/// Put struct fields into a standard format.
22pub fn strip_fields(fields: &Fields) -> FieldsStrip {
23    let mut field_bounds = match fields.clone() {
24        Fields::Named(f) => f.named,
25        Fields::Unnamed(f) => {
26            // Add placeholder identifiers for unnamed, since anonymous
27            // ident generated arguments are not supported.
28            let mut bounds = f.unnamed;
29            bounds.iter_mut().enumerate().for_each(|(idx, f)| {
30                let idx = format_ident!("_{idx}");
31                f.ident = Some(idx);
32            });
33            bounds
34        }
35        Fields::Unit => Punctuated::default(),
36    };
37
38    field_bounds.iter_mut().for_each(|f| {
39        f.attrs = vec![];
40        f.vis = Visibility::Inherited;
41        f.colon_token = None;
42    });
43
44    let field_idents = field_bounds
45        .clone()
46        .into_iter()
47        .flat_map(|f| f.ident)
48        .collect();
49
50    FieldsStrip {
51        bounds: field_bounds,
52        idents: field_idents,
53    }
54}