rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

lint suggestion `missing_const_blocks`

Open Lars-Schumann opened this issue 11 months ago • 1 comments

What it does

Suggest to add const {} blocks around every¹ const evaluatable expression.

¹There are many cases where this would probably do nothing, these would need to be ignored for this lint not to be allowed by everyone. In particular, if this lint were to only be triggered on the boundary from non-const fn's -> const fn's, and it was followed in all of those places, the effect should be equivalent to this lint being triggered everywhere.

Advantage

  • Catch certain classes of errors at compile time
  • Possibly better performance

Drawbacks

  • Increase in general clutter

Example

const fn black_box() -> i32 {
    -7
}

const fn new_counter(value: i32) -> NonZeroI32 {
    NonZeroI32::new(value).unwrap()
}

const fn frunctinator(x: u32) -> u32 {
    1 << (12 / x)
}

const fn prefix(s: &str) -> &str {
    &s[..1]
}

static DWARF_COUNT: i32 = 7;
fn main() {
    let x = new_counter(black_box() + DWARF_COUNT); // missing const blocks
    let y = frunctinator(0); // missing const blocks
    let z = prefix("éclair"); // missing const blocks
}

Could be written as:

fn main() {
    let x = const { new_counter(black_box() + DWARF_COUNT) }; // evaluation panicked: called `Option::unwrap()` on a `None` value
    let y = const { frunctinator(0) }; // attempt to divide `4096_u32` by zero
    let z = const { prefix("éclair") }; // evaluation panicked: failed to slice string
}

Comparison with existing lints

Unlike clippy::missing_const_for_thread_local, this lint would apply to every expression. Unlike clippy::missing_const_for_fn, this lint doesn't suggest changes whose reversal would break a crates public API.

Additional Context

No response

Lars-Schumann avatar Dec 31 '25 19:12 Lars-Schumann

Hi, I’d like to work on this issue and check the install instructions. Please let me know if anything specific needs attention.

akshayhat avatar Jan 04 '26 13:01 akshayhat