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