Skip to content

Commit 6b8e3f4

Browse files
committed
Add suspicious_mutation_of_interior_mutable_consts lint
1 parent 20f59e0 commit 6b8e3f4

12 files changed

+2503
-0
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -774,6 +774,13 @@ lint_suspicious_double_ref_clone =
774774
lint_suspicious_double_ref_deref =
775775
using `.deref()` on a double reference, which returns `{$ty}` instead of dereferencing the inner type
776776
777+
lint_suspicious_mutation_of_interior_mutable_consts =
778+
suspicious call to `{$method_name}` which mutates an interior mutable `const`
779+
.label = `{$const_name}` is a interior mutable `const` of type `{$const_ty}`
780+
.temporary = each usage of a `const` creates a new temporary
781+
.never_original = only the temporaries and never the original `const {$const_name}` will be modified
782+
.suggestion_static = for a shared instance of `{$const_name}`, consider making it a `static` item instead
783+
777784
lint_symbol_intern_string_literal = using `Symbol::intern` on a string literal
778785
.help = consider adding the symbol to `compiler/rustc_span/src/symbol.rs`
779786
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
use rustc_hir::attrs::AttributeKind;
2+
use rustc_hir::def::{DefKind, Res};
3+
use rustc_hir::{Expr, ExprKind, ItemKind, Node, find_attr};
4+
use rustc_session::{declare_lint, declare_lint_pass};
5+
6+
use crate::lints::{
7+
SuspiciousMutationOfInteriorMutableConstsDiag,
8+
SuspiciousMutationOfInteriorMutableConstsSuggestionStatic,
9+
};
10+
use crate::{LateContext, LateLintPass, LintContext};
11+
12+
declare_lint! {
13+
/// The `suspicious_mutation_of_interior_mutable_consts` lint checks for calls which
14+
/// mutates an interior mutable const-item.
15+
///
16+
/// ### Example
17+
///
18+
/// ```rust
19+
/// use std::sync::Once;
20+
///
21+
/// const INIT: Once = Once::new(); // using `INIT` will always create a temporary and
22+
/// // never modify it-self on use, should be a `static`
23+
/// // instead for shared use
24+
///
25+
/// fn init() {
26+
/// INIT.call_once(|| {
27+
/// println!("Once::call_once first call");
28+
/// });
29+
/// INIT.call_once(|| { // this second will also print
30+
/// println!("Once::call_once second call"); // as each call to `INIT` creates
31+
/// }); // new temporary
32+
/// }
33+
/// ```
34+
///
35+
/// {{produces}}
36+
///
37+
/// ### Explanation
38+
///
39+
/// Calling a method which mutates an interior mutable type has no effect as const-item
40+
/// are essentially inlined wherever they are used, meaning that they are copied
41+
/// directly into the relevant context when used rendering modification through
42+
/// interior mutability ineffective across usage of that const-item.
43+
///
44+
/// The current implementation of this lint only warns on significant `std` and
45+
/// `core` interior mutable types, like `Once`, `AtomicI32`, ... this is done out
46+
/// of prudence to avoid false-positive and may be extended in the future.
47+
pub SUSPICIOUS_MUTATION_OF_INTERIOR_MUTABLE_CONSTS,
48+
Warn,
49+
"checks for calls which mutates a interior mutable const-item"
50+
}
51+
52+
declare_lint_pass!(InteriorMutableConsts => [SUSPICIOUS_MUTATION_OF_INTERIOR_MUTABLE_CONSTS]);
53+
54+
impl<'tcx> LateLintPass<'tcx> for InteriorMutableConsts {
55+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
56+
let typeck = cx.typeck_results();
57+
58+
let (method_did, receiver) = match expr.kind {
59+
// matching on `<receiver>.method(..)`
60+
ExprKind::MethodCall(_, receiver, _, _) => {
61+
(typeck.type_dependent_def_id(expr.hir_id), receiver)
62+
}
63+
// matching on `function(&<receiver>, ...)`
64+
ExprKind::Call(path, [receiver, ..]) => match receiver.kind {
65+
ExprKind::AddrOf(_, _, receiver) => match path.kind {
66+
ExprKind::Path(ref qpath) => {
67+
(cx.qpath_res(qpath, path.hir_id).opt_def_id(), receiver)
68+
}
69+
_ => return,
70+
},
71+
_ => return,
72+
},
73+
_ => return,
74+
};
75+
76+
let Some(method_did) = method_did else {
77+
return;
78+
};
79+
80+
if let ExprKind::Path(qpath) = &receiver.kind
81+
&& let Res::Def(DefKind::Const | DefKind::AssocConst, const_did) =
82+
typeck.qpath_res(qpath, receiver.hir_id)
83+
// Let's do the attribute check after the other checks for perf reasons
84+
&& find_attr!(
85+
cx.tcx.get_all_attrs(method_did),
86+
AttributeKind::RustcMustNotCallOnInteriorMutableConsts(_)
87+
)
88+
&& let Some(method_name) = cx.tcx.opt_item_ident(method_did)
89+
&& let Some(const_name) = cx.tcx.opt_item_ident(const_did)
90+
&& let Some(const_ty) = typeck.node_type_opt(receiver.hir_id)
91+
{
92+
// Find the local `const`-item and create the suggestion to use `static` instead
93+
let sugg_static = if let Some(Node::Item(const_item)) =
94+
cx.tcx.hir_get_if_local(const_did)
95+
&& let ItemKind::Const(ident, _generics, _ty, _body_id) = const_item.kind
96+
{
97+
if let Some(vis_span) = const_item.vis_span.find_ancestor_inside(const_item.span)
98+
&& const_item.span.can_be_used_for_suggestions()
99+
&& vis_span.can_be_used_for_suggestions()
100+
{
101+
Some(SuspiciousMutationOfInteriorMutableConstsSuggestionStatic::Spanful {
102+
const_: const_item.vis_span.between(ident.span),
103+
before: if !vis_span.is_empty() { " " } else { "" },
104+
})
105+
} else {
106+
Some(SuspiciousMutationOfInteriorMutableConstsSuggestionStatic::Spanless)
107+
}
108+
} else {
109+
None
110+
};
111+
112+
cx.emit_span_lint(
113+
SUSPICIOUS_MUTATION_OF_INTERIOR_MUTABLE_CONSTS,
114+
expr.span,
115+
SuspiciousMutationOfInteriorMutableConstsDiag {
116+
method_name,
117+
const_name,
118+
const_ty,
119+
receiver_span: receiver.span,
120+
sugg_static,
121+
},
122+
);
123+
}
124+
}
125+
}

