]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/else_if_without_else.rs
Merge pull request #3189 from eddyb/rextern
[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 crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, in_external_macro, LintContext};
4 use crate::rustc::{declare_tool_lint, lint_array};
5 use crate::syntax::ast::*;
6
7 use crate::utils::span_lint_and_sugg;
8
9 /// **What it does:** Checks for usage of if expressions with an `else if` branch,
10 /// but without a final `else` branch.
11 ///
12 /// **Why is this bad?** Some coding guidelines require this (e.g. MISRA-C:2004 Rule 14.10).
13 ///
14 /// **Known problems:** None.
15 ///
16 /// **Example:**
17 /// ```rust
18 /// if x.is_positive() {
19 ///     a();
20 /// } else if x.is_negative() {
21 ///     b();
22 /// }
23 /// ```
24 ///
25 /// Could be written:
26 ///
27 /// ```rust
28 /// if x.is_positive() {
29 ///     a();
30 /// } else if x.is_negative() {
31 ///     b();
32 /// } else {
33 ///     // we don't care about zero
34 /// }
35 /// ```
36 declare_clippy_lint! {
37     pub ELSE_IF_WITHOUT_ELSE,
38     restriction,
39     "if expression with an `else if`, but without a final `else` branch"
40 }
41
42 #[derive(Copy, Clone)]
43 pub struct ElseIfWithoutElse;
44
45 impl LintPass for ElseIfWithoutElse {
46     fn get_lints(&self) -> LintArray {
47         lint_array!(ELSE_IF_WITHOUT_ELSE)
48     }
49 }
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.node {
58             if let ExprKind::If(_, _, None) = els.node {
59                 span_lint_and_sugg(
60                     cx,
61                     ELSE_IF_WITHOUT_ELSE,
62                     els.span,
63                     "if expression with an `else if`, but without a final `else`",
64                     "add an `else` block here",
65                     "".to_string()
66                 );
67             }
68
69             item = els;
70         }
71     }
72 }