/home/runner/work/bare_err_tree/bare_err_tree/bare_err_tree_proc/src/fields.rs
Line | Count | Source |
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 | | |
7 | | use quote::format_ident; |
8 | | use syn::{punctuated::Punctuated, token::Comma, Field, Fields, Ident, Meta, Visibility}; |
9 | | |
10 | | /// Dig out the struct/enum name. |
11 | 4 | pub fn name_attribute(args: &Punctuated<Meta, Comma>) -> Option<&proc_macro2::Ident> { |
12 | 4 | args.iter().find_map(|arg| arg.path().get_ident()1 ) |
13 | 4 | } |
14 | | |
15 | | #[derive(Debug)] |
16 | | pub struct FieldsStrip { |
17 | | pub bounds: Punctuated<Field, Comma>, |
18 | | pub idents: Vec<Ident>, |
19 | | } |
20 | | |
21 | | /// Put struct fields into a standard format. |
22 | 4 | pub fn strip_fields(fields: &Fields) -> FieldsStrip { |
23 | 4 | let mut field_bounds = match fields.clone() { |
24 | 4 | Fields::Named(f) => f.named, |
25 | 0 | Fields::Unnamed(f) => { |
26 | 0 | // Add placeholder identifiers for unnamed, since anonymous |
27 | 0 | // ident generated arguments are not supported. |
28 | 0 | let mut bounds = f.unnamed; |
29 | 0 | bounds.iter_mut().enumerate().for_each(|(idx, f)| { |
30 | 0 | let idx = format_ident!("_{idx}"); |
31 | 0 | f.ident = Some(idx); |
32 | 0 | }); |
33 | 0 | bounds |
34 | | } |
35 | 0 | Fields::Unit => Punctuated::default(), |
36 | | }; |
37 | | |
38 | 6 | field_bounds.iter_mut().for_each(4 |f| { |
39 | 6 | f.attrs = vec![]; |
40 | 6 | f.vis = Visibility::Inherited; |
41 | 6 | f.colon_token = None; |
42 | 6 | }); |
43 | 4 | |
44 | 4 | let field_idents = field_bounds |
45 | 4 | .clone() |
46 | 4 | .into_iter() |
47 | 6 | .flat_map(|f| f.ident) |
48 | 4 | .collect(); |
49 | 4 | |
50 | 4 | FieldsStrip { |
51 | 4 | bounds: field_bounds, |
52 | 4 | idents: field_idents, |
53 | 4 | } |
54 | 4 | } |