Skip to content

Commit 42b6ed1

Browse files
committed
account temporary borrow by raw-ptr
1 parent 2480c9e commit 42b6ed1

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

src/librustc/traits/error_reporting/suggestions.rs

+32-5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use rustc_errors::{
1313
};
1414
use rustc_hir as hir;
1515
use rustc_hir::def_id::DefId;
16+
use rustc_hir::def::DefKind;
1617
use rustc_hir::intravisit::Visitor;
1718
use rustc_hir::Node;
1819
use rustc_span::source_map::SourceMap;
@@ -1366,14 +1367,40 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
13661367

13671368
if let Some(expr_id) = expr {
13681369
let expr = hir.expect_expr(expr_id);
1369-
let is_ref = tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1370+
debug!("target_ty evaluated from {:?}", expr);
1371+
13701372
let parent = hir.get_parent_node(expr_id);
13711373
if let Some(hir::Node::Expr(e)) = hir.find(parent) {
1372-
let method_span = hir.span(parent);
1373-
if tables.is_method_call(e) && is_ref {
1374+
let parent_span = hir.span(parent);
1375+
let parent_did = parent.owner_def_id();
1376+
// ```rust
1377+
// impl T {
1378+
// fn foo(&self) -> i32 {}
1379+
// }
1380+
// T.foo();
1381+
// ^^^^^^^ a temporary `&T` created inside this method call due to `&self`
1382+
// ```
1383+
//
1384+
let is_region_borrow =
1385+
tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow());
1386+
1387+
// ```rust
1388+
// struct Foo(*const u8);
1389+
// bar(Foo(std::ptr::null())).await;
1390+
// ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor.
1391+
// ```
1392+
debug!("parent_def_kind: {:?}", self.tcx.def_kind(parent_did));
1393+
let is_raw_borrow_inside_fn_like_call = match self.tcx.def_kind(parent_did) {
1394+
Some(DefKind::Fn) | Some(DefKind::Ctor(..)) => target_ty.is_unsafe_ptr(),
1395+
_ => false,
1396+
};
1397+
1398+
if (tables.is_method_call(e) && is_region_borrow)
1399+
|| is_raw_borrow_inside_fn_like_call
1400+
{
13741401
err.span_help(
1375-
method_span,
1376-
"consider moving this method call into a `let` \
1402+
parent_span,
1403+
"consider moving this into a `let` \
13771404
binding to create a shorter lived borrow",
13781405
);
13791406
}

0 commit comments

Comments
 (0)