Skip to content

Const generic equivalence check overrides diagnostic::on_unimplemented #134881

Open
@juntyr

Description

@juntyr

Code

#![feature(generic_const_exprs)]

trait Trait {
    const VAL: usize;
}

struct A;
impl Trait for A {
    const VAL: usize = 1;
}

struct B;
impl Trait for B {
    const VAL: usize = 2;
}

#[diagnostic::on_unimplemented(
    message = "`{Self}` is not equivalent to `{T}`",
)]
trait Equivalent<T: Trait>: IsEquivalent<T, true> {}
impl<A: Trait + IsEquivalent<B, true>, B: Trait> Equivalent<B> for A {}

trait IsEquivalent<T: Trait, const EQUIVALENT: bool>: Trait {}
impl<A: Trait, B: Trait> IsEquivalent<A, {A::VAL == B::VAL}> for B {}

fn check_equivalent<A: Trait + Equivalent<B>, B: Trait>(_a: &A, _b: &B) {}

fn main() {
    check_equivalent(&A, &A); // works as expected
    check_equivalent(&B, &B); // works as expected
    
    check_equivalent(&A, &B);
 // ^^^^^^^^^^^^^^^^^^^^^^^^ expected `true`, found `false`
}

Current output

error[E0308]: mismatched types
  --> src/main.rs:32:5
   |
32 |     check_equivalent(&A, &B);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^ expected `true`, found `false`
   |
   = note: expected constant `true`
              found constant `false`

Desired output

--> src/main.rs:32:5
   |
32 |     check_equivalent(&A, &B);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^ `A` is not equivalent to `B`

Rationale and extra context

In the given example, the A does not implement the trait Equivalent<B> and there is a custom #[diagnostic::on_unimplemented] message. However, the diagnostic message is not shown, instead the mismatch between true and false const generics in the implementation of the equivalence check is leaked.

Other cases

Rust Version

1.85-nightly 2024-12-28 8742e0556dee3c64f714 (on Rust playground)

Anything else?

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=eaf4f6a4a8d5336e43446dc1d0e9b575

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsF-generic_const_exprs`#![feature(generic_const_exprs)]`T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions