Skip to content

PartialEq and matching in const contexts #13

@compiler-errors

Description

@compiler-errors

Currently we allow matches to emit PartialEq::partial_eq calls, but don't enforce anything about those calls' constness. AFAICT the only PartialEq::partial_eq call that seems to be emitted is for &str, since ADTs seem to be decomposed into matches on their fields.

The problem here is that I thought the whole point of matches requiring PartialEquality of scrutinees is that we can conceptually think of const arms as PartialEq calls; the fact that we decompose them seems like an impl detail.

When a struct contains a &str, this ends up getting caught by the MIR constness checking, but this seems sub-optimal. OTOH, we can't just require everyone to derive_const(PartialEq, Eq) on their match scrutinees, since they may be relying on this behavior...

What should we do 🤔

#[derive(Eq, PartialEq)]
struct Struct {
    f: &'static str,
    g: i32,
}

const FOO: Struct = Struct { f: "", g: 1 };
const BAR: Struct = Struct { f: "", g: 2 };

const fn test() {
    match BAR {
        FOO => {}
        _ => {}
    }
}
error[E0015]: cannot match on `str` in constant functions
  --> src/lib.rs:12:9
   |
12 |         FOO => {}
   |         ^^^
   |
   = note: `str` cannot be compared in compile-time, and therefore cannot be used in `match`es
   = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants

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