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, LintContext};
40 use rustc_session::{declare_lint_pass, declare_tool_lint};
43 declare_clippy_lint! {
45 /// The lint checks for `if`-statements appearing in loops
46 /// that contain a `continue` statement in either their main blocks or their
47 /// `else`-blocks, when omitting the `else`-block possibly with some
48 /// rearrangement of code can make the code easier to understand.
50 /// ### Why is this bad?
51 /// Having explicit `else` blocks for `if` statements
52 /// containing `continue` in their THEN branch adds unnecessary branching and
53 /// nesting to the code. Having an else block containing just `continue` can
54 /// also be better written by grouping the statements following the whole `if`
55 /// statement within the THEN block and omitting the else block completely.
59 /// # fn condition() -> bool { false }
60 /// # fn update_condition() {}
62 /// while condition() {
63 /// update_condition();
69 /// println!("Hello, world");
73 /// Could be rewritten as
76 /// # fn condition() -> bool { false }
77 /// # fn update_condition() {}
79 /// while condition() {
80 /// update_condition();
83 /// println!("Hello, world");
88 /// As another example, the following code
91 /// # fn waiting() -> bool { false }
96 /// // Do something useful
101 /// Could be rewritten as
104 /// # fn waiting() -> bool { false }
109 /// // Do something useful
113 pub NEEDLESS_CONTINUE,
115 "`continue` statements that can be replaced by a rearrangement of code"
118 declare_lint_pass!(NeedlessContinue => [NEEDLESS_CONTINUE]);
120 impl EarlyLintPass for NeedlessContinue {
121 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
122 if !expr.span.from_expansion() {
123 check_and_warn(cx, expr);
128 /* This lint has to mainly deal with two cases of needless continue
130 // Case 1 [Continue inside else block]:
142 // This code can better be written as follows:
152 // Case 2 [Continue inside then block]:
158 // // potentially more code here.
166 // This snippet can be refactored to:
177 /// Given an expression, returns true if either of the following is true
179 /// - The expression is a `continue` node.
180 /// - The expression node is a block with the first statement being a
182 fn needless_continue_in_else(else_expr: &ast::Expr, label: Option<&ast::Label>) -> bool {
183 match else_expr.kind {
184 ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block, label),
185 ast::ExprKind::Continue(l) => compare_labels(label, l.as_ref()),
190 fn is_first_block_stmt_continue(block: &ast::Block, label: Option<&ast::Label>) -> bool {
191 block.stmts.get(0).map_or(false, |stmt| match stmt.kind {
192 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
193 if let ast::ExprKind::Continue(ref l) = e.kind {
194 compare_labels(label, l.as_ref())
203 /// If the `continue` has a label, check it matches the label of the loop.
204 fn compare_labels(loop_label: Option<&ast::Label>, continue_label: Option<&ast::Label>) -> bool {
205 match (loop_label, continue_label) {
206 // `loop { continue; }` or `'a loop { continue; }`
208 // `loop { continue 'a; }`
210 // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
211 (Some(x), Some(y)) => x.ident == y.ident,
215 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
216 /// the AST object representing the loop block of `expr`.
217 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
219 F: FnMut(&ast::Block, Option<&ast::Label>),
221 if let ast::ExprKind::While(_, loop_block, label)
222 | ast::ExprKind::ForLoop(_, _, loop_block, label)
223 | ast::ExprKind::Loop(loop_block, label, ..) = &expr.kind
225 func(loop_block, label.as_ref());
229 /// If `stmt` is an if expression node with an `else` branch, calls func with
233 /// - The `if` expression itself,
234 /// - The `if` condition expression,
235 /// - The `then` block, and
236 /// - The `else` expression.
237 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
239 F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
242 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
243 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.kind {
244 func(e, cond, if_block, else_expr);
251 /// A type to distinguish between the two distinct cases this lint handles.
252 #[derive(Copy, Clone, Debug)]
254 ContinueInsideElseBlock,
255 ContinueInsideThenBlock,
258 /// Data we pass around for construction of help messages.
259 struct LintData<'a> {
260 /// The `if` expression encountered in the above loop.
261 if_expr: &'a ast::Expr,
262 /// The condition expression for the above `if`.
263 if_cond: &'a ast::Expr,
264 /// The `then` block of the `if` statement.
265 if_block: &'a ast::Block,
266 /// The `else` block of the `if` statement.
267 /// Note that we only work with `if` exprs that have an `else` branch.
268 else_expr: &'a ast::Expr,
269 /// The 0-based index of the `if` statement in the containing loop block.
271 /// The statements of the loop block.
272 loop_block: &'a ast::Block,
275 const MSG_REDUNDANT_CONTINUE_EXPRESSION: &str = "this `continue` expression is redundant";
277 const MSG_REDUNDANT_ELSE_BLOCK: &str = "this `else` block is redundant";
279 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "there is no need for an explicit `else` block for this `if` \
282 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "consider dropping the `else` clause and merging the code that \
283 follows (in the loop) with the `if` block";
285 const DROP_ELSE_BLOCK_MSG: &str = "consider dropping the `else` clause";
287 const DROP_CONTINUE_EXPRESSION_MSG: &str = "consider dropping the `continue` expression";
289 fn emit_warning<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
290 // snip is the whole *help* message that appears after the warning.
291 // message is the warning message.
292 // expr is the expression which the lint warning message refers to.
293 let (snip, message, expr) = match typ {
294 LintType::ContinueInsideElseBlock => (
295 suggestion_snippet_for_continue_inside_else(cx, data),
296 MSG_REDUNDANT_ELSE_BLOCK,
299 LintType::ContinueInsideThenBlock => (
300 suggestion_snippet_for_continue_inside_if(cx, data),
301 MSG_ELSE_BLOCK_NOT_NEEDED,
311 &format!("{}\n{}", header, snip),
315 fn suggestion_snippet_for_continue_inside_if<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
316 let cond_code = snippet(cx, data.if_cond.span, "..");
318 let continue_code = snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span));
320 let else_code = snippet_block(cx, data.else_expr.span, "..", Some(data.if_expr.span));
322 let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
324 "{indent}if {} {}\n{indent}{}",
328 indent = " ".repeat(indent_if),
332 fn suggestion_snippet_for_continue_inside_else<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
333 let cond_code = snippet(cx, data.if_cond.span, "..");
336 let block_code = erode_from_back(&snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span)));
339 // These is the code in the loop block that follows the if/else construction
340 // we are complaining about. We want to pull all of this code into the
341 // `then` block of the `if` statement.
342 let indent = span_of_first_expr_in_block(data.if_block)
343 .and_then(|span| indent_of(cx, span))
345 let to_annex = data.loop_block.stmts[data.stmt_idx + 1..]
348 let span = cx.sess().source_map().stmt_span(stmt.span, data.loop_block.span);
349 let snip = snippet_block(cx, span, "..", None).into_owned();
351 .map(|line| format!("{}{}", " ".repeat(indent), line))
358 let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
360 "{indent_if}if {} {}\n{indent}// merged code follows:\n{}\n{indent_if}}}",
364 indent = " ".repeat(indent),
365 indent_if = " ".repeat(indent_if),
369 fn check_and_warn<'a>(cx: &EarlyContext<'_>, expr: &'a ast::Expr) {
371 if let ast::ExprKind::Loop(loop_block, ..) = &expr.kind;
372 if let Some(last_stmt) = loop_block.stmts.last();
373 if let ast::StmtKind::Expr(inner_expr) | ast::StmtKind::Semi(inner_expr) = &last_stmt.kind;
374 if let ast::ExprKind::Continue(_) = inner_expr.kind;
380 MSG_REDUNDANT_CONTINUE_EXPRESSION,
382 DROP_CONTINUE_EXPRESSION_MSG,
386 with_loop_block(expr, |loop_block, label| {
387 for (i, stmt) in loop_block.stmts.iter().enumerate() {
388 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
389 let data = &LintData {
393 if_block: then_block,
397 if needless_continue_in_else(else_expr, label) {
401 DROP_ELSE_BLOCK_AND_MERGE_MSG,
402 LintType::ContinueInsideElseBlock,
404 } else if is_first_block_stmt_continue(then_block, label) {
405 emit_warning(cx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
412 /// Eats at `s` from the end till a closing brace `}` is encountered, and then continues eating
413 /// till a non-whitespace character is found. e.g., the string. If no closing `}` is present, the
414 /// string will be preserved.
422 /// is transformed to
429 fn erode_from_back(s: &str) -> String {
430 let mut ret = s.to_string();
431 while ret.pop().map_or(false, |c| c != '}') {}
432 while let Some(c) = ret.pop() {
433 if !c.is_whitespace() {
438 if ret.is_empty() { s.to_string() } else { ret }
441 fn span_of_first_expr_in_block(block: &ast::Block) -> Option<Span> {
442 block.stmts.get(0).map(|stmt| stmt.span)
447 use super::erode_from_back;
451 fn test_erode_from_back() {
455 let y = format!(\"{}\", 42);
461 let y = format!(\"{}\", 42);";
463 let got = erode_from_back(input);
464 assert_eq!(expected, got);
469 fn test_erode_from_back_no_brace() {
474 let expected = input;
475 let got = erode_from_back(input);
476 assert_eq!(expected, got);