1 //! Checks for continue statements in loops that are redundant.
3 //! For example, the lint would catch
6 //! while condition() {
7 //! update_condition();
13 //! println!("Hello, world");
17 //! And suggest something like this:
20 //! while condition() {
21 //! update_condition();
24 //! println!("Hello, world");
29 //! This lint is **warn** by default.
30 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
31 use rustc::{declare_tool_lint, lint_array};
34 use syntax::source_map::{original_sp, DUMMY_SP};
36 use crate::utils::{in_macro, snippet, snippet_block, span_help_and_lint, trim_multiline};
38 /// **What it does:** The lint checks for `if`-statements appearing in loops
39 /// that contain a `continue` statement in either their main blocks or their
40 /// `else`-blocks, when omitting the `else`-block possibly with some
41 /// rearrangement of code can make the code easier to understand.
43 /// **Why is this bad?** Having explicit `else` blocks for `if` statements
44 /// containing `continue` in their THEN branch adds unnecessary branching and
45 /// nesting to the code. Having an else block containing just `continue` can
46 /// also be better written by grouping the statements following the whole `if`
47 /// statement within the THEN block and omitting the else block completely.
49 /// **Known problems:** None
53 /// while condition() {
54 /// update_condition();
60 /// println!("Hello, world");
64 /// Could be rewritten as
67 /// while condition() {
68 /// update_condition();
71 /// println!("Hello, world");
76 /// As another example, the following code
83 /// // Do something useful
87 /// Could be rewritten as
94 /// // Do something useful
97 declare_clippy_lint! {
98 pub NEEDLESS_CONTINUE,
100 "`continue` statements that can be replaced by a rearrangement of code"
103 #[derive(Copy, Clone)]
104 pub struct NeedlessContinue;
106 impl LintPass for NeedlessContinue {
107 fn get_lints(&self) -> LintArray {
108 lint_array!(NEEDLESS_CONTINUE)
111 fn name(&self) -> &'static str {
116 impl EarlyLintPass for NeedlessContinue {
117 fn check_expr(&mut self, ctx: &EarlyContext<'_>, expr: &ast::Expr) {
118 if !in_macro(expr.span) {
119 check_and_warn(ctx, expr);
124 /* This lint has to mainly deal with two cases of needless continue
126 // Case 1 [Continue inside else block]:
138 // This code can better be written as follows:
148 // Case 2 [Continue inside then block]:
154 // // potentially more code here.
162 // This snippet can be refactored to:
173 /// Given an expression, returns true if either of the following is true
175 /// - The expression is a `continue` node.
176 /// - The expression node is a block with the first statement being a
178 fn needless_continue_in_else(else_expr: &ast::Expr) -> bool {
179 match else_expr.node {
180 ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block),
181 ast::ExprKind::Continue(_) => true,
186 fn is_first_block_stmt_continue(block: &ast::Block) -> bool {
187 block.stmts.get(0).map_or(false, |stmt| match stmt.node {
188 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
189 if let ast::ExprKind::Continue(_) = e.node {
199 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
200 /// the AST object representing the loop block of `expr`.
201 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
203 F: FnMut(&ast::Block),
206 ast::ExprKind::While(_, ref loop_block, _)
207 | ast::ExprKind::WhileLet(_, _, ref loop_block, _)
208 | ast::ExprKind::ForLoop(_, _, ref loop_block, _)
209 | ast::ExprKind::Loop(ref loop_block, _) => func(loop_block),
214 /// If `stmt` is an if expression node with an `else` branch, calls func with
218 /// - The `if` expression itself,
219 /// - The `if` condition expression,
220 /// - The `then` block, and
221 /// - The `else` expression.
222 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
224 F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
227 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
228 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
229 func(e, cond, if_block, else_expr);
236 /// A type to distinguish between the two distinct cases this lint handles.
237 #[derive(Copy, Clone, Debug)]
239 ContinueInsideElseBlock,
240 ContinueInsideThenBlock,
243 /// Data we pass around for construction of help messages.
244 struct LintData<'a> {
245 /// The `if` expression encountered in the above loop.
246 if_expr: &'a ast::Expr,
247 /// The condition expression for the above `if`.
248 if_cond: &'a ast::Expr,
249 /// The `then` block of the `if` statement.
250 if_block: &'a ast::Block,
251 /// The `else` block of the `if` statement.
252 /// Note that we only work with `if` exprs that have an `else` branch.
253 else_expr: &'a ast::Expr,
254 /// The 0-based index of the `if` statement in the containing loop block.
256 /// The statements of the loop block.
257 block_stmts: &'a [ast::Stmt],
260 const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";
262 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "There is no need for an explicit `else` block for this `if` \
265 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "Consider dropping the else clause and merging the code that \
266 follows (in the loop) with the if block, like so:\n";
268 const DROP_ELSE_BLOCK_MSG: &str = "Consider dropping the else clause, and moving out the code in the else \
271 fn emit_warning<'a>(ctx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
272 // snip is the whole *help* message that appears after the warning.
273 // message is the warning message.
274 // expr is the expression which the lint warning message refers to.
275 let (snip, message, expr) = match typ {
276 LintType::ContinueInsideElseBlock => (
277 suggestion_snippet_for_continue_inside_else(ctx, data, header),
278 MSG_REDUNDANT_ELSE_BLOCK,
281 LintType::ContinueInsideThenBlock => (
282 suggestion_snippet_for_continue_inside_if(ctx, data, header),
283 MSG_ELSE_BLOCK_NOT_NEEDED,
287 span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
290 fn suggestion_snippet_for_continue_inside_if<'a>(
291 ctx: &EarlyContext<'_>,
292 data: &'a LintData<'_>,
295 let cond_code = snippet(ctx, data.if_cond.span, "..");
297 let if_code = format!("if {} {{\n continue;\n}}\n", cond_code);
298 /* ^^^^--- Four spaces of indentation. */
300 let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
301 let else_code = erode_block(&else_code);
302 let else_code = trim_multiline(Cow::from(else_code), false);
304 let mut ret = String::from(header);
305 ret.push_str(&if_code);
306 ret.push_str(&else_code);
307 ret.push_str("\n...");
311 fn suggestion_snippet_for_continue_inside_else<'a>(
312 ctx: &EarlyContext<'_>,
313 data: &'a LintData<'_>,
316 let cond_code = snippet(ctx, data.if_cond.span, "..");
317 let mut if_code = format!("if {} {{\n", cond_code);
320 let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
321 let block_code = erode_block(block_code);
322 let block_code = trim_multiline(Cow::from(block_code), false);
324 if_code.push_str(&block_code);
327 // These is the code in the loop block that follows the if/else construction
328 // we are complaining about. We want to pull all of this code into the
329 // `then` block of the `if` statement.
330 let to_annex = data.block_stmts[data.stmt_idx + 1..]
332 .map(|stmt| original_sp(stmt.span, DUMMY_SP))
333 .map(|span| snippet_block(ctx, span, "..").into_owned())
337 let mut ret = String::from(header);
339 ret.push_str(&if_code);
340 ret.push_str("\n// Merged code follows...");
341 ret.push_str(&to_annex);
342 ret.push_str("\n}\n");
346 fn check_and_warn<'a>(ctx: &EarlyContext<'_>, expr: &'a ast::Expr) {
347 with_loop_block(expr, |loop_block| {
348 for (i, stmt) in loop_block.stmts.iter().enumerate() {
349 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
350 let data = &LintData {
354 if_block: then_block,
356 block_stmts: &loop_block.stmts,
358 if needless_continue_in_else(else_expr) {
362 DROP_ELSE_BLOCK_AND_MERGE_MSG,
363 LintType::ContinueInsideElseBlock,
365 } else if is_first_block_stmt_continue(then_block) {
366 emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
373 /// Eats at `s` from the end till a closing brace `}` is encountered, and then
374 /// continues eating till a non-whitespace character is found.
383 /// is transformed to
390 /// NOTE: when there is no closing brace in `s`, `s` is _not_ preserved, i.e.,
391 /// an empty string will be returned in that case.
392 pub fn erode_from_back(s: &str) -> String {
393 let mut ret = String::from(s);
394 while ret.pop().map_or(false, |c| c != '}') {}
395 while let Some(c) = ret.pop() {
396 if !c.is_whitespace() {
404 /// Eats at `s` from the front by first skipping all leading whitespace. Then,
405 /// any number of opening braces are eaten, followed by any number of newlines.
411 /// inside_a_block();
415 /// is transformed to
419 /// inside_a_block();
422 pub fn erode_from_front(s: &str) -> String {
424 .skip_while(|c| c.is_whitespace())
425 .skip_while(|c| *c == '{')
426 .skip_while(|c| *c == '\n')
430 /// If `s` contains the code for a block, delimited by braces, this function
431 /// tries to get the contents of the block. If there is no closing brace
433 /// an empty string is returned.
434 pub fn erode_block(s: &str) -> String {
435 erode_from_back(&erode_from_front(s))