]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/else_if_without_else.rs
Run rustfmt on clippy_lints
[rust.git] / clippy_lints / src / else_if_without_else.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 //! lint on if expressions with an else if, but without a final else branch
11
12 use crate::rustc::lint::{in_external_macro, EarlyContext, EarlyLintPass, LintArray, LintContext, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::syntax::ast::*;
15
16 use crate::utils::span_help_and_lint;
17
18 /// **What it does:** Checks for usage of if expressions with an `else if` branch,
19 /// but without a final `else` branch.
20 ///
21 /// **Why is this bad?** Some coding guidelines require this (e.g. MISRA-C:2004 Rule 14.10).
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// if x.is_positive() {
28 ///     a();
29 /// } else if x.is_negative() {
30 ///     b();
31 /// }
32 /// ```
33 ///
34 /// Could be written:
35 ///
36 /// ```rust
37 /// if x.is_positive() {
38 ///     a();
39 /// } else if x.is_negative() {
40 ///     b();
41 /// } else {
42 ///     // we don't care about zero
43 /// }
44 /// ```
45 declare_clippy_lint! {
46     pub ELSE_IF_WITHOUT_ELSE,
47     restriction,
48     "if expression with an `else if`, but without a final `else` branch"
49 }
50
51 #[derive(Copy, Clone)]
52 pub struct ElseIfWithoutElse;
53
54 impl LintPass for ElseIfWithoutElse {
55     fn get_lints(&self) -> LintArray {
56         lint_array!(ELSE_IF_WITHOUT_ELSE)
57     }
58 }
59
60 impl EarlyLintPass for ElseIfWithoutElse {
61     fn check_expr(&mut self, cx: &EarlyContext<'_>, mut item: &Expr) {
62         if in_external_macro(cx.sess(), item.span) {
63             return;
64         }
65
66         while let ExprKind::If(_, _, Some(ref els)) = item.node {
67             if let ExprKind::If(_, _, None) = els.node {
68                 span_help_and_lint(
69                     cx,
70                     ELSE_IF_WITHOUT_ELSE,
71                     els.span,
72                     "if expression with an `else if`, but without a final `else`",
73                     "add an `else` block here",
74                 );
75             }
76
77             item = els;
78         }
79     }
80 }