]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_continue.rs
Auto merge of #4886 - rust-lang:must-use-pub-only, r=phansch
[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 //! ```rust
6 //! let mut a = 1;
7 //! let x = true;
8 //!
9 //! while a < 5 {
10 //!     a = 6;
11 //!     if x {
12 //!         // ...
13 //!     } else {
14 //!         continue;
15 //!     }
16 //!     println!("Hello, world");
17 //! }
18 //! ```
19 //!
20 //! And suggest something like this:
21 //!
22 //! ```rust
23 //! let mut a = 1;
24 //! let x = true;
25 //!
26 //! while a < 5 {
27 //!     a = 6;
28 //!     if x {
29 //!         // ...
30 //!         println!("Hello, world");
31 //!     }
32 //! }
33 //! ```
34 //!
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;
39 use std::borrow::Cow;
40 use syntax::ast;
41 use syntax::source_map::{original_sp, DUMMY_SP};
42
43 use crate::utils::{snippet, snippet_block, span_help_and_lint, trim_multiline};
44
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.
50     ///
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.
56     ///
57     /// **Known problems:** None
58     ///
59     /// **Example:**
60     /// ```rust
61     /// # fn condition() -> bool { false }
62     /// # fn update_condition() {}
63     /// # let x = false;
64     /// while condition() {
65     ///     update_condition();
66     ///     if x {
67     ///         // ...
68     ///     } else {
69     ///         continue;
70     ///     }
71     ///     println!("Hello, world");
72     /// }
73     /// ```
74     ///
75     /// Could be rewritten as
76     ///
77     /// ```rust
78     /// # fn condition() -> bool { false }
79     /// # fn update_condition() {}
80     /// # let x = false;
81     /// while condition() {
82     ///     update_condition();
83     ///     if x {
84     ///         // ...
85     ///         println!("Hello, world");
86     ///     }
87     /// }
88     /// ```
89     ///
90     /// As another example, the following code
91     ///
92     /// ```rust
93     /// # fn waiting() -> bool { false }
94     /// loop {
95     ///     if waiting() {
96     ///         continue;
97     ///     } else {
98     ///         // Do something useful
99     ///     }
100     ///     # break;
101     /// }
102     /// ```
103     /// Could be rewritten as
104     ///
105     /// ```rust
106     /// # fn waiting() -> bool { false }
107     /// loop {
108     ///     if waiting() {
109     ///         continue;
110     ///     }
111     ///     // Do something useful
112     ///     # break;
113     /// }
114     /// ```
115     pub NEEDLESS_CONTINUE,
116     pedantic,
117     "`continue` statements that can be replaced by a rearrangement of code"
118 }
119
120 declare_lint_pass!(NeedlessContinue => [NEEDLESS_CONTINUE]);
121
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);
126         }
127     }
128 }
129
130 /* This lint has to mainly deal with two cases of needless continue
131  * statements. */
132 // Case 1 [Continue inside else block]:
133 //
134 //     loop {
135 //         // region A
136 //         if cond {
137 //             // region B
138 //         } else {
139 //             continue;
140 //         }
141 //         // region C
142 //     }
143 //
144 // This code can better be written as follows:
145 //
146 //     loop {
147 //         // region A
148 //         if cond {
149 //             // region B
150 //             // region C
151 //         }
152 //     }
153 //
154 // Case 2 [Continue inside then block]:
155 //
156 //     loop {
157 //       // region A
158 //       if cond {
159 //           continue;
160 //           // potentially more code here.
161 //       } else {
162 //           // region B
163 //       }
164 //       // region C
165 //     }
166 //
167 //
168 // This snippet can be refactored to:
169 //
170 //     loop {
171 //       // region A
172 //       if !cond {
173 //           // region B
174 //           // region C
175 //       }
176 //     }
177 //
178
179 /// Given an expression, returns true if either of the following is true
180 ///
181 /// - The expression is a `continue` node.
182 /// - The expression node is a block with the first statement being a
183 /// `continue`.
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()),
188         _ => false,
189     }
190 }
191
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())
197             } else {
198                 false
199             }
200         },
201         _ => false,
202     })
203 }
204
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; }`
209         (_, None) => true,
210         // `loop { continue 'a; }`
211         (None, _) => false,
212         // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
213         (Some(x), Some(y)) => x.ident == y.ident,
214     }
215 }
216
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)
220 where
221     F: FnMut(&ast::Block, Option<&ast::Label>),
222 {
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
226     {
227         func(loop_block, label.as_ref());
228     }
229 }
230
231 /// If `stmt` is an if expression node with an `else` branch, calls func with
232 /// the
233 /// following:
234 ///
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)
240 where
241     F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
242 {
243     match stmt.kind {
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);
247             }
248         },
249         _ => {},
250     }
251 }
252
253 /// A type to distinguish between the two distinct cases this lint handles.
254 #[derive(Copy, Clone, Debug)]
255 enum LintType {
256     ContinueInsideElseBlock,
257     ContinueInsideThenBlock,
258 }
259
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.
272     stmt_idx: usize,
273     /// The statements of the loop block.
274     block_stmts: &'a [ast::Stmt],
275 }
276
277 const MSG_REDUNDANT_ELSE_BLOCK: &str = "This else block is redundant.\n";
278
279 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "There is no need for an explicit `else` block for this `if` \
280                                          expression\n";
281
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";
284
285 const DROP_ELSE_BLOCK_MSG: &str = "Consider dropping the else clause, and moving out the code in the else \
286                                    block, like so:\n";
287
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,
296             data.else_expr,
297         ),
298         LintType::ContinueInsideThenBlock => (
299             suggestion_snippet_for_continue_inside_if(ctx, data, header),
300             MSG_ELSE_BLOCK_NOT_NEEDED,
301             data.if_expr,
302         ),
303     };
304     span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
305 }
306
307 fn suggestion_snippet_for_continue_inside_if<'a>(
308     ctx: &EarlyContext<'_>,
309     data: &'a LintData<'_>,
310     header: &str,
311 ) -> String {
312     let cond_code = snippet(ctx, data.if_cond.span, "..");
313
314     let if_code = format!("if {} {{\n    continue;\n}}\n", cond_code);
315     /* ^^^^--- Four spaces of indentation. */
316     // region B
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);
320
321     let mut ret = String::from(header);
322     ret.push_str(&if_code);
323     ret.push_str(&else_code);
324     ret.push_str("\n...");
325     ret
326 }
327
328 fn suggestion_snippet_for_continue_inside_else<'a>(
329     ctx: &EarlyContext<'_>,
330     data: &'a LintData<'_>,
331     header: &str,
332 ) -> String {
333     let cond_code = snippet(ctx, data.if_cond.span, "..");
334     let mut if_code = format!("if {} {{\n", cond_code);
335
336     // Region B
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);
340
341     if_code.push_str(&block_code);
342
343     // Region C
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..]
348         .iter()
349         .map(|stmt| original_sp(stmt.span, DUMMY_SP))
350         .map(|span| snippet_block(ctx, span, "..").into_owned())
351         .collect::<Vec<_>>()
352         .join("\n");
353
354     let mut ret = String::from(header);
355
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");
360     ret
361 }
362
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 {
368                     stmt_idx: i,
369                     if_expr,
370                     if_cond: cond,
371                     if_block: then_block,
372                     else_expr,
373                     block_stmts: &loop_block.stmts,
374                 };
375                 if needless_continue_in_else(else_expr, label) {
376                     emit_warning(
377                         ctx,
378                         data,
379                         DROP_ELSE_BLOCK_AND_MERGE_MSG,
380                         LintType::ContinueInsideElseBlock,
381                     );
382                 } else if is_first_block_stmt_continue(then_block, label) {
383                     emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
384                 }
385             });
386         }
387     });
388 }
389
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.
392 /// e.g., the string
393 ///
394 /// ```rust
395 /// {
396 ///     let x = 5;
397 /// }
398 /// ```
399 ///
400 /// is transformed to
401 ///
402 /// ```ignore
403 ///     {
404 ///         let x = 5;
405 /// ```
406 ///
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.
409 #[must_use]
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() {
415             ret.push(c);
416             break;
417         }
418     }
419     ret
420 }
421
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.
424 /// e.g.,  the string
425 ///
426 /// ```ignore
427 ///         {
428 ///             something();
429 ///             inside_a_block();
430 ///         }
431 /// ```
432 ///
433 /// is transformed to
434 ///
435 /// ```ignore
436 ///             something();
437 ///             inside_a_block();
438 ///         }
439 /// ```
440 #[must_use]
441 pub fn erode_from_front(s: &str) -> String {
442     s.chars()
443         .skip_while(|c| c.is_whitespace())
444         .skip_while(|c| *c == '{')
445         .skip_while(|c| *c == '\n')
446         .collect::<String>()
447 }
448
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
451 /// present,
452 /// an empty string is returned.
453 #[must_use]
454 pub fn erode_block(s: &str) -> String {
455     erode_from_back(&erode_from_front(s))
456 }