use syn::parse::{Parse, ParseStream, Result}; use syn::token::Brace; use syn::{Attribute, Expr, Ident, Token, Type, braced, bracketed}; #[derive(Debug)] pub(crate) struct ParseBase { pub(crate) name: Ident, pub(crate) fields: Vec, pub(crate) imports: Vec, } #[derive(Clone, Debug)] #[expect(clippy::large_enum_variant)] pub(crate) enum ParsePart { Section { name: Ident, fields: Vec, documentation: Vec, }, Field { name: Ident, ty: Type, default: Option, documentation: Vec, finalizer: Option, }, } #[derive(Clone, Debug)] pub(crate) struct FieldDefault { pub(crate) default: Expr, pub(crate) may_error: bool, } impl Parse for FieldDefault { fn parse(input: ParseStream<'_>) -> Result { let lookahead = input.lookahead1(); let (may_error, expr) = if lookahead.peek(Token![try]) { input.parse::()?; (true, input.parse()?) } else { (false, input.parse()?) }; Ok(Self { default: expr, may_error, }) } } impl Parse for ParsePart { fn parse(input: ParseStream<'_>) -> Result { let documentation = input.call(Attribute::parse_outer)?; let name = input.parse()?; input.parse::()?; let lookahead = input.lookahead1(); if lookahead.peek(Brace) { let content; braced!(content in input); let fields = content .parse_terminated(ParsePart::parse, Token![,])? .into_iter() .collect(); Ok(Self::Section { name, fields, documentation, }) } else { let ty = input.parse()?; let lookahead = input.lookahead1(); let mut default = None; let mut finalizer = None; if lookahead.peek(Token![=>]) { input.parse::]>()?; finalizer = Some(input.parse::()?); let lookahead = input.lookahead1(); if !lookahead.peek(Token![,]) { return Err(lookahead.error()); } } else if lookahead.peek(Token![=]) { input.parse::()?; default = Some(input.parse()?); let lookahead = input.lookahead1(); if lookahead.peek(Token![=>]) { input.parse::]>()?; finalizer = Some(input.parse::()?); let lookahead = input.lookahead1(); if !lookahead.peek(Token![,]) { return Err(lookahead.error()); } } } else if lookahead.peek(Token![,]) { // leave the `,` so that the `parse_terminated` can remove it } else { return Err(lookahead.error()); } Ok(Self::Field { name, ty, default, documentation, finalizer, }) } } } impl Parse for ParseBase { fn parse(input: ParseStream<'_>) -> Result { input.parse::()?; let content; bracketed!(content in input); let imports = content .parse_terminated(syn::Path::parse, Token![;])? .into_iter() .collect(); input.parse::()?; let name: Ident = input.parse()?; let content; braced!(content in input); let fields = content .parse_terminated(ParsePart::parse, Token![,])? .into_iter() .collect(); Ok(ParseBase { name, fields, imports, }) } }