rustc_lint/
early.rs

1//! Implementation of the early lint pass.
2//!
3//! The early lint pass works on AST nodes after macro expansion and name
4//! resolution, just before AST lowering. These lints are for purely
5//! syntactical lints.
6
7use rustc_ast::ptr::P;
8use rustc_ast::visit::{self as ast_visit, Visitor, walk_list};
9use rustc_ast::{self as ast, HasAttrs};
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_feature::Features;
12use rustc_middle::ty::{RegisteredTools, TyCtxt};
13use rustc_session::Session;
14use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
15use rustc_span::{Ident, Span};
16use tracing::debug;
17
18use crate::context::{EarlyContext, LintContext, LintStore};
19use crate::passes::{EarlyLintPass, EarlyLintPassObject};
20
21pub(super) mod diagnostics;
22
23macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
24    $cx.pass.$f(&$cx.context, $($args),*);
25}) }
26
27/// Implements the AST traversal for early lint passes. `T` provides the
28/// `check_*` methods.
29pub struct EarlyContextAndPass<'ecx, 'tcx, T: EarlyLintPass> {
30    context: EarlyContext<'ecx>,
31    tcx: Option<TyCtxt<'tcx>>,
32    pass: T,
33}
34
35impl<'ecx, 'tcx, T: EarlyLintPass> EarlyContextAndPass<'ecx, 'tcx, T> {
36    #[allow(rustc::diagnostic_outside_of_impl)]
37    fn check_id(&mut self, id: ast::NodeId) {
38        for early_lint in self.context.buffered.take(id) {
39            let BufferedEarlyLint { span, node_id: _, lint_id, diagnostic } = early_lint;
40            self.context.opt_span_lint(lint_id.lint, span, |diag| {
41                diagnostics::decorate_builtin_lint(self.context.sess(), self.tcx, diagnostic, diag);
42            });
43        }
44    }
45
46    /// Merge the lints specified by any lint attributes into the
47    /// current lint context, call the provided function, then reset the
48    /// lints in effect to their previous state.
49    fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'_ [ast::Attribute], f: F)
50    where
51        F: FnOnce(&mut Self),
52    {
53        let is_crate_node = id == ast::CRATE_NODE_ID;
54        debug!(?id);
55        let push = self.context.builder.push(attrs, is_crate_node, None);
56
57        debug!("early context: enter_attrs({:?})", attrs);
58        lint_callback!(self, check_attributes, attrs);
59        ensure_sufficient_stack(|| f(self));
60        debug!("early context: exit_attrs({:?})", attrs);
61        lint_callback!(self, check_attributes_post, attrs);
62        self.context.builder.pop(push);
63    }
64}
65
66impl<'ast, 'ecx, 'tcx, T: EarlyLintPass> ast_visit::Visitor<'ast>
67    for EarlyContextAndPass<'ecx, 'tcx, T>
68{
69    fn visit_id(&mut self, id: rustc_ast::NodeId) {
70        self.check_id(id);
71    }
72
73    fn visit_param(&mut self, param: &'ast ast::Param) {
74        self.with_lint_attrs(param.id, &param.attrs, |cx| {
75            lint_callback!(cx, check_param, param);
76            ast_visit::walk_param(cx, param);
77        });
78    }
79
80    fn visit_item(&mut self, it: &'ast ast::Item) {
81        self.with_lint_attrs(it.id, &it.attrs, |cx| {
82            lint_callback!(cx, check_item, it);
83            ast_visit::walk_item(cx, it);
84            lint_callback!(cx, check_item_post, it);
85        })
86    }
87
88    fn visit_foreign_item(&mut self, it: &'ast ast::ForeignItem) {
89        self.with_lint_attrs(it.id, &it.attrs, |cx| {
90            ast_visit::walk_item(cx, it);
91        })
92    }
93
94    fn visit_pat(&mut self, p: &'ast ast::Pat) {
95        lint_callback!(self, check_pat, p);
96        ast_visit::walk_pat(self, p);
97        lint_callback!(self, check_pat_post, p);
98    }
99
100    fn visit_pat_field(&mut self, field: &'ast ast::PatField) {
101        self.with_lint_attrs(field.id, &field.attrs, |cx| {
102            ast_visit::walk_pat_field(cx, field);
103        });
104    }
105
106    fn visit_expr(&mut self, e: &'ast ast::Expr) {
107        self.with_lint_attrs(e.id, &e.attrs, |cx| {
108            lint_callback!(cx, check_expr, e);
109            ast_visit::walk_expr(cx, e);
110            lint_callback!(cx, check_expr_post, e);
111        })
112    }
113
114    fn visit_expr_field(&mut self, f: &'ast ast::ExprField) {
115        self.with_lint_attrs(f.id, &f.attrs, |cx| {
116            ast_visit::walk_expr_field(cx, f);
117        })
118    }
119
120    fn visit_stmt(&mut self, s: &'ast ast::Stmt) {
121        // Add the statement's lint attributes to our
122        // current state when checking the statement itself.
123        // This allows us to handle attributes like
124        // `#[allow(unused_doc_comments)]`, which apply to
125        // sibling attributes on the same target
126        //
127        // Note that statements get their attributes from
128        // the AST struct that they wrap (e.g. an item)
129        self.with_lint_attrs(s.id, s.attrs(), |cx| {
130            lint_callback!(cx, check_stmt, s);
131            ast_visit::walk_stmt(cx, s);
132        });
133    }
134
135    fn visit_fn(&mut self, fk: ast_visit::FnKind<'ast>, span: Span, id: ast::NodeId) {
136        lint_callback!(self, check_fn, fk, span, id);
137        ast_visit::walk_fn(self, fk);
138    }
139
140    fn visit_field_def(&mut self, s: &'ast ast::FieldDef) {
141        self.with_lint_attrs(s.id, &s.attrs, |cx| {
142            ast_visit::walk_field_def(cx, s);
143        })
144    }
145
146    fn visit_variant(&mut self, v: &'ast ast::Variant) {
147        self.with_lint_attrs(v.id, &v.attrs, |cx| {
148            lint_callback!(cx, check_variant, v);
149            ast_visit::walk_variant(cx, v);
150        })
151    }
152
153    fn visit_ty(&mut self, t: &'ast ast::Ty) {
154        lint_callback!(self, check_ty, t);
155        ast_visit::walk_ty(self, t);
156    }
157
158    fn visit_ident(&mut self, ident: &Ident) {
159        lint_callback!(self, check_ident, ident);
160    }
161
162    fn visit_local(&mut self, l: &'ast ast::Local) {
163        self.with_lint_attrs(l.id, &l.attrs, |cx| {
164            lint_callback!(cx, check_local, l);
165            ast_visit::walk_local(cx, l);
166        })
167    }
168
169    fn visit_block(&mut self, b: &'ast ast::Block) {
170        lint_callback!(self, check_block, b);
171        ast_visit::walk_block(self, b);
172    }
173
174    fn visit_arm(&mut self, a: &'ast ast::Arm) {
175        self.with_lint_attrs(a.id, &a.attrs, |cx| {
176            lint_callback!(cx, check_arm, a);
177            ast_visit::walk_arm(cx, a);
178        })
179    }
180
181    fn visit_generic_arg(&mut self, arg: &'ast ast::GenericArg) {
182        lint_callback!(self, check_generic_arg, arg);
183        ast_visit::walk_generic_arg(self, arg);
184    }
185
186    fn visit_generic_param(&mut self, param: &'ast ast::GenericParam) {
187        self.with_lint_attrs(param.id, &param.attrs, |cx| {
188            lint_callback!(cx, check_generic_param, param);
189            ast_visit::walk_generic_param(cx, param);
190        });
191    }
192
193    fn visit_generics(&mut self, g: &'ast ast::Generics) {
194        lint_callback!(self, check_generics, g);
195        ast_visit::walk_generics(self, g);
196    }
197
198    fn visit_where_predicate(&mut self, p: &'ast ast::WherePredicate) {
199        lint_callback!(self, enter_where_predicate, p);
200        ast_visit::walk_where_predicate(self, p);
201        lint_callback!(self, exit_where_predicate, p);
202    }
203
204    fn visit_poly_trait_ref(&mut self, t: &'ast ast::PolyTraitRef) {
205        lint_callback!(self, check_poly_trait_ref, t);
206        ast_visit::walk_poly_trait_ref(self, t);
207    }
208
209    fn visit_assoc_item(&mut self, item: &'ast ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
210        self.with_lint_attrs(item.id, &item.attrs, |cx| {
211            match ctxt {
212                ast_visit::AssocCtxt::Trait => {
213                    lint_callback!(cx, check_trait_item, item);
214                }
215                ast_visit::AssocCtxt::Impl { .. } => {
216                    lint_callback!(cx, check_impl_item, item);
217                }
218            }
219            ast_visit::walk_assoc_item(cx, item, ctxt);
220            match ctxt {
221                ast_visit::AssocCtxt::Trait => {
222                    lint_callback!(cx, check_trait_item_post, item);
223                }
224                ast_visit::AssocCtxt::Impl { .. } => {
225                    lint_callback!(cx, check_impl_item_post, item);
226                }
227            }
228        });
229    }
230
231    fn visit_attribute(&mut self, attr: &'ast ast::Attribute) {
232        lint_callback!(self, check_attribute, attr);
233        ast_visit::walk_attribute(self, attr);
234    }
235
236    fn visit_macro_def(&mut self, mac: &'ast ast::MacroDef) {
237        lint_callback!(self, check_mac_def, mac);
238    }
239
240    fn visit_mac_call(&mut self, mac: &'ast ast::MacCall) {
241        lint_callback!(self, check_mac, mac);
242        ast_visit::walk_mac(self, mac);
243    }
244}
245
246// Combines multiple lint passes into a single pass, at runtime. Each
247// `check_foo` method in `$methods` within this pass simply calls `check_foo`
248// once per `$pass`. Compare with `declare_combined_early_lint_pass`, which is
249// similar, but combines lint passes at compile time.
250struct RuntimeCombinedEarlyLintPass<'a> {
251    passes: &'a mut [EarlyLintPassObject],
252}
253
254#[allow(rustc::lint_pass_impl_without_macro)]
255impl LintPass for RuntimeCombinedEarlyLintPass<'_> {
256    fn name(&self) -> &'static str {
257        panic!()
258    }
259    fn get_lints(&self) -> crate::LintVec {
260        panic!()
261    }
262}
263
264macro_rules! impl_early_lint_pass {
265    ([], [$($(#[$attr:meta])* fn $f:ident($($param:ident: $arg:ty),*);)*]) => (
266        impl EarlyLintPass for RuntimeCombinedEarlyLintPass<'_> {
267            $(fn $f(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
268                for pass in self.passes.iter_mut() {
269                    pass.$f(context, $($param),*);
270                }
271            })*
272        }
273    )
274}
275
276crate::early_lint_methods!(impl_early_lint_pass, []);
277
278/// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
279/// This trait generalizes over those nodes.
280pub trait EarlyCheckNode<'a>: Copy {
281    fn id(self) -> ast::NodeId;
282    fn attrs(self) -> &'a [ast::Attribute];
283    fn check<'ecx, 'tcx, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'ecx, 'tcx, T>);
284}
285
286impl<'a> EarlyCheckNode<'a> for (&'a ast::Crate, &'a [ast::Attribute]) {
287    fn id(self) -> ast::NodeId {
288        ast::CRATE_NODE_ID
289    }
290    fn attrs(self) -> &'a [ast::Attribute] {
291        self.1
292    }
293    fn check<'ecx, 'tcx, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'ecx, 'tcx, T>) {
294        lint_callback!(cx, check_crate, self.0);
295        ast_visit::walk_crate(cx, self.0);
296        lint_callback!(cx, check_crate_post, self.0);
297    }
298}
299
300impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
301    fn id(self) -> ast::NodeId {
302        self.0
303    }
304    fn attrs(self) -> &'a [ast::Attribute] {
305        self.1
306    }
307    fn check<'ecx, 'tcx, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'ecx, 'tcx, T>) {
308        walk_list!(cx, visit_attribute, self.1);
309        walk_list!(cx, visit_item, self.2);
310    }
311}
312
313pub fn check_ast_node<'a>(
314    sess: &Session,
315    tcx: Option<TyCtxt<'_>>,
316    features: &Features,
317    pre_expansion: bool,
318    lint_store: &LintStore,
319    registered_tools: &RegisteredTools,
320    lint_buffer: Option<LintBuffer>,
321    builtin_lints: impl EarlyLintPass + 'static,
322    check_node: impl EarlyCheckNode<'a>,
323) {
324    let context = EarlyContext::new(
325        sess,
326        features,
327        !pre_expansion,
328        lint_store,
329        registered_tools,
330        lint_buffer.unwrap_or_default(),
331    );
332
333    // Note: `passes` is often empty. In that case, it's faster to run
334    // `builtin_lints` directly rather than bundling it up into the
335    // `RuntimeCombinedEarlyLintPass`.
336    let passes =
337        if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
338    if passes.is_empty() {
339        check_ast_node_inner(sess, tcx, check_node, context, builtin_lints);
340    } else {
341        let mut passes: Vec<_> = passes.iter().map(|mk_pass| (mk_pass)()).collect();
342        passes.push(Box::new(builtin_lints));
343        let pass = RuntimeCombinedEarlyLintPass { passes: &mut passes[..] };
344        check_ast_node_inner(sess, tcx, check_node, context, pass);
345    }
346}
347
348fn check_ast_node_inner<'a, T: EarlyLintPass>(
349    sess: &Session,
350    tcx: Option<TyCtxt<'_>>,
351    check_node: impl EarlyCheckNode<'a>,
352    context: EarlyContext<'_>,
353    pass: T,
354) {
355    let mut cx = EarlyContextAndPass { context, tcx, pass };
356
357    cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
358
359    // All of the buffered lints should have been emitted at this point.
360    // If not, that means that we somehow buffered a lint for a node id
361    // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
362    for (id, lints) in cx.context.buffered.map {
363        if !lints.is_empty() {
364            assert!(
365                sess.dcx().has_errors().is_some(),
366                "failed to process buffered lint here (dummy = {})",
367                id == ast::DUMMY_NODE_ID
368            );
369            break;
370        }
371    }
372}