]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_continue.rs
Fix `needless_continue` false positive
[rust.git] / clippy_lints / src / needless_continue.rs
1 //! Checks for continue statements in loops that are redundant.
2 //!
3 //! For example, the lint would catch
4 //!
5 //! ```ignore
6 //! while condition() {
7 //!     update_condition();
8 //!     if x {
9 //!         // ...
10 //!     } else {
11 //!         continue;
12 //!     }
13 //!     println!("Hello, world");
14 //! }
15 //! ```
16 //!
17 //! And suggest something like this:
18 //!
19 //! ```ignore
20 //! while condition() {
21 //!     update_condition();
22 //!     if x {
23 //!         // ...
24 //!         println!("Hello, world");
25 //!     }
26 //! }
27 //! ```
28 //!
29 //! This lint is **warn** by default.
30 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
31 use rustc::{declare_tool_lint, lint_array};
32 use std::borrow::Cow;
33 use syntax::ast;
34 use syntax::source_map::{original_sp, DUMMY_SP};
35
36 use crate::utils::{in_macro, snippet, snippet_block, span_help_and_lint, trim_multiline};
37
38 declare_clippy_lint! {
39     /// **What it does:** The lint checks for `if`-statements appearing in loops
40     /// that contain a `continue` statement in either their main blocks or their
41     /// `else`-blocks, when omitting the `else`-block possibly with some
42     /// rearrangement of code can make the code easier to understand.
43     ///
44     /// **Why is this bad?** Having explicit `else` blocks for `if` statements
45     /// containing `continue` in their THEN branch adds unnecessary branching and
46     /// nesting to the code. Having an else block containing just `continue` can
47     /// also be better written by grouping the statements following the whole `if`
48     /// statement within the THEN block and omitting the else block completely.
49     ///
50     /// **Known problems:** None
51     ///
52     /// **Example:**
53     /// ```rust
54     /// while condition() {
55     ///     update_condition();
56     ///     if x {
57     ///         // ...
58     ///     } else {
59     ///         continue;
60     ///     }
61     ///     println!("Hello, world");
62     /// }
63     /// ```
64     ///
65     /// Could be rewritten as
66     ///
67     /// ```rust
68     /// while condition() {
69     ///     update_condition();
70     ///     if x {
71     ///         // ...
72     ///         println!("Hello, world");
73     ///     }
74     /// }
75     /// ```
76     ///
77     /// As another example, the following code
78     ///
79     /// ```rust
80     /// loop {
81     ///     if waiting() {
82     ///         continue;
83     ///     } else {
84     ///         // Do something useful
85     ///     }
86     /// }
87     /// ```
88     /// Could be rewritten as
89     ///
90     /// ```rust
91     /// loop {
92     ///     if waiting() {
93     ///         continue;
94     ///     }
95     ///     // Do something useful
96     /// }
97     /// ```
98     pub NEEDLESS_CONTINUE,
99     pedantic,
100     "`continue` statements that can be replaced by a rearrangement of code"
101 }
102
103 #[derive(Copy, Clone)]
104 pub struct NeedlessContinue;
105
106 impl LintPass for NeedlessContinue {
107     fn get_lints(&self) -> LintArray {
108         lint_array!(NEEDLESS_CONTINUE)
109     }
110
111     fn name(&self) -> &'static str {
112         "NeedlessContinue"
113     }
114 }
115
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);
120         }
121     }
122 }
123
124 /* This lint has to mainly deal with two cases of needless continue
125  * statements. */
126 // Case 1 [Continue inside else block]:
127 //
128 //     loop {
129 //         // region A
130 //         if cond {
131 //             // region B
132 //         } else {
133 //             continue;
134 //         }
135 //         // region C
136 //     }
137 //
138 // This code can better be written as follows:
139 //
140 //     loop {
141 //         // region A
142 //         if cond {
143 //             // region B
144 //             // region C
145 //         }
146 //     }
147 //
148 // Case 2 [Continue inside then block]:
149 //
150 //     loop {
151 //       // region A
152 //       if cond {
153 //           continue;
154 //           // potentially more code here.
155 //       } else {
156 //           // region B
157 //       }
158 //       // region C
159 //     }
160 //
161 //
162 // This snippet can be refactored to:
163 //
164 //     loop {
165 //       // region A
166 //       if !cond {
167 //           // region B
168 //           // region C
169 //       }
170 //     }
171 //
172
173 /// Given an expression, returns true if either of the following is true
174 ///
175 /// - The expression is a `continue` node.
176 /// - The expression node is a block with the first statement being a
177 /// `continue`.
178 fn needless_continue_in_else(else_expr: &ast::Expr, label: Option<&ast::Label>) -> bool {
179     match else_expr.node {
180         ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block, label),
181         ast::ExprKind::Continue(l) => compare_labels(label, l.as_ref()),
182         _ => false,
183     }
184 }
185
186 fn is_first_block_stmt_continue(block: &ast::Block, label: Option<&ast::Label>) -> 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(ref l) = e.node {
190                 compare_labels(label, l.as_ref())
191             } else {
192                 false
193             }
194         },
195         _ => false,
196     })
197 }
198
199 /// If the `continue` has a label, check it matches the label of the loop.
200 fn compare_labels(loop_label: Option<&ast::Label>, continue_label: Option<&ast::Label>) -> bool {
201     match (loop_label, continue_label) {
202         // `loop { continue; }` or `'a loop { continue; }`
203         (_, None) => true,
204         // `loop { continue 'a; }`
205         (None, _) => false,
206         // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
207         (Some(x), Some(y)) => x.ident == y.ident,
208     }
209 }
210
211 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
212 /// the AST object representing the loop block of `expr`.
213 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
214 where
215     F: FnMut(&ast::Block, Option<&ast::Label>),
216 {
217     match expr.node {
218         ast::ExprKind::While(_, ref loop_block, ref label)
219         | ast::ExprKind::WhileLet(_, _, ref loop_block, ref label)
220         | ast::ExprKind::ForLoop(_, _, ref loop_block, ref label)
221         | ast::ExprKind::Loop(ref loop_block, ref label) => func(loop_block, label.as_ref()),
222         _ => {},
223     }
224 }
225
226 /// If `stmt` is an if expression node with an `else` branch, calls func with
227 /// the
228 /// following:
229 ///
230 /// - The `if` expression itself,
231 /// - The `if` condition expression,
232 /// - The `then` block, and
233 /// - The `else` expression.
234 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
235 where
236     F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
237 {
238     match stmt.node {
239         ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
240             if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
241                 func(e, cond, if_block, else_expr);
242             }
243         },
244         _ => {},
245     }
246 }
247
248 /// A type to distinguish between the two distinct cases this lint handles.
249 #[derive(Copy, Clone, Debug)]
250 enum LintType {
251     ContinueInsideElseBlock,
252     ContinueInsideThenBlock,
253 }
254
255 /// Data we pass around for construction of help messages.
256 struct LintData<'a> {
257     /// The `if` expression encountered in the above loop.
258     if_expr: &'a ast::Expr,
259     /// The condition expression for the above `if`.
260     if_cond: &'a ast::Expr,
261     /// The `then` block of the `if` statement.
262     if_block: &'a ast::Block,
263     /// The `else` block of the `if` statement.
264     /// Note that we only work with `if` exprs that have an `else` branch.
265     else_expr: &'a ast::Expr,
266     /// The 0-based index of the `if` statement in the containing loop block.
267     stmt_idx: usize,
268     /// The statements of the loop block.
269     block_stmts: &'a [ast::Stmt],
270 }
271
272 const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";
273
274 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "There is no need for an explicit `else` block for this `if` \
275                                          expression\n";
276
277 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "Consider dropping the else clause and merging the code that \
278                                              follows (in the loop) with the if block, like so:\n";
279
280 const DROP_ELSE_BLOCK_MSG: &str = "Consider dropping the else clause, and moving out the code in the else \
281                                    block, like so:\n";
282
283 fn emit_warning<'a>(ctx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
284     // snip    is the whole *help* message that appears after the warning.
285     // message is the warning message.
286     // expr    is the expression which the lint warning message refers to.
287     let (snip, message, expr) = match typ {
288         LintType::ContinueInsideElseBlock => (
289             suggestion_snippet_for_continue_inside_else(ctx, data, header),
290             MSG_REDUNDANT_ELSE_BLOCK,
291             data.else_expr,
292         ),
293         LintType::ContinueInsideThenBlock => (
294             suggestion_snippet_for_continue_inside_if(ctx, data, header),
295             MSG_ELSE_BLOCK_NOT_NEEDED,
296             data.if_expr,
297         ),
298     };
299     span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
300 }
301
302 fn suggestion_snippet_for_continue_inside_if<'a>(
303     ctx: &EarlyContext<'_>,
304     data: &'a LintData<'_>,
305     header: &str,
306 ) -> String {
307     let cond_code = snippet(ctx, data.if_cond.span, "..");
308
309     let if_code = format!("if {} {{\n    continue;\n}}\n", cond_code);
310     /* ^^^^--- Four spaces of indentation. */
311     // region B
312     let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
313     let else_code = erode_block(&else_code);
314     let else_code = trim_multiline(Cow::from(else_code), false);
315
316     let mut ret = String::from(header);
317     ret.push_str(&if_code);
318     ret.push_str(&else_code);
319     ret.push_str("\n...");
320     ret
321 }
322
323 fn suggestion_snippet_for_continue_inside_else<'a>(
324     ctx: &EarlyContext<'_>,
325     data: &'a LintData<'_>,
326     header: &str,
327 ) -> String {
328     let cond_code = snippet(ctx, data.if_cond.span, "..");
329     let mut if_code = format!("if {} {{\n", cond_code);
330
331     // Region B
332     let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
333     let block_code = erode_block(block_code);
334     let block_code = trim_multiline(Cow::from(block_code), false);
335
336     if_code.push_str(&block_code);
337
338     // Region C
339     // These is the code in the loop block that follows the if/else construction
340     // we are complaining about. We want to pull all of this code into the
341     // `then` block of the `if` statement.
342     let to_annex = data.block_stmts[data.stmt_idx + 1..]
343         .iter()
344         .map(|stmt| original_sp(stmt.span, DUMMY_SP))
345         .map(|span| snippet_block(ctx, span, "..").into_owned())
346         .collect::<Vec<_>>()
347         .join("\n");
348
349     let mut ret = String::from(header);
350
351     ret.push_str(&if_code);
352     ret.push_str("\n// Merged code follows...");
353     ret.push_str(&to_annex);
354     ret.push_str("\n}\n");
355     ret
356 }
357
358 fn check_and_warn<'a>(ctx: &EarlyContext<'_>, expr: &'a ast::Expr) {
359     with_loop_block(expr, |loop_block, label| {
360         for (i, stmt) in loop_block.stmts.iter().enumerate() {
361             with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
362                 let data = &LintData {
363                     stmt_idx: i,
364                     if_expr,
365                     if_cond: cond,
366                     if_block: then_block,
367                     else_expr,
368                     block_stmts: &loop_block.stmts,
369                 };
370                 if needless_continue_in_else(else_expr, label) {
371                     emit_warning(
372                         ctx,
373                         data,
374                         DROP_ELSE_BLOCK_AND_MERGE_MSG,
375                         LintType::ContinueInsideElseBlock,
376                     );
377                 } else if is_first_block_stmt_continue(then_block, label) {
378                     emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
379                 }
380             });
381         }
382     });
383 }
384
385 /// Eats at `s` from the end till a closing brace `}` is encountered, and then
386 /// continues eating till a non-whitespace character is found.
387 /// e.g., the string
388 ///
389 /// ```
390 /// {
391 ///     let x = 5;
392 /// }
393 /// ```
394 ///
395 /// is transformed to
396 ///
397 /// ```ignore
398 ///     {
399 ///         let x = 5;
400 /// ```
401 ///
402 /// NOTE: when there is no closing brace in `s`, `s` is _not_ preserved, i.e.,
403 /// an empty string will be returned in that case.
404 pub fn erode_from_back(s: &str) -> String {
405     let mut ret = String::from(s);
406     while ret.pop().map_or(false, |c| c != '}') {}
407     while let Some(c) = ret.pop() {
408         if !c.is_whitespace() {
409             ret.push(c);
410             break;
411         }
412     }
413     ret
414 }
415
416 /// Eats at `s` from the front by first skipping all leading whitespace. Then,
417 /// any number of opening braces are eaten, followed by any number of newlines.
418 /// e.g.,  the string
419 ///
420 /// ```ignore
421 ///         {
422 ///             something();
423 ///             inside_a_block();
424 ///         }
425 /// ```
426 ///
427 /// is transformed to
428 ///
429 /// ```ignore
430 ///             something();
431 ///             inside_a_block();
432 ///         }
433 /// ```
434 pub fn erode_from_front(s: &str) -> String {
435     s.chars()
436         .skip_while(|c| c.is_whitespace())
437         .skip_while(|c| *c == '{')
438         .skip_while(|c| *c == '\n')
439         .collect::<String>()
440 }
441
442 /// If `s` contains the code for a block, delimited by braces, this function
443 /// tries to get the contents of the block. If there is no closing brace
444 /// present,
445 /// an empty string is returned.
446 pub fn erode_block(s: &str) -> String {
447     erode_from_back(&erode_from_front(s))
448 }