]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/items_after_statements.rs
Reintroduce `extern crate` for non-Cargo dependencies.
[rust.git] / clippy_lints / src / items_after_statements.rs
1 //! lint when items are used after statements
2
3 use matches::matches;
4 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
5 use crate::rustc::{declare_tool_lint, lint_array};
6 use crate::syntax::ast::*;
7 use crate::utils::{in_macro, span_lint};
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.stmts
53             .iter()
54             .map(|stmt| &stmt.node)
55             .skip_while(|s| matches!(**s, StmtKind::Item(..)));
56
57         // lint on all further items
58         for stmt in stmts {
59             if let StmtKind::Item(ref it) = *stmt {
60                 if in_macro(it.span) {
61                     return;
62                 }
63                 if let ItemKind::MacroDef(..) = it.node {
64                     // do not lint `macro_rules`, but continue processing further statements
65                     continue;
66                 }
67                 span_lint(
68                     cx,
69                     ITEMS_AFTER_STATEMENTS,
70                     it.span,
71                     "adding items after statements is confusing, since items exist from the \
72                      start of the scope",
73                 );
74             }
75         }
76     }
77 }