Skip to content

macro generated enum with explicit discriminant values hits panic #56

@tjallingt

Description

@tjallingt

The following example hits a panic in speedy:

macro_rules! define_enum {
    (
        $(#[$enum_meta:meta])*
        enum $name:ident {
            $($(#[$variant_meta:meta])* $variant:ident $(= $value:literal)?),* $(,)?
        }
    ) => {
        $(#[$enum_meta])*
        enum $name {
            $($(#[$variant_meta])* $variant $(= $value)? ,)*
        }
    };
}

define_enum! {
#[derive(Readable, Writable)]
#[speedy(tag_type = u8)]
enum TestBreaks {
    One = 1,
    Two = 2,
}
}
error: Enum discriminant `TestBreaks::One` is currently unsupported!
  --> src/main.rs:13:49
   |
13 |               $($(#[$variant_meta])* $variant $(= $value)? ,)*
   |                                                   ^^^^^^
...
30 | / define_enum! {
31 | | #[derive(Readable, Writable)]
32 | | #[speedy(tag_type = u8)]
33 | | enum TestBreaks {
...  |
36 | | }
37 | | }
   | |_- in this macro invocation
   |
   = note: this error originates in the macro `bug` (in Nightly builds, run with -Z macro-backtrace for more info)

error: could not compile `workspace` due to previous error

This originates from the following match https://github.com/koute/speedy/blob/master/speedy-derive/src/lib.rs#L1905-L1936

There is a workaround using speedy(tag = $expr):

define_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Readable, Writable)]
#[speedy(tag_type = u8)]
enum TestWorks {
    #[speedy(tag = 1)]
    One,
    #[speedy(tag = 2)]
    Two,
}
}

But I would expect both to work.

I expect this can be supported by adding a new case to the variant.discriminant match statement, I'll look into what tokens speedy-derive is getting from the macro and make a PR.

To answer why such a macro is useful; I'm defining copies/subsets of enums that are used in an API and using a macro like this to automatically add From/TryFrom implementations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions