1 //! Checks for continue statements in loops that are redundant.
3 //! For example, the lint would catch
16 //! println!("Hello, world");
20 //! And suggest something like this:
30 //! println!("Hello, world");
35 //! This lint is **warn** by default.
36 use clippy_utils::diagnostics::span_lint_and_help;
37 use clippy_utils::source::{indent_of, snippet, snippet_block};
39 use rustc_lint::{EarlyContext, EarlyLintPass};
40 use rustc_session::{declare_lint_pass, declare_tool_lint};
41 use rustc_span::source_map::{original_sp, DUMMY_SP};
44 declare_clippy_lint! {
46 /// The lint checks for `if`-statements appearing in loops
47 /// that contain a `continue` statement in either their main blocks or their
48 /// `else`-blocks, when omitting the `else`-block possibly with some
49 /// rearrangement of code can make the code easier to understand.
51 /// ### Why is this bad?
52 /// Having explicit `else` blocks for `if` statements
53 /// containing `continue` in their THEN branch adds unnecessary branching and
54 /// nesting to the code. Having an else block containing just `continue` can
55 /// also be better written by grouping the statements following the whole `if`
56 /// statement within the THEN block and omitting the else block completely.
60 /// # fn condition() -> bool { false }
61 /// # fn update_condition() {}
63 /// while condition() {
64 /// update_condition();
70 /// println!("Hello, world");
74 /// Could be rewritten as
77 /// # fn condition() -> bool { false }
78 /// # fn update_condition() {}
80 /// while condition() {
81 /// update_condition();
84 /// println!("Hello, world");
89 /// As another example, the following code
92 /// # fn waiting() -> bool { false }
97 /// // Do something useful
102 /// Could be rewritten as
105 /// # fn waiting() -> bool { false }
110 /// // Do something useful
114 pub NEEDLESS_CONTINUE,
116 "`continue` statements that can be replaced by a rearrangement of code"
119 declare_lint_pass!(NeedlessContinue => [NEEDLESS_CONTINUE]);
121 impl EarlyLintPass for NeedlessContinue {
122 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
123 if !expr.span.from_expansion() {
124 check_and_warn(cx, expr);
129 /* This lint has to mainly deal with two cases of needless continue
131 // Case 1 [Continue inside else block]:
143 // This code can better be written as follows:
153 // Case 2 [Continue inside then block]:
159 // // potentially more code here.
167 // This snippet can be refactored to:
178 /// Given an expression, returns true if either of the following is true
180 /// - The expression is a `continue` node.
181 /// - The expression node is a block with the first statement being a
183 fn needless_continue_in_else(else_expr: &ast::Expr, label: Option<&ast::Label>) -> bool {
184 match else_expr.kind {
185 ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block, label),
186 ast::ExprKind::Continue(l) => compare_labels(label, l.as_ref()),
191 fn is_first_block_stmt_continue(block: &ast::Block, label: Option<&ast::Label>) -> bool {
192 block.stmts.get(0).map_or(false, |stmt| match stmt.kind {
193 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
194 if let ast::ExprKind::Continue(ref l) = e.kind {
195 compare_labels(label, l.as_ref())
204 /// If the `continue` has a label, check it matches the label of the loop.
205 fn compare_labels(loop_label: Option<&ast::Label>, continue_label: Option<&ast::Label>) -> bool {
206 match (loop_label, continue_label) {
207 // `loop { continue; }` or `'a loop { continue; }`
209 // `loop { continue 'a; }`
211 // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
212 (Some(x), Some(y)) => x.ident == y.ident,
216 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
217 /// the AST object representing the loop block of `expr`.
218 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
220 F: FnMut(&ast::Block, Option<&ast::Label>),
222 if let ast::ExprKind::While(_, loop_block, label)
223 | ast::ExprKind::ForLoop(_, _, loop_block, label)
224 | ast::ExprKind::Loop(loop_block, label, ..) = &expr.kind
226 func(loop_block, label.as_ref());
230 /// If `stmt` is an if expression node with an `else` branch, calls func with
234 /// - The `if` expression itself,
235 /// - The `if` condition expression,
236 /// - The `then` block, and
237 /// - The `else` expression.
238 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
240 F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
243 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
244 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.kind {
245 func(e, cond, if_block, else_expr);
252 /// A type to distinguish between the two distinct cases this lint handles.
253 #[derive(Copy, Clone, Debug)]
255 ContinueInsideElseBlock,
256 ContinueInsideThenBlock,
259 /// Data we pass around for construction of help messages.
260 struct LintData<'a> {
261 /// The `if` expression encountered in the above loop.
262 if_expr: &'a ast::Expr,
263 /// The condition expression for the above `if`.
264 if_cond: &'a ast::Expr,
265 /// The `then` block of the `if` statement.
266 if_block: &'a ast::Block,
267 /// The `else` block of the `if` statement.
268 /// Note that we only work with `if` exprs that have an `else` branch.
269 else_expr: &'a ast::Expr,
270 /// The 0-based index of the `if` statement in the containing loop block.
272 /// The statements of the loop block.
273 block_stmts: &'a [ast::Stmt],
276 const MSG_REDUNDANT_CONTINUE_EXPRESSION: &str = "this `continue` expression is redundant";
278 const MSG_REDUNDANT_ELSE_BLOCK: &str = "this `else` block is redundant";
280 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "there is no need for an explicit `else` block for this `if` \
283 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "consider dropping the `else` clause and merging the code that \
284 follows (in the loop) with the `if` block";
286 const DROP_ELSE_BLOCK_MSG: &str = "consider dropping the `else` clause";
288 const DROP_CONTINUE_EXPRESSION_MSG: &str = "consider dropping the `continue` expression";
290 fn emit_warning<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
291 // snip is the whole *help* message that appears after the warning.
292 // message is the warning message.
293 // expr is the expression which the lint warning message refers to.
294 let (snip, message, expr) = match typ {
295 LintType::ContinueInsideElseBlock => (
296 suggestion_snippet_for_continue_inside_else(cx, data),
297 MSG_REDUNDANT_ELSE_BLOCK,
300 LintType::ContinueInsideThenBlock => (
301 suggestion_snippet_for_continue_inside_if(cx, data),
302 MSG_ELSE_BLOCK_NOT_NEEDED,
312 &format!("{}\n{}", header, snip),
316 fn suggestion_snippet_for_continue_inside_if<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
317 let cond_code = snippet(cx, data.if_cond.span, "..");
319 let continue_code = snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span));
321 let else_code = snippet_block(cx, data.else_expr.span, "..", Some(data.if_expr.span));
323 let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
325 "{indent}if {} {}\n{indent}{}",
329 indent = " ".repeat(indent_if),
333 fn suggestion_snippet_for_continue_inside_else<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
334 let cond_code = snippet(cx, data.if_cond.span, "..");
337 let block_code = erode_from_back(&snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span)));
340 // These is the code in the loop block that follows the if/else construction
341 // we are complaining about. We want to pull all of this code into the
342 // `then` block of the `if` statement.
343 let indent = span_of_first_expr_in_block(data.if_block)
344 .and_then(|span| indent_of(cx, span))
346 let to_annex = data.block_stmts[data.stmt_idx + 1..]
348 .map(|stmt| original_sp(stmt.span, DUMMY_SP))
350 let snip = snippet_block(cx, span, "..", None).into_owned();
352 .map(|line| format!("{}{}", " ".repeat(indent), line))
359 let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
361 "{indent_if}if {} {}\n{indent}// merged code follows:\n{}\n{indent_if}}}",
365 indent = " ".repeat(indent),
366 indent_if = " ".repeat(indent_if),
370 fn check_and_warn<'a>(cx: &EarlyContext<'_>, expr: &'a ast::Expr) {
372 if let ast::ExprKind::Loop(loop_block, ..) = &expr.kind;
373 if let Some(last_stmt) = loop_block.stmts.last();
374 if let ast::StmtKind::Expr(inner_expr) | ast::StmtKind::Semi(inner_expr) = &last_stmt.kind;
375 if let ast::ExprKind::Continue(_) = inner_expr.kind;
381 MSG_REDUNDANT_CONTINUE_EXPRESSION,
383 DROP_CONTINUE_EXPRESSION_MSG,
387 with_loop_block(expr, |loop_block, label| {
388 for (i, stmt) in loop_block.stmts.iter().enumerate() {
389 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
390 let data = &LintData {
394 if_block: then_block,
396 block_stmts: &loop_block.stmts,
398 if needless_continue_in_else(else_expr, label) {
402 DROP_ELSE_BLOCK_AND_MERGE_MSG,
403 LintType::ContinueInsideElseBlock,
405 } else if is_first_block_stmt_continue(then_block, label) {
406 emit_warning(cx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
413 /// Eats at `s` from the end till a closing brace `}` is encountered, and then continues eating
414 /// till a non-whitespace character is found. e.g., the string. If no closing `}` is present, the
415 /// string will be preserved.
423 /// is transformed to
430 fn erode_from_back(s: &str) -> String {
431 let mut ret = s.to_string();
432 while ret.pop().map_or(false, |c| c != '}') {}
433 while let Some(c) = ret.pop() {
434 if !c.is_whitespace() {
439 if ret.is_empty() { s.to_string() } else { ret }
442 fn span_of_first_expr_in_block(block: &ast::Block) -> Option<Span> {
443 block.stmts.get(0).map(|stmt| stmt.span)
448 use super::erode_from_back;
452 fn test_erode_from_back() {
456 let y = format!(\"{}\", 42);
462 let y = format!(\"{}\", 42);";
464 let got = erode_from_back(input);
465 assert_eq!(expected, got);
470 fn test_erode_from_back_no_brace() {
475 let expected = input;
476 let got = erode_from_back(input);
477 assert_eq!(expected, got);