aboutsummaryrefslogtreecommitdiffstats
path: root/crates/mk_config
diff options
context:
space:
mode:
authorBenedikt Peetz <benedikt.peetz@b-peetz.de>2026-11-07 15:00:04 +0100
committerBenedikt Peetz <benedikt.peetz@b-peetz.de>2026-11-07 15:00:04 +0100
commit73cc6d79192ce1cd7851f990b2666c354d105939 (patch)
treef5efead8659d64a7e835d9680942a52d209ebc9b /crates/mk_config
parentrefactor(yt_dlp/): Make the options more like the builder pattern (diff)
downloadyt-73cc6d79192ce1cd7851f990b2666c354d105939.zip
feat(yt/{cli,config}): Rewrite the config generation macro
That now is both cleaner and supports config overrides (i.e. `yt --option NAME VALUE`).
Diffstat (limited to 'crates/mk_config')
-rw-r--r--crates/mk_config/Cargo.toml33
-rw-r--r--crates/mk_config/src/generate.rs727
-rw-r--r--crates/mk_config/src/lib.rs19
-rw-r--r--crates/mk_config/src/parse.rs145
4 files changed, 924 insertions, 0 deletions
diff --git a/crates/mk_config/Cargo.toml b/crates/mk_config/Cargo.toml
new file mode 100644
index 0000000..b75c16c
--- /dev/null
+++ b/crates/mk_config/Cargo.toml
@@ -0,0 +1,33 @@
+# yt - A fully featured command line YouTube client
+#
+# Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
+# Copyright (C) 2025 uutils developers
+# SPDX-License-Identifier: MIT
+#
+# This file is part of Yt.
+#
+# You should have received a copy of the License along with this program.
+# If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
+
+[package]
+name = "mk_config"
+authors.workspace = true
+license.workspace = true
+description = "config proc macro"
+version.workspace = true
+edition.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+publish = false
+
+[lib]
+proc-macro = true
+
+[dependencies]
+prettyplease = "0.3.0"
+proc-macro2 = "1.0.107"
+quote = "1.0.47"
+syn = { version = "3.0.9", features = ["full"] }
+
+[lints]
+workspace = true
diff --git a/crates/mk_config/src/generate.rs b/crates/mk_config/src/generate.rs
new file mode 100644
index 0000000..30b560d
--- /dev/null
+++ b/crates/mk_config/src/generate.rs
@@ -0,0 +1,727 @@
+use std::iter;
+
+use proc_macro2::TokenStream as TokenStream2;
+use quote::{ToTokens, TokenStreamExt, format_ident, quote};
+use syn::{Attribute, Expr, Ident, Type};
+
+use crate::parse;
+
+#[derive(Debug)]
+pub(crate) struct Config {
+ name: Ident,
+ sections: Vec<ConfigSection>,
+ fields: Vec<ConfigField>,
+ imports: Vec<syn::Path>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ConfigSection {
+ name: Vec<Ident>,
+ fields: Vec<ConfigField>,
+ is_public: bool,
+ documentation: Vec<Attribute>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ConfigField {
+ name: Vec<Ident>,
+ default: Option<ConfigFieldDefault>,
+ ty: Type,
+ documentation: Vec<Attribute>,
+
+ /// Whether this config field was create to include the parent-child relation ships between
+ /// config sections.
+ is_section: bool,
+ is_public: bool,
+ finalizer: Option<Ident>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ConfigFieldDefault {
+ default: Expr,
+ may_error: bool,
+}
+
+impl From<parse::FieldDefault> for ConfigFieldDefault {
+ fn from(value: parse::FieldDefault) -> Self {
+ Self {
+ default: value.default,
+ may_error: value.may_error,
+ }
+ }
+}
+
+impl ToTokens for ConfigFieldDefault {
+ fn to_tokens(&self, tokens: &mut TokenStream2) {
+ let Self { default, may_error } = self;
+ if *may_error {
+ tokens.extend(quote! {
+ #default?
+ });
+ } else {
+ tokens.extend(quote! {
+ #default
+ });
+ }
+ }
+}
+
+impl From<parse::ParseBase> for Config {
+ fn from(value: parse::ParseBase) -> Self {
+ let mut sections = vec![];
+ let mut new_fields = vec![];
+
+ value.fields.into_iter().for_each(|field| match field {
+ parse::ParsePart::Section { .. } => {
+ sections.extend(ConfigSection::from_parse_part(vec![], field.clone()));
+ new_fields.push(ConfigField::spawn_from_section(vec![], field));
+ }
+ parse::ParsePart::Field { .. } => {
+ new_fields.push(ConfigField::from_parse_part(vec![], field));
+ }
+ });
+
+ Self {
+ name: value.name,
+ sections,
+ fields: new_fields,
+ imports: value.imports,
+ }
+ }
+}
+
+impl ConfigSection {
+ fn from_parse_part(prefix: Vec<Ident>, value: parse::ParsePart) -> Vec<Self> {
+ if let parse::ParsePart::Section {
+ name,
+ fields,
+ documentation,
+ } = value
+ {
+ let new_name: Vec<_> = prefix.into_iter().chain(iter::once(name)).collect();
+
+ let mut sections = vec![];
+ let mut new_fields = vec![];
+
+ for field in fields {
+ match field {
+ parse::ParsePart::Section { .. } => {
+ sections.extend(Self::from_parse_part(new_name.clone(), field.clone()));
+ new_fields.push(ConfigField::spawn_from_section(new_name.clone(), field));
+ }
+ parse::ParsePart::Field { .. } => {
+ new_fields.push(ConfigField::from_parse_part(new_name.clone(), field));
+ }
+ }
+ }
+
+ sections.push(Self {
+ name: new_name,
+ fields: new_fields,
+ is_public: true,
+ documentation,
+ });
+
+ sections
+ } else {
+ unreachable!("Only called on sections")
+ }
+ }
+}
+
+impl ConfigField {
+ fn from_parse_part(prefix: Vec<Ident>, value: parse::ParsePart) -> Self {
+ if let parse::ParsePart::Field {
+ name,
+ ty,
+ default,
+ documentation,
+ finalizer,
+ } = value
+ {
+ let new_name = prefix.into_iter().chain(iter::once(name)).collect();
+
+ Self {
+ name: new_name,
+ default: default.map(Into::into),
+ ty,
+ is_section: false,
+ is_public: true,
+ documentation,
+ finalizer,
+ }
+ } else {
+ unreachable!("Only called on fields")
+ }
+ }
+
+ fn spawn_from_section(prefix: Vec<Ident>, field: parse::ParsePart) -> ConfigField {
+ if let parse::ParsePart::Section {
+ name,
+ documentation,
+ ..
+ } = field
+ {
+ let config_name = name_ident(&name);
+ let new_name = prefix.into_iter().chain(iter::once(name)).collect();
+
+ Self {
+ name: new_name,
+ default: None,
+ ty: syn::parse_quote!(#config_name),
+ is_section: true,
+ is_public: true,
+ documentation,
+ finalizer: None,
+ }
+ } else {
+ unreachable!("Should only be called, on Sections")
+ }
+ }
+}
+
+struct ConfDeser {
+ sections: Vec<ConfigSection>,
+ fields: Vec<ConfigField>,
+}
+
+impl From<&Config> for ConfDeser {
+ fn from(value: &Config) -> Self {
+ fn field_to_deser(field: &ConfigField) -> ConfigField {
+ let field_ty = field.ty.clone();
+
+ ConfigField {
+ name: field.name.clone(),
+ default: None,
+ documentation: field.documentation.clone(),
+ ty: if field.default.is_some() || field.is_section {
+ syn::parse_quote!(Option<#field_ty>)
+ } else {
+ // TODO: We could also accept this value here, and then throw an error later.
+ // But right now, we just use serde to complain to the user <2026-08-20>
+ field_ty
+ },
+ is_section: field.is_section,
+ is_public: false,
+ finalizer: None,
+ }
+ }
+
+ Self {
+ sections: value
+ .sections
+ .iter()
+ .map(|section| ConfigSection {
+ name: section.name.clone(),
+ fields: section.fields.iter().map(field_to_deser).collect(),
+ is_public: false,
+ documentation: section.documentation.clone(),
+ })
+ .collect(),
+ fields: value.fields.iter().map(field_to_deser).collect(),
+ }
+ }
+}
+
+impl ToTokens for ConfDeser {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let Self { sections, fields } = self;
+
+ let serde = serde(false);
+ tokens.extend(quote! {
+ #serde
+ #[derive(Clone, Debug)]
+ pub(super) struct ConfDeser {
+ #(
+ #fields
+ )*
+ }
+ #(
+ #sections
+ )*
+ });
+ }
+}
+
+impl ToTokens for Config {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let Self {
+ name,
+ sections,
+ fields,
+ imports,
+ } = self;
+
+ let serde = serde(true);
+ tokens.extend(quote! {
+ #(
+ use #imports;
+ )*
+
+ #[derive(Debug)]
+ #serde
+ pub(crate) struct #name {
+ #(
+ #fields
+ )*
+ }
+ });
+ tokens.append_all(sections.iter());
+
+ let default_config = generate_default_config(fields, sections);
+ let option_assign = generate_option_assign(fields, sections);
+ let option_finalizer = generate_option_finalizer(fields, sections);
+ let field_deser_assign: Vec<_> = fields
+ .iter()
+ .map(|field| field.field_assign_deser(&[]))
+ .collect();
+ let conf_deser = ConfDeser::from(self);
+ tokens.extend(quote! {
+ mod __inner {
+ #(
+ use #imports;
+ )*
+
+ #conf_deser
+ }
+
+ impl #name {
+ /// Parse the configuration from a config file at `config_file_path`.
+ ///
+ /// This will then also take the config overrides via `options` into consideration,
+ /// and finally run the finalizers, defined via the macro.
+ pub(crate) fn from_config_file(
+ config_file_path: &std::path::Path,
+ options: Vec<(Vec<String>, toml::Value)>
+ ) -> anyhow::Result<Self> {
+ use anyhow::Context;
+
+ let config: __inner::ConfDeser = toml::from_str(
+ &std::fs::read_to_string(config_file_path).unwrap_or(String::new()),
+ ).context("Failed to parse the config file as toml")?;
+
+ let mut base = Self {
+ #(
+ #field_deser_assign
+ )*
+ };
+
+ for (name, value) in options {
+ let name = name.join(".");
+
+ match name.as_str() {
+ #option_assign
+ other => anyhow::bail!("Option name '{other}' is not known")
+ }
+ }
+
+ // Run the finalizers
+ {
+ #option_finalizer
+ }
+
+ Ok(base)
+ }
+
+ /// Return the default configuration in semi TOML format, with it's doc comments appended
+ /// to the document.
+ ///
+ /// The default values, will be the pretty-printed rust defaults, so it's not
+ /// actually possible to parse it as TOML.
+ pub(crate) const fn config_doc() -> &'static str {
+ #default_config
+ }
+ }
+ });
+ }
+}
+
+impl ToTokens for ConfigSection {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ fn field_to_default(field: &ConfigField) -> TokenStream2 {
+ let ConfigField {
+ name,
+ default,
+ is_section,
+ ty,
+ ..
+ } = field;
+
+ let last_name = name.last().expect("Exists");
+ if let Some(default) = default {
+ quote! {
+ #last_name: #default,
+ }
+ } else if *is_section {
+ quote! {
+ #last_name: #ty::default()?,
+ }
+ } else {
+ let msg = format!(
+ "No default value for field '{last_name}'. Auto defaults are not yet implemented."
+ );
+ quote! {
+ #last_name: {compile_error!(#msg)},
+ }
+ }
+ }
+
+ let Self {
+ name,
+ fields,
+ is_public,
+ documentation,
+ } = self;
+ let last_name = name_ident(name.last().expect("Exists"));
+
+ let default_fields: Vec<_> = fields.iter().map(field_to_default).collect();
+ let from_deser_fields: Vec<_> = fields
+ .iter()
+ .map(|field| field.field_assign_deser(name))
+ .collect();
+
+ let vis = vis(*is_public);
+ let serde = serde(*is_public);
+ tokens.extend(quote! {
+ #serde
+ #[derive(Clone, Debug)]
+ #(#documentation)*
+ #vis struct #last_name {
+ #(
+ #fields
+ )*
+ }
+ });
+ if *is_public {
+ tokens.extend(quote! {
+ impl #last_name {
+ fn default() -> anyhow::Result<Self> {
+ Ok(Self {
+ #(
+ #default_fields
+ )*
+ })
+ }
+ fn from_inner(from: Option<__inner::#last_name>, config: __inner::ConfDeser) -> anyhow::Result<Self> {
+ if let Some(from) = from {
+ Ok(Self {
+ #(
+ #from_deser_fields
+ )*
+ })
+ } else {
+ Self::default()
+ }
+ }
+ }
+ });
+ }
+ }
+}
+
+impl ConfigField {
+ fn field_assign_deser(&self, prefix: &[Ident]) -> TokenStream2 {
+ let ConfigField {
+ name,
+ is_section,
+ default,
+ ty,
+ ..
+ } = self;
+
+ let base = if prefix.is_empty() {
+ quote! {
+ config.#(#name).*
+ }
+ } else {
+ let mut new = name.clone();
+ for p in prefix {
+ let next = new.remove(0);
+ assert_eq!(p, &next);
+ }
+ quote! {
+ from.#(#new).*
+ }
+ };
+
+ let last_name = name.last().expect("Exists");
+
+ if *is_section {
+ quote! {
+ #last_name: #ty::from_inner(#base.clone(), config.clone())?,
+ }
+ } else {
+ match default {
+ Some(default) => {
+ quote! {
+ #last_name: {
+ match #base {
+ Some(val) => val,
+ None => #default,
+ }
+ },
+ }
+ }
+ None => {
+ // NOTE: When there is no default value, we also don't accept one in the __inner
+ // part. <2026-08-20>
+ quote! {
+ #last_name: #base,
+ }
+ }
+ }
+ }
+ }
+}
+impl ToTokens for ConfigField {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ let Self {
+ name,
+ ty,
+ is_public,
+ documentation,
+ ..
+ } = self;
+ let last_name = name.last().expect("Exists");
+
+ let vis = vis(*is_public);
+ tokens.extend(quote! {
+ #(#documentation)*
+ #vis #last_name: #ty,
+ });
+ }
+}
+
+fn name_ident(name: &Ident) -> Ident {
+ let mut name: Vec<_> = name.to_string().chars().collect();
+ name[0] = name[0].to_ascii_uppercase();
+
+ format_ident!("{}Config", name.into_iter().collect::<String>())
+}
+fn vis(is_public: bool) -> TokenStream2 {
+ if is_public {
+ quote! {pub(crate)}
+ } else {
+ quote! {pub(super)}
+ }
+}
+fn serde(is_public: bool) -> TokenStream2 {
+ if is_public {
+ quote! {
+ #[derive(serde::Serialize, serde::Deserialize)]
+ }
+ } else {
+ quote! {
+ #[derive(serde::Deserialize)]
+ }
+ }
+ // quote! {}
+}
+
+fn generate_option_assign(fields: &[ConfigField], sections: &[ConfigSection]) -> TokenStream2 {
+ fn name_str(name: &[Ident]) -> String {
+ name.iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join(".")
+ }
+ fn value(ty: &Type) -> TokenStream2 {
+ let ty_str = ty.to_token_stream().to_string();
+
+ quote! {
+ {
+ use serde::Deserialize;
+
+ let value_str = value.to_string();
+ let deserializer = toml::de::ValueDeserializer::parse(&value_str)
+ .with_context(|| format!("Failed to parse value for option override '{name}' as '{}'", #ty_str))?;
+ <#ty>::deserialize(deserializer).context("Failed to deserialize default value for '{name}'")?
+ }
+ }
+ }
+
+ fn mk_field(field: &ConfigField) -> TokenStream2 {
+ let ConfigField { name, ty, .. } = field;
+
+ let name_str = name_str(name);
+ let value = value(ty);
+
+ quote! {
+ #name_str => base.#(#name).* = #value,
+ }
+ }
+ fn mk_section(section: &ConfigSection) -> TokenStream2 {
+ let ConfigSection { name, fields, .. } = section;
+
+ let name_str = name_str(name);
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ let value = {
+ let last_name = name.last().expect("to exist");
+ let ty = name_ident(last_name);
+ let ty: Type = syn::parse_quote! {#ty};
+
+ value(&ty)
+ };
+
+ quote! {
+ #name_str => base.#(#name).* = #value,
+ #(
+ #fields
+ )*
+ }
+ }
+
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ let sections: Vec<_> = sections.iter().map(mk_section).collect();
+
+ quote! {
+ #(
+ #fields
+ )*
+ #(
+ #sections
+ )*
+ }
+}
+fn generate_option_finalizer(fields: &[ConfigField], sections: &[ConfigSection]) -> TokenStream2 {
+ fn mk_field(field: &ConfigField) -> TokenStream2 {
+ let ConfigField {
+ name, finalizer, ..
+ } = field;
+
+ match finalizer {
+ Some(finalizer) => {
+ let context_msg = format!(
+ "While running the finalizer for config value '{}'",
+ name.iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join(".")
+ );
+
+ quote! {
+ #finalizer(&base.#(#name).*).context(#context_msg)?;
+ }
+ }
+ None => quote! {},
+ }
+ }
+ fn mk_section(section: &ConfigSection) -> TokenStream2 {
+ let ConfigSection { fields, .. } = section;
+
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ quote! {
+ #(
+ #fields
+ )*
+ }
+ }
+ let fields: Vec<_> = fields.iter().map(mk_field).collect();
+ let sections: Vec<_> = sections.iter().map(mk_section).collect();
+
+ quote! {
+ #(
+ #fields
+ )*
+ #(
+ #sections
+ )*
+ }
+}
+
+fn generate_default_config(fields: &[ConfigField], sections: &[ConfigSection]) -> String {
+ fn mk_doc_comment(attr: &Attribute) -> String {
+ let comment = match &attr.meta {
+ syn::Meta::Path(_) => todo!(),
+ syn::Meta::List(_) => todo!(),
+ syn::Meta::NameValue(meta_name_value) => &meta_name_value.value,
+ };
+
+ let comment = comment.to_token_stream().to_string();
+ let comment = comment.trim_matches('\"').trim();
+ format!("# {comment}")
+ }
+
+ fn mk_field(field: &ConfigField) -> Option<String> {
+ let ConfigField {
+ name,
+ default,
+ documentation,
+ is_section,
+ ..
+ } = field;
+
+ let documentation = documentation.iter().map(mk_doc_comment).collect::<Vec<_>>();
+
+ let last_name = name.last().expect("to exist");
+ if let Some(default) = default {
+ let default = {
+ let file = syn::parse2::<syn::File>(quote::quote! {
+ fn deleteme(){
+ #default
+ }
+ })
+ .expect("The default value is valid rust code, and should be parsable");
+
+ {
+ let mut str = prettyplease::unparse(&file);
+
+ // remove the outer function
+ str = str.replace("fn deleteme() {\n", "");
+
+ if let Some(pos) = str.rfind("\n}\n") {
+ str.replace_range(pos..pos + 3, "");
+ }
+
+ // remove the function indent
+ str = str
+ .lines()
+ .map(|line| if line.len() >= 4 { &line[4..] } else { line })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ str
+ }
+ };
+
+ Some(format!(
+ "{}{}{} = {}\n",
+ documentation.join("\n"),
+ if documentation.is_empty() { "" } else { "\n" },
+ last_name,
+ default
+ ))
+ } else if *is_section {
+ None
+ } else {
+ todo!("no default fields, to yet supported")
+ }
+ }
+ fn mk_section(section: &ConfigSection) -> String {
+ let ConfigSection {
+ fields,
+ name,
+ documentation,
+ ..
+ } = section;
+
+ let documentation = documentation.iter().map(mk_doc_comment).collect::<Vec<_>>();
+ let fields: Vec<_> = fields.iter().filter_map(mk_field).collect();
+ let name = name.iter().map(ToString::to_string).collect::<Vec<_>>();
+
+ format!(
+ "{}{}[{}]\n{}\n",
+ documentation.join("\n"),
+ if documentation.is_empty() { "" } else { "\n" },
+ name.join("."),
+ fields.join("\n")
+ )
+ }
+ let fields: Vec<_> = fields.iter().filter_map(mk_field).collect();
+ let sections: Vec<_> = sections.iter().map(mk_section).collect();
+
+ format!(
+ "{}\n",
+ format!("{}{}", fields.join("\n"), sections.join("\n")).trim()
+ )
+}
diff --git a/crates/mk_config/src/lib.rs b/crates/mk_config/src/lib.rs
new file mode 100644
index 0000000..0686b27
--- /dev/null
+++ b/crates/mk_config/src/lib.rs
@@ -0,0 +1,19 @@
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::parse_macro_input;
+
+use crate::parse::ParseBase;
+
+mod generate;
+mod parse;
+
+#[proc_macro]
+pub fn mk_config(input: TokenStream) -> TokenStream {
+ // eprintln!("{}", input);
+ let parsed = parse_macro_input!(input as ParseBase);
+
+ let config = generate::Config::from(parsed);
+ let expanded = quote! {#config};
+
+ TokenStream::from(expanded)
+}
diff --git a/crates/mk_config/src/parse.rs b/crates/mk_config/src/parse.rs
new file mode 100644
index 0000000..c48aef6
--- /dev/null
+++ b/crates/mk_config/src/parse.rs
@@ -0,0 +1,145 @@
+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<ParsePart>,
+ pub(crate) imports: Vec<syn::Path>,
+}
+
+#[derive(Clone, Debug)]
+#[expect(clippy::large_enum_variant)]
+pub(crate) enum ParsePart {
+ Section {
+ name: Ident,
+ fields: Vec<ParsePart>,
+ documentation: Vec<Attribute>,
+ },
+ Field {
+ name: Ident,
+ ty: Type,
+ default: Option<FieldDefault>,
+ documentation: Vec<Attribute>,
+ finalizer: Option<Ident>,
+ },
+}
+
+#[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<Self> {
+ let lookahead = input.lookahead1();
+ let (may_error, expr) = if lookahead.peek(Token![try]) {
+ input.parse::<Token![try]>()?;
+ (true, input.parse()?)
+ } else {
+ (false, input.parse()?)
+ };
+
+ Ok(Self {
+ default: expr,
+ may_error,
+ })
+ }
+}
+
+impl Parse for ParsePart {
+ fn parse(input: ParseStream<'_>) -> Result<Self> {
+ let documentation = input.call(Attribute::parse_outer)?;
+
+ let name = input.parse()?;
+ input.parse::<Token![:]>()?;
+
+ 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::<Token![=>]>()?;
+ finalizer = Some(input.parse::<Ident>()?);
+
+ let lookahead = input.lookahead1();
+ if !lookahead.peek(Token![,]) {
+ return Err(lookahead.error());
+ }
+ } else if lookahead.peek(Token![=]) {
+ input.parse::<Token![=]>()?;
+ default = Some(input.parse()?);
+
+ let lookahead = input.lookahead1();
+ if lookahead.peek(Token![=>]) {
+ input.parse::<Token![=>]>()?;
+ finalizer = Some(input.parse::<Ident>()?);
+
+ 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<Self> {
+ input.parse::<Token![use]>()?;
+ let content;
+ bracketed!(content in input);
+ let imports = content
+ .parse_terminated(syn::Path::parse, Token![;])?
+ .into_iter()
+ .collect();
+
+ input.parse::<Token![struct]>()?;
+ 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,
+ })
+ }
+}