diff options
| author | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2026-11-07 15:00:04 +0100 |
|---|---|---|
| committer | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2026-11-07 15:00:04 +0100 |
| commit | 73cc6d79192ce1cd7851f990b2666c354d105939 (patch) | |
| tree | f5efead8659d64a7e835d9680942a52d209ebc9b /crates/mk_config/src/generate.rs | |
| parent | refactor(yt_dlp/): Make the options more like the builder pattern (diff) | |
| download | yt-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/src/generate.rs')
| -rw-r--r-- | crates/mk_config/src/generate.rs | 727 |
1 files changed, 727 insertions, 0 deletions
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() + ) +} |
