]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/needless_continue.rs
Rollup merge of #102300 - scottmcm:simpler-fold-closures, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / 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     #[clippy::version = "pre 1.29.0"]
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, cx: &EarlyContext<'_>, expr: &ast::Expr) {
123         if !expr.span.from_expansion() {
124             check_and_warn(cx, 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     loop_block: &'a ast::Block,
274 }
275
276 const MSG_REDUNDANT_CONTINUE_EXPRESSION: &str = "this `continue` expression is redundant";
277
278 const MSG_REDUNDANT_ELSE_BLOCK: &str = "this `else` block is redundant";
279
280 const MSG_ELSE_BLOCK_NOT_NEEDED: &str = "there is no need for an explicit `else` block for this `if` \
281                                          expression";
282
283 const DROP_ELSE_BLOCK_AND_MERGE_MSG: &str = "consider dropping the `else` clause and merging the code that \
284                                              follows (in the loop) with the `if` block";
285
286 const DROP_ELSE_BLOCK_MSG: &str = "consider dropping the `else` clause";
287
288 const DROP_CONTINUE_EXPRESSION_MSG: &str = "consider dropping the `continue` expression";
289
290 fn emit_warning<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>, header: &str, typ: LintType) {
291     // snip    is the whole *help* message that appears after the warning.
292     // message is the warning message.
293     // expr    is the expression which the lint warning message refers to.
294     let (snip, message, expr) = match typ {
295         LintType::ContinueInsideElseBlock => (
296             suggestion_snippet_for_continue_inside_else(cx, data),
297             MSG_REDUNDANT_ELSE_BLOCK,
298             data.else_expr,
299         ),
300         LintType::ContinueInsideThenBlock => (
301             suggestion_snippet_for_continue_inside_if(cx, data),
302             MSG_ELSE_BLOCK_NOT_NEEDED,
303             data.if_expr,
304         ),
305     };
306     span_lint_and_help(
307         cx,
308         NEEDLESS_CONTINUE,
309         expr.span,
310         message,
311         None,
312         &format!("{header}\n{snip}"),
313     );
314 }
315
316 fn suggestion_snippet_for_continue_inside_if<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
317     let cond_code = snippet(cx, data.if_cond.span, "..");
318
319     let continue_code = snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span));
320
321     let else_code = snippet_block(cx, data.else_expr.span, "..", Some(data.if_expr.span));
322
323     let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
324     format!(
325         "{indent}if {cond_code} {continue_code}\n{indent}{else_code}",
326         indent = " ".repeat(indent_if),
327     )
328 }
329
330 fn suggestion_snippet_for_continue_inside_else<'a>(cx: &EarlyContext<'_>, data: &'a LintData<'_>) -> String {
331     let cond_code = snippet(cx, data.if_cond.span, "..");
332
333     // Region B
334     let block_code = erode_from_back(&snippet_block(cx, data.if_block.span, "..", Some(data.if_expr.span)));
335
336     // Region C
337     // These is the code in the loop block that follows the if/else construction
338     // we are complaining about. We want to pull all of this code into the
339     // `then` block of the `if` statement.
340     let indent = span_of_first_expr_in_block(data.if_block)
341         .and_then(|span| indent_of(cx, span))
342         .unwrap_or(0);
343     let to_annex = data.loop_block.stmts[data.stmt_idx + 1..]
344         .iter()
345         .map(|stmt| {
346             let span = cx.sess().source_map().stmt_span(stmt.span, data.loop_block.span);
347             let snip = snippet_block(cx, span, "..", None).into_owned();
348             snip.lines()
349                 .map(|line| format!("{}{line}", " ".repeat(indent)))
350                 .collect::<Vec<_>>()
351                 .join("\n")
352         })
353         .collect::<Vec<_>>()
354         .join("\n");
355
356     let indent_if = indent_of(cx, data.if_expr.span).unwrap_or(0);
357     format!(
358         "{indent_if}if {cond_code} {block_code}\n{indent}// merged code follows:\n{to_annex}\n{indent_if}}}",
359         indent = " ".repeat(indent),
360         indent_if = " ".repeat(indent_if),
361     )
362 }
363
364 fn check_and_warn<'a>(cx: &EarlyContext<'_>, expr: &'a ast::Expr) {
365     if_chain! {
366         if let ast::ExprKind::Loop(loop_block, ..) = &expr.kind;
367         if let Some(last_stmt) = loop_block.stmts.last();
368         if let ast::StmtKind::Expr(inner_expr) | ast::StmtKind::Semi(inner_expr) = &last_stmt.kind;
369         if let ast::ExprKind::Continue(_) = inner_expr.kind;
370         then {
371             span_lint_and_help(
372                 cx,
373                 NEEDLESS_CONTINUE,
374                 last_stmt.span,
375                 MSG_REDUNDANT_CONTINUE_EXPRESSION,
376                 None,
377                 DROP_CONTINUE_EXPRESSION_MSG,
378             );
379         }
380     }
381     with_loop_block(expr, |loop_block, label| {
382         for (i, stmt) in loop_block.stmts.iter().enumerate() {
383             with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
384                 let data = &LintData {
385                     stmt_idx: i,
386                     if_expr,
387                     if_cond: cond,
388                     if_block: then_block,
389                     else_expr,
390                     loop_block,
391                 };
392                 if needless_continue_in_else(else_expr, label) {
393                     emit_warning(
394                         cx,
395                         data,
396                         DROP_ELSE_BLOCK_AND_MERGE_MSG,
397                         LintType::ContinueInsideElseBlock,
398                     );
399                 } else if is_first_block_stmt_continue(then_block, label) {
400                     emit_warning(cx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
401                 }
402             });
403         }
404     });
405 }
406
407 /// Eats at `s` from the end till a closing brace `}` is encountered, and then continues eating
408 /// till a non-whitespace character is found.  e.g., the string. If no closing `}` is present, the
409 /// string will be preserved.
410 ///
411 /// ```rust
412 /// {
413 ///     let x = 5;
414 /// }
415 /// ```
416 ///
417 /// is transformed to
418 ///
419 /// ```text
420 ///     {
421 ///         let x = 5;
422 /// ```
423 #[must_use]
424 fn erode_from_back(s: &str) -> String {
425     let mut ret = s.to_string();
426     while ret.pop().map_or(false, |c| c != '}') {}
427     while let Some(c) = ret.pop() {
428         if !c.is_whitespace() {
429             ret.push(c);
430             break;
431         }
432     }
433     if ret.is_empty() { s.to_string() } else { ret }
434 }
435
436 fn span_of_first_expr_in_block(block: &ast::Block) -> Option<Span> {
437     block.stmts.get(0).map(|stmt| stmt.span)
438 }
439
440 #[cfg(test)]
441 mod test {
442     use super::erode_from_back;
443
444     #[test]
445     #[rustfmt::skip]
446     fn test_erode_from_back() {
447         let input = "\
448 {
449     let x = 5;
450     let y = format!(\"{}\", 42);
451 }";
452
453         let expected = "\
454 {
455     let x = 5;
456     let y = format!(\"{}\", 42);";
457
458         let got = erode_from_back(input);
459         assert_eq!(expected, got);
460     }
461
462     #[test]
463     #[rustfmt::skip]
464     fn test_erode_from_back_no_brace() {
465         let input = "\
466 let x = 5;
467 let y = something();
468 ";
469         let expected = input;
470         let got = erode_from_back(input);
471         assert_eq!(expected, got);
472     }
473 }