Skip to content

Stabilize guaranteed compile time evaluation of unnamed constant items #93838

Closed
@XrXr

Description

@XrXr

This is a request to stabilize the implementation fact that the definition of unnamed constant items are always evaluated at compile time (through CTFE). There is no associated RFC as this feature is already available in stable releases and this is mostly a request for using an FCP to reach consensus for future support.

The stabilization of const-panic introduced a way for CTFE to emit hard compile errors. This allows users to perform compile time assertions using familiar language constructs and a growing set of const APIs. Before const-panic, users could emit the const_err lint, which was less dependable since whether lints fail builds is configurable.

Authors of compile time assertions that utilize const-panic would probably like to have confidence that what they wrote is in fact evaluated by rustc during compilation. Currently, users can ensure evaluation by utilizing const contexts that are inputs to the type checker:

const _: [(); panic!("custom error")] = [];

This trick relies on the fact that type checking is guaranteed to happen during compilation. Utilizing this to initiate constant evaluation feels more cumbersome than necessary.

This report aims to stabilize a more obvious way to initiate compile time evaluation.

What is being stabilized

The current rustc behavior that unnamed constant definitions are evaluated at least once at compile time. Note that compile time evaluation happens even when the function enclosing the unnamed constant is unused:

fn unused() {
    const _: () = panic!("always a compile error");
}

Stabilizing this seems unlikely to cause maintenance issues in the future due to the constrained nature of unnamed constants. However, I defer to people with rustc maintenance experience to judge this claim.

What is not being stabilized

The evaluation timing of named constant items. Named constant items can be associated constants, which could use generics. Unnamed constants cannot be associated constants and cannot use generic parameters. While it might be useful to also stabilize the evaluation timing of named constant items, they require more consideration and are out of scope for this report.


I would like to thank Ralf Jung, Oli Scherer, and Eric Huss for the generous amount of guidance I received. Here is the Zulip discussion leading up to this stabilization request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions