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.
32 use syntax::codemap::{original_sp, DUMMY_SP};
35 use utils::{in_macro, span_help_and_lint, snippet_block, snippet, trim_multiline};
37 /// **What it does:** The lint checks for `if`-statements appearing in loops
38 /// that contain a `continue` statement in either their main blocks or their
39 /// `else`-blocks, when omitting the `else`-block possibly with some
40 /// rearrangement of code can make the code easier to understand.
42 /// **Why is this bad?** Having explicit `else` blocks for `if` statements
43 /// containing `continue` in their THEN branch adds unnecessary branching and
44 /// nesting to the code. Having an else block containing just `continue` can
45 /// also be better written by grouping the statements following the whole `if`
46 /// statement within the THEN block and omitting the else block completely.
48 /// **Known problems:** None
52 /// while condition() {
53 /// update_condition();
59 /// println!("Hello, world");
63 /// Could be rewritten as
66 /// while condition() {
67 /// update_condition();
70 /// println!("Hello, world");
75 /// As another example, the following code
82 /// // Do something useful
86 /// Could be rewritten as
93 /// // Do something useful
97 pub NEEDLESS_CONTINUE,
99 "`continue` statements that can be replaced by a rearrangement of code"
102 #[derive(Copy,Clone)]
103 pub struct NeedlessContinue;
105 impl LintPass for NeedlessContinue {
106 fn get_lints(&self) -> LintArray {
107 lint_array!(NEEDLESS_CONTINUE)
111 impl EarlyLintPass for NeedlessContinue {
112 fn check_expr(&mut self, ctx: &EarlyContext, expr: &ast::Expr) {
113 if !in_macro(expr.span) {
114 check_and_warn(ctx, expr);
119 /* This lint has to mainly deal with two cases of needless continue statements.
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 `continue`.
173 fn needless_continue_in_else(else_expr: &ast::Expr) -> bool {
174 match else_expr.node {
175 ast::ExprKind::Block(ref else_block) => is_first_block_stmt_continue(else_block),
176 ast::ExprKind::Continue(_) => true,
181 fn is_first_block_stmt_continue(block: &ast::Block) -> bool {
182 block.stmts.get(0).map_or(false, |stmt| match stmt.node {
183 ast::StmtKind::Semi(ref e) |
184 ast::StmtKind::Expr(ref e) => {
185 if let ast::ExprKind::Continue(_) = e.node {
195 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
196 /// the AST object representing the loop block of `expr`.
197 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
198 where F: FnMut(&ast::Block)
201 ast::ExprKind::While(_, ref loop_block, _) |
202 ast::ExprKind::WhileLet(_, _, ref loop_block, _) |
203 ast::ExprKind::ForLoop(_, _, ref loop_block, _) |
204 ast::ExprKind::Loop(ref loop_block, _) => func(loop_block),
209 /// If `stmt` is an if expression node with an `else` branch, calls func with the
212 /// - The `if` expression itself,
213 /// - The `if` condition expression,
214 /// - The `then` block, and
215 /// - The `else` expression.
217 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
218 where F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr)
221 ast::StmtKind::Semi(ref e) |
222 ast::StmtKind::Expr(ref e) => {
223 if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
224 func(e, cond, if_block, else_expr);
231 /// A type to distinguish between the two distinct cases this lint handles.
232 #[derive(Copy, Clone, Debug)]
234 ContinueInsideElseBlock,
235 ContinueInsideThenBlock,
238 /// Data we pass around for construction of help messages.
239 struct LintData<'a> {
240 /// The `if` expression encountered in the above loop.
241 if_expr: &'a ast::Expr,
242 /// The condition expression for the above `if`.
243 if_cond: &'a ast::Expr,
244 /// The `then` block of the `if` statement.
245 if_block: &'a ast::Block,
246 /// The `else` block of the `if` statement.
247 /// Note that we only work with `if` exprs that have an `else` branch.
248 else_expr: &'a ast::Expr,
249 /// The 0-based index of the `if` statement in the containing loop block.
251 /// The statements of the loop block.
252 block_stmts: &'a [ast::Stmt],
255 const MSG_REDUNDANT_ELSE_BLOCK: &'static str = "This else block is redundant.\n";
257 const MSG_ELSE_BLOCK_NOT_NEEDED: &'static str = "There is no need for an explicit `else` block for this `if` \
260 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &'static str = "Consider dropping the else clause and merging the code that \
261 follows (in the loop) with the if block, like so:\n";
263 const DROP_ELSE_BLOCK_MSG: &'static str = "Consider dropping the else clause, and moving out the code in the else \
267 fn emit_warning<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str, typ: LintType) {
269 // snip is the whole *help* message that appears after the warning.
270 // message is the warning message.
271 // expr is the expression which the lint warning message refers to.
272 let (snip, message, expr) = match typ {
273 LintType::ContinueInsideElseBlock => {
274 (suggestion_snippet_for_continue_inside_else(ctx, data, header), MSG_REDUNDANT_ELSE_BLOCK, data.else_expr)
276 LintType::ContinueInsideThenBlock => {
277 (suggestion_snippet_for_continue_inside_if(ctx, data, header), MSG_ELSE_BLOCK_NOT_NEEDED, data.if_expr)
280 span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
283 fn suggestion_snippet_for_continue_inside_if<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str) -> String {
284 let cond_code = snippet(ctx, data.if_cond.span, "..");
286 let if_code = format!("if {} {{\n continue;\n}}\n", cond_code);
287 /* ^^^^--- Four spaces of indentation. */
289 let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
290 let else_code = erode_block(&else_code);
291 let else_code = trim_multiline(Cow::from(else_code), false);
293 let mut ret = String::from(header);
294 ret.push_str(&if_code);
295 ret.push_str(&else_code);
296 ret.push_str("\n...");
300 fn suggestion_snippet_for_continue_inside_else<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str) -> String {
301 let cond_code = snippet(ctx, data.if_cond.span, "..");
302 let mut if_code = format!("if {} {{\n", cond_code);
305 let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
306 let block_code = erode_block(block_code);
307 let block_code = trim_multiline(Cow::from(block_code), false);
309 if_code.push_str(&block_code);
312 // These is the code in the loop block that follows the if/else construction
313 // we are complaining about. We want to pull all of this code into the
314 // `then` block of the `if` statement.
315 let to_annex = data.block_stmts[data.stmt_idx + 1..]
317 .map(|stmt| original_sp(stmt.span, DUMMY_SP))
318 .map(|span| snippet_block(ctx, span, "..").into_owned())
322 let mut ret = String::from(header);
324 ret.push_str(&if_code);
325 ret.push_str("\n// Merged code follows...");
326 ret.push_str(&to_annex);
327 ret.push_str("\n}\n");
331 fn check_and_warn<'a>(ctx: &EarlyContext, expr: &'a ast::Expr) {
332 with_loop_block(expr, |loop_block| for (i, stmt) in loop_block.stmts.iter().enumerate() {
333 with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
334 let data = &LintData {
338 if_block: then_block,
339 else_expr: else_expr,
340 block_stmts: &loop_block.stmts,
342 if needless_continue_in_else(else_expr) {
343 emit_warning(ctx, data, DROP_ELSE_BLOCK_AND_MERGE_MSG, LintType::ContinueInsideElseBlock);
344 } else if is_first_block_stmt_continue(then_block) {
345 emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
351 /// Eats at `s` from the end till a closing brace `}` is encountered, and then
352 /// continues eating till a non-whitespace character is found.
361 /// is transformed to
368 /// NOTE: when there is no closing brace in `s`, `s` is _not_ preserved, i.e.,
369 /// an empty string will be returned in that case.
370 pub fn erode_from_back(s: &str) -> String {
371 let mut ret = String::from(s);
372 while ret.pop().map_or(false, |c| c != '}') {}
373 while let Some(c) = ret.pop() {
374 if !c.is_whitespace() {
382 /// Eats at `s` from the front by first skipping all leading whitespace. Then,
383 /// any number of opening braces are eaten, followed by any number of newlines.
389 /// inside_a_block();
393 /// is transformed to
397 /// inside_a_block();
401 pub fn erode_from_front(s: &str) -> String {
403 .skip_while(|c| c.is_whitespace())
404 .skip_while(|c| *c == '{')
405 .skip_while(|c| *c == '\n')
409 /// If `s` contains the code for a block, delimited by braces, this function
410 /// tries to get the contents of the block. If there is no closing brace present,
411 /// an empty string is returned.
412 pub fn erode_block(s: &str) -> String {
413 erode_from_back(&erode_from_front(s))