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, LintContext};
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 pub ITEMS_AFTER_STATEMENTS,
50 "blocks where an item comes after a statement"
53 declare_lint_pass!(ItemsAfterStatements => [ITEMS_AFTER_STATEMENTS]);
55 impl EarlyLintPass for ItemsAfterStatements {
56 fn check_block(&mut self, cx: &EarlyContext<'_>, item: &Block) {
57 if in_external_macro(cx.sess(), item.span) {
61 // skip initial items and trailing semicolons
65 .map(|stmt| &stmt.kind)
66 .skip_while(|s| matches!(**s, StmtKind::Item(..) | StmtKind::Empty));
68 // lint on all further items
70 if let StmtKind::Item(ref it) = *stmt {
71 if in_external_macro(cx.sess(), it.span) {
74 if let ItemKind::MacroDef(..) = it.kind {
75 // do not lint `macro_rules`, but continue processing further statements
80 ITEMS_AFTER_STATEMENTS,
82 "adding items after statements is confusing, since items exist from the \