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