1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! Checks for continue statements in loops that are redundant.
13 //! For example, the lint would catch
16 //! while condition() {
17 //! update_condition();
23 //! println!("Hello, world");
27 //! And suggest something like this:
30 //! while condition() {
31 //! update_condition();
34 //! println!("Hello, world");
39 //! This lint is **warn** by default.
40 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
41 use crate::rustc::{declare_tool_lint, lint_array};
42 use crate::syntax::ast;
43 use crate::syntax::source_map::{original_sp, DUMMY_SP};
46 use crate::utils::{in_macro, snippet, snippet_block, span_help_and_lint, trim_multiline};
48 /// **What it does:** The lint checks for `if`-statements appearing in loops
49 /// that contain a `continue` statement in either their main blocks or their
50 /// `else`-blocks, when omitting the `else`-block possibly with some
51 /// rearrangement of code can make the code easier to understand.
53 /// **Why is this bad?** Having explicit `else` blocks for `if` statements
54 /// containing `continue` in their THEN branch adds unnecessary branching and
55 /// nesting to the code. Having an else block containing just `continue` can
56 /// also be better written by grouping the statements following the whole `if`
57 /// statement within the THEN block and omitting the else block completely.
59 /// **Known problems:** None
63 /// while condition() {
64 /// update_condition();
70 /// println!("Hello, world");
74 /// Could be rewritten as
77 /// while condition() {
78 /// update_condition();
81 /// println!("Hello, world");
86 /// As another example, the following code
93 /// // Do something useful
97 /// Could be rewritten as
104 /// // Do something useful
107 declare_clippy_lint! {
108 pub NEEDLESS_CONTINUE,
110 "`continue` statements that can be replaced by a rearrangement of code"
113 #[derive(Copy, Clone)]
114 pub struct NeedlessContinue;
116 impl LintPass for NeedlessContinue {
117 fn get_lints(&self) -> LintArray {
118 lint_array!(NEEDLESS_CONTINUE)
122 impl EarlyLintPass for NeedlessContinue {
123 fn check_expr(&mut self, ctx: &EarlyContext<'_>, expr: &ast::Expr) {
124 if !in_macro(expr.span) {
125 check_and_warn(ctx, expr);
130 /* This lint has to mainly deal with two cases of needless continue
132 // Case 1 [Continue inside else block]:
144 // This code can better be written as follows:
154 // Case 2 [Continue inside then block]:
160 // // potentially more code here.
168 // This snippet can be refactored to:
179 /// Given an expression, returns true if either of the following is true
181 /// - The expression is a `continue` node.
182 /// - The expression node is a block with the first statement being a
185 fn needless_continue_in_else(else_expr: &ast::Expr) -> bool {
186 match else_expr.node {
187 ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block),
188 ast::ExprKind::Continue(_) => true,
193 fn is_first_block_stmt_continue(block: &ast::Block) -> bool {
194 block.stmts.get(0).map_or(false, |stmt| match stmt.node {
195 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => if let ast::ExprKind::Continue(_) = e.node {
204 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
205 /// the AST object representing the loop block of `expr`.
206 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
208 F: FnMut(&ast::Block),
211 ast::ExprKind::While(_, ref loop_block, _) |
212 ast::ExprKind::WhileLet(_, _, ref loop_block, _) |
213 ast::ExprKind::ForLoop(_, _, ref loop_block, _) |
214 ast::ExprKind::Loop(ref loop_block, _) => func(loop_block),
219 /// If `stmt` is an if expression node with an `else` branch, calls func with
223 /// - The `if` expression itself,
224 /// - The `if` condition expression,
225 /// - The `then` block, and
226 /// - The `else` expression.
228 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
230 F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
233 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
234 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
235 func(e, cond, if_block, else_expr);
242 /// A type to distinguish between the two distinct cases this lint handles.
243 #[derive(Copy, Clone, Debug)]
245 ContinueInsideElseBlock,
246 ContinueInsideThenBlock,
249 /// Data we pass around for construction of help messages.
250 struct LintData<'a> {
251 /// The `if` expression encountered in the above loop.
252 if_expr: &'a ast::Expr,
253 /// The condition expression for the above `if`.
254 if_cond: &'a ast::Expr,
255 /// The `then` block of the `if` statement.
256 if_block: &'a ast::Block,
257 /// The `else` block of the `if` statement.
258 /// Note that we only work with `if` exprs that have an `else` branch.
259 else_expr: &'a ast::Expr,
260 /// The 0-based index of the `if` statement in the containing loop block.
262 /// The statements of the loop block.
263 block_stmts: &'a [ast::Stmt],
266 const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";
268 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "There is no need for an explicit `else` block for this `if` \
271 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "Consider dropping the else clause and merging the code that \
272 follows (in the loop) with the if block, like so:\n";
274 const DROP_ELSE_BLOCK_MSG: &str = "Consider dropping the else clause, and moving out the code in the else \
278 fn emit_warning<'a>(ctx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
279 // snip is the whole *help* message that appears after the warning.
280 // message is the warning message.
281 // expr is the expression which the lint warning message refers to.
282 let (snip, message, expr) = match typ {
283 LintType::ContinueInsideElseBlock => (
284 suggestion_snippet_for_continue_inside_else(ctx, data, header),
285 MSG_REDUNDANT_ELSE_BLOCK,
288 LintType::ContinueInsideThenBlock => (
289 suggestion_snippet_for_continue_inside_if(ctx, data, header),
290 MSG_ELSE_BLOCK_NOT_NEEDED,
294 span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
297 fn suggestion_snippet_for_continue_inside_if<'a>(ctx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str) -> String {
298 let cond_code = snippet(ctx, data.if_cond.span, "..");
300 let if_code = format!("if {} {{\n continue;\n}}\n", cond_code);
301 /* ^^^^--- Four spaces of indentation. */
303 let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
304 let else_code = erode_block(&else_code);
305 let else_code = trim_multiline(Cow::from(else_code), false);
307 let mut ret = String::from(header);
308 ret.push_str(&if_code);
309 ret.push_str(&else_code);
310 ret.push_str("\n...");
314 fn suggestion_snippet_for_continue_inside_else<'a>(ctx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str) -> String {
315 let cond_code = snippet(ctx, data.if_cond.span, "..");
316 let mut if_code = format!("if {} {{\n", cond_code);
319 let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
320 let block_code = erode_block(block_code);
321 let block_code = trim_multiline(Cow::from(block_code), false);
323 if_code.push_str(&block_code);
326 // These is the code in the loop block that follows the if/else construction
327 // we are complaining about. We want to pull all of this code into the
328 // `then` block of the `if` statement.
329 let to_annex = data.block_stmts[data.stmt_idx + 1..]
331 .map(|stmt| original_sp(stmt.span, DUMMY_SP))
332 .map(|span| snippet_block(ctx, span, "..").into_owned())
336 let mut ret = String::from(header);
338 ret.push_str(&if_code);
339 ret.push_str("\n// Merged code follows...");
340 ret.push_str(&to_annex);
341 ret.push_str("\n}\n");
345 fn check_and_warn<'a>(ctx: &EarlyContext<'_>, expr: &'a ast::Expr) {
346 with_loop_block(expr, |loop_block| {
347 for (i, stmt) in loop_block.stmts.iter().enumerate() {
348 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
349 let data = &LintData {
353 if_block: then_block,
355 block_stmts: &loop_block.stmts,
357 if needless_continue_in_else(else_expr) {
358 emit_warning(ctx, data, DROP_ELSE_BLOCK_AND_MERGE_MSG, LintType::ContinueInsideElseBlock);
359 } else if is_first_block_stmt_continue(then_block) {
360 emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
367 /// Eats at `s` from the end till a closing brace `}` is encountered, and then
368 /// continues eating till a non-whitespace character is found.
377 /// is transformed to
384 /// NOTE: when there is no closing brace in `s`, `s` is _not_ preserved, i.e.,
385 /// an empty string will be returned in that case.
386 pub fn erode_from_back(s: &str) -> String {
387 let mut ret = String::from(s);
388 while ret.pop().map_or(false, |c| c != '}') {}
389 while let Some(c) = ret.pop() {
390 if !c.is_whitespace() {
398 /// Eats at `s` from the front by first skipping all leading whitespace. Then,
399 /// any number of opening braces are eaten, followed by any number of newlines.
405 /// inside_a_block();
409 /// is transformed to
413 /// inside_a_block();
417 pub fn erode_from_front(s: &str) -> String {
419 .skip_while(|c| c.is_whitespace())
420 .skip_while(|c| *c == '{')
421 .skip_while(|c| *c == '\n')
425 /// If `s` contains the code for a block, delimited by braces, this function
426 /// tries to get the contents of the block. If there is no closing brace
428 /// an empty string is returned.
429 pub fn erode_block(s: &str) -> String {
430 erode_from_back(&erode_from_front(s))