]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/items_after_statements.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / items_after_statements.rs
1 //! lint when items are used after statements
2
3 use crate::utils::{in_macro, span_lint};
4 use matches::matches;
5 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
7 use syntax::ast::*;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for items declared after some statement in a block.
11     ///
12     /// **Why is this bad?** Items live for the entire scope they are declared
13     /// in. But statements are processed in order. This might cause confusion as
14     /// it's hard to figure out which item is meant in a statement.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// fn foo() {
21     ///     println!("cake");
22     /// }
23     ///
24     /// fn main() {
25     ///     foo(); // prints "foo"
26     ///     fn foo() {
27     ///         println!("foo");
28     ///     }
29     ///     foo(); // prints "foo"
30     /// }
31     /// ```
32     pub ITEMS_AFTER_STATEMENTS,
33     pedantic,
34     "blocks where an item comes after a statement"
35 }
36
37 pub struct ItemsAfterStatements;
38
39 impl LintPass for ItemsAfterStatements {
40     fn get_lints(&self) -> LintArray {
41         lint_array!(ITEMS_AFTER_STATEMENTS)
42     }
43
44     fn name(&self) -> &'static str {
45         "ItemsAfterStatements"
46     }
47 }
48
49 impl EarlyLintPass for ItemsAfterStatements {
50     fn check_block(&mut self, cx: &EarlyContext<'_>, item: &Block) {
51         if in_macro(item.span) {
52             return;
53         }
54
55         // skip initial items
56         let stmts = item
57             .stmts
58             .iter()
59             .map(|stmt| &stmt.node)
60             .skip_while(|s| matches!(**s, StmtKind::Item(..)));
61
62         // lint on all further items
63         for stmt in stmts {
64             if let StmtKind::Item(ref it) = *stmt {
65                 if in_macro(it.span) {
66                     return;
67                 }
68                 if let ItemKind::MacroDef(..) = it.node {
69                     // do not lint `macro_rules`, but continue processing further statements
70                     continue;
71                 }
72                 span_lint(
73                     cx,
74                     ITEMS_AFTER_STATEMENTS,
75                     it.span,
76                     "adding items after statements is confusing, since items exist from the \
77                      start of the scope",
78                 );
79             }
80         }
81     }
82 }