]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/items_after_statements.rs
Auto merge of #76071 - khyperia:configurable_to_immediate, r=eddyb
[rust.git] / src / tools / clippy / 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     /// // Bad
20     /// fn foo() {
21     ///     println!("cake");
22     /// }
23     ///
24     /// fn main() {
25     ///     foo(); // prints "foo"
26     ///     fn foo() {
27     ///         println!("foo");
28     ///     }
29     ///     foo(); // prints "foo"
30     /// }
31     /// ```
32     ///
33     /// ```rust
34     /// // Good
35     /// fn foo() {
36     ///     println!("cake");
37     /// }
38     ///
39     /// fn main() {
40     ///     fn foo() {
41     ///         println!("foo");
42     ///     }
43     ///     foo(); // prints "foo"
44     ///     foo(); // prints "foo"
45     /// }
46     /// ```
47     pub ITEMS_AFTER_STATEMENTS,
48     pedantic,
49     "blocks where an item comes after a statement"
50 }
51
52 declare_lint_pass!(ItemsAfterStatements => [ITEMS_AFTER_STATEMENTS]);
53
54 impl EarlyLintPass for ItemsAfterStatements {
55     fn check_block(&mut self, cx: &EarlyContext<'_>, item: &Block) {
56         if item.span.from_expansion() {
57             return;
58         }
59
60         // skip initial items
61         let stmts = item
62             .stmts
63             .iter()
64             .map(|stmt| &stmt.kind)
65             .skip_while(|s| matches!(**s, StmtKind::Item(..)));
66
67         // lint on all further items
68         for stmt in stmts {
69             if let StmtKind::Item(ref it) = *stmt {
70                 if it.span.from_expansion() {
71                     return;
72                 }
73                 if let ItemKind::MacroDef(..) = it.kind {
74                     // do not lint `macro_rules`, but continue processing further statements
75                     continue;
76                 }
77                 span_lint(
78                     cx,
79                     ITEMS_AFTER_STATEMENTS,
80                     it.span,
81                     "adding items after statements is confusing, since items exist from the \
82                      start of the scope",
83                 );
84             }
85         }
86     }
87 }