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 rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
37 use rustc::{declare_lint_pass, declare_tool_lint};
40 use syntax::source_map::{original_sp, DUMMY_SP};
42 use crate::utils::{in_macro_or_desugar, snippet, snippet_block, span_help_and_lint, trim_multiline};
44 declare_clippy_lint! {
45 /// **What it does:** 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?** Having explicit `else` blocks for `if` statements
51 /// containing `continue` in their THEN branch adds unnecessary branching and
52 /// nesting to the code. Having an else block containing just `continue` can
53 /// also be better written by grouping the statements following the whole `if`
54 /// statement within the THEN block and omitting the else block completely.
56 /// **Known problems:** None
60 /// while condition() {
61 /// update_condition();
67 /// println!("Hello, world");
71 /// Could be rewritten as
74 /// while condition() {
75 /// update_condition();
78 /// println!("Hello, world");
83 /// As another example, the following code
90 /// // Do something useful
94 /// Could be rewritten as
101 /// // Do something useful
104 pub NEEDLESS_CONTINUE,
106 "`continue` statements that can be replaced by a rearrangement of code"
109 declare_lint_pass!(NeedlessContinue => [NEEDLESS_CONTINUE]);
111 impl EarlyLintPass for NeedlessContinue {
112 fn check_expr(&mut self, ctx: &EarlyContext<'_>, expr: &ast::Expr) {
113 if !in_macro_or_desugar(expr.span) {
114 check_and_warn(ctx, expr);
119 /* This lint has to mainly deal with two cases of needless continue
121 // Case 1 [Continue inside else block]:
133 // This code can better be written as follows:
143 // Case 2 [Continue inside then block]:
149 // // potentially more code here.
157 // This snippet can be refactored to:
168 /// Given an expression, returns true if either of the following is true
170 /// - The expression is a `continue` node.
171 /// - The expression node is a block with the first statement being a
173 fn needless_continue_in_else(else_expr: &ast::Expr, label: Option<&ast::Label>) -> bool {
174 match else_expr.node {
175 ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block, label),
176 ast::ExprKind::Continue(l) => compare_labels(label, l.as_ref()),
181 fn is_first_block_stmt_continue(block: &ast::Block, label: Option<&ast::Label>) -> bool {
182 block.stmts.get(0).map_or(false, |stmt| match stmt.node {
183 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
184 if let ast::ExprKind::Continue(ref l) = e.node {
185 compare_labels(label, l.as_ref())
194 /// If the `continue` has a label, check it matches the label of the loop.
195 fn compare_labels(loop_label: Option<&ast::Label>, continue_label: Option<&ast::Label>) -> bool {
196 match (loop_label, continue_label) {
197 // `loop { continue; }` or `'a loop { continue; }`
199 // `loop { continue 'a; }`
201 // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
202 (Some(x), Some(y)) => x.ident == y.ident,
206 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
207 /// the AST object representing the loop block of `expr`.
208 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
210 F: FnMut(&ast::Block, Option<&ast::Label>),
213 ast::ExprKind::While(_, ref loop_block, ref label)
214 | ast::ExprKind::WhileLet(_, _, ref loop_block, ref label)
215 | ast::ExprKind::ForLoop(_, _, ref loop_block, ref label)
216 | ast::ExprKind::Loop(ref loop_block, ref label) => func(loop_block, label.as_ref()),
221 /// If `stmt` is an if expression node with an `else` branch, calls func with
225 /// - The `if` expression itself,
226 /// - The `if` condition expression,
227 /// - The `then` block, and
228 /// - The `else` expression.
229 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
231 F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
234 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
235 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
236 func(e, cond, if_block, else_expr);
243 /// A type to distinguish between the two distinct cases this lint handles.
244 #[derive(Copy, Clone, Debug)]
246 ContinueInsideElseBlock,
247 ContinueInsideThenBlock,
250 /// Data we pass around for construction of help messages.
251 struct LintData<'a> {
252 /// The `if` expression encountered in the above loop.
253 if_expr: &'a ast::Expr,
254 /// The condition expression for the above `if`.
255 if_cond: &'a ast::Expr,
256 /// The `then` block of the `if` statement.
257 if_block: &'a ast::Block,
258 /// The `else` block of the `if` statement.
259 /// Note that we only work with `if` exprs that have an `else` branch.
260 else_expr: &'a ast::Expr,
261 /// The 0-based index of the `if` statement in the containing loop block.
263 /// The statements of the loop block.
264 block_stmts: &'a [ast::Stmt],
267 const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";
269 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "There is no need for an explicit `else` block for this `if` \
272 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "Consider dropping the else clause and merging the code that \
273 follows (in the loop) with the if block, like so:\n";
275 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>(
298 ctx: &EarlyContext<'_>,
299 data: &'a LintData<'_>,
302 let cond_code = snippet(ctx, data.if_cond.span, "..");
304 let if_code = format!("if {} {{\n continue;\n}}\n", cond_code);
305 /* ^^^^--- Four spaces of indentation. */
307 let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
308 let else_code = erode_block(&else_code);
309 let else_code = trim_multiline(Cow::from(else_code), false);
311 let mut ret = String::from(header);
312 ret.push_str(&if_code);
313 ret.push_str(&else_code);
314 ret.push_str("\n...");
318 fn suggestion_snippet_for_continue_inside_else<'a>(
319 ctx: &EarlyContext<'_>,
320 data: &'a LintData<'_>,
323 let cond_code = snippet(ctx, data.if_cond.span, "..");
324 let mut if_code = format!("if {} {{\n", cond_code);
327 let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
328 let block_code = erode_block(block_code);
329 let block_code = trim_multiline(Cow::from(block_code), false);
331 if_code.push_str(&block_code);
334 // These is the code in the loop block that follows the if/else construction
335 // we are complaining about. We want to pull all of this code into the
336 // `then` block of the `if` statement.
337 let to_annex = data.block_stmts[data.stmt_idx + 1..]
339 .map(|stmt| original_sp(stmt.span, DUMMY_SP))
340 .map(|span| snippet_block(ctx, span, "..").into_owned())
344 let mut ret = String::from(header);
346 ret.push_str(&if_code);
347 ret.push_str("\n// Merged code follows...");
348 ret.push_str(&to_annex);
349 ret.push_str("\n}\n");
353 fn check_and_warn<'a>(ctx: &EarlyContext<'_>, expr: &'a ast::Expr) {
354 with_loop_block(expr, |loop_block, label| {
355 for (i, stmt) in loop_block.stmts.iter().enumerate() {
356 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
357 let data = &LintData {
361 if_block: then_block,
363 block_stmts: &loop_block.stmts,
365 if needless_continue_in_else(else_expr, label) {
369 DROP_ELSE_BLOCK_AND_MERGE_MSG,
370 LintType::ContinueInsideElseBlock,
372 } else if is_first_block_stmt_continue(then_block, label) {
373 emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
380 /// Eats at `s` from the end till a closing brace `}` is encountered, and then
381 /// continues eating till a non-whitespace character is found.
390 /// is transformed to
397 /// NOTE: when there is no closing brace in `s`, `s` is _not_ preserved, i.e.,
398 /// an empty string will be returned in that case.
399 pub fn erode_from_back(s: &str) -> String {
400 let mut ret = String::from(s);
401 while ret.pop().map_or(false, |c| c != '}') {}
402 while let Some(c) = ret.pop() {
403 if !c.is_whitespace() {
411 /// Eats at `s` from the front by first skipping all leading whitespace. Then,
412 /// any number of opening braces are eaten, followed by any number of newlines.
418 /// inside_a_block();
422 /// is transformed to
426 /// inside_a_block();
429 pub fn erode_from_front(s: &str) -> String {
431 .skip_while(|c| c.is_whitespace())
432 .skip_while(|c| *c == '{')
433 .skip_while(|c| *c == '\n')
437 /// If `s` contains the code for a block, delimited by braces, this function
438 /// tries to get the contents of the block. If there is no closing brace
440 /// an empty string is returned.
441 pub fn erode_block(s: &str) -> String {
442 erode_from_back(&erode_from_front(s))