compiler/rustc_lint/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ mod for_loops_over_fallibles;
5050
mod foreign_modules;
5151
mod if_let_rescope;
5252
mod impl_trait_overcaptures;
53+
mod interior_mutable_consts;
5354
mod internal;
5455
mod invalid_from_utf8;
5556
mod late;
@@ -94,6 +95,7 @@ use enum_intrinsics_non_enums::EnumIntrinsicsNonEnums;
9495
use for_loops_over_fallibles::*;
9596
use if_let_rescope::IfLetRescope;
9697
use impl_trait_overcaptures::ImplTraitOvercaptures;
98+
use interior_mutable_consts::*;
9799
use internal::*;
98100
use invalid_from_utf8::*;
99101
use let_underscore::*;
@@ -240,6 +242,7 @@ late_lint_methods!(
240242
AsyncClosureUsage: AsyncClosureUsage,
241243
AsyncFnInTrait: AsyncFnInTrait,
242244
NonLocalDefinitions: NonLocalDefinitions::default(),
245+
InteriorMutableConsts: InteriorMutableConsts,
243246
ImplTraitOvercaptures: ImplTraitOvercaptures,
244247
IfLetRescope: IfLetRescope::default(),
245248
StaticMutRefs: StaticMutRefs,

compiler/rustc_lint/src/lints.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -784,6 +784,38 @@ pub(crate) enum InvalidFromUtf8Diag {
784784
},
785785
}
786786

