Skip to content

#[derive]'d PartialOrd and Ord use variant declaration order, not explicit discriminant values, for (partially) C-like enums #15523

Closed
@huonw

Description

@huonw
#[deriving(Ord, PartialOrd, Eq, PartialEq, Show)]
enum Foo {
    A = 10,
    B = 0,
    C,
}

fn main() {
    let v = [A, B, C];

    println!("      deriving\tdiscriminant");
    for x in v.iter() {
        for y in v.iter() {
            println!("{}, {}: {}  \t{}", *x, *y, x.cmp(y), (*x as uint).cmp(&(*y as uint)));
        }
    }
}
      deriving  discriminant
A, A: Equal     Equal
A, B: Less      Greater
A, C: Less      Greater
B, A: Greater   Less
B, B: Equal     Equal
B, C: Less      Less
C, A: Greater   Less
C, B: Greater   Greater
C, C: Equal     Equal

That is, deriving considers A the smallest, but it has the largest discriminant.

I would think that #[deriving] should be changed to use the explicit discriminants (if they are available), but there is some possibility that declaration order may be the correct thing (you can always reorder the variants to match their discriminants).

There's also an edge case due to the (apparent?) untypedness of enum variant discriminants: when ordering enum Foo { A = 1, B = -1 }, is the discriminant of B considered negative, or is it positive and huge?

Metadata

Metadata

Assignees

Labels

A-syntaxextArea: Syntax extensionsE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions