]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/else_if_without_else.rs
Auto merge of #71780 - jcotton42:string_remove_matches, r=joshtriplett
[rust.git] / src / tools / clippy / clippy_lints / src / else_if_without_else.rs
1 //! Lint on if expressions with an else if, but without a final else branch.
2
3 use rustc_ast::ast::{Expr, ExprKind};
4 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
5 use rustc_middle::lint::in_external_macro;
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 use crate::utils::span_lint_and_help;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for usage of if expressions with an `else if` branch,
12     /// but without a final `else` branch.
13     ///
14     /// **Why is this bad?** Some coding guidelines require this (e.g., MISRA-C:2004 Rule 14.10).
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// # fn a() {}
21     /// # fn b() {}
22     /// # let x: i32 = 1;
23     /// if x.is_positive() {
24     ///     a();
25     /// } else if x.is_negative() {
26     ///     b();
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```rust
33     /// # fn a() {}
34     /// # fn b() {}
35     /// # let x: i32 = 1;
36     /// if x.is_positive() {
37     ///     a();
38     /// } else if x.is_negative() {
39     ///     b();
40     /// } else {
41     ///     // We don't care about zero.
42     /// }
43     /// ```
44     pub ELSE_IF_WITHOUT_ELSE,
45     restriction,
46     "`if` expression with an `else if`, but without a final `else` branch"
47 }
48
49 declare_lint_pass!(ElseIfWithoutElse => [ELSE_IF_WITHOUT_ELSE]);
50
51 impl EarlyLintPass for ElseIfWithoutElse {
52     fn check_expr(&mut self, cx: &EarlyContext<'_>, mut item: &Expr) {
53         if in_external_macro(cx.sess(), item.span) {
54             return;
55         }
56
57         while let ExprKind::If(_, _, Some(ref els)) = item.kind {
58             if let ExprKind::If(_, _, None) = els.kind {
59                 span_lint_and_help(
60                     cx,
61                     ELSE_IF_WITHOUT_ELSE,
62                     els.span,
63                     "`if` expression with an `else if`, but without a final `else`",
64                     None,
65                     "add an `else` block here",
66                 );
67             }
68
69             item = els;
70         }
71     }
72 }