1 //! lint when items are used after statements
3 use clippy_utils::diagnostics::span_lint;
4 use rustc_ast::ast::{Block, ItemKind, StmtKind};
5 use rustc_lint::{EarlyContext, EarlyLintPass};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 /// Checks for items declared after some statement in a block.
13 /// ### Why is this bad?
14 /// Items live for the entire scope they are declared
15 /// in. But statements are processed in order. This might cause confusion as
16 /// it's hard to figure out which item is meant in a statement.
26 /// foo(); // prints "foo"
30 /// foo(); // prints "foo"
44 /// foo(); // prints "foo"
45 /// foo(); // prints "foo"
48 #[clippy::version = "pre 1.29.0"]
49 pub ITEMS_AFTER_STATEMENTS,
51 "blocks where an item comes after a statement"
54 declare_lint_pass!(ItemsAfterStatements => [ITEMS_AFTER_STATEMENTS]);
56 impl EarlyLintPass for ItemsAfterStatements {
57 fn check_block(&mut self, cx: &EarlyContext<'_>, item: &Block) {
58 if in_external_macro(cx.sess, item.span) {
62 // skip initial items and trailing semicolons
66 .map(|stmt| &stmt.kind)
67 .skip_while(|s| matches!(**s, StmtKind::Item(..) | StmtKind::Empty));
69 // lint on all further items
71 if let StmtKind::Item(ref it) = *stmt {
72 if in_external_macro(cx.sess, it.span) {
75 if let ItemKind::MacroDef(..) = it.kind {
76 // do not lint `macro_rules`, but continue processing further statements
81 ITEMS_AFTER_STATEMENTS,
83 "adding items after statements is confusing, since items exist from the \