]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/else_if_without_else.rs
Merge pull request #2589 from rust-lang-nursery/rangearg
[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_clippy_lint! {
36     pub ELSE_IF_WITHOUT_ELSE,
37     restriction,
38     "if expression with an `else if`, but without a final `else` branch"
39 }
40
41 #[derive(Copy, Clone)]
42 pub struct ElseIfWithoutElse;
43
44 impl LintPass for ElseIfWithoutElse {
45     fn get_lints(&self) -> LintArray {
46         lint_array!(ELSE_IF_WITHOUT_ELSE)
47     }
48 }
49
50 impl EarlyLintPass for ElseIfWithoutElse {
51     fn check_expr(&mut self, cx: &EarlyContext, mut item: &Expr) {
52         if in_external_macro(cx, item.span) {
53             return;
54         }
55
56         while let ExprKind::If(_, _, Some(ref els)) = item.node {
57             if let ExprKind::If(_, _, None) = els.node {
58                 span_lint_and_sugg(
59                     cx,
60                     ELSE_IF_WITHOUT_ELSE,
61                     els.span,
62                     "if expression with an `else if`, but without a final `else`",
63                     "add an `else` block here",
64                     "".to_string()
65                 );
66             }
67
68             item = els;
69         }
70     }
71 }