Skip to content

Commit 251dd30

Browse files
committed
Improve manual_map
In some cases check if a borrow made in the scrutinee expression would prevent creating the closure used by `map`
1 parent 4838c78 commit 251dd30

File tree

4 files changed

+145
-20
lines changed

4 files changed

+145
-20
lines changed

clippy_lints/src/manual_map.rs

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
44
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
55
use clippy_utils::{
66
can_move_expr_to_closure, in_constant, is_else_clause, is_lang_ctor, is_lint_allowed, path_to_local_id,
7-
peel_hir_expr_refs,
7+
peel_hir_expr_refs, peel_hir_expr_while, CaptureKind,
88
};
99
use rustc_ast::util::parser::PREC_POSTFIX;
1010
use rustc_errors::Applicability;
1111
use rustc_hir::LangItem::{OptionNone, OptionSome};
12-
use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, MatchSource, Mutability, Pat, PatKind};
12+
use rustc_hir::{
13+
def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, MatchSource, Mutability, Pat, PatKind, Path, QPath,
14+
};
1315
use rustc_lint::{LateContext, LateLintPass, LintContext};
1416
use rustc_middle::lint::in_external_macro;
1517
use rustc_session::{declare_lint_pass, declare_tool_lint};
@@ -111,10 +113,6 @@ impl LateLintPass<'_> for ManualMap {
111113
return;
112114
}
113115

114-
if !can_move_expr_to_closure(cx, some_expr) {
115-
return;
116-
}
117-
118116
// Determine which binding mode to use.
119117
let explicit_ref = some_pat.contains_explicit_ref_binding();
120118
let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
@@ -125,6 +123,32 @@ impl LateLintPass<'_> for ManualMap {
125123
None => "",
126124
};
127125

126+
match can_move_expr_to_closure(cx, some_expr) {
127+
Some(captures) => {
128+
// Check if captures the closure will need conflict with borrows made in the scrutinee.
129+
// TODO: check all the references made in the scrutinee expression. This will require interacting
130+
// with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
131+
if let Some(binding_ref_mutability) = binding_ref {
132+
let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
133+
ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
134+
_ => None,
135+
});
136+
if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l), .. })) = e.kind {
137+
match captures.get(l) {
138+
Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return,
139+
Some(CaptureKind::Ref(Mutability::Not))
140+
if binding_ref_mutability == Mutability::Mut =>
141+
{
142+
return;
143+
}
144+
Some(CaptureKind::Ref(Mutability::Not)) | None => (),
145+
}
146+
}
147+
}
148+
},
149+
None => return,
150+
};
151+
128152
let mut app = Applicability::MachineApplicable;
129153

130154
// Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or

clippy_utils/src/lib.rs

Lines changed: 103 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,19 +67,20 @@ use rustc_data_structures::unhash::UnhashMap;
6767
use rustc_hir as hir;
6868
use rustc_hir::def::{DefKind, Res};
6969
use rustc_hir::def_id::DefId;
70-
use rustc_hir::hir_id::HirIdSet;
70+
use rustc_hir::hir_id::{HirIdMap, HirIdSet};
7171
use rustc_hir::intravisit::{self, walk_expr, ErasedMap, FnKind, NestedVisitorMap, Visitor};
7272
use rustc_hir::LangItem::{ResultErr, ResultOk};
7373
use rustc_hir::{
7474
def, Arm, BindingAnnotation, Block, Body, Constness, Destination, Expr, ExprKind, FnDecl, GenericArgs, HirId, Impl,
75-
ImplItem, ImplItemKind, IsAsync, Item, ItemKind, LangItem, Local, MatchSource, Node, Param, Pat, PatKind, Path,
76-
PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitRef, TyKind, UnOp,
75+
ImplItem, ImplItemKind, IsAsync, Item, ItemKind, LangItem, Local, MatchSource, Mutability, Node, Param, Pat,
76+
PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitRef, TyKind, UnOp,
7777
};
7878
use rustc_lint::{LateContext, Level, Lint, LintContext};
7979
use rustc_middle::hir::exports::Export;
8080
use rustc_middle::hir::map::Map;
8181
use rustc_middle::ty as rustc_ty;
82-
use rustc_middle::ty::{layout::IntegerExt, DefIdTree, Ty, TyCtxt, TypeFoldable};
82+
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
83+
use rustc_middle::ty::{layout::IntegerExt, DefIdTree, Ty, TyCtxt, TypeAndMut, TypeFoldable};
8384
use rustc_semver::RustcVersion;
8485
use rustc_session::Session;
8586
use rustc_span::hygiene::{ExpnKind, MacroKind};
@@ -670,8 +671,82 @@ pub fn can_move_expr_to_closure_no_visit(
670671
}
671672
}
672673

