Skip to content

Commit 15dc75f

Browse files
cast_ref_to_mut lint
1 parent 6cba3da commit 15dc75f

File tree

6 files changed

+118
-1
lines changed

6 files changed

+118
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,7 @@ All notable changes to this project will be documented in this file.
634634
[`cast_possible_wrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_wrap
635635
[`cast_precision_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_precision_loss
636636
[`cast_ptr_alignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_ptr_alignment
637+
[`cast_ref_to_mut`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_ref_to_mut
637638
[`cast_sign_loss`]: https://rust-lang.github.io/rust-clippy/master/index.html#cast_sign_loss
638639
[`char_lit_as_u8`]: https://rust-lang.github.io/rust-clippy/master/index.html#char_lit_as_u8
639640
[`chars_last_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#chars_last_cmp

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
99

10-
[There are 290 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
10+
[There are 291 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1111

1212
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1313

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
484484
reg.register_late_lint_pass(box ptr_offset_with_cast::Pass);
485485
reg.register_late_lint_pass(box redundant_clone::RedundantClone);
486486
reg.register_late_lint_pass(box slow_vector_initialization::Pass);
487+
reg.register_late_lint_pass(box types::RefToMut);
487488

488489
reg.register_lint_group("clippy::restriction", Some("clippy_restriction"), vec![
489490
arithmetic::FLOAT_ARITHMETIC,
@@ -1024,6 +1025,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
10241025
mutex_atomic::MUTEX_INTEGER,
10251026
needless_borrow::NEEDLESS_BORROW,
10261027
redundant_clone::REDUNDANT_CLONE,
1028+
types::CAST_REF_TO_MUT,
10271029
unwrap::PANICKING_UNWRAP,
10281030
unwrap::UNNECESSARY_UNWRAP,
10291031
]);

clippy_lints/src/types.rs

+61
Original file line numberDiff line numberDiff line change
@@ -2240,3 +2240,64 @@ impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'
22402240
NestedVisitorMap::OnlyBodies(&self.cx.tcx.hir())
22412241
}
22422242
}
2243+
2244+
/// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2245+
///
2246+
/// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2247+
/// `UnsafeCell` is the only way to obtain aliasable data that is considered
2248+
/// mutable.
2249+
///
2250+
/// **Known problems:** None.
2251+
///
2252+
/// **Example:**
2253+
/// ```rust
2254+
/// fn x(r: &i32) {
2255+
/// unsafe {
2256+
/// *(r as *const _ as *mut _) += 1;
2257+
/// }
2258+
/// }
2259+
/// ```
2260+
///
2261+
/// Instead consider using interior mutability types.
2262+
///
2263+
/// ```rust
2264+
/// fn x(r: &UnsafeCell<i32>) {
2265+
/// unsafe {
2266+
/// *r.get() += 1;
2267+
/// }
2268+
/// }
2269+
/// ```
2270+
declare_clippy_lint! {
2271+
pub CAST_REF_TO_MUT,
2272+
nursery,
2273+
"a cast of reference to a mutable pointer"
2274+
}
2275+
2276+
pub struct RefToMut;
2277+
2278+
impl LintPass for RefToMut {
2279+
fn get_lints(&self) -> LintArray {
2280+
lint_array!(CAST_REF_TO_MUT)
2281+
}
2282+
}
2283+
2284+
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2285+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
2286+
if_chain! {
2287+
if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.node;
2288+
if let ExprKind::Cast(e, t) = &e.node;
2289+
if let TyKind::Ptr(MutTy { mutbl: Mutability::MutMutable, .. }) = t.node;
2290+
if let ExprKind::Cast(e, t) = &e.node;
2291+
if let TyKind::Ptr(MutTy { mutbl: Mutability::MutImmutable, .. }) = t.node;
2292+
if let ty::TyKind::Ref(..) = cx.tables.node_id_to_type(e.hir_id).sty;
2293+
then {
2294+
span_lint(
2295+
cx,
2296+
CAST_REF_TO_MUT,
2297+
expr.span,
2298+
&"casting immutable reference to a mutable reference"
2299+
);
2300+
}
2301+
}
2302+
}
2303+
}

tests/ui/cast_ref_to_mut.rs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#![warn(clippy::cast_ref_to_mut)]
2+
#![allow(clippy::no_effect)]
3+
4+
extern "C" {
5+
// NB. Mutability can be easily incorrect in FFI calls, as
6+
// in C, the default are mutable pointers.
7+
fn ffi(c: *mut u8);
8+
fn int_ffi(c: *mut i32);
9+
}
10+
11+
fn main() {
12+
let s = String::from("Hello");
13+
let a = &s;
14+
unsafe {
15+
let num = &3i32;
16+
let mut_num = &mut 3i32;
17+
// Should be warned against
18+
(*(a as *const _ as *mut String)).push_str(" world");
19+
*(a as *const _ as *mut _) = String::from("Replaced");
20+
*(a as *const _ as *mut String) += " world";
21+
// Shouldn't be warned against
22+
println!("{}", *(num as *const _ as *const i16));
23+
println!("{}", *(mut_num as *mut _ as *mut i16));
24+
ffi(a.as_ptr() as *mut _);
25+
int_ffi(num as *const _ as *mut _);
26+
int_ffi(&3 as *const _ as *mut _);
27+
let mut value = 3;
28+
let value: *const i32 = &mut value;
29+
*(value as *const i16 as *mut i16) = 42;
30+
}
31+
}

tests/ui/cast_ref_to_mut.stderr

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: casting immutable reference to a mutable reference
2+
--> $DIR/cast_ref_to_mut.rs:18:9
3+
|
4+
LL | (*(a as *const _ as *mut String)).push_str(" world");
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::cast-ref-to-mut` implied by `-D warnings`
8+
9+
error: casting immutable reference to a mutable reference
10+
--> $DIR/cast_ref_to_mut.rs:19:9
11+
|
12+
LL | *(a as *const _ as *mut _) = String::from("Replaced");
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: casting immutable reference to a mutable reference
16+
--> $DIR/cast_ref_to_mut.rs:20:9
17+
|
18+
LL | *(a as *const _ as *mut String) += " world";
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
21+
error: aborting due to 3 previous errors
22+

0 commit comments

Comments
 (0)