]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/else_if_without_else.rs
a306cff6eba5f5924b942ec1e2b348e54163211e
[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::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5 use syntax::ast::*;
6
7 use crate::utils::span_help_and_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     /// if x.is_positive() {
20     ///     a();
21     /// } else if x.is_negative() {
22     ///     b();
23     /// }
24     /// ```
25     ///
26     /// Could be written:
27     ///
28     /// ```rust
29     /// if x.is_positive() {
30     ///     a();
31     /// } else if x.is_negative() {
32     ///     b();
33     /// } else {
34     ///     // we don't care about zero
35     /// }
36     /// ```
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     fn name(&self) -> &'static str {
51         "ElseIfWithoutElse"
52     }
53 }
54
55 impl EarlyLintPass for ElseIfWithoutElse {
56     fn check_expr(&mut self, cx: &EarlyContext<'_>, mut item: &Expr) {
57         if in_external_macro(cx.sess(), item.span) {
58             return;
59         }
60
61         while let ExprKind::If(_, _, Some(ref els)) = item.node {
62             if let ExprKind::If(_, _, None) = els.node {
63                 span_help_and_lint(
64                     cx,
65                     ELSE_IF_WITHOUT_ELSE,
66                     els.span,
67                     "if expression with an `else if`, but without a final `else`",
68                     "add an `else` block here",
69                 );
70             }
71
72             item = els;
73         }
74     }
75 }