673-
/// Checks if the expression can be moved into a closure as is.
674-
pub fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
674+
/// How a local is captured by a closure
675+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
676+
pub enum CaptureKind {
677+
Value,
678+
Ref(Mutability),
679+
}
680+
impl std::ops::BitOr for CaptureKind {
681+
type Output = Self;
682+
fn bitor(self, rhs: Self) -> Self::Output {
683+
match (self, rhs) {
684+
(CaptureKind::Value, _) | (_, CaptureKind::Value) => CaptureKind::Value,
685+
(CaptureKind::Ref(Mutability::Mut), CaptureKind::Ref(_))
686+
| (CaptureKind::Ref(_), CaptureKind::Ref(Mutability::Mut)) => CaptureKind::Ref(Mutability::Mut),
687+
(CaptureKind::Ref(Mutability::Not), CaptureKind::Ref(Mutability::Not)) => CaptureKind::Ref(Mutability::Not),
688+
}
689+
}
690+
}
691+
impl std::ops::BitOrAssign for CaptureKind {
692+
fn bitor_assign(&mut self, rhs: Self) {
693+
*self = *self | rhs;
694+
}
695+
}
696+
697+
/// Given an expression referencing a local, determines how it would be captured in a closure.
698+
/// Note as this will walk up to parent expressions until the capture can be determined it should
699+
/// only be used while making a closure somewhere a value is consumed. e.g. a block, match arm, or
700+
/// function argument (other than a receiver).
701+
pub fn capture_local_usage(cx: &LateContext<'tcx>, e: &Expr<'_>) -> CaptureKind {
702+
debug_assert!(matches!(
703+
e.kind,
704+
ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(_), .. }))
705+
));
706+
707+
let map = cx.tcx.hir();
708+
let mut child_id = e.hir_id;
709+
let mut capture = CaptureKind::Value;
710+
711+
for (parent_id, parent) in map.parent_iter(e.hir_id) {
712+
if let [Adjustment {
713+
kind: Adjust::Deref(_) | Adjust::Borrow(AutoBorrow::Ref(..)),
714+
target,
715+
}, ref adjust @ ..] = *cx
716+
.typeck_results()
717+
.adjustments()
718+
.get(child_id)
719+
.map_or(&[][..], |x| &**x)
720+
{
721+
if let rustc_ty::RawPtr(TypeAndMut { mutbl: mutability, .. }) | rustc_ty::Ref(_, _, mutability) =
722+
*adjust.last().map_or(target, |a| a.target).kind()
723+
{
724+
return CaptureKind::Ref(mutability);
725+
}
726+
}
727+
728+
if let Node::Expr(e) = parent {
729+
match e.kind {
730+
ExprKind::AddrOf(_, mutability, _) => return CaptureKind::Ref(mutability),
731+
ExprKind::Index(..) | ExprKind::Unary(UnOp::Deref, _) => capture = CaptureKind::Ref(Mutability::Not),
732+
ExprKind::Assign(lhs, ..) | ExprKind::Assign(_, lhs, _) if lhs.hir_id == child_id => {
733+
return CaptureKind::Ref(Mutability::Mut);
734+
},
735+
_ => break,
736+
}
737+
} else {
738+
break;
739+
}
740+
741+
child_id = parent_id;
742+
}
743+
744+
capture
745+
}
746+
747+
/// Checks if the expression can be moved into a closure as is. This will return a list of captures
748+
/// if so, otherwise, `None`.
749+
pub fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<HirIdMap<CaptureKind>> {
675750
struct V<'cx, 'tcx> {
676751
cx: &'cx LateContext<'tcx>,
677752
// Stack of potential break targets contained in the expression.
@@ -680,6 +755,9 @@ pub fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) ->
680755
locals: HirIdSet,
681756
/// Whether this expression can be turned into a closure.
682757
allow_closure: bool,
758+
/// Locals which need to be captured, and whether they need to be by value, reference, or
759+
/// mutable reference.
760+
captures: HirIdMap<CaptureKind>,
683761
}
684762
impl Visitor<'tcx> for V<'_, 'tcx> {
685763
type Map = ErasedMap<'tcx>;
@@ -691,13 +769,23 @@ pub fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) ->
691769
if !self.allow_closure {
692770
return;
693771
}
694-
if let ExprKind::Loop(b, ..) = e.kind {
695-
self.loops.push(e.hir_id);
696-
self.visit_block(b);
697-
self.loops.pop();
698-
} else {
699-
self.allow_closure &= can_move_expr_to_closure_no_visit(self.cx, e, &self.loops, &self.locals);
700-
walk_expr(self, e);
772+
773+
match e.kind {
774+
ExprKind::Path(QPath::Resolved(None, &Path { res: Res::Local(l), .. })) => {
775+
if !self.locals.contains(&l) {
776+
let cap = capture_local_usage(self.cx, e);
777+
self.captures.entry(l).and_modify(|e| *e |= cap).or_insert(cap);
778+
}
779+
},
780+
ExprKind::Loop(b, ..) => {
781+
self.loops.push(e.hir_id);
782+
self.visit_block(b);
783+
self.loops.pop();
784+
},
785+
_ => {
786+
self.allow_closure &= can_move_expr_to_closure_no_visit(self.cx, e, &self.loops, &self.locals);
787+
walk_expr(self, e);
788+
},
701789
}
702790
}
703791

@@ -713,9 +801,10 @@ pub fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) ->
713801
allow_closure: true,
714802
loops: Vec::new(),
715803
locals: HirIdSet::default(),
804+
captures: HirIdMap::default(),
716805
};
717806
v.visit_expr(expr);
718-
v.allow_closure
807+
v.allow_closure.then(|| v.captures)
719808
}
720809

721810
/// Returns the method names and argument list of nested method call expressions that make up

tests/ui/manual_map_option_2.fixed

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,10 @@ fn main() {
77
let y = (String::new(), String::new());
88
(x, y.0)
99
});
10+
11+
let s = Some(String::new());
12+
let _ = match &s {
13+
Some(x) => Some((x.clone(), s)),
14+
None => None,
15+
};
1016
}

tests/ui/manual_map_option_2.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,10 @@ fn main() {
1010
}),
1111
None => None,
1212
};
13+
14+
let s = Some(String::new());
15+
let _ = match &s {
16+
Some(x) => Some((x.clone(), s)),
17+
None => None,
18+
};
1319
}

0 commit comments

Comments
 (0)