Skip to content

thread_local_initializer_can_be_made_const false positive: panicking Cell and RefCell initialization #12637

Closed
@dtolnay

Description

@dtolnay

Summary

The set methods on LocalKey<Cell<T>> and LocalKey<RefCell<T>> are guaranteed to bypass the thread_local's initialization expression. See rust-lang/rust#92122. Thus, = panic!() is a useful idiom for forcing the use of set on each thread before it accesses the thread local in any other manner.

Clippy suggests replacing this with = const { panic!() }, which does not compile.

Lint Name

thread_local_initializer_can_be_made_const

Reproducer

use std::cell::Cell;

thread_local! {
    static STATE: Cell<usize> = panic!();
}

fn main() {
    STATE.set(9);
    println!("{}", STATE.get());
}
warning: initializer for `thread_local` value can be made `const`
 --> src/main.rs:4:33
  |
4 |     static STATE: Cell<usize> = panic!();
  |                                 ^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#thread_local_initializer_can_be_made_const
  = note: `#[warn(clippy::thread_local_initializer_can_be_made_const)]` on by default
  = note: this warning originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)

The suggested change makes the code not compile.

error[E0080]: evaluation of constant value failed
 --> src/main.rs:4:41
  |
4 |     static STATE: Cell<usize> = const { panic!() };
  |                                         ^^^^^^^^ the evaluated program panicked at 'explicit panic', src/main.rs:4:41
  |
  = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info)

note: erroneous constant encountered
 --> src/main.rs:3:1
  |
3 | / thread_local! {
4 | |     static STATE: Cell<usize> = const { panic!() };
5 | | }
  | |_^
  |
  = note: this note originates in the macro `$crate::thread::local_impl::thread_local_inner` which comes from the expansion of the macro `thread_local` (in Nightly builds, run with -Z macro-backtrace for more info)

Version

rustc 1.79.0-nightly (385fa9d84 2024-04-04)
binary: rustc
commit-hash: 385fa9d845dd326c6bbfd58c22244215e431948a
commit-date: 2024-04-04
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.2

Additional Labels

@rustbot label +I-suggestion-causes-error

Metadata

Metadata

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions