rust/tests/ui/thread_local_initializer_can_be_made_const.rs
Quinn Sinclair 70024e16c0 New Lint: [thread_local_initializer_can_be_made_const]
Adds a new lint to suggest using `const` on `thread_local!`
initializers that can be evaluated at compile time.

Impl details:

The lint relies on the expansion of `thread_local!`. For non
const-labelled initializers, `thread_local!` produces a function
called `__init` that lazily initializes the value. We check the function
and decide whether the body can be const. The body of the function is
exactly the initializer. If so, we lint the body.

changelog: new lint [`thread_local_initializer_can_be_made_const`]
2024-01-01 18:06:10 +02:00

31 lines
1013 B
Rust

#![warn(clippy::thread_local_initializer_can_be_made_const)]
use std::cell::RefCell;
fn main() {
// lint and suggest const
thread_local! {
static BUF_1: RefCell<String> = RefCell::new(String::new());
}
//~^^ ERROR: initializer for `thread_local` value can be made `const`
// don't lint
thread_local! {
static BUF_2: RefCell<String> = const { RefCell::new(String::new()) };
}
thread_local! {
static SIMPLE:i32 = 1;
}
//~^^ ERROR: initializer for `thread_local` value can be made `const`
// lint and suggest const for all non const items
thread_local! {
static BUF_3_CAN_BE_MADE_CONST: RefCell<String> = RefCell::new(String::new());
static CONST_MIXED_WITH:i32 = const { 1 };
static BUF_4_CAN_BE_MADE_CONST: RefCell<String> = RefCell::new(String::new());
}
//~^^^^ ERROR: initializer for `thread_local` value can be made `const`
//~^^^ ERROR: initializer for `thread_local` value can be made `const`
}