-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New Lint: [thread_local_initializer_can_be_made_const
]
#12026
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
clippy_lints/src/thread_local_initializer_can_be_made_const.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
use clippy_config::msrvs::Msrv; | ||
use clippy_utils::diagnostics::span_lint_and_sugg; | ||
use clippy_utils::fn_has_unsatisfiable_preds; | ||
use clippy_utils::qualify_min_const_fn::is_min_const_fn; | ||
use clippy_utils::source::snippet; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{intravisit, ExprKind}; | ||
use rustc_lint::{LateContext, LateLintPass, LintContext}; | ||
use rustc_middle::lint::in_external_macro; | ||
use rustc_session::impl_lint_pass; | ||
use rustc_span::sym::thread_local_macro; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// Suggests to use `const` in `thread_local!` macro if possible. | ||
/// ### Why is this bad? | ||
/// | ||
/// The `thread_local!` macro wraps static declarations and makes them thread-local. | ||
/// It supports using a `const` keyword that may be used for declarations that can | ||
/// be evaluated as a constant expression. This can enable a more efficient thread | ||
/// local implementation that can avoid lazy initialization. For types that do not | ||
/// need to be dropped, this can enable an even more efficient implementation that | ||
/// does not need to track any additional state. | ||
/// | ||
/// https://doc.rust-lang.org/std/macro.thread_local.html | ||
/// | ||
/// ### Example | ||
/// ```no_run | ||
/// // example code where clippy issues a warning | ||
/// thread_local! { | ||
/// static BUF: String = String::new(); | ||
/// } | ||
/// ``` | ||
/// Use instead: | ||
/// ```no_run | ||
/// // example code which does not raise clippy warning | ||
/// thread_local! { | ||
/// static BUF: String = const { String::new() }; | ||
/// } | ||
/// ``` | ||
#[clippy::version = "1.76.0"] | ||
pub THREAD_LOCAL_INITIALIZER_CAN_BE_MADE_CONST, | ||
perf, | ||
"suggest using `const` in `thread_local!` macro" | ||
} | ||
|
||
pub struct ThreadLocalInitializerCanBeMadeConst { | ||
msrv: Msrv, | ||
} | ||
|
||
impl ThreadLocalInitializerCanBeMadeConst { | ||
#[must_use] | ||
pub fn new(msrv: Msrv) -> Self { | ||
Self { msrv } | ||
} | ||
} | ||
|
||
impl_lint_pass!(ThreadLocalInitializerCanBeMadeConst => [THREAD_LOCAL_INITIALIZER_CAN_BE_MADE_CONST]); | ||
|
||
impl<'tcx> LateLintPass<'tcx> for ThreadLocalInitializerCanBeMadeConst { | ||
fn check_fn( | ||
&mut self, | ||
cx: &LateContext<'tcx>, | ||
fn_kind: rustc_hir::intravisit::FnKind<'tcx>, | ||
_: &'tcx rustc_hir::FnDecl<'tcx>, | ||
body: &'tcx rustc_hir::Body<'tcx>, | ||
span: rustc_span::Span, | ||
defid: rustc_span::def_id::LocalDefId, | ||
) { | ||
if in_external_macro(cx.sess(), span) | ||
&& let Some(callee) = span.source_callee() | ||
&& let Some(macro_def_id) = callee.macro_def_id | ||
&& cx.tcx.is_diagnostic_item(thread_local_macro, macro_def_id) | ||
&& let intravisit::FnKind::ItemFn(..) = fn_kind | ||
// Building MIR for `fn`s with unsatisfiable preds results in ICE. | ||
&& !fn_has_unsatisfiable_preds(cx, defid.to_def_id()) | ||
&& let mir = cx.tcx.optimized_mir(defid.to_def_id()) | ||
&& let Ok(()) = is_min_const_fn(cx.tcx, mir, &self.msrv) | ||
// this is the `__init` function emitted by the `thread_local!` macro | ||
// when the `const` keyword is not used. We avoid checking the `__init` directly | ||
// as that is not a public API. | ||
// we know that the function is const-qualifiable, so now we need only to get the | ||
// initializer expression to span-lint it. | ||
&& let ExprKind::Block(block, _) = body.value.kind | ||
&& let Some(ret_expr) = block.expr | ||
&& let initializer_snippet = snippet(cx, ret_expr.span, "thread_local! { ... }") | ||
&& initializer_snippet != "thread_local! { ... }" | ||
{ | ||
span_lint_and_sugg( | ||
cx, | ||
THREAD_LOCAL_INITIALIZER_CAN_BE_MADE_CONST, | ||
ret_expr.span, | ||
"initializer for `thread_local` value can be made `const`", | ||
"replace with", | ||
format!("const {{ {initializer_snippet} }}"), | ||
Applicability::MachineApplicable, | ||
); | ||
} | ||
} | ||
|
||
extract_msrv_attr!(LateContext); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
#![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> = const { 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 = const { 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> = const { RefCell::new(String::new()) }; | ||
static CONST_MIXED_WITH:i32 = const { 1 }; | ||
static BUF_4_CAN_BE_MADE_CONST: RefCell<String> = const { RefCell::new(String::new()) }; | ||
} | ||
//~^^^^ ERROR: initializer for `thread_local` value can be made `const` | ||
//~^^^ ERROR: initializer for `thread_local` value can be made `const` | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
#![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` | ||
} |
29 changes: 29 additions & 0 deletions
29
tests/ui/thread_local_initializer_can_be_made_const.stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
error: initializer for `thread_local` value can be made `const` | ||
--> $DIR/thread_local_initializer_can_be_made_const.rs:8:41 | ||
| | ||
LL | static BUF_1: RefCell<String> = RefCell::new(String::new()); | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `const { RefCell::new(String::new()) }` | ||
| | ||
= note: `-D clippy::thread-local-initializer-can-be-made-const` implied by `-D warnings` | ||
= help: to override `-D warnings` add `#[allow(clippy::thread_local_initializer_can_be_made_const)]` | ||
|
||
error: initializer for `thread_local` value can be made `const` | ||
--> $DIR/thread_local_initializer_can_be_made_const.rs:18:29 | ||
| | ||
LL | static SIMPLE:i32 = 1; | ||
| ^ help: replace with: `const { 1 }` | ||
|
||
error: initializer for `thread_local` value can be made `const` | ||
--> $DIR/thread_local_initializer_can_be_made_const.rs:24:59 | ||
| | ||
LL | static BUF_3_CAN_BE_MADE_CONST: RefCell<String> = RefCell::new(String::new()); | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `const { RefCell::new(String::new()) }` | ||
|
||
error: initializer for `thread_local` value can be made `const` | ||
--> $DIR/thread_local_initializer_can_be_made_const.rs:26:59 | ||
| | ||
LL | static BUF_4_CAN_BE_MADE_CONST: RefCell<String> = RefCell::new(String::new()); | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: `const { RefCell::new(String::new()) }` | ||
|
||
error: aborting due to 4 previous errors | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@joboet I have reduced the dependency on internal details to "just" knowing that the last expression in the initializer is the original snippet and that an initializer function exists. Name doesn't matter anymore.
I have also reviewed the storage pr you listed, and it looks fine from the perspective of this, but having a comment there indicating that the initializer is checked would most likely avoid breaking it buuut I really don't want to tie this to particular impl.