Skip to content

Commit 8cbe199

Browse files
committed
Extract util functions from redundant_pattern_match
1 parent 70f1d0d commit 8cbe199

File tree

2 files changed

+132
-84
lines changed

2 files changed

+132
-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: 128 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,125 @@ 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+
#[expect(clippy::too_many_lines)]
504+
pub fn for_each_unconsumed_temporary<'tcx, B>(
505+
cx: &LateContext<'tcx>,
506+
e: &'tcx Expr<'tcx>,
507+
mut f: impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
508+
) -> ControlFlow<B> {
509+
// Todo: Handle partially consumed values.
510+
fn helper<'tcx, B>(
511+
typeck: &'tcx TypeckResults<'tcx>,
512+
consume: bool,
513+
e: &'tcx Expr<'tcx>,
514+
f: &mut impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
515+
) -> ControlFlow<B> {
516+
if !consume
517+
|| matches!(
518+
typeck.expr_adjustments(e),
519+
[adjust, ..] if matches!(adjust.kind, Adjust::Borrow(_) | Adjust::Deref(_))
520+
)
521+
{
522+
match e.kind {
523+
ExprKind::Path(QPath::Resolved(None, p))
524+
if matches!(p.res, Res::Def(DefKind::Ctor(_, CtorKind::Const), _)) =>
525+
{
526+
f(typeck.expr_ty(e))?;
527+
},
528+
ExprKind::Path(_)
529+
| ExprKind::Unary(UnOp::Deref, _)
530+
| ExprKind::Index(..)
531+
| ExprKind::Field(..)
532+
| ExprKind::AddrOf(..) => (),
533+
_ => f(typeck.expr_ty(e))?,
534+
}
535+
}
536+
match e.kind {
537+
ExprKind::AddrOf(_, _, e)
538+
| ExprKind::Field(e, _)
539+
| ExprKind::Unary(UnOp::Deref, e)
540+
| ExprKind::Match(e, ..)
541+
| ExprKind::Let(&Let { init: e, .. }) => {
542+
helper(typeck, false, e, f)?;
543+
},
544+
ExprKind::Block(&Block { expr: Some(e), .. }, _)
545+
| ExprKind::Box(e)
546+
| ExprKind::Cast(e, _)
547+
| ExprKind::Unary(_, e) => {
548+
helper(typeck, true, e, f)?;
549+
},
550+
ExprKind::Call(callee, args) => {
551+
helper(typeck, true, callee, f)?;
552+
for arg in args {
553+
helper(typeck, true, arg, f)?;
554+
}
555+
},
556+
ExprKind::MethodCall(_, args, _) | ExprKind::Tup(args) | ExprKind::Array(args) => {
557+
for arg in args {
558+
helper(typeck, true, arg, f)?;
559+
}
560+
},
561+
ExprKind::Index(borrowed, consumed)
562+
| ExprKind::Assign(borrowed, consumed, _)
563+
| ExprKind::AssignOp(_, borrowed, consumed) => {
564+
helper(typeck, false, borrowed, f)?;
565+
helper(typeck, true, consumed, f)?;
566+
},
567+
ExprKind::Binary(_, lhs, rhs) => {
568+
helper(typeck, true, lhs, f)?;
569+
helper(typeck, true, rhs, f)?;
570+
},
571+
ExprKind::Struct(_, fields, default) => {
572+
for field in fields {
573+
helper(typeck, true, field.expr, f)?;
574+
}
575+
if let Some(default) = default {
576+
helper(typeck, false, default, f)?;
577+
}
578+
},
579+
ExprKind::If(cond, then, else_expr) => {
580+
helper(typeck, true, cond, f)?;
581+
helper(typeck, true, then, f)?;
582+
if let Some(else_expr) = else_expr {
583+
helper(typeck, true, else_expr, f)?;
584+
}
585+
},
586+
ExprKind::Type(e, _) => {
587+
helper(typeck, consume, e, f)?;
588+
},
589+
590+
// Either drops temporaries, jumps out of the current expression, or has no sub expression.
591+
ExprKind::DropTemps(_)
592+
| ExprKind::Ret(_)
593+
| ExprKind::Break(..)
594+
| ExprKind::Yield(..)
595+
| ExprKind::Block(..)
596+
| ExprKind::Loop(..)
597+
| ExprKind::Repeat(..)
598+
| ExprKind::Lit(_)
599+
| ExprKind::ConstBlock(_)
600+
| ExprKind::Closure { .. }
601+
| ExprKind::Path(_)
602+
| ExprKind::Continue(_)
603+
| ExprKind::InlineAsm(_)
604+
| ExprKind::Err => (),
605+
}
606+
ControlFlow::Continue(())
607+
}
608+
helper(cx.typeck_results(), true, e, &mut f)
609+
}
610+
611+
pub fn any_temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> bool {
612+
for_each_unconsumed_temporary(cx, e, |ty| {
613+
if needs_ordered_drop(cx, ty) {
614+
ControlFlow::Break(())
615+
} else {
616+
ControlFlow::Continue(())
617+
}
618+
})
619+
.is_break()
620+
}

0 commit comments

Comments
 (0)