Skip to content

Commit

Permalink
Auto merge of rust-lang#10948 - Centri3:borrow_as_ptr, r=dswij
Browse files Browse the repository at this point in the history
[`borrow_as_ptr`]: Ignore temporaries

Fixes rust-lang#9884

changelog: [`borrow_as_ptr`]: Ignore temporaries
  • Loading branch information
bors committed Jun 21, 2023
2 parents b3ae038 + 72aa180 commit b3fd7b8
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
10 changes: 10 additions & 0 deletions clippy_lints/src/casts/borrow_as_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use clippy_utils::source::snippet_with_context;
use rustc_errors::Applicability;
use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Ty, TyKind};
use rustc_lint::LateContext;
use rustc_middle::ty::adjustment::Adjust;

use super::BORROW_AS_PTR;

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

span_lint_and_sugg(
cx,
Expand Down
9 changes: 9 additions & 0 deletions tests/ui/borrow_as_ptr.fixed
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
//@run-rustfix
#![warn(clippy::borrow_as_ptr)]
#![allow(clippy::useless_vec)]

fn a() -> i32 {
0
}

fn main() {
let val = 1;
let _p = std::ptr::addr_of!(val);
let _p = &0 as *const i32;
let _p = &a() as *const i32;
let vec = vec![1];
let _p = &vec.len() as *const usize;

let mut val_mut = 1;
let _p_mut = std::ptr::addr_of_mut!(val_mut);
Expand Down
9 changes: 9 additions & 0 deletions tests/ui/borrow_as_ptr.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
//@run-rustfix
#![warn(clippy::borrow_as_ptr)]
#![allow(clippy::useless_vec)]

fn a() -> i32 {
0
}

fn main() {
let val = 1;
let _p = &val as *const i32;
let _p = &0 as *const i32;
let _p = &a() as *const i32;
let vec = vec![1];
let _p = &vec.len() as *const usize;

let mut val_mut = 1;
let _p_mut = &mut val_mut as *mut i32;
Expand Down
4 changes: 2 additions & 2 deletions tests/ui/borrow_as_ptr.stderr
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
error: borrow as raw pointer
--> $DIR/borrow_as_ptr.rs:6:14
--> $DIR/borrow_as_ptr.rs:11:14
|
LL | let _p = &val as *const i32;
| ^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::addr_of!(val)`
|
= note: `-D clippy::borrow-as-ptr` implied by `-D warnings`

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

0 comments on commit b3fd7b8

Please sign in to comment.