Skip to content

Const evaluation can fail during cargo build but not cargo check #112301

Closed as not planned
@joshlf

Description

@joshlf

I have the following code:

trait Foo {
    const FOO: ();
}

impl Foo for () {
    const FOO: () = unimplemented!();
}

pub fn foo() {
    let _: () = <() as Foo>::FOO;
}

Running cargo check succeeds, while cargo build fails:

$ cargo build
   Compiling check-panicking-const v0.1.0 (.../check-panicking-const)
error[E0080]: evaluation of constant value failed
 --> src/lib.rs:6:21
  |
6 |     const FOO: () = unimplemented!();
  |                     ^^^^^^^^^^^^^^^^ the evaluated program panicked at 'not implemented', src/lib.rs:6:21
  |
  = note: this error originates in the macro `unimplemented` (in Nightly builds, run with -Z macro-backtrace for more info)

note: erroneous constant used
  --> src/lib.rs:10:17
   |
10 |     let _: () = <() as Foo>::FOO;
   |                 ^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0080`.
error: could not compile `check-panicking-const` (lib) due to previous error

I would expect cargo build and cargo check to exhibit the same behavior.

This has practical implications. For example, I'm working on implementing this technique in zerocopy, which intentionally generates panicking constants when an unsound transmutation is attempted. The behavior mismatch between cargo check and cargo build means that unsound transmutes appear to compile until the user runs cargo build. For users who primarily use cargo check during development (I am included in this group), this can result in spending a lot of time going down a path that will end up with a dead end.

This is an instance of #70923.

Version

$ cargo --version
cargo 1.72.0-nightly (b0fa79679 2023-06-03)

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