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