Skip to content

Commit f0bf200

Browse files
committed
Auto merge of rust-lang#8916 - Jarcho:swap_ptr_to_ref, r=Manishearth
New lint `swap_ptr_to_ref` fixes: rust-lang#7381 changelog: New lint `swap_ptr_to_ref`
2 parents 5b1a4c0 + ca78e24 commit f0bf200

12 files changed

+203
-0
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3753,6 +3753,7 @@ Released 2018-09-13
37533753
[`suspicious_operation_groupings`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_operation_groupings
37543754
[`suspicious_splitn`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_splitn
37553755
[`suspicious_unary_op_formatting`]: https://rust-lang.github.io/rust-clippy/master/index.html#suspicious_unary_op_formatting
3756+
[`swap_ptr_to_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#swap_ptr_to_ref
37563757
[`tabs_in_doc_comments`]: https://rust-lang.github.io/rust-clippy/master/index.html#tabs_in_doc_comments
37573758
[`temporary_assignment`]: https://rust-lang.github.io/rust-clippy/master/index.html#temporary_assignment
37583759
[`temporary_cstring_as_ptr`]: https://rust-lang.github.io/rust-clippy/master/index.html#temporary_cstring_as_ptr

clippy_lints/src/lib.register_all.rs

+1
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
292292
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
293293
LintId::of(swap::ALMOST_SWAPPED),
294294
LintId::of(swap::MANUAL_SWAP),
295+
LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF),
295296
LintId::of(tabs_in_doc_comments::TABS_IN_DOC_COMMENTS),
296297
LintId::of(temporary_assignment::TEMPORARY_ASSIGNMENT),
297298
LintId::of(to_digit_is_some::TO_DIGIT_IS_SOME),

clippy_lints/src/lib.register_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,7 @@ store.register_lints(&[
497497
suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL,
498498
swap::ALMOST_SWAPPED,
499499
swap::MANUAL_SWAP,
500+
swap_ptr_to_ref::SWAP_PTR_TO_REF,
500501
tabs_in_doc_comments::TABS_IN_DOC_COMMENTS,
501502
temporary_assignment::TEMPORARY_ASSIGNMENT,
502503
to_digit_is_some::TO_DIGIT_IS_SOME,

clippy_lints/src/lib.register_suspicious.rs

+1
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,5 @@ store.register_group(true, "clippy::suspicious", Some("clippy_suspicious"), vec!
3232
LintId::of(significant_drop_in_scrutinee::SIGNIFICANT_DROP_IN_SCRUTINEE),
3333
LintId::of(suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL),
3434
LintId::of(suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL),
35+
LintId::of(swap_ptr_to_ref::SWAP_PTR_TO_REF),
3536
])

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,7 @@ mod strlen_on_c_strings;
380380
mod suspicious_operation_groupings;
381381
mod suspicious_trait_impl;
382382
mod swap;
383+
mod swap_ptr_to_ref;
383384
mod tabs_in_doc_comments;
384385
mod temporary_assignment;
385386
mod to_digit_is_some;
@@ -913,6 +914,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
913914
store.register_late_pass(|| Box::new(get_first::GetFirst));
914915
store.register_early_pass(|| Box::new(unused_rounding::UnusedRounding));
915916
store.register_early_pass(move || Box::new(almost_complete_letter_range::AlmostCompleteLetterRange::new(msrv)));
917+
store.register_late_pass(|| Box::new(swap_ptr_to_ref::SwapPtrToRef));
916918
// add lints here, do not remove this comment, it's used in `new_lint`
917919
}
918920

clippy_lints/src/swap_ptr_to_ref.rs

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::source::snippet_with_context;
3+
use clippy_utils::{match_def_path, path_def_id, paths};
4+
use rustc_errors::Applicability;
5+
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, UnOp};
6+
use rustc_lint::{LateContext, LateLintPass};
7+
use rustc_session::{declare_lint_pass, declare_tool_lint};
8+
use rustc_span::{Span, SyntaxContext};
9+
10+
declare_clippy_lint! {
11+
/// ### What it does
12+
/// Checks for calls to `core::mem::swap` where either parameter is derived from a pointer
13+
///
14+
/// ### Why is this bad?
15+
/// When at least one parameter to `swap` is derived from a pointer it may overlap with the
16+
/// other. This would then lead to undefined behavior.
17+
///
18+
/// ### Example
19+
/// ```rust
20+
/// unsafe fn swap(x: &[*mut u32], y: &[*mut u32]) {
21+
/// for (&x, &y) in x.iter().zip(y) {
22+
/// core::mem::swap(&mut *x, &mut *y);
23+
/// }
24+
/// }
25+
/// ```
26+
/// Use instead:
27+
/// ```rust
28+
/// unsafe fn swap(x: &[*mut u32], y: &[*mut u32]) {
29+
/// for (&x, &y) in x.iter().zip(y) {
30+
/// core::ptr::swap(x, y);
31+
/// }
32+
/// }
33+
/// ```
34+
#[clippy::version = "1.63.0"]
35+
pub SWAP_PTR_TO_REF,
36+
suspicious,
37+
"call to `mem::swap` using pointer derived references"
38+
}
39+
declare_lint_pass!(SwapPtrToRef => [SWAP_PTR_TO_REF]);
40+
41+
impl LateLintPass<'_> for SwapPtrToRef {
42+
fn check_expr(&mut self, cx: &LateContext<'_>, e: &Expr<'_>) {
43+
if let ExprKind::Call(fn_expr, [arg1, arg2]) = e.kind
44+
&& let Some(fn_id) = path_def_id(cx, fn_expr)
45+
&& match_def_path(cx, fn_id, &paths::MEM_SWAP)
46+
&& let ctxt = e.span.ctxt()
47+
&& let (from_ptr1, arg1_span) = is_ptr_to_ref(cx, arg1, ctxt)
48+
&& let (from_ptr2, arg2_span) = is_ptr_to_ref(cx, arg2, ctxt)
49+
&& (from_ptr1 || from_ptr2)
50+
{
51+
span_lint_and_then(
52+
cx,
53+
SWAP_PTR_TO_REF,
54+
e.span,
55+
"call to `core::mem::swap` with a parameter derived from a raw pointer",
56+
|diag| {
57+
if !((from_ptr1 && arg1_span.is_none()) || (from_ptr2 && arg2_span.is_none())) {
58+
let mut app = Applicability::MachineApplicable;
59+
let snip1 = snippet_with_context(cx, arg1_span.unwrap_or(arg1.span), ctxt, "..", &mut app).0;
60+
let snip2 = snippet_with_context(cx, arg2_span.unwrap_or(arg2.span), ctxt, "..", &mut app).0;
61+
diag.span_suggestion(e.span, "use ptr::swap", format!("core::ptr::swap({}, {})", snip1, snip2), app);
62+
}
63+
}
64+
);
65+
}
66+
}
67+
}
68+
69+
/// Checks if the expression converts a mutable pointer to a mutable reference. If it is, also
70+
/// returns the span of the pointer expression if it's suitable for making a suggestion.
71+
fn is_ptr_to_ref(cx: &LateContext<'_>, e: &Expr<'_>, ctxt: SyntaxContext) -> (bool, Option<Span>) {
72+
if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, borrowed_expr) = e.kind
73+
&& let ExprKind::Unary(UnOp::Deref, derefed_expr) = borrowed_expr.kind
74+
&& cx.typeck_results().expr_ty(derefed_expr).is_unsafe_ptr()
75+
{
76+
(true, (borrowed_expr.span.ctxt() == ctxt || derefed_expr.span.ctxt() == ctxt).then(|| derefed_expr.span))
77+
} else {
78+
(false, None)
79+
}
80+
}

