diff options
Diffstat (limited to 'alacritty_config_derive/src/config_deserialize')
3 files changed, 274 insertions, 0 deletions
diff --git a/alacritty_config_derive/src/config_deserialize/de_enum.rs b/alacritty_config_derive/src/config_deserialize/de_enum.rs new file mode 100644 index 00000000..73634e73 --- /dev/null +++ b/alacritty_config_derive/src/config_deserialize/de_enum.rs @@ -0,0 +1,71 @@ +use proc_macro::TokenStream; +use proc_macro2::TokenStream as TokenStream2; +use quote::{format_ident, quote}; +use syn::{DataEnum, Generics, Ident}; + +use crate::serde_replace; + +pub fn derive_deserialize(ident: Ident, generics: Generics, data_enum: DataEnum) -> TokenStream { + let visitor = format_ident!("{}Visitor", ident); + + // Create match arm streams and get a list with all available values. + let mut match_arms_stream = TokenStream2::new(); + let mut available_values = String::from("one of "); + for variant in data_enum.variants.iter().filter(|variant| { + // Skip deserialization for `#[config(skip)]` fields. + variant.attrs.iter().all(|attr| { + !crate::path_ends_with(&attr.path, "config") || attr.tokens.to_string() != "(skip)" + }) + }) { + let variant_ident = &variant.ident; + let variant_str = variant_ident.to_string(); + available_values = format!("{}`{}`, ", available_values, variant_str); + + let literal = variant_str.to_lowercase(); + + match_arms_stream.extend(quote! { + #literal => Ok(#ident :: #variant_ident), + }); + } + + // Remove trailing `, ` from the last enum variant. + available_values.truncate(available_values.len().saturating_sub(2)); + + // Generate deserialization impl. + let mut tokens = quote! { + struct #visitor; + impl<'de> serde::de::Visitor<'de> for #visitor { + type Value = #ident; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str(#available_values) + } + + fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> + where + E: serde::de::Error, + { + match s.to_lowercase().as_str() { + #match_arms_stream + _ => Err(E::custom( + &format!("unknown variant `{}`, expected {}", s, #available_values) + )), + } + } + } + + impl<'de> serde::Deserialize<'de> for #ident { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_str(#visitor) + } + } + }; + + // Automatically implement [`alacritty_config::SerdeReplace`]. + tokens.extend(serde_replace::derive_direct(ident, generics)); + + tokens.into() +} diff --git a/alacritty_config_derive/src/config_deserialize/de_struct.rs b/alacritty_config_derive/src/config_deserialize/de_struct.rs new file mode 100644 index 00000000..4245764f --- /dev/null +++ b/alacritty_config_derive/src/config_deserialize/de_struct.rs @@ -0,0 +1,181 @@ +use proc_macro::TokenStream; +use proc_macro2::TokenStream as TokenStream2; +use quote::{format_ident, quote}; +use syn::punctuated::Punctuated; +use syn::spanned::Spanned; +use syn::{Error, Field, Generics, Ident, Type}; + +use crate::{serde_replace, Attr, GenericsStreams, MULTIPLE_FLATTEN_ERROR}; + +/// Use this crate's name as log target. +const LOG_TARGET: &str = env!("CARGO_PKG_NAME"); + +pub fn derive_deserialize<T>( + ident: Ident, + generics: Generics, + fields: Punctuated<Field, T>, +) -> TokenStream { + // Create all necessary tokens for the implementation. + let GenericsStreams { unconstrained, constrained, phantoms } = + crate::generics_streams(&generics.params); + let FieldStreams { flatten, match_assignments } = fields_deserializer(&fields); + let visitor = format_ident!("{}Visitor", ident); + + // Generate deserialization impl. + let mut tokens = quote! { + #[derive(Default)] + #[allow(non_snake_case)] + struct #visitor <#unconstrained> { + #phantoms + } + + impl <'de, #constrained> serde::de::Visitor<'de> for #visitor <#unconstrained> { + type Value = #ident <#unconstrained>; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a mapping") + } + + fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error> + where + M: serde::de::MapAccess<'de>, + { + let mut config = Self::Value::default(); + + // NOTE: This could be used to print unused keys. + let mut unused = serde_yaml::Mapping::new(); + + while let Some((key, value)) = map.next_entry::<String, serde_yaml::Value>()? { + match key.as_str() { + #match_assignments + _ => { + unused.insert(serde_yaml::Value::String(key), value); + }, + } + } + + #flatten + + Ok(config) + } + } + + impl <'de, #constrained> serde::Deserialize<'de> for #ident <#unconstrained> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_map(#visitor :: default()) + } + } + }; + + // Automatically implement [`alacritty_config::SerdeReplace`]. + tokens.extend(serde_replace::derive_recursive(ident, generics, fields)); + + tokens.into() +} + +// Token streams created from the fields in the struct. +#[derive(Default)] +struct FieldStreams { + match_assignments: TokenStream2, + flatten: TokenStream2, +} + +/// Create the deserializers for match arms and flattened fields. +fn fields_deserializer<T>(fields: &Punctuated<Field, T>) -> FieldStreams { + let mut field_streams = FieldStreams::default(); + + // Create the deserialization stream for each field. + for field in fields.iter() { + if let Err(err) = field_deserializer(&mut field_streams, field) { + field_streams.flatten = err.to_compile_error(); + return field_streams; + } + } + + field_streams +} + +/// Append a single field deserializer to the stream. +fn field_deserializer(field_streams: &mut FieldStreams, field: &Field) -> Result<(), Error> { + let ident = field.ident.as_ref().expect("unreachable tuple struct"); + let literal = ident.to_string(); + let mut literals = vec![literal.clone()]; + + // Create default stream for deserializing fields. + let mut match_assignment_stream = quote! { + match serde::Deserialize::deserialize(value) { + Ok(value) => config.#ident = value, + Err(err) => { + log::error!(target: #LOG_TARGET, "Config error: {}: {}", #literal, err); + }, + } + }; + + // Iterate over all #[config(...)] attributes. + for attr in field.attrs.iter().filter(|attr| crate::path_ends_with(&attr.path, "config")) { + let parsed = match attr.parse_args::<Attr>() { + Ok(parsed) => parsed, + Err(_) => continue, + }; + + match parsed.ident.as_str() { + // Skip deserialization for `#[config(skip)]` fields. + "skip" => return Ok(()), + "flatten" => { + // NOTE: Currently only a single instance of flatten is supported per struct + // for complexity reasons. + if !field_streams.flatten.is_empty() { + return Err(Error::new(attr.span(), MULTIPLE_FLATTEN_ERROR)); + } + + // Create the tokens to deserialize the flattened struct from the unused fields. + field_streams.flatten.extend(quote! { + let unused = serde_yaml::Value::Mapping(unused); + config.#ident = serde::Deserialize::deserialize(unused).unwrap_or_default(); + }); + }, + "deprecated" | "removed" => { + // Construct deprecation/removal message with optional attribute override. + let mut message = format!("Config warning: {} has been {}", literal, parsed.ident); + if let Some(warning) = parsed.param { + message = format!("{}; {}", message, warning.value()); + } + + // Append stream to log deprecation/removal warning. + match_assignment_stream.extend(quote! { + log::warn!(target: #LOG_TARGET, #message); + }); + }, + // Add aliases to match pattern. + "alias" => { + if let Some(alias) = parsed.param { + literals.push(alias.value()); + } + }, + _ => (), + } + } + + // Create token stream for deserializing "none" string into `Option<T>`. + if let Type::Path(type_path) = &field.ty { + if crate::path_ends_with(&type_path.path, "Option") { + match_assignment_stream = quote! { + if value.as_str().map_or(false, |s| s.eq_ignore_ascii_case("none")) { + config.#ident = None; + continue; + } + #match_assignment_stream + }; + } + } + + // Create the token stream for deserialization and error handling. + field_streams.match_assignments.extend(quote! { + #(#literals)|* => { #match_assignment_stream }, + }); + + Ok(()) +} diff --git a/alacritty_config_derive/src/config_deserialize/mod.rs b/alacritty_config_derive/src/config_deserialize/mod.rs new file mode 100644 index 00000000..b1923377 --- /dev/null +++ b/alacritty_config_derive/src/config_deserialize/mod.rs @@ -0,0 +1,22 @@ +use proc_macro::TokenStream; +use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Error, Fields}; + +/// Error if the derive was used on an unsupported type. +const UNSUPPORTED_ERROR: &str = "ConfigDeserialize must be used on an enum or struct with fields"; + +mod de_enum; +mod de_struct; + +pub fn derive(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + + match input.data { + Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => { + de_struct::derive_deserialize(input.ident, input.generics, fields.named) + }, + Data::Enum(data_enum) => { + de_enum::derive_deserialize(input.ident, input.generics, data_enum) + }, + _ => Error::new(input.ident.span(), UNSUPPORTED_ERROR).to_compile_error().into(), + } +} |