diff --git a/clippy_lints/src/dereference.rs b/clippy_lints/src/dereference.rs index 7e2e32a20d4f..4d2f5eea1059 100644 --- a/clippy_lints/src/dereference.rs +++ b/clippy_lints/src/dereference.rs @@ -9,6 +9,7 @@ use clippy_utils::{ }; use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX}; use rustc_data_structures::fx::FxIndexMap; +use rustc_data_structures::graph::iterate::{CycleDetector, TriColorDepthFirstSearch}; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_ty, Visitor}; use rustc_hir::{ @@ -1242,6 +1243,8 @@ fn referent_used_exactly_once<'a, 'tcx>( && let Some(statement) = mir.basic_blocks[location.block].statements.get(location.statement_index) && let StatementKind::Assign(box (_, Rvalue::Ref(_, _, place))) = statement.kind && !place.has_deref() + // Ensure not in a loop (https://github.com/rust-lang/rust-clippy/issues/9710) + && TriColorDepthFirstSearch::new(&mir.basic_blocks).run_from(location.block, &mut CycleDetector).is_none() { let body_owner_local_def_id = cx.tcx.hir().enclosing_body_owner(reference.hir_id); if possible_borrowers diff --git a/tests/ui/needless_borrow.fixed b/tests/ui/needless_borrow.fixed index 57a682d62c0c..9931fab04ebc 100644 --- a/tests/ui/needless_borrow.fixed +++ b/tests/ui/needless_borrow.fixed @@ -408,3 +408,15 @@ mod issue_9111 { a.extend(&[]); // vs a.extend([]); } } + +#[allow(dead_code)] +mod issue_9710 { + fn main() { + let string = String::new(); + for _i in 0..10 { + f(&string); + } + } + + fn f>(_: T) {} +} diff --git a/tests/ui/needless_borrow.rs b/tests/ui/needless_borrow.rs index 0d325b48ab81..4460f16d191b 100644 --- a/tests/ui/needless_borrow.rs +++ b/tests/ui/needless_borrow.rs @@ -408,3 +408,15 @@ mod issue_9111 { a.extend(&[]); // vs a.extend([]); } } + +#[allow(dead_code)] +mod issue_9710 { + fn main() { + let string = String::new(); + for _i in 0..10 { + f(&string); + } + } + + fn f>(_: T) {} +}