-
Notifications
You must be signed in to change notification settings - Fork 121
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix generics tokenization in
Error
derive macro (#238)
## Synopsis `#[derive(Error)]` on `enum`s or `struct`s that have *both* `const` generics and generic types... ```rust #[derive(Debug, Display, Error)] enum ErrConstGeneric<const X: usize, E> { Inner(E), } ``` ...panics: ``` error: proc-macro derive panicked --> tests/error/derives_for_generic_enums_with_source.rs:270:30 | 270 | #[derive(Debug, Display, Error)] | ^^^^^ | = help: message: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime ``` ## Solution For some reason, iterating over [`syn::Generics::params`](https://docs.rs/syn/latest/syn/struct.Generics.html#structfield.params) that consists of only `const` generics or only generic types, tokenizes them as identifiers only, but when we mix them, `syn` decides to output `const` generics like they were defined, with `const` keyword, type annotation, etc. So when we are rendering the trait `impl`, adding bounds for an item in `where` clause, we get this: ```rust #[automatically_derived] impl<const X: usize, E> ::std::error::Error for ErrConstGeneric<X, E> where E: ::std::fmt::Debug + ::std::fmt::Display + ::std::error::Error + 'static, ErrConstGeneric<const X: usize, E>: ::std::fmt::Debug + ::std::fmt::Display, // obv wrong { fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> { match self { ErrConstGeneric::Inner(source) => { Some(source as &(dyn ::std::error::Error + 'static)) } } } } ``` Use `syn`'s built-in [`Generics::split_for_impl`](https://docs.rs/syn/latest/syn/struct.Generics.html#method.split_for_impl) to obtain a [type](https://docs.rs/syn/latest/syn/struct.TypeGenerics.html) that properly tokenizes all generic parameters. Co-authored-by: tyranron <[email protected]>
- Loading branch information
Showing
3 changed files
with
144 additions
and
6 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