]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/items_after_statements.rs
Merge branch 'master' into add-lints-aseert-checks
[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 /// **What it does:** Checks for items declared after some statement in a block.
10 ///
11 /// **Why is this bad?** Items live for the entire scope they are declared
12 /// in. But statements are processed in order. This might cause confusion as
13 /// it's hard to figure out which item is meant in a statement.
14 ///
15 /// **Known problems:** None.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// fn foo() {
20 ///     println!("cake");
21 /// }
22 ///
23 /// fn main() {
24 ///     foo(); // prints "foo"
25 ///     fn foo() {
26 ///         println!("foo");
27 ///     }
28 ///     foo(); // prints "foo"
29 /// }
30 /// ```
31 declare_clippy_lint! {
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
45 impl EarlyLintPass for ItemsAfterStatements {
46     fn check_block(&mut self, cx: &EarlyContext<'_>, item: &Block) {
47         if in_macro(item.span) {
48             return;
49         }
50
51         // skip initial items
52         let stmts = item
53             .stmts
54             .iter()
55             .map(|stmt| &stmt.node)
56             .skip_while(|s| matches!(**s, StmtKind::Item(..)));
57
58         // lint on all further items
59         for stmt in stmts {
60             if let StmtKind::Item(ref it) = *stmt {
61                 if in_macro(it.span) {
62                     return;
63                 }
64                 if let ItemKind::MacroDef(..) = it.node {
65                     // do not lint `macro_rules`, but continue processing further statements
66                     continue;
67                 }
68                 span_lint(
69                     cx,
70                     ITEMS_AFTER_STATEMENTS,
71                     it.span,
72                     "adding items after statements is confusing, since items exist from the \
73                      start of the scope",
74                 );
75             }
76         }
77     }
78 }