Skip to content

Commit

Permalink
Refactor #[wasm_bindgen] attribute parsing
Browse files Browse the repository at this point in the history
This commit moves to having a struct per `syn::Item` type that the
macro operates on, then uses `darling` to handle validation of the
attribute.

This implicitly fixes rustwasm#2874, since `darling` automatically generates
errors for unexpected properties. It also makes the macro code easier
to follow by hiding the complexity associated with parsing out of sight
in a well-tested crate. This also precludes a class of bug where someone
might have attempted to read a property that was not accepted for that
syntax item, since each syntax item now has its own options receiver.

`darling` operates on `syn::Meta`, which only allows a literal to the
right side of `=` signs in attributes. This is a problem for wasm_bindgen,
which does not use them.

To maintain API compatibility while using `darling`, this commit adds
`macro_support::meta::Meta<T>`, a replica of `syn::Meta` where `Lit` is
replaced by a type parameter. This may be useful enough beyond `wasm_bindgen`
for it to move upstream to `darling`, which would mean this change would
reduce the overall amount of code in `macro-support`.
  • Loading branch information
Ted Driggs committed Apr 29, 2022
1 parent e8ea739 commit 8857f76
Show file tree
Hide file tree
Showing 8 changed files with 835 additions and 576 deletions.
1 change: 1 addition & 0 deletions crates/backend/Cargo.toml
Expand Up @@ -17,6 +17,7 @@ extra-traits = ["syn/extra-traits"]

[dependencies]
bumpalo = "3.0.0"
darling = "0.14.1"
lazy_static = "1.0.2"
log = "0.4"
proc-macro2 = "1.0"
Expand Down
6 changes: 6 additions & 0 deletions crates/backend/src/error.rs
Expand Up @@ -98,6 +98,12 @@ impl From<Error> for Diagnostic {
}
}

impl From<darling::Error> for Diagnostic {
fn from(err: darling::Error) -> Self {
Self::from(Error::from(err))
}
}

fn extract_spans(node: &dyn ToTokens) -> Option<(Span, Span)> {
let mut t = TokenStream::new();
node.to_tokens(&mut t);
Expand Down
1 change: 1 addition & 0 deletions crates/macro-support/Cargo.toml
Expand Up @@ -17,6 +17,7 @@ extra-traits = ["syn/extra-traits"]
strict-macro = []

[dependencies]
darling = "0.14.1"
syn = { version = '1.0.67', features = ['visit', 'full'] }
quote = '1.0'
proc-macro2 = "1.0"
Expand Down

0 comments on commit 8857f76

Please sign in to comment.