1 use super::REDUNDANT_PATTERN_MATCHING;
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::source::snippet;
4 use clippy_utils::sugg::Sugg;
5 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};
8 use if_chain::if_chain;
9 use rustc_ast::ast::LitKind;
10 use rustc_errors::Applicability;
11 use rustc_hir::LangItem::{OptionNone, PollPending};
13 intravisit::{walk_expr, Visitor},
14 Arm, Block, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp,
16 use rustc_lint::LateContext;
17 use rustc_middle::ty::{self, subst::GenericArgKind, DefIdTree, Ty};
20 pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
21 if let Some(higher::WhileLet { let_pat, let_expr, .. }) = higher::WhileLet::hir(expr) {
22 find_sugg_for_if_let(cx, expr, let_pat, let_expr, "while", false);
26 pub(super) fn check_if_let<'tcx>(
27 cx: &LateContext<'tcx>,
30 scrutinee: &'tcx Expr<'_>,
33 find_sugg_for_if_let(cx, expr, pat, scrutinee, "if", has_else);
36 // Extract the generic arguments out of a type
37 fn try_get_generic_ty(ty: Ty<'_>, index: usize) -> Option<Ty<'_>> {
39 if let ty::Adt(_, subs) = ty.kind();
40 if let Some(sub) = subs.get(index);
41 if let GenericArgKind::Type(sub_ty) = sub.unpack();
50 // Checks if there are any temporaries created in the given expression for which drop order
52 fn temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
54 cx: &'a LateContext<'tcx>,
57 impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> {
58 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
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)) {
69 self.visit_expr(expr);
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)) {
80 self.visit_expr(base);
83 self.visit_expr(index);
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
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)) {
97 self.visit_expr(self_arg);
100 args.iter().for_each(|arg| self.visit_expr(arg));
102 // Either explicitly drops values, or changes control flow.
103 ExprKind::DropTemps(_)
105 | ExprKind::Break(..)
106 | ExprKind::Yield(..)
107 | ExprKind::Block(Block { expr: None, .. }, _)
108 | ExprKind::Loop(..) => (),
110 // Only consider the final expression.
111 ExprKind::Block(Block { expr: Some(expr), .. }, _) => self.visit_expr(expr),
113 _ => walk_expr(self, expr),
118 let mut v = V { cx, res: false };
123 fn find_sugg_for_if_let<'tcx>(
124 cx: &LateContext<'tcx>,
125 expr: &'tcx Expr<'_>,
127 let_expr: &'tcx Expr<'_>,
128 keyword: &'static str,
131 // also look inside refs
132 // if we have &None for example, peel it so we can detect "if let None = x"
133 let check_pat = match let_pat.kind {
134 PatKind::Ref(inner, _mutability) => inner,
137 let op_ty = cx.typeck_results().expr_ty(let_expr);
138 // Determine which function should be used, and the type contained by the corresponding
140 let (good_method, inner_ty) = match check_pat.kind {
141 PatKind::TupleStruct(ref qpath, [sub_pat], _) => {
142 if let PatKind::Wild = sub_pat.kind {
143 let res = cx.typeck_results().qpath_res(qpath, check_pat.hir_id);
144 let Some(id) = res.opt_def_id().map(|ctor_id| cx.tcx.parent(ctor_id)) else { return };
145 let lang_items = cx.tcx.lang_items();
146 if Some(id) == lang_items.result_ok_variant() {
147 ("is_ok()", try_get_generic_ty(op_ty, 0).unwrap_or(op_ty))
148 } else if Some(id) == lang_items.result_err_variant() {
149 ("is_err()", try_get_generic_ty(op_ty, 1).unwrap_or(op_ty))
150 } else if Some(id) == lang_items.option_some_variant() {
152 } else if Some(id) == lang_items.poll_ready_variant() {
153 ("is_ready()", op_ty)
154 } else if match_def_path(cx, id, &paths::IPADDR_V4) {
156 } else if match_def_path(cx, id, &paths::IPADDR_V6) {
165 PatKind::Path(ref path) => {
166 let method = if is_lang_ctor(cx, path, OptionNone) {
168 } else if is_lang_ctor(cx, path, PollPending) {
173 // `None` and `Pending` don't have an inner type.
174 (method, cx.tcx.types.unit)
179 // If this is the last expression in a block or there is an else clause then the whole
180 // type needs to be considered, not just the inner type of the branch being matched on.
181 // Note the last expression in a block is dropped after all local bindings.
182 let check_ty = if has_else
183 || (keyword == "if" && matches!(cx.tcx.hir().parent_iter(expr.hir_id).next(), Some((_, Node::Block(..)))))
190 // All temporaries created in the scrutinee expression are dropped at the same time as the
191 // scrutinee would be, so they have to be considered as well.
192 // e.g. in `if let Some(x) = foo.lock().unwrap().baz.as_ref() { .. }` the lock will be held
193 // for the duration if body.
194 let needs_drop = needs_ordered_drop(cx, check_ty) || temporaries_need_ordered_drop(cx, let_expr);
196 // check that `while_let_on_iterator` lint does not trigger
198 if keyword == "while";
199 if let ExprKind::MethodCall(method_path, _, _) = let_expr.kind;
200 if method_path.ident.name == sym::next;
201 if is_trait_method(cx, let_expr, sym::Iterator);
207 let result_expr = match &let_expr.kind {
208 ExprKind::AddrOf(_, _, borrowed) => borrowed,
209 ExprKind::Unary(UnOp::Deref, deref) => deref,
215 REDUNDANT_PATTERN_MATCHING,
217 &format!("redundant pattern matching, consider using `{}`", good_method),
219 // if/while let ... = ... { ... }
220 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
221 let expr_span = expr.span;
223 // if/while let ... = ... { ... }
225 let op_span = result_expr.span.source_callsite();
227 // if/while let ... = ... { ... }
228 // ^^^^^^^^^^^^^^^^^^^
229 let span = expr_span.until(op_span.shrink_to_hi());
231 let app = if needs_drop {
232 Applicability::MaybeIncorrect
234 Applicability::MachineApplicable
237 let sugg = Sugg::hir_with_macro_callsite(cx, result_expr, "_")
241 diag.span_suggestion(span, "try this", format!("{} {}.{}", keyword, sugg, good_method), app);
244 diag.note("this will change drop order of the result, as well as all temporaries");
245 diag.note("add `#[allow(clippy::redundant_pattern_matching)]` if this is important");
251 pub(super) fn check_match<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, op: &Expr<'_>, arms: &[Arm<'_>]) {
253 let node_pair = (&arms[0].pat.kind, &arms[1].pat.kind);
255 let found_good_method = match node_pair {
257 PatKind::TupleStruct(ref path_left, patterns_left, _),
258 PatKind::TupleStruct(ref path_right, patterns_right, _),
259 ) if patterns_left.len() == 1 && patterns_right.len() == 1 => {
260 if let (PatKind::Wild, PatKind::Wild) = (&patterns_left[0].kind, &patterns_right[0].kind) {
261 find_good_method_for_match(
272 find_good_method_for_match(
287 (PatKind::TupleStruct(ref path_left, patterns, _), PatKind::Path(ref path_right))
288 | (PatKind::Path(ref path_left), PatKind::TupleStruct(ref path_right, patterns, _))
289 if patterns.len() == 1 =>
291 if let PatKind::Wild = patterns[0].kind {
292 find_good_method_for_match(
303 find_good_method_for_match(
309 &paths::POLL_PENDING,
321 if let Some(good_method) = found_good_method {
322 let span = expr.span.to(op.span);
323 let result_expr = match &op.kind {
324 ExprKind::AddrOf(_, _, borrowed) => borrowed,
329 REDUNDANT_PATTERN_MATCHING,
331 &format!("redundant pattern matching, consider using `{}`", good_method),
333 diag.span_suggestion(
336 format!("{}.{}", snippet(cx, result_expr.span, "_"), good_method),
337 Applicability::MaybeIncorrect, // snippet
345 #[expect(clippy::too_many_arguments)]
346 fn find_good_method_for_match<'a>(
347 cx: &LateContext<'_>,
349 path_left: &QPath<'_>,
350 path_right: &QPath<'_>,
351 expected_left: &[&str],
352 expected_right: &[&str],
353 should_be_left: &'a str,
354 should_be_right: &'a str,
355 ) -> Option<&'a str> {
358 .qpath_res(path_left, arms[0].pat.hir_id)
362 .qpath_res(path_right, arms[1].pat.hir_id)
364 let body_node_pair = if match_def_path(cx, left_id, expected_left) && match_def_path(cx, right_id, expected_right) {
365 (&(*arms[0].body).kind, &(*arms[1].body).kind)
366 } else if match_def_path(cx, right_id, expected_left) && match_def_path(cx, right_id, expected_right) {
367 (&(*arms[1].body).kind, &(*arms[0].body).kind)
372 match body_node_pair {
373 (ExprKind::Lit(ref lit_left), ExprKind::Lit(ref lit_right)) => match (&lit_left.node, &lit_right.node) {
374 (LitKind::Bool(true), LitKind::Bool(false)) => Some(should_be_left),
375 (LitKind::Bool(false), LitKind::Bool(true)) => Some(should_be_right),