#parse #either #variant #enum #speculative


Derive the syn::parse::Parse trait for enumerations and use it to comfortably parse a variant of the enumeration

4 releases (2 stable)

1.0.1 Mar 20, 2023
0.1.1 Jun 12, 2021
0.1.0 Jun 10, 2021

#53 in Procedural macros

Download history 136/week @ 2023-02-07 209/week @ 2023-02-14 107/week @ 2023-02-21 142/week @ 2023-02-28 122/week @ 2023-03-07 184/week @ 2023-03-14 105/week @ 2023-03-21 149/week @ 2023-03-28 250/week @ 2023-04-04 431/week @ 2023-04-11 164/week @ 2023-04-18 206/week @ 2023-04-25 256/week @ 2023-05-02 174/week @ 2023-05-09 247/week @ 2023-05-16 194/week @ 2023-05-23

895 downloads per month
Used in 50 crates (4 directly)

MIT license

225 lines


build lints tests approval-tests maintenance-status

Derive the syn::parse::Parse trait for enumerations and use it to comfortably parse a variant of the enumeration.


For a little project, I was trying to parse tokens that could either be an integer literal or an identifier from a ParseBuffer. This inspired me to write a custom derive macro for these kinds of use cases. We can now write

enum Number {

and then use this type to parse either variant from a parse buffer like so:

// input : &ParseBuffer
let num : Number = input.parse()?;

This operation returns the first variant (in order of declaration) that can be successfully parsed from the contents of the parse buffer. If none of the variants can be parsed, a compile error is returned. We can use this in any context where we wish to parse this type. The custom derive macro can also be used on much more general enum types, enabling pretty powerful parsing of variant types.

Advanced Use Cases

Enumerations do not have to be as simple as in the example above, because this crate will let you use the custom derive on enumerations with struct-like or tuple-like variants (or any combination of them). See this silly example for a more advanced use case:

mod kw {

enum SillyEnum {
    ExpressionInMeters {
        first: syn::Expr,
        _meters: kw::meters,
    IdentPlusPlus(Ident, syn::Token![+], syn::Token![+]),

This parses the tokens 16 + 12*length meters as the first and C++ as the second variant.

Consult the crate documentation for more information on how to use this macro and what to watch out for.


~23K SLoC