]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/needless_continue.rs
Rollup merge of #88860 - nbdd0121:panic, r=m-ou-se
[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 clippy_utils::diagnostics::span_lint_and_help;
37 use clippy_utils::source::{indent_of, snippet, snippet_block};
38 use rustc_ast::ast;
39 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
40 use rustc_session::{declare_lint_pass, declare_tool_lint};
41 use rustc_span::Span;
42
43 declare_clippy_lint! {
44     /// ### What it does
45     /// 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?
51     /// 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     /// ### Example
58     /// ```rust
59     /// # fn condition() -> bool { false }
60     /// # fn update_condition() {}
61     /// # let x = false;
62     /// while condition() {
63     ///     update_condition();
64     ///     if x {
65     ///         // ...
66     ///     } else {
67     ///         continue;
68     ///     }
69     ///     println!("Hello, world");
70     /// }
71     /// ```
72     ///
73     /// Could be rewritten as
74     ///
75     /// ```rust
76     /// # fn condition() -> bool { false }
77     /// # fn update_condition() {}
78     /// # let x = false;
79     /// while condition() {
80     ///     update_condition();
81     ///     if x {
82     ///         // ...
83     ///         println!("Hello, world");
84     ///     }
85     /// }
86     /// ```
87     ///
88     /// As another example, the following code
89     ///
90     /// ```rust
91     /// # fn waiting() -> bool { false }
92     /// loop {
93     ///     if waiting() {
94     ///         continue;
95     ///     } else {
96     ///         // Do something useful
97     ///     }
98     ///     # break;
99     /// }
100     /// ```
101     /// Could be rewritten as
102     ///
103     /// ```rust
104     /// # fn waiting() -> bool { false }
105     /// loop {
106     ///     if waiting() {
107     ///         continue;
108     ///     }
109     ///     // Do something useful
110     ///     # break;
111     /// }
112     /// ```
113     pub NEEDLESS_CONTINUE,
114     pedantic,
115     "`continue` statements that can be replaced by a rearrangement of code"
116 }
117
118 declare_lint_pass!(NeedlessContinue => [NEEDLESS_CONTINUE]);
119
120 impl EarlyLintPass for NeedlessContinue {
121     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
122         if !expr.span.from_expansion() {
123             check_and_warn(cx, expr);
124         }
125     }
126 }
127
128 /* This lint has to mainly deal with two cases of needless continue
129  * statements. */
130 // Case 1 [Continue inside else block]:
131 //
132 //     loop {
133 //         // region A
134 //         if cond {
135 //             // region B
136 //         } else {
137 //             continue;
138 //         }
139 //         // region C
140 //     }
141 //
142 // This code can better be written as follows:
143 //
144 //     loop {
145 //         // region A
146 //         if cond {
147 //             // region B
148 //             // region C
149 //         }
150 //     }
151 //
152 // Case 2 [Continue inside then block]:
153 //
154 //     loop {
155 //       // region A
156 //       if cond {
157 //           continue;
158 //           // potentially more code here.
159 //       } else {
160 //           // region B
161 //       }
162 //       // region C
163 //     }
164 //
165 //
166 // This snippet can be refactored to:
167 //
168 //     loop {
169 //       // region A
170 //       if !cond {
171 //           // region B
172 //           // region C
173 //       }
174 //     }
175 //
176
177 /// Given an expression, returns true if either of the following is true
178 ///
179 /// - The expression is a `continue` node.
180 /// - The expression node is a block with the first statement being a
181 /// `continue`.
182 fn needless_continue_in_else(else_expr: &ast::Expr, label: Option<&ast::Label>) -> bool {
183     match else_expr.kind {
184         ast::ExprKind::Block(ref else_block, _) => is_first_block_stmt_continue(else_block, label),
185         ast::ExprKind::Continue(l) => compare_labels(label, l.as_ref()),
186         _ => false,
187     }
188 }
189
190 fn is_first_block_stmt_continue(block: &ast::Block, label: Option<&ast::Label>) -> bool {
191     block.stmts.get(0).map_or(false, |stmt| match stmt.kind {
192         ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
193             if let ast::ExprKind::Continue(ref l) = e.kind {
194                 compare_labels(label, l.as_ref())
195             } else {
196                 false
197             }
198         },
199         _ => false,
200     })
201 }
202
203 /// If the `continue` has a label, check it matches the label of the loop.
204 fn compare_labels(loop_label: Option<&ast::Label>, continue_label: Option<&ast::Label>) -> bool {
205     match (loop_label, continue_label) {
206         // `loop { continue; }` or `'a loop { continue; }`
207         (_, None) => true,
208         // `loop { continue 'a; }`
209         (None, _) => false,
210         // `'a loop { continue 'a; }` or `'a loop { continue 'b; }`
211         (Some(x), Some(y)) => x.ident == y.ident,
212     }
213 }
214
215 /// If `expr` is a loop expression (while/while let/for/loop), calls `func` with
216 /// the AST object representing the loop block of `expr`.
217 fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
218 where
219     F: FnMut(&ast::Block, Option<&ast::Label>),
220 {
221     if let ast::ExprKind::While(_, loop_block, label)
222     | ast::ExprKind::ForLoop(_, _, loop_block, label)
223     | ast::ExprKind::Loop(loop_block, label, ..) = &expr.kind
224     {
225         func(loop_block, label.as_ref());
226     }
227 }
228
229 /// If `stmt` is an if expression node with an `else` branch, calls func with
230 /// the
231 /// following:
232 ///
233 /// - The `if` expression itself,
234 /// - The `if` condition expression,
235 /// - The `then` block, and
236 /// - The `else` expression.
237 fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
238 where
239     F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
240 {
241     match stmt.kind {
242         ast::StmtKind::Semi(ref e) | ast::StmtKind::Expr(ref e) => {
243             if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.kind {
244                 func(e, cond, if_block, else_expr);
245             }
246         },
247         _ => {},
248     }
249 }
250
251 /// A type to distinguish between the two distinct cases this lint handles.
252 #[derive(Copy, Clone, Debug)]
253 enum LintType {
254     ContinueInsideElseBlock,
255     ContinueInsideThenBlock,
256 }
257
258 /// Data we pass around for construction of help messages.
259 struct LintData<'a> {
260     /// The `if` expression encountered in the above loop.
261     if_expr: &'a ast::Expr,
262     /// The condition expression for the above `if`.
263     if_cond: &'a ast::Expr,
264     /// The `then` block of the `if` statement.
265     if_block: &'a ast::Block,
266     /// The `else` block of the `if` statement.
267     /// Note that we only work with `if` exprs that have an `else` branch.
268     else_expr: &'a ast::Expr,
269     /// The 0-based index of the `if` statement in the containing loop block.
270     stmt_idx: usize,
271     /// The statements of the loop block.
272     loop_block: &'a ast::Block,
273 }
274
275 const MSG_REDUNDANT_CONTINUE_EXPRESSION: &str = "this `continue` expression is redundant";
276
277 const MSG_REDUNDANT_ELSE_BLOCK: &str = "this `else` block is redundant";
278
279 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "there is no need for an explicit `else` block for this `if` \
280                                          expression";
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";
284
285 const DROP_ELSE_BLOCK_MSG: &str = "consider dropping the `else` clause";
286
287 const DROP_CONTINUE_EXPRESSION_MSG: &str = "consider dropping the `continue` expression";
288
289 fn emit_warning<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
290     // snip    is the whole *help* message that appears after the warning.
291     // message is the warning message.
292     // expr    is the expression which the lint warning message refers to.
293     let (snip, message, expr) = match typ {
294         LintType::ContinueInsideElseBlock => (
295             suggestion_snippet_for_continue_inside_else(cx, data),
296             MSG_REDUNDANT_ELSE_BLOCK,
297             data.else_expr,
298         ),
299         LintType::ContinueInsideThenBlock => (
300             suggestion_snippet_for_continue_inside_if(cx, data),
301             MSG_ELSE_BLOCK_NOT_NEEDED,
302             data.if_expr,
303         ),
304     };
305     span_lint_and_help(
306         cx,
307         NEEDLESS_CONTINUE,
308         expr.span,
309         message,
310         None,
311         &format!("{}\n{}", header, snip),
312     );
313 }
314
315 fn suggestion_snippet_for_continue_inside_if<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
316     let cond_code = snippet(cx, data.if_cond.span, "..");
317
318     let continue_code = snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span));
319
320     let else_code = snippet_block(cx, data.else_expr.span, "..", Some(data.if_expr.span));
321
322     let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
323     format!(
324         "{indent}if {} {}\n{indent}{}",
325         cond_code,
326         continue_code,
327         else_code,
328         indent = " ".repeat(indent_if),
329     )
330 }
331
332 fn suggestion_snippet_for_continue_inside_else<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
333     let cond_code = snippet(cx, data.if_cond.span, "..");
334
335     // Region B
336     let block_code = erode_from_back(&snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span)));
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 indent = span_of_first_expr_in_block(data.if_block)
343         .and_then(|span| indent_of(cx, span))
344         .unwrap_or(0);
345     let to_annex = data.loop_block.stmts[data.stmt_idx + 1..]
346         .iter()
347         .map(|stmt| {
348             let span = cx.sess().source_map().stmt_span(stmt.span, data.loop_block.span);
349             let snip = snippet_block(cx, span, "..", None).into_owned();
350             snip.lines()
351                 .map(|line| format!("{}{}", " ".repeat(indent), line))
352                 .collect::<Vec<_>>()
353                 .join("\n")
354         })
355         .collect::<Vec<_>>()
356         .join("\n");
357
358     let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
359     format!(
360         "{indent_if}if {} {}\n{indent}// merged code follows:\n{}\n{indent_if}}}",
361         cond_code,
362         block_code,
363         to_annex,
364         indent = " ".repeat(indent),
365         indent_if = " ".repeat(indent_if),
366     )
367 }
368
369 fn check_and_warn<'a>(cx: &EarlyContext<'_>, expr: &'a ast::Expr) {
370     if_chain! {
371         if let ast::ExprKind::Loop(loop_block, ..) = &expr.kind;
372         if let Some(last_stmt) = loop_block.stmts.last();
373         if let ast::StmtKind::Expr(inner_expr) | ast::StmtKind::Semi(inner_expr) = &last_stmt.kind;
374         if let ast::ExprKind::Continue(_) = inner_expr.kind;
375         then {
376             span_lint_and_help(
377                 cx,
378                 NEEDLESS_CONTINUE,
379                 last_stmt.span,
380                 MSG_REDUNDANT_CONTINUE_EXPRESSION,
381                 None,
382                 DROP_CONTINUE_EXPRESSION_MSG,
383             );
384         }
385     }
386     with_loop_block(expr, |loop_block, label| {
387         for (i, stmt) in loop_block.stmts.iter().enumerate() {
388             with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
389                 let data = &LintData {
390                     stmt_idx: i,
391                     if_expr,
392                     if_cond: cond,
393                     if_block: then_block,
394                     else_expr,
395                     loop_block,
396                 };
397                 if needless_continue_in_else(else_expr, label) {
398                     emit_warning(
399                         cx,
400                         data,
401                         DROP_ELSE_BLOCK_AND_MERGE_MSG,
402                         LintType::ContinueInsideElseBlock,
403                     );
404                 } else if is_first_block_stmt_continue(then_block, label) {
405                     emit_warning(cx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
406                 }
407             });
408         }
409     });
410 }
411
412 /// Eats at `s` from the end till a closing brace `}` is encountered, and then continues eating
413 /// till a non-whitespace character is found.  e.g., the string. If no closing `}` is present, the
414 /// string will be preserved.
415 ///
416 /// ```rust
417 /// {
418 ///     let x = 5;
419 /// }
420 /// ```
421 ///
422 /// is transformed to
423 ///
424 /// ```text
425 ///     {
426 ///         let x = 5;
427 /// ```
428 #[must_use]
429 fn erode_from_back(s: &str) -> String {
430     let mut ret = s.to_string();
431     while ret.pop().map_or(false, |c| c != '}') {}
432     while let Some(c) = ret.pop() {
433         if !c.is_whitespace() {
434             ret.push(c);
435             break;
436         }
437     }
438     if ret.is_empty() { s.to_string() } else { ret }
439 }
440
441 fn span_of_first_expr_in_block(block: &ast::Block) -> Option<Span> {
442     block.stmts.get(0).map(|stmt| stmt.span)
443 }
444
445 #[cfg(test)]
446 mod test {
447     use super::erode_from_back;
448
449     #[test]
450     #[rustfmt::skip]
451     fn test_erode_from_back() {
452         let input = "\
453 {
454     let x = 5;
455     let y = format!(\"{}\", 42);
456 }";
457
458         let expected = "\
459 {
460     let x = 5;
461     let y = format!(\"{}\", 42);";
462
463         let got = erode_from_back(input);
464         assert_eq!(expected, got);
465     }
466
467     #[test]
468     #[rustfmt::skip]
469     fn test_erode_from_back_no_brace() {
470         let input = "\
471 let x = 5;
472 let y = something();
473 ";
474         let expected = input;
475         let got = erode_from_back(input);
476         assert_eq!(expected, got);
477     }
478 }