Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support fields aliases #177

Merged
merged 2 commits into from
Nov 4, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 65 additions & 19 deletions crates/jrsonnet-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ impl Parse for Field {
mod kw {
syn::custom_keyword!(fields);
syn::custom_keyword!(rename);
syn::custom_keyword!(alias);
syn::custom_keyword!(flatten);
syn::custom_keyword!(add);
syn::custom_keyword!(hide);
Expand Down Expand Up @@ -412,6 +413,7 @@ fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream
#[allow(clippy::struct_excessive_bools)]
struct TypedAttr {
rename: Option<String>,
aliases: Vec<String>,
flatten: bool,
/// flatten(ok) strategy for flattened optionals
/// field would be None in case of any parsing error (as in serde)
Expand All @@ -437,6 +439,11 @@ impl Parse for TypedAttr {
));
}
out.rename = Some(name.value());
} else if lookahead.peek(kw::alias) {
input.parse::<kw::alias>()?;
input.parse::<Token![=]>()?;
let alias = input.parse::<LitStr>()?;
out.aliases.push(alias.value());
} else if lookahead.peek(kw::flatten) {
input.parse::<kw::flatten>()?;
out.flatten = true;
Expand Down Expand Up @@ -538,40 +545,79 @@ impl TypedField {
})
}
fn expand_parse(&self) -> TokenStream {
if self.is_option {
self.expand_parse_optional()
} else {
self.expand_parse_mandatory()
}
}

fn expand_parse_optional(&self) -> TokenStream {
let ident = &self.ident;
let ty = &self.ty;

// optional flatten is handled in same way as serde
if self.attr.flatten {
// optional flatten is handled in same way as serde
return if self.is_option {
quote! {
#ident: <#ty as TypedObj>::parse(&obj).ok(),
}
} else {
quote! {
#ident: <#ty as TypedObj>::parse(&obj)?,
}
return quote! {
#ident: <#ty as TypedObj>::parse(&obj).ok(),
};
};
}

let name = self.name().unwrap();
let value = if self.is_option {
quote! {
if let Some(value) = obj.get(#name.into())? {
Some(<#ty as Typed>::from_untyped(value)?)
} else {
None
}
let aliases = &self.attr.aliases;

let value = quote! {
if let Some(__value) = obj.get(#name.into())? {
Some(<#ty as Typed>::from_untyped(__value)?)
} #(else if let Some(__value) = obj.get(#aliases) {
vklachkov marked this conversation as resolved.
Show resolved Hide resolved
Some(<#ty as Typed>::from_untyped(__value)?)
})* else {
None
}
};

quote! {
#ident: #value,
}
}

fn expand_parse_mandatory(&self) -> TokenStream {
let ident = &self.ident;
let ty = &self.ty;

// optional flatten is handled in same way as serde
if self.attr.flatten {
return quote! {
#ident: <#ty as TypedObj>::parse(&obj)?,
};
}

let name = self.name().unwrap();
let aliases = &self.attr.aliases;

let error_text = if aliases.is_empty() {
// clippy does not understand name variable usage in quote! macro
#[allow(clippy::redundant_clone)]
name.clone()
} else {
quote! {
<#ty as Typed>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?
format!("{name} (alias {})", aliases.join(", "))
};

let value = quote! {
if let Some(__value) = obj.get(#name.into())? {
vklachkov marked this conversation as resolved.
Show resolved Hide resolved
<#ty as Typed>::from_untyped(__value)?
} #(else if let Some(__value) = obj.get(#aliases.into())? {
<#ty as Typed>::from_untyped(__value)?
})* else {
return Err(ErrorKind::NoSuchField(#error_text.into(), vec![]).into());
}
};

quote! {
#ident: #value,
}
}

fn expand_serialize(&self) -> TokenStream {
let ident = &self.ident;
let ty = &self.ty;
Expand Down