Skip to content

Commit b3fd7b8

Browse files
committed
Auto merge of #10948 - Centri3:borrow_as_ptr, r=dswij
[`borrow_as_ptr`]: Ignore temporaries Fixes #9884 changelog: [`borrow_as_ptr`]: Ignore temporaries
2 parents b3ae038 + 72aa180 commit b3fd7b8

File tree

4 files changed

+30
-2
lines changed

4 files changed

+30
-2
lines changed

clippy_lints/src/casts/borrow_as_ptr.rs

+10
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use clippy_utils::source::snippet_with_context;
44
use rustc_errors::Applicability;
55
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Ty, TyKind};
66
use rustc_lint::LateContext;
7+
use rustc_middle::ty::adjustment::Adjust;
78

89
use super::BORROW_AS_PTR;
910

@@ -23,6 +24,15 @@ pub(super) fn check<'tcx>(
2324
};
2425
let mut app = Applicability::MachineApplicable;
2526
let snip = snippet_with_context(cx, e.span, cast_expr.span.ctxt(), "..", &mut app).0;
27+
// Fix #9884
28+
if !e.is_place_expr(|base| {
29+
cx.typeck_results()
30+
.adjustments()
31+
.get(base.hir_id)
32+
.is_some_and(|x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
33+
}) {
34+
return;
35+
}
2636

2737
span_lint_and_sugg(
2838
cx,

tests/ui/borrow_as_ptr.fixed

+9
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
//@run-rustfix
22
#![warn(clippy::borrow_as_ptr)]
3+
#![allow(clippy::useless_vec)]
4+
5+
fn a() -> i32 {
6+
0
7+
}
38

49
fn main() {
510
let val = 1;
611
let _p = std::ptr::addr_of!(val);
12+
let _p = &0 as *const i32;
13+
let _p = &a() as *const i32;
14+
let vec = vec![1];
15+
let _p = &vec.len() as *const usize;
716

817
let mut val_mut = 1;
918
let _p_mut = std::ptr::addr_of_mut!(val_mut);

tests/ui/borrow_as_ptr.rs

+9
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
//@run-rustfix
22
#![warn(clippy::borrow_as_ptr)]
3+
#![allow(clippy::useless_vec)]
4+
5+
fn a() -> i32 {
6+
0
7+
}
38

49
fn main() {
510
let val = 1;
611
let _p = &val as *const i32;
12+
let _p = &0 as *const i32;
13+
let _p = &a() as *const i32;
14+
let vec = vec![1];
15+
let _p = &vec.len() as *const usize;
716

817
let mut val_mut = 1;
918
let _p_mut = &mut val_mut as *mut i32;

tests/ui/borrow_as_ptr.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
error: borrow as raw pointer
2-
--> $DIR/borrow_as_ptr.rs:6:14
2+
--> $DIR/borrow_as_ptr.rs:11:14
33
|
44
LL | let _p = &val as *const i32;
55
| ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::addr_of!(val)`
66
|
77
= note: `-D clippy::borrow-as-ptr` implied by `-D warnings`
88

99
error: borrow as raw pointer
10-
--> $DIR/borrow_as_ptr.rs:9:18
10+
--> $DIR/borrow_as_ptr.rs:18:18
1111
|
1212
LL | let _p_mut = &mut val_mut as *mut i32;
1313
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::addr_of_mut!(val_mut)`

0 commit comments

Comments
 (0)