787+
// interior_mutable_consts.rs
788+
#[derive(LintDiagnostic)]
789+
#[diag(lint_suspicious_mutation_of_interior_mutable_consts)]
790+
#[note(lint_temporary)]
791+
#[note(lint_never_original)]
792+
pub(crate) struct SuspiciousMutationOfInteriorMutableConstsDiag<'tcx> {
793+
pub method_name: Ident,
794+
pub const_name: Ident,
795+
pub const_ty: Ty<'tcx>,
796+
#[label]
797+
pub receiver_span: Span,
798+
#[subdiagnostic]
799+
pub sugg_static: Option<SuspiciousMutationOfInteriorMutableConstsSuggestionStatic>,
800+
}
801+
802+
#[derive(Subdiagnostic)]
803+
pub(crate) enum SuspiciousMutationOfInteriorMutableConstsSuggestionStatic {
804+
#[suggestion(
805+
lint_suggestion_static,
806+
code = "{before}static ",
807+
style = "verbose",
808+
applicability = "maybe-incorrect"
809+
)]
810+
Spanful {
811+
#[primary_span]
812+
const_: Span,
813+
before: &'static str,
814+
},
815+
#[help(lint_suggestion_static)]
816+
Spanless,
817+
}
818+
787819
// reference_casting.rs
788820
#[derive(LintDiagnostic)]
789821
pub(crate) enum InvalidReferenceCastingDiag<'tcx> {
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
//@ check-pass
2+
//@ run-rustfix
3+
4+
#![allow(deprecated)]
5+
#![allow(dead_code)]
6+
#![feature(atomic_try_update)]
7+
8+
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, Ordering};
9+
10+
fn atomic_bool() {
11+
static A: AtomicBool = AtomicBool::new(false);
12+
13+
let _a = A.load(Ordering::SeqCst);
14+
//~^ WARN suspicious call to `load`
15+
16+
let _a = A.store(true, Ordering::SeqCst);
17+
//~^ WARN suspicious call to `store`
18+
19+
let _a = A.swap(true, Ordering::SeqCst);
20+
//~^ WARN suspicious call to `swap`
21+
22+
let _a = A.compare_and_swap(false, true, Ordering::SeqCst);
23+
//~^ WARN suspicious call to `compare_and_swap`
24+
25+
let _a = A.compare_exchange(false, true, Ordering::SeqCst, Ordering::Relaxed);
26+
//~^ WARN suspicious call to `compare_exchange`
27+
28+
let _a = A.compare_exchange_weak(false, true, Ordering::SeqCst, Ordering::Relaxed);
29+
//~^ WARN suspicious call to `compare_exchange_weak`
30+
31+
let _a = A.fetch_and(true, Ordering::SeqCst);
32+
//~^ WARN suspicious call to `fetch_and`
33+
34+
let _a = A.fetch_nand(true, Ordering::SeqCst);
35+
//~^ WARN suspicious call to `fetch_nand`
36+
37+
let _a = A.fetch_or(true, Ordering::SeqCst);
38+
//~^ WARN suspicious call to `fetch_or`
39+
40+
let _a = A.fetch_xor(true, Ordering::SeqCst);
41+
//~^ WARN suspicious call to `fetch_xor`
42+
43+
let _a = A.fetch_not(Ordering::SeqCst);
44+
//~^ WARN suspicious call to `fetch_not`
45+
46+
let _a = A.fetch_update(Ordering::SeqCst, Ordering::Relaxed, |_| Some(true));
47+
//~^ WARN suspicious call to `fetch_update`
48+
49+
let _a = A.try_update(Ordering::SeqCst, Ordering::Relaxed, |_| Some(false));
50+
//~^ WARN suspicious call to `try_update`
51+
52+
let _a = A.update(Ordering::SeqCst, Ordering::Relaxed, |_| true);
53+
//~^ WARN suspicious call to `update`
54+
}
55+
56+
fn atomic_ptr() {
57+
static A: AtomicPtr<i32> = AtomicPtr::new(std::ptr::null_mut());
58+
59+
let _a = A.load(Ordering::SeqCst);
60+
//~^ WARN suspicious call to `load`
61+
62+
let _a = A.store(std::ptr::null_mut(), Ordering::SeqCst);
63+
//~^ WARN suspicious call to `store`
64+
65+
let _a = A.swap(std::ptr::null_mut(), Ordering::SeqCst);
66+
//~^ WARN suspicious call to `swap`
67+
68+
let _a = A.compare_and_swap(std::ptr::null_mut(), std::ptr::null_mut(), Ordering::SeqCst);
69+
//~^ WARN suspicious call to `compare_and_swap`
70+
71+
let _a = A.compare_exchange(
72+
//~^ WARN suspicious call to `compare_exchange`
73+
std::ptr::null_mut(),
74+
std::ptr::null_mut(),
75+
Ordering::SeqCst,
76+
Ordering::Relaxed,
77+
);
78+
79+
let _a = A.compare_exchange_weak(
80+
//~^ WARN suspicious call to `compare_exchange_weak`
81+
std::ptr::null_mut(),
82+
std::ptr::null_mut(),
83+
Ordering::SeqCst,
84+
Ordering::Relaxed,
85+
);
86+
87+
let _a = A.fetch_update(Ordering::SeqCst, Ordering::Relaxed, |_| Some(std::ptr::null_mut()));
88+
//~^ WARN suspicious call to `fetch_update`
89+
90+
let _a = A.try_update(Ordering::SeqCst, Ordering::Relaxed, |_| Some(std::ptr::null_mut()));
91+
//~^ WARN suspicious call to `try_update`
92+
93+
let _a = A.update(Ordering::SeqCst, Ordering::Relaxed, |_| std::ptr::null_mut());
94+
//~^ WARN suspicious call to `update`
95+
96+
let _a = A.fetch_ptr_add(1, Ordering::SeqCst);
97+
//~^ WARN suspicious call to `fetch_ptr_add`
98+
99+
let _a = A.fetch_ptr_sub(1, Ordering::SeqCst);
100+
//~^ WARN suspicious call to `fetch_ptr_sub`
101+
102+
let _a = A.fetch_byte_add(1, Ordering::SeqCst);
103+
//~^ WARN suspicious call to `fetch_byte_add`
104+
105+
let _a = A.fetch_byte_sub(1, Ordering::SeqCst);
106+
//~^ WARN suspicious call to `fetch_byte_sub`
107+
108+
let _a = A.fetch_and(1, Ordering::SeqCst);
109+
//~^ WARN suspicious call to `fetch_and`
110+
111+
let _a = A.fetch_or(1, Ordering::SeqCst);
112+
//~^ WARN suspicious call to `fetch_or`
113+
114+
let _a = A.fetch_xor(1, Ordering::SeqCst);
115+
//~^ WARN suspicious call to `fetch_xor`
116+
}
117+
118+
fn atomic_u32() {
119+
static A: AtomicU32 = AtomicU32::new(0);
120+
121+
let _a = A.load(Ordering::SeqCst);
122+
//~^ WARN suspicious call to `load`
123+
124+
let _a = A.store(1, Ordering::SeqCst);
125+
//~^ WARN suspicious call to `store`
126+
127+
let _a = A.swap(2, Ordering::SeqCst);
128+
//~^ WARN suspicious call to `swap`
129+
130+
let _a = A.compare_and_swap(2, 3, Ordering::SeqCst);
131+
//~^ WARN suspicious call to `compare_and_swap`
132+
133+
let _a = A.compare_exchange(3, 4, Ordering::SeqCst, Ordering::Relaxed);
134+
//~^ WARN suspicious call to `compare_exchange`
135+
136+
let _a = A.compare_exchange_weak(4, 5, Ordering::SeqCst, Ordering::Relaxed);
137+
//~^ WARN suspicious call to `compare_exchange_weak`
138+
139+
let _a = A.fetch_add(1, Ordering::SeqCst);
140+
//~^ WARN suspicious call to `fetch_add`
141+
142+
let _a = A.fetch_sub(1, Ordering::SeqCst);
143+
//~^ WARN suspicious call to `fetch_sub`
144+
145+
let _a = A.fetch_add(2, Ordering::SeqCst);
146+
//~^ WARN suspicious call to `fetch_add`
147+
148+
let _a = A.fetch_nand(1, Ordering::SeqCst);
149+
//~^ WARN suspicious call to `fetch_nand`
150+
151+
let _a = A.fetch_or(1, Ordering::SeqCst);
152+
//~^ WARN suspicious call to `fetch_or`
153+
154+
let _a = A.fetch_xor(1, Ordering::SeqCst);
155+
//~^ WARN suspicious call to `fetch_xor`
156+
157+
let _a = A.fetch_update(Ordering::SeqCst, Ordering::Relaxed, |_| Some(10));
158+
//~^ WARN suspicious call to `fetch_update`
159+
160+
let _a = A.try_update(Ordering::SeqCst, Ordering::Relaxed, |_| Some(11));
161+
//~^ WARN suspicious call to `try_update`
162+
163+
let _a = A.update(Ordering::SeqCst, Ordering::Relaxed, |_| 12);
164+
//~^ WARN suspicious call to `update`
165+
166+
let _a = A.fetch_max(20, Ordering::SeqCst);
167+
//~^ WARN suspicious call to `fetch_max`
168+
169+
let _a = A.fetch_min(5, Ordering::SeqCst);
170+
//~^ WARN suspicious call to `fetch_min`
171+
}
172+
173+
fn main() {}

0 commit comments

Comments
 (0)