Skip to content

Commit

Permalink
feat(derive): improved derive support, including partial help format …
Browse files Browse the repository at this point in the history
…string support!
  • Loading branch information
zkat committed Aug 16, 2021
1 parent 9a78a94 commit 9ef0dd2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
42 changes: 34 additions & 8 deletions miette-derive/src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,37 @@ impl Parse for Help {
if la.peek(syn::token::Paren) {
let content;
parenthesized!(content in input);
let str = content.parse::<syn::LitStr>()?;
Ok(Help {
fmt: str.value(),
args: Vec::new(),
})
let mut fmt = None;
let mut args = Vec::new();
let punc = syn::punctuated::Punctuated::<syn::Expr, Token![,]>::parse_terminated(
&content,
)?;
for (i, arg) in punc.into_iter().enumerate() {
if i == 0 {
if let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(str),
..
}) = arg
{
fmt = Some(str.value());
}
} else {
args.push(arg);
}
}
if let Some(fmt) = fmt {
Ok(Help { fmt, args })
} else if !args.is_empty() {
Err(syn::Error::new(
ident.span(),
"The first arg to help() must be a literal format string.",
))
} else {
Err(syn::Error::new(
ident.span(),
"help() format string is required",
))
}
} else {
input.parse::<Token![=]>()?;
Ok(Help {
Expand Down Expand Up @@ -53,9 +79,9 @@ impl Help {
ref fields,
..
}| {
let help = &help.as_ref().unwrap();
let fmt = &help.fmt;
let args = help.args.iter().map(|arg| quote! { #arg, });
let help = &help.as_ref().unwrap();
let fmt = &help.fmt;
let args = &help.args;
match fields {
syn::Fields::Named(_) => {
quote! { Self::#ident{..} => std::option::Option::Some(std::boxed::Box::new(format!(#fmt, #(#args),*))), }
Expand Down
6 changes: 2 additions & 4 deletions tests/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ fn list_help() {
);
}

/*
#[test]
fn fmt_help() {
#[derive(Debug, Diagnostic, Error)]
Expand All @@ -144,8 +143,8 @@ fn fmt_help() {
struct FooStruct(String);

assert_eq!(
"1 bar".to_string(),
FooStruct.help().unwrap().to_string()
"1 hello".to_string(),
FooStruct("hello".into()).help().unwrap().to_string()
);

#[derive(Debug, Diagnostic, Error)]
Expand All @@ -163,4 +162,3 @@ fn fmt_help() {
FooEnum::X.help().unwrap().to_string()
);
}
*/

0 comments on commit 9ef0dd2

Please sign in to comment.