clippy_utils/src/paths.rs

+1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"];
7373
pub const LATE_LINT_PASS: [&str; 3] = ["rustc_lint", "passes", "LateLintPass"];
7474
#[cfg(feature = "internal")]
7575
pub const LINT: [&str; 2] = ["rustc_lint_defs", "Lint"];
76+
pub const MEM_SWAP: [&str; 3] = ["core", "mem", "swap"];
7677
pub const MUTEX_GUARD: [&str; 4] = ["std", "sync", "mutex", "MutexGuard"];
7778
pub const OPEN_OPTIONS: [&str; 3] = ["std", "fs", "OpenOptions"];
7879
/// Preferably use the diagnostic item `sym::Option` where possible

tests/ui/swap_ptr_to_ref.fixed

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::swap_ptr_to_ref)]
4+
5+
use core::ptr::addr_of_mut;
6+
7+
fn main() {
8+
let mut x = 0u32;
9+
let y: *mut _ = &mut x;
10+
let z: *mut _ = &mut x;
11+
12+
unsafe {
13+
core::ptr::swap(y, z);
14+
core::ptr::swap(y, &mut x);
15+
core::ptr::swap(&mut x, y);
16+
core::ptr::swap(addr_of_mut!(x), addr_of_mut!(x));
17+
}
18+
19+
let y = &mut x;
20+
let mut z = 0u32;
21+
let z = &mut z;
22+
23+
core::mem::swap(y, z);
24+
}

