Skip to content

Commit dc9807d

Browse files
committed
add new lint [once_cell_lazy] to detect usage of static Lazy type from once_cell
1 parent 3e5a02b commit dc9807d

13 files changed

+631
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5675,6 +5675,7 @@ Released 2018-09-13
56755675
[`obfuscated_if_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#obfuscated_if_else
56765676
[`octal_escapes`]: https://rust-lang.github.io/rust-clippy/master/index.html#octal_escapes
56775677
[`ok_expect`]: https://rust-lang.github.io/rust-clippy/master/index.html#ok_expect
5678+
[`once_cell_lazy`]: https://rust-lang.github.io/rust-clippy/master/index.html#once_cell_lazy
56785679
[`only_used_in_recursion`]: https://rust-lang.github.io/rust-clippy/master/index.html#only_used_in_recursion
56795680
[`op_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
56805681
[`option_and_then_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_and_then_some

clippy_config/src/conf.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ define_Conf! {
265265
///
266266
/// Suppress lints whenever the suggested change would cause breakage for other crates.
267267
(avoid_breaking_exported_api: bool = true),
268-
/// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS, TUPLE_ARRAY_CONVERSIONS, MANUAL_TRY_FOLD, MANUAL_HASH_ONE, ITER_KV_MAP, MANUAL_C_STR_LITERALS, ASSIGNING_CLONES, LEGACY_NUMERIC_CONSTANTS.
268+
/// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS, TUPLE_ARRAY_CONVERSIONS, MANUAL_TRY_FOLD, MANUAL_HASH_ONE, ITER_KV_MAP, MANUAL_C_STR_LITERALS, ASSIGNING_CLONES, LEGACY_NUMERIC_CONSTANTS, ONCE_CELL_LAZY.
269269
///
270270
/// The minimum rust version that the project supports. Defaults to the `rust-version` field in `Cargo.toml`
271271
#[default_text = ""]

clippy_config/src/msrvs.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ macro_rules! msrv_aliases {
1717

1818
// names may refer to stabilized feature flags or library items
1919
msrv_aliases! {
20+
1,80,0 { LAZY_CELL }
2021
1,77,0 { C_STR_LITERALS }
2122
1,76,0 { PTR_FROM_REF }
2223
1,71,0 { TUPLE_ARRAY_CONVERSIONS, BUILD_HASHER_HASH_ONE }

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
553553
crate::non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY_INFO,
554554
crate::nonstandard_macro_braces::NONSTANDARD_MACRO_BRACES_INFO,
555555
crate::octal_escapes::OCTAL_ESCAPES_INFO,
556+
crate::once_cell_lazy::ONCE_CELL_LAZY_INFO,
556557
crate::only_used_in_recursion::ONLY_USED_IN_RECURSION_INFO,
557558
crate::operators::ABSURD_EXTREME_COMPARISONS_INFO,
558559
crate::operators::ARITHMETIC_SIDE_EFFECTS_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ mod non_octal_unix_permissions;
269269
mod non_send_fields_in_send_ty;
270270
mod nonstandard_macro_braces;
271271
mod octal_escapes;
272+
mod once_cell_lazy;
272273
mod only_used_in_recursion;
273274
mod operators;
274275
mod option_env_unwrap;
@@ -1169,6 +1170,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
11691170
})
11701171
});
11711172
store.register_late_pass(|_| Box::new(string_patterns::StringPatterns));
1173+
store.register_late_pass(move |_| Box::new(once_cell_lazy::OnceCellLazy::new(msrv())));
11721174
// add lints here, do not remove this comment, it's used in `new_lint`
11731175
}
11741176

clippy_lints/src/once_cell_lazy.rs

Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,277 @@
1+
use clippy_config::msrvs::Msrv;
2+
use clippy_utils::diagnostics::span_lint_and_then;
3+
use clippy_utils::visitors::for_each_expr;
4+
use clippy_utils::{def_path_def_ids, fn_def_id, match_def_path, path_def_id};
5+
use rustc_data_structures::fx::FxIndexMap;
6+
use rustc_errors::Applicability;
7+
use rustc_hir::def::{DefKind, Res};
8+
use rustc_hir::def_id::DefId;
9+
use rustc_hir::{self as hir, BodyId, Expr, ExprKind, Item, ItemKind};
10+
use rustc_lint::{LateContext, LateLintPass};
11+
use rustc_session::impl_lint_pass;
12+
use rustc_span::Span;
13+
14+
declare_clippy_lint! {
15+
/// ### What it does
16+
/// Lints when a `once_cell::sync::Lazy` type is declared as static variables.
17+
///
18+
/// ### Why restrict this?
19+
/// Such useage have been superseded by the `std::sync::LazyLock` type,
20+
/// replacing them would reduce dependency of `once_cell` crate.
21+
///
22+
/// ### Example
23+
/// ```rust
24+
/// use once_cell_lazy::once_cell_lazy;
25+
/// use once_cell::sync::Lazy;
26+
///
27+
/// once_cell_lazy! {
28+
/// static ref FOO: String = "foo".to_uppercase();
29+
/// }
30+
/// static BAR: Lazy<String> = Lazy::new(|| "BAR".to_lowercase());
31+
/// ```
32+
/// Use instead:
33+
/// ```rust
34+
/// static FOO: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| "foo".to_uppercase());
35+
/// static BAR: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| "BAR".to_lowercase());
36+
/// ```
37+
#[clippy::version = "1.81.0"]
38+
pub ONCE_CELL_LAZY,
39+
restriction,
40+
"using `once_cell::sync::Lazy` type that could be replaced by `std::sync::LazyLock`"
41+
}
42+
43+
/// A list containing functions with coresponding replacements in `LazyLock`.
44+
///
45+
/// Some functions could be replaced as well if we have replaced `Lazy` to `LazyLock`,
46+
/// therefore after suggesting replace the type, we need to make sure the function calls can be
47+
/// replaced, otherwise the suggestions cannot be applied thus the applicability should be
48+
/// `Unspecified` or `MaybeIncorret`.
49+
static FUNCTION_REPLACEMENTS: &[(&str, Option<&str>)] = &[
50+
("once_cell::sync::Lazy::force", Some("std::sync::LazyLock::force")),
51+
("once_cell::sync::Lazy::force_mut", None),
52+
("once_cell::sync::Lazy::get", None),
53+
("once_cell::sync::Lazy::get_mut", None),
54+
("once_cell::sync::Lazy::new", Some("std::sync::LazyLock::new")),
55+
// Note that `Lazy::into_value` is not in the list,
56+
// because we only check for `static`s in this lint, and `into_value` attempts to take ownership
57+
// of the parameter, which means it would fail natively.
58+
// But do keep in mind that the equivalant replacement is called `LazyLock::into_inner`
59+
// if somehow we decided to expand this lint to catch "non-static"s.
60+
];
61+
62+
pub struct OnceCellLazy {
63+
msrv: Msrv,
64+
sugg_map: FxIndexMap<DefId, Option<String>>,
65+
lazy_type_defs: FxIndexMap<DefId, LazyInfo>,
66+
}
67+
68+
impl OnceCellLazy {
69+
#[must_use]
70+
pub fn new(msrv: Msrv) -> Self {
71+
Self {
72+
msrv,
73+
sugg_map: FxIndexMap::default(),
74+
lazy_type_defs: FxIndexMap::default(),
75+
}
76+
}
77+
}
78+
79+
impl_lint_pass!(OnceCellLazy => [ONCE_CELL_LAZY]);
80+
81+
macro_rules! ensure_prerequisite {
82+
($msrv:expr, $cx:ident) => {
83+
if !$msrv.meets(clippy_config::msrvs::LAZY_CELL) || clippy_utils::is_no_std_crate($cx) {
84+
return;
85+
}
86+
};
87+
}
88+
89+
impl<'hir> LateLintPass<'hir> for OnceCellLazy {
90+
extract_msrv_attr!(LateContext);
91+
92+
fn check_crate(&mut self, cx: &LateContext<'hir>) {
93+
// Do not link if current crate does not support `LazyLock`.
94+
ensure_prerequisite!(self.msrv, cx);
95+
96+
// Convert hardcoded fn replacement list into a map with def_id
97+
for (path, sugg) in FUNCTION_REPLACEMENTS {
98+
let path_vec = path.split("::").collect::<Vec<_>>();
99+
for did in def_path_def_ids(cx, &path_vec) {
100+
self.sugg_map.insert(did, sugg.map(ToOwned::to_owned));
101+
}
102+
}
103+
}
104+
105+
fn check_item(&mut self, cx: &LateContext<'hir>, item: &Item<'hir>) {
106+
ensure_prerequisite!(self.msrv, cx);
107+
108+
if let Some(lazy_kind) = LazyInfo::from_item(cx, item) {
109+
self.lazy_type_defs.insert(item.owner_id.to_def_id(), lazy_kind);
110+
}
111+
}
112+
113+
fn check_expr(&mut self, cx: &LateContext<'hir>, expr: &Expr<'hir>) {
114+
ensure_prerequisite!(self.msrv, cx);
115+
116+
// All functions in the `FUNCTION_REPLACEMENTS` have only one args
117+
if let ExprKind::Call(callee, [arg]) = expr.kind
118+
&& let Some(call_def_id) = fn_def_id(cx, expr)
119+
&& self.sugg_map.contains_key(&call_def_id)
120+
&& let ExprKind::Path(qpath) = arg.peel_borrows().kind
121+
&& let Some(arg_def_id) = cx.typeck_results().qpath_res(&qpath, arg.hir_id).opt_def_id()
122+
&& let Some(lazy_info) = self.lazy_type_defs.get_mut(&arg_def_id)
123+
{
124+
lazy_info.calls_span_and_id.insert(callee.span, call_def_id);
125+
}
126+
}
127+
128+
fn check_crate_post(&mut self, cx: &LateContext<'hir>) {
129+
ensure_prerequisite!(self.msrv, cx);
130+
131+
for (_, lazy_info) in &self.lazy_type_defs {
132+
lazy_info.lint(cx, &self.sugg_map);
133+
}
134+
135+
self.sugg_map = FxIndexMap::default();
136+
}
137+
}
138+
139+
struct LazyInfo {
140+
/// Span of the [`hir::Ty`] where this `Lazy` type was declared,
141+
/// without including args.
142+
/// i.e.:
143+
/// ```ignore
144+
/// static FOO: Lazy<String> = Lazy::new(...);
145+
/// // ^^^^
146+
/// ```
147+
ty_span_no_args: Span,
148+
/// `Span` and `DefId` of calls on `Lazy` type.
149+
/// i.e.:
150+
/// ```ignore
151+
/// static FOO: Lazy<String> = {
152+
/// if cond {
153+
/// Lazy::new(...)
154+
/// // ^^^^^^^^^
155+
/// } else {
156+
/// Lazy::new(...)
157+
/// // ^^^^^^^^^
158+
/// }
159+
/// }
160+
/// ```
161+
///
162+
/// Or:
163+
///
164+
/// ```ignore
165+
/// let x = Lazy::get(&FOO);
166+
/// // ^^^^^^^^
167+
/// ```
168+
calls_span_and_id: FxIndexMap<Span, DefId>,
169+
}
170+
171+
impl LazyInfo {
172+
fn from_item(cx: &LateContext<'_>, item: &Item<'_>) -> Option<Self> {
173+
// Check if item is a `once_cell:sync::Lazy` static.
174+
if let ItemKind::Static(ty, _, body_id) = item.kind
175+
&& let Some(path_def_id) = path_def_id(cx, ty)
176+
&& let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind
177+
&& match_def_path(cx, path_def_id, &["once_cell", "sync", "Lazy"])
178+
{
179+
let ty_span_no_args = path_span_without_args(path);
180+
let body = cx.tcx.hir().body(body_id);
181+
182+
// visit body to collect `Lazy::new` calls
183+
let mut new_fn_calls = FxIndexMap::default();
184+
for_each_expr::<(), ()>(cx, body, |ex| {
185+
if let Some((fn_did, call_span)) = fn_def_id_and_span_from_body(cx, ex, body_id)
186+
&& match_def_path(cx, fn_did, &["once_cell", "sync", "Lazy", "new"])
187+
{
188+
new_fn_calls.insert(call_span, fn_did);
189+
}
190+
std::ops::ControlFlow::Continue(())
191+
});
192+
193+
Some(LazyInfo {
194+
ty_span_no_args,
195+
calls_span_and_id: new_fn_calls,
196+
})
197+
} else {
198+
None
199+
}
200+
}
201+
202+
fn lint(&self, cx: &LateContext<'_>, sugg_map: &FxIndexMap<DefId, Option<String>>) {
203+
// Applicability might get adjusted to `MachineApplicable` later if
204+
// all calls in `calls_span_and_id` is replaceable judging by the `sugg_map`.
205+
let mut appl = Applicability::Unspecified;
206+
let mut suggs = vec![(self.ty_span_no_args, "std::sync::LazyLock".to_string())];
207+
208+
if self
209+
.calls_span_and_id
210+
.iter()
211+
// Filtering the calls that DOES NOT have a suggested replacement.
212+
.filter(|(span, def_id)| {
213+
let maybe_sugg = sugg_map.get(*def_id).cloned().flatten();
214+
if let Some(sugg) = maybe_sugg {
215+
suggs.push((**span, sugg));
216+
false
217+
} else {
218+
true
219+
}
220+
})
221+
.collect::<Vec<_>>()
222+
.is_empty()
223+
{
224+
appl = Applicability::MachineApplicable;
225+
}
226+
227+
span_lint_and_then(
228+
cx,
229+
ONCE_CELL_LAZY,
230+
self.ty_span_no_args,
231+
"this type has been superceded by `LazyLock`",
232+
|diag| {
233+
diag.multipart_suggestion("consider using the `LazyLock` from standard library", suggs, appl);
234+
},
235+
);
236+
}
237+
}
238+
239+
/// Return the span of a given `Path` without including any of its args.
240+
///
241+
/// NB: Re-write of a private function `rustc_lint::non_local_def::path_span_without_args`.
242+
fn path_span_without_args(path: &hir::Path<'_>) -> Span {
243+
path.segments
244+
.last()
245+
.and_then(|seg| seg.args)
246+
.map_or(path.span, |args| path.span.until(args.span_ext))
247+
}
248+
249+
/// Returns the `DefId` and `Span` of the callee if the given expression is a function call.
250+
///
251+
/// NB: Modified from [`clippy_utils::fn_def_id`], to support calling in an static `Item`'s body.
252+
fn fn_def_id_and_span_from_body(cx: &LateContext<'_>, expr: &Expr<'_>, body_id: BodyId) -> Option<(DefId, Span)> {
253+
// FIXME: find a way to cache the result.
254+
let typeck = cx.tcx.typeck_body(body_id);
255+
match &expr.kind {
256+
ExprKind::Call(
257+
Expr {
258+
kind: ExprKind::Path(qpath),
259+
hir_id: path_hir_id,
260+
span,
261+
..
262+
},
263+
..,
264+
) => {
265+
// Only return Fn-like DefIds, not the DefIds of statics/consts/etc that contain or
266+
// deref to fn pointers, dyn Fn, impl Fn - #8850
267+
if let Res::Def(DefKind::Fn | DefKind::Ctor(..) | DefKind::AssocFn, id) =
268+
typeck.qpath_res(qpath, *path_hir_id)
269+
{
270+
Some((id, *span))
271+
} else {
272+
None
273+
}
274+
},
275+
_ => None,
276+
}
277+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//! **FAKE** once_cell crate.
2+
3+
pub mod sync {
4+
use core::cell::Cell;
5+
use std::marker::PhantomData;
6+
7+
pub struct OnceCell<T>(PhantomData<T>);
8+
impl<T> OnceCell<T> {
9+
pub const fn new() -> OnceCell<T> {
10+
OnceCell(PhantomData)
11+
}
12+
}
13+
impl<T> Default for OnceCell<T> {
14+
fn default() -> Self {
15+
Self::new()
16+
}
17+
}
18+
19+
pub struct Lazy<T, F = fn() -> T> {
20+
cell: OnceCell<T>,
21+
init: Cell<Option<F>>,
22+
}
23+
unsafe impl<T, F: Send> Sync for Lazy<T, F> where OnceCell<T>: Sync {}
24+
impl<T, F> Lazy<T, F> {
25+
pub const fn new(f: F) -> Lazy<T, F> {
26+
Lazy {
27+
cell: OnceCell::new(),
28+
init: Cell::new(Some(f)),
29+
}
30+
}
31+
32+
pub fn into_value(this: Lazy<T, F>) -> Result<T, i32> {
33+
Err(1)
34+
}
35+
36+
pub fn force(_this: &Lazy<T, F>) -> i32 {
37+
0
38+
}
39+
40+
pub fn force_mut(_this: &mut Lazy<T, F>) -> i32 {
41+
0
42+
}
43+
44+
pub fn get(_this: &Lazy<T, F>) -> i32 {
45+
0
46+
}
47+
48+
pub fn get_mut(_this: &mut Lazy<T, F>) -> i32 {
49+
0
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)