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