]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/items_after_statements.rs
Make lint descriptions short and to the point; always fitting the column "triggers...
[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.iter()
51                               .map(|stmt| &stmt.node)
52                               .skip_while(|s| matches!(**s, StmtKind::Item(..)));
53
54         // lint on all further items
55         for stmt in stmts {
56             if let StmtKind::Item(ref it) = *stmt {
57                 if in_macro(cx, it.span) {
58                     return;
59                 }
60                 span_lint(cx,
61                           ITEMS_AFTER_STATEMENTS,
62                           it.span,
63                           "adding items after statements is confusing, since items exist from the \
64                            start of the scope");
65             }
66         }
67     }
68 }