]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/items_after_statements.rs
Auto merge of #5365 - mgr-inz-rafal:issue4983_bool_updates, r=yaahc
[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 rustc_ast::ast::{Block, ItemKind, StmtKind};
5 use rustc_lint::{EarlyContext, EarlyLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
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     pub ITEMS_AFTER_STATEMENTS,
32     pedantic,
33     "blocks where an item comes after a statement"
34 }
35
36 declare_lint_pass!(ItemsAfterStatements => [ITEMS_AFTER_STATEMENTS]);
37
38 impl EarlyLintPass for ItemsAfterStatements {
39     fn check_block(&mut self, cx: &EarlyContext<'_>, item: &Block) {
40         if item.span.from_expansion() {
41             return;
42         }
43
44         // skip initial items
45         let stmts = item
46             .stmts
47             .iter()
48             .map(|stmt| &stmt.kind)
49             .skip_while(|s| matches!(**s, StmtKind::Item(..)));
50
51         // lint on all further items
52         for stmt in stmts {
53             if let StmtKind::Item(ref it) = *stmt {
54                 if it.span.from_expansion() {
55                     return;
56                 }
57                 if let ItemKind::MacroDef(..) = it.kind {
58                     // do not lint `macro_rules`, but continue processing further statements
59                     continue;
60                 }
61                 span_lint(
62                     cx,
63                     ITEMS_AFTER_STATEMENTS,
64                     it.span,
65                     "adding items after statements is confusing, since items exist from the \
66                      start of the scope",
67                 );
68             }
69         }
70     }
71 }