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