Skip to content

Bug: incorrect index assignment with #[codec(index = ...)] #724

Open
@breathx

Description

@breathx

Hey! I recently encountered a bug with both the Encode and Decode derive macros, which causes incorrect discriminant values (indexes) to be assigned to enum variants.

Here’s a minimal reproducible example:

use parity_scale_codec::{Decode, Encode};

#[derive(Decode, Encode)]
enum MyEnum {
    #[codec(index = 1)]
    A, // will have index 1
    B, // will also get index 1, incorrectly
}

This results in a compile-time error:

error[E0080]: evaluation of constant value failed
 --> src/lib.rs:3:10
  |
3 | #[derive(Decode, Encode)]
  |          ^^^^^^ the evaluated program panicked at 'Found variants that have duplicate indexes. Both `A` and `B` have the index `1`. Use different indexes for each variant.', src/lib.rs:3:10
  |
  = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `::core::panic` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0080]: evaluation of constant value failed
 --> src/lib.rs:3:18
  |
3 | #[derive(Decode, Encode)]
  |                  ^^^^^^ the evaluated program panicked at 'Found variants that have duplicate indexes. Both `A` and `B` have the index `1`. Use different indexes for each variant.', src/lib.rs:3:18
  |
  = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `::core::panic` (in Nightly builds, run with -Z macro-backtrace for more info)

If we change the index to 3, the code compiles, but B is still incorrectly assigned index 1, instead of the expected next available index (which should be 4 in this case).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions