Skip to content

Commit 58434ae

Browse files
committed
Extract util functions from redundant_pattern_match
1 parent 70f1d0d commit 58434ae

File tree

2 files changed

+131
-84
lines changed

2 files changed

+131
-84
lines changed

clippy_lints/src/matches/redundant_pattern_match.rs

Lines changed: 4 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,13 @@ use clippy_utils::diagnostics::span_lint_and_then;
33
use clippy_utils::source::snippet;
44
use clippy_utils::sugg::Sugg;
55
use clippy_utils::ty::needs_ordered_drop;
6-
use clippy_utils::{higher, match_def_path};
7-
use clippy_utils::{is_lang_ctor, is_trait_method, paths};
6+
use clippy_utils::visitors::any_temporaries_need_ordered_drop;
7+
use clippy_utils::{higher, is_lang_ctor, is_trait_method, match_def_path, paths};
88
use if_chain::if_chain;
99
use rustc_ast::ast::LitKind;
1010
use rustc_errors::Applicability;
1111
use rustc_hir::LangItem::{OptionNone, PollPending};
12-
use rustc_hir::{
13-
intravisit::{walk_expr, Visitor},
14-
Arm, Block, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp,
15-
};
12+
use rustc_hir::{Arm, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp};
1613
use rustc_lint::LateContext;
1714
use rustc_middle::ty::{self, subst::GenericArgKind, DefIdTree, Ty};
1815
use rustc_span::sym;
@@ -47,79 +44,6 @@ fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
4744
}
4845
}
4946

50-
// Checks if there are any temporaries created in the given expression for which drop order
51-
// matters.
52-
fn temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
53-
struct V<'a, 'tcx> {
54-
cx: &'a LateContext<'tcx>,
55-
res: bool,
56-
}
57-
impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
58-
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
59-
match expr.kind {
60-
// Taking the reference of a value leaves a temporary
61-
// e.g. In `&String::new()` the string is a temporary value.
62-
// Remaining fields are temporary values
63-
// e.g. In `(String::new(), 0).1` the string is a temporary value.
64-
ExprKind::AddrOf(_, _, expr) | ExprKind::Field(expr, _) => {
65-
if !matches!(expr.kind, ExprKind::Path(_)) {
66-
if needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(expr)) {
67-
self.res = true;
68-
} else {
69-
self.visit_expr(expr);
70-
}
71-
}
72-
},
73-
// the base type is always taken by reference.
74-
// e.g. In `(vec![0])[0]` the vector is a temporary value.
75-
ExprKind::Index(base, index) => {
76-
if !matches!(base.kind, ExprKind::Path(_)) {
77-
if needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(base)) {
78-
self.res = true;
79-
} else {
80-
self.visit_expr(base);
81-
}
82-
}
83-
self.visit_expr(index);
84-
},
85-
// Method calls can take self by reference.
86-
// e.g. In `String::new().len()` the string is a temporary value.
87-
ExprKind::MethodCall(_, [self_arg, args @ ..], _) => {
88-
if !matches!(self_arg.kind, ExprKind::Path(_)) {
89-
let self_by_ref = self
90-
.cx
91-
.typeck_results()
92-
.type_dependent_def_id(expr.hir_id)
93-
.map_or(false, |id| self.cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref());
94-
if self_by_ref && needs_ordered_drop(self.cx, self.cx.typeck_results().expr_ty(self_arg)) {
95-
self.res = true;
96-
} else {
97-
self.visit_expr(self_arg);
98-
}
99-
}
100-
args.iter().for_each(|arg| self.visit_expr(arg));
101-
},
102-
// Either explicitly drops values, or changes control flow.
103-
ExprKind::DropTemps(_)
104-
| ExprKind::Ret(_)
105-
| ExprKind::Break(..)
106-
| ExprKind::Yield(..)
107-
| ExprKind::Block(Block { expr: None, .. }, _)
108-
| ExprKind::Loop(..) => (),
109-
110-
// Only consider the final expression.
111-
ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
112-
113-
_ => walk_expr(self, expr),
114-
}
115-
}
116-
}
117-
118-
let mut v = V { cx, res: false };
119-
v.visit_expr(expr);
120-
v.res
121-
}
122-
12347
fn find_sugg_for_if_let<'tcx>(
12448
cx: &LateContext<'tcx>,
12549
expr: &'tcx Expr<'_>,
@@ -191,7 +115,7 @@ fn find_sugg_for_if_let<'tcx>(
191115
// scrutinee would be, so they have to be considered as well.
192116
// e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
193117
// for the duration if body.
194-
let needs_drop = needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
118+
let needs_drop = needs_ordered_drop(cx, check_ty) || any_temporaries_need_ordered_drop(cx, let_expr);
195119

196120
// check that `while_let_on_iterator` lint does not trigger
197121
if_chain! {

clippy_utils/src/visitors.rs

Lines changed: 127 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1+
use crate::ty::needs_ordered_drop;
12
use crate::{get_enclosing_block, path_to_local_id};
23
use core::ops::ControlFlow;
34
use rustc_hir as hir;
4-
use rustc_hir::def::{DefKind, Res};
5+
use rustc_hir::def::{CtorKind, DefKind, Res};
56
use rustc_hir::intravisit::{self, walk_block, walk_expr, Visitor};
67
use rustc_hir::{
7-
Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Stmt, UnOp, UnsafeSource,
8-
Unsafety,
8+
Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Let, QPath, Stmt, UnOp,
9+
UnsafeSource, Unsafety,
910
};
1011
use rustc_lint::LateContext;
1112
use rustc_middle::hir::map::Map;
1213
use rustc_middle::hir::nested_filter;
13-
use rustc_middle::ty;
14+
use rustc_middle::ty::adjustment::Adjust;
15+
use rustc_middle::ty::{self, Ty, TypeckResults};
1416

1517
/// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
1618
/// bodies (i.e. closures) are visited.
@@ -494,3 +496,124 @@ pub fn for_each_local_use_after_expr<'tcx, B>(
494496
ControlFlow::Continue(())
495497
}
496498
}
499+
500+
// Calls the given function for every unconsumed temporary created by the expression. Note the
501+
// function is only guaranteed to be called for types which need to be dropped, but it may be called
502+
// for other types.
503+
pub fn for_each_unconsumed_temporary<'tcx, B>(
504+
cx: &LateContext<'tcx>,
505+
e: &'tcx Expr<'tcx>,
506+
mut f: impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
507+
) -> ControlFlow<B> {
508+
// Todo: Handle partially consumed values.
509+
fn helper<'tcx, B>(
510+
typeck: &'tcx TypeckResults<'tcx>,
511+
consume: bool,
512+
e: &'tcx Expr<'tcx>,
513+
f: &mut impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
514+
) -> ControlFlow<B> {
515+
if !consume
516+
|| matches!(
517+
typeck.expr_adjustments(e),
518+
[adjust, ..] if matches!(adjust.kind, Adjust::Borrow(_) | Adjust::Deref(_))
519+
)
520+
{
521+
match e.kind {
522+
ExprKind::Path(QPath::Resolved(None, p))
523+
if matches!(p.res, Res::Def(DefKind::Ctor(_, CtorKind::Const), _)) =>
524+
{
525+
f(typeck.expr_ty(e))?;
526+
},
527+
ExprKind::Path(_)
528+
| ExprKind::Unary(UnOp::Deref, _)
529+
| ExprKind::Index(..)
530+
| ExprKind::Field(..)
531+
| ExprKind::AddrOf(..) => (),
532+
_ => f(typeck.expr_ty(e))?,
533+
}
534+
}
535+
match e.kind {
536+
ExprKind::AddrOf(_, _, e)
537+
| ExprKind::Field(e, _)
538+
| ExprKind::Unary(UnOp::Deref, e)
539+
| ExprKind::Match(e, ..)
540+
| ExprKind::Let(&Let { init: e, .. }) => {
541+
helper(typeck, false, e, f)?;
542+
},
543+
ExprKind::Block(&Block { expr: Some(e), .. }, _)
544+
| ExprKind::Box(e)
545+
| ExprKind::Cast(e, _)
546+
| ExprKind::Unary(_, e) => {
547+
helper(typeck, true, e, f)?;
548+
},
549+
ExprKind::Call(callee, args) => {
550+
helper(typeck, true, callee, f)?;
551+
for arg in args {
552+
helper(typeck, true, arg, f)?;
553+
}
554+
},
555+
ExprKind::MethodCall(_, args, _) | ExprKind::Tup(args) | ExprKind::Array(args) => {
556+
for arg in args {
557+
helper(typeck, true, arg, f)?;
558+
}
559+
},
560+
ExprKind::Index(borrowed, consumed)
561+
| ExprKind::Assign(borrowed, consumed, _)
562+
| ExprKind::AssignOp(_, borrowed, consumed) => {
563+
helper(typeck, false, borrowed, f)?;
564+
helper(typeck, true, consumed, f)?;
565+
},
566+
ExprKind::Binary(_, lhs, rhs) => {
567+
helper(typeck, true, lhs, f)?;
568+
helper(typeck, true, rhs, f)?;
569+
},
570+
ExprKind::Struct(_, fields, default) => {
571+
for field in fields {
572+
helper(typeck, true, field.expr, f)?;
573+
}
574+
if let Some(default) = default {
575+
helper(typeck, false, default, f)?;
576+
}
577+
},
578+
ExprKind::If(cond, then, else_expr) => {
579+
helper(typeck, true, cond, f)?;
580+
helper(typeck, true, then, f)?;
581+
if let Some(else_expr) = else_expr {
582+
helper(typeck, true, else_expr, f)?;
583+
}
584+
},
585+
ExprKind::Type(e, _) => {
586+
helper(typeck, consume, e, f)?;
587+
},
588+
589+
// Either drops temporaries, jumps out of the current expression, or has no sub expression.
590+
ExprKind::DropTemps(_)
591+
| ExprKind::Ret(_)
592+
| ExprKind::Break(..)
593+
| ExprKind::Yield(..)
594+
| ExprKind::Block(..)
595+
| ExprKind::Loop(..)
596+
| ExprKind::Repeat(..)
597+
| ExprKind::Lit(_)
598+
| ExprKind::ConstBlock(_)
599+
| ExprKind::Closure { .. }
600+
| ExprKind::Path(_)
601+
| ExprKind::Continue(_)
602+
| ExprKind::InlineAsm(_)
603+
| ExprKind::Err => (),
604+
}
605+
ControlFlow::Continue(())
606+
}
607+
helper(cx.typeck_results(), true, e, &mut f)
608+
}
609+
610+
pub fn any_temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> bool {
611+
for_each_unconsumed_temporary(cx, e, |ty| {
612+
if needs_ordered_drop(cx, ty) {
613+
ControlFlow::Break(())
614+
} else {
615+
ControlFlow::Continue(())
616+
}
617+
})
618+
.is_break()
619+
}

0 commit comments

Comments
 (0)