-
Notifications
You must be signed in to change notification settings - Fork 68
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Report errors on unsupported attributes (#113)
`darling` pre-dates Rust support for non-meta attributes. These increase flexibility for Rust code, but mean that not `darling` does not parse all valid attributes. `darling` previously ignored these outright, creating misleading errors, such as claiming all fields were missing. This commit makes unsupported attributes explicit errors. To allow for detailed diagnostic information in the future without changing the crate's public API, the parsing of `Attribute` into `MetaList` is handled in a new function that wraps `syn`'s own `parse_meta`. This commit uses that structure to include an attribute path in an example for the name-value error case; future commits could expand that function to identify places where the caller may have missed quotation marks, for example. Fixes #96
- Loading branch information
Showing
6 changed files
with
158 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
use crate::{util::SpannedValue, Error, Result}; | ||
use std::fmt; | ||
use syn::{punctuated::Pair, spanned::Spanned, token, Attribute, Meta, MetaList, Path}; | ||
|
||
/// Try to parse an attribute into a meta list. Path-type meta values are accepted and returned | ||
/// as empty lists with their passed-in path. Name-value meta values and non-meta attributes | ||
/// will cause errors to be returned. | ||
pub fn parse_attribute_to_meta_list(attr: &Attribute) -> Result<MetaList> { | ||
match attr.parse_meta() { | ||
Ok(Meta::List(list)) => Ok(list), | ||
Ok(Meta::NameValue(nv)) => Err(Error::custom(format!( | ||
"Name-value arguments are not supported. Use #[{}(...)]", | ||
DisplayPath(&nv.path) | ||
)) | ||
.with_span(&nv)), | ||
Ok(Meta::Path(path)) => Ok(MetaList { | ||
path, | ||
paren_token: token::Paren(attr.span()), | ||
nested: Default::default(), | ||
}), | ||
Err(e) => Err(Error::custom(format!("Unable to parse attribute: {}", e)) | ||
.with_span(&SpannedValue::new((), e.span()))), | ||
} | ||
} | ||
|
||
struct DisplayPath<'a>(&'a Path); | ||
|
||
impl fmt::Display for DisplayPath<'_> { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
let path = self.0; | ||
if path.leading_colon.is_some() { | ||
write!(f, "::")?; | ||
} | ||
for segment in path.segments.pairs() { | ||
match segment { | ||
Pair::Punctuated(segment, _) => write!(f, "{}::", segment.ident)?, | ||
Pair::End(segment) => segment.ident.fmt(f)?, | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::parse_attribute_to_meta_list; | ||
use syn::{parse_quote, spanned::Spanned, Ident}; | ||
|
||
#[test] | ||
fn parse_list() { | ||
let meta = parse_attribute_to_meta_list(&parse_quote!(#[bar(baz = 4)])).unwrap(); | ||
assert_eq!(meta.nested.len(), 1); | ||
} | ||
|
||
#[test] | ||
fn parse_path_returns_empty_list() { | ||
let meta = parse_attribute_to_meta_list(&parse_quote!(#[bar])).unwrap(); | ||
assert!(meta.path.is_ident(&Ident::new("bar", meta.path.span()))); | ||
assert!(meta.nested.is_empty()); | ||
} | ||
|
||
#[test] | ||
fn parse_name_value_returns_error() { | ||
parse_attribute_to_meta_list(&parse_quote!(#[bar = 4])).unwrap_err(); | ||
} | ||
|
||
#[test] | ||
fn parse_name_value_error_includes_example() { | ||
let err = parse_attribute_to_meta_list(&parse_quote!(#[bar = 4])).unwrap_err(); | ||
assert!(err.to_string().contains("#[bar(...)]")); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
#[macro_use] | ||
extern crate darling; | ||
#[macro_use] | ||
extern crate syn; | ||
|
||
use darling::FromDeriveInput; | ||
use syn::{Ident, LitStr, Path}; | ||
|
||
#[derive(Debug, FromDeriveInput)] | ||
#[darling(supports(struct_unit), attributes(bar))] | ||
pub struct Bar { | ||
pub ident: Ident, | ||
pub st: Path, | ||
pub file: LitStr, | ||
} | ||
|
||
/// Per [#96](https://github.com/TedDriggs/darling/issues/96), make sure that an | ||
/// attribute which isn't a valid meta gets an error. | ||
#[test] | ||
fn non_meta_attribute_gets_own_error() { | ||
let di = parse_quote! { | ||
#[derive(Bar)] | ||
#[bar(file = "motors/example_6.csv", st = RocketEngine)] | ||
pub struct EstesC6; | ||
}; | ||
|
||
let errors: darling::Error = Bar::from_derive_input(&di).unwrap_err().flatten(); | ||
// The number of errors here is 1 for the bad attribute + 2 for the missing fields | ||
assert_eq!(3, errors.len()); | ||
// Make sure one of the errors propagates the syn error | ||
assert!(errors | ||
.into_iter() | ||
.any(|e| e.to_string().contains("expected lit"))); | ||
} | ||
|
||
/// Properties can be split across multiple attributes; this test ensures that one | ||
/// non-meta attribute does not interfere with the parsing of other, well-formed attributes. | ||
#[test] | ||
fn non_meta_attribute_does_not_block_others() { | ||
let di = parse_quote! { | ||
#[derive(Bar)] | ||
#[bar(st = RocketEngine)] | ||
#[bar(file = "motors/example_6.csv")] | ||
pub struct EstesC6; | ||
}; | ||
|
||
let errors: darling::Error = Bar::from_derive_input(&di).unwrap_err().flatten(); | ||
// The number of errors here is 1 for the bad attribute + 1 for the missing "st" field | ||
assert_eq!(2, errors.len()); | ||
// Make sure one of the errors propagates the syn error | ||
assert!(errors | ||
.into_iter() | ||
.any(|e| e.to_string().contains("expected lit"))); | ||
} |