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