tests/ui/swap_ptr_to_ref.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::swap_ptr_to_ref)]
4+
5+
use core::ptr::addr_of_mut;
6+
7+
fn main() {
8+
let mut x = 0u32;
9+
let y: *mut _ = &mut x;
10+
let z: *mut _ = &mut x;
11+
12+
unsafe {
13+
core::mem::swap(&mut *y, &mut *z);
14+
core::mem::swap(&mut *y, &mut x);
15+
core::mem::swap(&mut x, &mut *y);
16+
core::mem::swap(&mut *addr_of_mut!(x), &mut *addr_of_mut!(x));
17+
}
18+
19+
let y = &mut x;
20+
let mut z = 0u32;
21+
let z = &mut z;
22+
23+
core::mem::swap(y, z);
24+
}

tests/ui/swap_ptr_to_ref.stderr

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
2+
--> $DIR/swap_ptr_to_ref.rs:13:9
3+
|
4+
LL | core::mem::swap(&mut *y, &mut *z);
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use ptr::swap: `core::ptr::swap(y, z)`
6+
|
7+
= note: `-D clippy::swap-ptr-to-ref` implied by `-D warnings`
8+
9+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
10+
--> $DIR/swap_ptr_to_ref.rs:14:9
11+
|
12+
LL | core::mem::swap(&mut *y, &mut x);
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use ptr::swap: `core::ptr::swap(y, &mut x)`
14+
15+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
16+
--> $DIR/swap_ptr_to_ref.rs:15:9
17+
|
18+
LL | core::mem::swap(&mut x, &mut *y);
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use ptr::swap: `core::ptr::swap(&mut x, y)`
20+
21+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
22+
--> $DIR/swap_ptr_to_ref.rs:16:9
23+
|
24+
LL | core::mem::swap(&mut *addr_of_mut!(x), &mut *addr_of_mut!(x));
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use ptr::swap: `core::ptr::swap(addr_of_mut!(x), addr_of_mut!(x))`
26+
27+
error: aborting due to 4 previous errors
28+

tests/ui/swap_ptr_to_ref_unfixable.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#![warn(clippy::swap_ptr_to_ref)]
2+
3+
macro_rules! addr_of_mut_to_ref {
4+
($e:expr) => {
5+
&mut *core::ptr::addr_of_mut!($e)
6+
};
7+
}
8+
9+
fn main() {
10+
let mut x = 0u32;
11+
let y: *mut _ = &mut x;
12+
13+
unsafe {
14+
core::mem::swap(addr_of_mut_to_ref!(x), &mut *y);
15+
core::mem::swap(&mut *y, addr_of_mut_to_ref!(x));
16+
core::mem::swap(addr_of_mut_to_ref!(x), addr_of_mut_to_ref!(x));
17+
}
18+
}
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
2+
--> $DIR/swap_ptr_to_ref_unfixable.rs:14:9
3+
|
4+
LL | core::mem::swap(addr_of_mut_to_ref!(x), &mut *y);
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::swap-ptr-to-ref` implied by `-D warnings`
8+
9+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
10+
--> $DIR/swap_ptr_to_ref_unfixable.rs:15:9
11+
|
12+
LL | core::mem::swap(&mut *y, addr_of_mut_to_ref!(x));
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14+
15+
error: call to `core::mem::swap` with a parameter derived from a raw pointer
16+
--> $DIR/swap_ptr_to_ref_unfixable.rs:16:9
17+
|
18+
LL | core::mem::swap(addr_of_mut_to_ref!(x), addr_of_mut_to_ref!(x));
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
20+
21+
error: aborting due to 3 previous errors
22+

0 commit comments

Comments
 (0)