1 use super::WHILE_LET_LOOP;
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::higher;
4 use clippy_utils::source::snippet_with_applicability;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Block, Expr, ExprKind, MatchSource, Pat, StmtKind};
7 use rustc_lint::{LateContext, LintContext};
8 use rustc_middle::lint::in_external_macro;
10 pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, loop_block: &'tcx Block<'_>) {
11 // extract the expression from the first statement (if any) in a block
12 let inner_stmt_expr = extract_expr_from_first_stmt(loop_block);
13 // or extract the first expression (if any) from the block
14 if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(loop_block)) {
15 if let Some(higher::IfLet {
18 if_else: Some(if_else),
20 }) = higher::IfLet::hir(cx, inner)
22 if is_simple_break_expr(if_else) {
23 could_be_while_let(cx, expr, let_pat, let_expr);
27 if let ExprKind::Match(matchexpr, arms, MatchSource::Normal) = inner.kind {
29 && arms[0].guard.is_none()
30 && arms[1].guard.is_none()
31 && is_simple_break_expr(arms[1].body)
33 could_be_while_let(cx, expr, arms[0].pat, matchexpr);
39 /// If a block begins with a statement (possibly a `let` binding) and has an
40 /// expression, return it.
41 fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
42 if let Some(first_stmt) = block.stmts.get(0) {
43 if let StmtKind::Local(local) = first_stmt.kind {
50 /// If a block begins with an expression (with or without semicolon), return it.
51 fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
53 Some(expr) if block.stmts.is_empty() => Some(expr),
54 None if !block.stmts.is_empty() => match block.stmts[0].kind {
55 StmtKind::Expr(expr) | StmtKind::Semi(expr) => Some(expr),
56 StmtKind::Local(..) | StmtKind::Item(..) => None,
62 /// Returns `true` if expr contains a single break expr without destination label
64 /// passed expression. The expression may be within a block.
65 fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
67 ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
68 ExprKind::Block(b, _) => extract_first_expr(b).map_or(false, is_simple_break_expr),
73 fn could_be_while_let<'tcx>(
74 cx: &LateContext<'tcx>,
76 let_pat: &'tcx Pat<'_>,
77 let_expr: &'tcx Expr<'_>,
79 if in_external_macro(cx.sess(), expr.span) {
83 // NOTE: we used to build a body here instead of using
84 // ellipsis, this was removed because:
85 // 1) it was ugly with big bodies;
86 // 2) it was not indented properly;
87 // 3) it wasn’t very smart (see #675).
88 let mut applicability = Applicability::HasPlaceholders;
93 "this loop could be written as a `while let` loop",
96 "while let {} = {} {{ .. }}",
97 snippet_with_applicability(cx, let_pat.span, "..", &mut applicability),
98 snippet_with_applicability(cx, let_expr.span, "..", &mut applicability),