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::declare_lint_pass;
37 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
38 use rustc_session::declare_tool_lint;
41 use syntax::source_map::{original_sp, DUMMY_SP};
43 use crate::utils::{snippet, snippet_block, span_help_and_lint, trim_multiline};
45 declare_clippy_lint! {
46 /// **What it does:** 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?** 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.
57 /// **Known problems:** None
61 /// # fn condition() -> bool { false }
62 /// # fn update_condition() {}
64 /// while condition() {
65 /// update_condition();
71 /// println!("Hello, world");
75 /// Could be rewritten as
78 /// # fn condition() -> bool { false }
79 /// # fn update_condition() {}
81 /// while condition() {
82 /// update_condition();
85 /// println!("Hello, world");
90 /// As another example, the following code
93 /// # fn waiting() -> bool { false }
98 /// // Do something useful
103 /// Could be rewritten as
106 /// # fn waiting() -> bool { false }
111 /// // Do something useful
115 pub NEEDLESS_CONTINUE,
117 "`continue` statements that can be replaced by a rearrangement of code"
120 declare_lint_pass!(NeedlessContinue => [NEEDLESS_CONTINUE]);
122 impl EarlyLintPass for NeedlessContinue {
123 fn check_expr(&mut self, ctx: &EarlyContext<'_>, expr: &ast::Expr) {
124 if !expr.span.from_expansion() {
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
184 fn needless_continue_in_else(else_expr: &ast::Expr, label: Option<&ast::Label>) -> bool {
185 match else_expr.kind {
186 ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block, label),
187 ast::ExprKind::Continue(l) => compare_labels(label, l.as_ref()),
192 fn is_first_block_stmt_continue(block: &ast::Block, label: Option<&ast::Label>) -> bool {
193 block.stmts.get(0).map_or(false, |stmt| match stmt.kind {
194 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
195 if let ast::ExprKind::Continue(ref l) = e.kind {
196 compare_labels(label, l.as_ref())
205 /// If the `continue` has a label, check it matches the label of the loop.
206 fn compare_labels(loop_label: Option<&ast::Label>, continue_label: Option<&ast::Label>) -> bool {
207 match (loop_label, continue_label) {
208 // `loop { continue; }` or `'a loop { continue; }`
210 // `loop { continue 'a; }`
212 // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
213 (Some(x), Some(y)) => x.ident == y.ident,
217 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
218 /// the AST object representing the loop block of `expr`.
219 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
221 F: FnMut(&ast::Block, Option<&ast::Label>),
223 if let ast::ExprKind::While(_, loop_block, label)
224 | ast::ExprKind::ForLoop(_, _, loop_block, label)
225 | ast::ExprKind::Loop(loop_block, label) = &expr.kind
227 func(loop_block, label.as_ref());
231 /// If `stmt` is an if expression node with an `else` branch, calls func with
235 /// - The `if` expression itself,
236 /// - The `if` condition expression,
237 /// - The `then` block, and
238 /// - The `else` expression.
239 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
241 F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
244 ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
245 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.kind {
246 func(e, cond, if_block, else_expr);
253 /// A type to distinguish between the two distinct cases this lint handles.
254 #[derive(Copy, Clone, Debug)]
256 ContinueInsideElseBlock,
257 ContinueInsideThenBlock,
260 /// Data we pass around for construction of help messages.
261 struct LintData<'a> {
262 /// The `if` expression encountered in the above loop.
263 if_expr: &'a ast::Expr,
264 /// The condition expression for the above `if`.
265 if_cond: &'a ast::Expr,
266 /// The `then` block of the `if` statement.
267 if_block: &'a ast::Block,
268 /// The `else` block of the `if` statement.
269 /// Note that we only work with `if` exprs that have an `else` branch.
270 else_expr: &'a ast::Expr,
271 /// The 0-based index of the `if` statement in the containing loop block.
273 /// The statements of the loop block.
274 block_stmts: &'a [ast::Stmt],
277 const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";
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, like so:\n";
285 const DROP_ELSE_BLOCK_MSG: &str = "Consider dropping the else clause, and moving out the code in the else \
288 fn emit_warning<'a>(ctx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
289 // snip is the whole *help* message that appears after the warning.
290 // message is the warning message.
291 // expr is the expression which the lint warning message refers to.
292 let (snip, message, expr) = match typ {
293 LintType::ContinueInsideElseBlock => (
294 suggestion_snippet_for_continue_inside_else(ctx, data, header),
295 MSG_REDUNDANT_ELSE_BLOCK,
298 LintType::ContinueInsideThenBlock => (
299 suggestion_snippet_for_continue_inside_if(ctx, data, header),
300 MSG_ELSE_BLOCK_NOT_NEEDED,
304 span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
307 fn suggestion_snippet_for_continue_inside_if<'a>(
308 ctx: &EarlyContext<'_>,
309 data: &'a LintData<'_>,
312 let cond_code = snippet(ctx, data.if_cond.span, "..");
314 let if_code = format!("if {} {{\n continue;\n}}\n", cond_code);
315 /* ^^^^--- Four spaces of indentation. */
317 let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
318 let else_code = erode_block(&else_code);
319 let else_code = trim_multiline(Cow::from(else_code), false);
321 let mut ret = String::from(header);
322 ret.push_str(&if_code);
323 ret.push_str(&else_code);
324 ret.push_str("\n...");
328 fn suggestion_snippet_for_continue_inside_else<'a>(
329 ctx: &EarlyContext<'_>,
330 data: &'a LintData<'_>,
333 let cond_code = snippet(ctx, data.if_cond.span, "..");
334 let mut if_code = format!("if {} {{\n", cond_code);
337 let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
338 let block_code = erode_block(block_code);
339 let block_code = trim_multiline(Cow::from(block_code), false);
341 if_code.push_str(&block_code);
344 // These is the code in the loop block that follows the if/else construction
345 // we are complaining about. We want to pull all of this code into the
346 // `then` block of the `if` statement.
347 let to_annex = data.block_stmts[data.stmt_idx + 1..]
349 .map(|stmt| original_sp(stmt.span, DUMMY_SP))
350 .map(|span| snippet_block(ctx, span, "..").into_owned())
354 let mut ret = String::from(header);
356 ret.push_str(&if_code);
357 ret.push_str("\n// Merged code follows...");
358 ret.push_str(&to_annex);
359 ret.push_str("\n}\n");
363 fn check_and_warn<'a>(ctx: &EarlyContext<'_>, expr: &'a ast::Expr) {
364 with_loop_block(expr, |loop_block, label| {
365 for (i, stmt) in loop_block.stmts.iter().enumerate() {
366 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
367 let data = &LintData {
371 if_block: then_block,
373 block_stmts: &loop_block.stmts,
375 if needless_continue_in_else(else_expr, label) {
379 DROP_ELSE_BLOCK_AND_MERGE_MSG,
380 LintType::ContinueInsideElseBlock,
382 } else if is_first_block_stmt_continue(then_block, label) {
383 emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
390 /// Eats at `s` from the end till a closing brace `}` is encountered, and then
391 /// continues eating till a non-whitespace character is found.
400 /// is transformed to
407 /// NOTE: when there is no closing brace in `s`, `s` is _not_ preserved, i.e.,
408 /// an empty string will be returned in that case.
410 pub fn erode_from_back(s: &str) -> String {
411 let mut ret = String::from(s);
412 while ret.pop().map_or(false, |c| c != '}') {}
413 while let Some(c) = ret.pop() {
414 if !c.is_whitespace() {
422 /// Eats at `s` from the front by first skipping all leading whitespace. Then,
423 /// any number of opening braces are eaten, followed by any number of newlines.
429 /// inside_a_block();
433 /// is transformed to
437 /// inside_a_block();
441 pub fn erode_from_front(s: &str) -> String {
443 .skip_while(|c| c.is_whitespace())
444 .skip_while(|c| *c == '{')
445 .skip_while(|c| *c == '\n')
449 /// If `s` contains the code for a block, delimited by braces, this function
450 /// tries to get the contents of the block. If there is no closing brace
452 /// an empty string is returned.
454 pub fn erode_block(s: &str) -> String {
455 erode_from_back(&erode_from_front(s))