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