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