1 //! Implementation of lint checking.
3 //! The lint checking is mostly consolidated into one pass which runs
4 //! after all other analyses. Throughout compilation, lint warnings
5 //! can be added via the `add_lint` method on the Session structure. This
6 //! requires a span and an ID of the node that the lint is being added to. The
7 //! lint isn't actually emitted at that time because it is unknown what the
8 //! actual lint level at that location is.
10 //! To actually emit lint warnings/errors, a separate pass is used.
11 //! A context keeps track of the current state of all lint levels.
12 //! Upon entering a node of the ast which can modify the lint settings, the
13 //! previous lint state is pushed onto a stack and the ast is then recursed
14 //! upon. As the ast is traversed, this keeps track of the current lint level
15 //! for all lint attributes.
17 use crate::context::{EarlyContext, LintContext, LintStore};
18 use crate::passes::{EarlyLintPass, EarlyLintPassObject};
19 use rustc_ast::ptr::P;
20 use rustc_ast::visit::{self as ast_visit, Visitor};
21 use rustc_ast::{self as ast, walk_list, HasAttrs};
22 use rustc_data_structures::stack::ensure_sufficient_stack;
23 use rustc_middle::ty::RegisteredTools;
24 use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
25 use rustc_session::Session;
26 use rustc_span::symbol::Ident;
29 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
30 $cx.pass.$f(&$cx.context, $($args),*);
33 /// Implements the AST traversal for early lint passes. `T` provides the
34 /// `check_*` methods.
35 pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
36 context: EarlyContext<'a>,
40 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
41 // This always-inlined function is for the hot call site.
43 fn inlined_check_id(&mut self, id: ast::NodeId) {
44 for early_lint in self.context.buffered.take(id) {
45 let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
46 self.context.lookup_with_diagnostics(
56 // This non-inlined function is for the cold call sites.
57 fn check_id(&mut self, id: ast::NodeId) {
58 self.inlined_check_id(id)
61 /// Merge the lints specified by any lint attributes into the
62 /// current lint context, call the provided function, then reset the
63 /// lints in effect to their previous state.
64 fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
68 let is_crate_node = id == ast::CRATE_NODE_ID;
70 let push = self.context.builder.push(attrs, is_crate_node, None);
72 self.inlined_check_id(id);
73 debug!("early context: enter_attrs({:?})", attrs);
74 lint_callback!(self, enter_lint_attrs, attrs);
75 ensure_sufficient_stack(|| f(self));
76 debug!("early context: exit_attrs({:?})", attrs);
77 lint_callback!(self, exit_lint_attrs, attrs);
78 self.context.builder.pop(push);
82 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
83 fn visit_param(&mut self, param: &'a ast::Param) {
84 self.with_lint_attrs(param.id, ¶m.attrs, |cx| {
85 lint_callback!(cx, check_param, param);
86 ast_visit::walk_param(cx, param);
90 fn visit_item(&mut self, it: &'a ast::Item) {
91 self.with_lint_attrs(it.id, &it.attrs, |cx| {
92 lint_callback!(cx, check_item, it);
93 ast_visit::walk_item(cx, it);
94 lint_callback!(cx, check_item_post, it);
98 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
99 self.with_lint_attrs(it.id, &it.attrs, |cx| {
100 ast_visit::walk_foreign_item(cx, it);
104 fn visit_pat(&mut self, p: &'a ast::Pat) {
105 lint_callback!(self, check_pat, p);
107 ast_visit::walk_pat(self, p);
108 lint_callback!(self, check_pat_post, p);
111 fn visit_pat_field(&mut self, field: &'a ast::PatField) {
112 self.with_lint_attrs(field.id, &field.attrs, |cx| {
113 ast_visit::walk_pat_field(cx, field);
117 fn visit_anon_const(&mut self, c: &'a ast::AnonConst) {
119 ast_visit::walk_anon_const(self, c);
122 fn visit_expr(&mut self, e: &'a ast::Expr) {
123 self.with_lint_attrs(e.id, &e.attrs, |cx| {
124 lint_callback!(cx, check_expr, e);
125 ast_visit::walk_expr(cx, e);
129 fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
130 self.with_lint_attrs(f.id, &f.attrs, |cx| {
131 ast_visit::walk_expr_field(cx, f);
135 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
136 // Add the statement's lint attributes to our
137 // current state when checking the statement itself.
138 // This allows us to handle attributes like
139 // `#[allow(unused_doc_comments)]`, which apply to
140 // sibling attributes on the same target
142 // Note that statements get their attributes from
143 // the AST struct that they wrap (e.g. an item)
144 self.with_lint_attrs(s.id, s.attrs(), |cx| {
145 lint_callback!(cx, check_stmt, s);
148 // The visitor for the AST struct wrapped
149 // by the statement (e.g. `Item`) will call
150 // `with_lint_attrs`, so do this walk
151 // outside of the above `with_lint_attrs` call
152 ast_visit::walk_stmt(self, s);
155 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) {
156 lint_callback!(self, check_fn, fk, span, id);
158 ast_visit::walk_fn(self, fk);
160 // Explicitly check for lints associated with 'closure_id', since
161 // it does not have a corresponding AST node
162 if let ast_visit::FnKind::Fn(_, _, sig, _, _, _) = fk {
163 if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness {
164 self.check_id(closure_id);
169 fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
170 if let Some(ctor_node_id) = s.ctor_node_id() {
171 self.check_id(ctor_node_id);
173 ast_visit::walk_struct_def(self, s);
176 fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
177 self.with_lint_attrs(s.id, &s.attrs, |cx| {
178 ast_visit::walk_field_def(cx, s);
182 fn visit_variant(&mut self, v: &'a ast::Variant) {
183 self.with_lint_attrs(v.id, &v.attrs, |cx| {
184 lint_callback!(cx, check_variant, v);
185 ast_visit::walk_variant(cx, v);
189 fn visit_ty(&mut self, t: &'a ast::Ty) {
190 lint_callback!(self, check_ty, t);
192 ast_visit::walk_ty(self, t);
195 fn visit_ident(&mut self, ident: Ident) {
196 lint_callback!(self, check_ident, ident);
199 fn visit_local(&mut self, l: &'a ast::Local) {
200 self.with_lint_attrs(l.id, &l.attrs, |cx| {
201 lint_callback!(cx, check_local, l);
202 ast_visit::walk_local(cx, l);
206 fn visit_block(&mut self, b: &'a ast::Block) {
207 lint_callback!(self, check_block, b);
209 ast_visit::walk_block(self, b);
212 fn visit_arm(&mut self, a: &'a ast::Arm) {
213 self.with_lint_attrs(a.id, &a.attrs, |cx| {
214 lint_callback!(cx, check_arm, a);
215 ast_visit::walk_arm(cx, a);
219 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
220 // Explicitly check for lints associated with 'closure_id', since
221 // it does not have a corresponding AST node
223 ast::ExprKind::Closure(box ast::Closure {
224 asyncness: ast::Async::Yes { closure_id, .. },
227 | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id),
232 fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) {
233 lint_callback!(self, check_generic_arg, arg);
234 ast_visit::walk_generic_arg(self, arg);
237 fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
238 self.with_lint_attrs(param.id, ¶m.attrs, |cx| {
239 lint_callback!(cx, check_generic_param, param);
240 ast_visit::walk_generic_param(cx, param);
244 fn visit_generics(&mut self, g: &'a ast::Generics) {
245 lint_callback!(self, check_generics, g);
246 ast_visit::walk_generics(self, g);
249 fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
250 ast_visit::walk_where_predicate(self, p);
253 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
254 lint_callback!(self, check_poly_trait_ref, t);
255 ast_visit::walk_poly_trait_ref(self, t);
258 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
259 self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
260 ast_visit::AssocCtxt::Trait => {
261 lint_callback!(cx, check_trait_item, item);
262 ast_visit::walk_assoc_item(cx, item, ctxt);
264 ast_visit::AssocCtxt::Impl => {
265 lint_callback!(cx, check_impl_item, item);
266 ast_visit::walk_assoc_item(cx, item, ctxt);
271 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt) {
272 self.check_id(lt.id);
275 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
277 ast_visit::walk_path(self, p);
280 fn visit_path_segment(&mut self, s: &'a ast::PathSegment) {
282 ast_visit::walk_path_segment(self, s);
285 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
286 lint_callback!(self, check_attribute, attr);
289 fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
290 lint_callback!(self, check_mac_def, mac);
294 fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
295 lint_callback!(self, check_mac, mac);
296 ast_visit::walk_mac(self, mac);
300 // Combines multiple lint passes into a single pass, at runtime. Each
301 // `check_foo` method in `$methods` within this pass simply calls `check_foo`
302 // once per `$pass`. Compare with `declare_combined_early_lint_pass`, which is
303 // similar, but combines lint passes at compile time.
304 struct RuntimeCombinedEarlyLintPass<'a> {
305 passes: &'a mut [EarlyLintPassObject],
308 #[allow(rustc::lint_pass_impl_without_macro)]
309 impl LintPass for RuntimeCombinedEarlyLintPass<'_> {
310 fn name(&self) -> &'static str {
315 macro_rules! impl_early_lint_pass {
316 ([], [$($(#[$attr:meta])* fn $f:ident($($param:ident: $arg:ty),*);)*]) => (
317 impl EarlyLintPass for RuntimeCombinedEarlyLintPass<'_> {
318 $(fn $f(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
319 for pass in self.passes.iter_mut() {
320 pass.$f(context, $($param),*);
327 crate::early_lint_methods!(impl_early_lint_pass, []);
329 /// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
330 /// This trait generalizes over those nodes.
331 pub trait EarlyCheckNode<'a>: Copy {
332 fn id(self) -> ast::NodeId;
333 fn attrs<'b>(self) -> &'b [ast::Attribute]
336 fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>)
341 impl<'a> EarlyCheckNode<'a> for &'a ast::Crate {
342 fn id(self) -> ast::NodeId {
345 fn attrs<'b>(self) -> &'b [ast::Attribute]
351 fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>)
355 lint_callback!(cx, check_crate, self);
356 ast_visit::walk_crate(cx, self);
357 lint_callback!(cx, check_crate_post, self);
361 impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
362 fn id(self) -> ast::NodeId {
365 fn attrs<'b>(self) -> &'b [ast::Attribute]
371 fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>)
375 walk_list!(cx, visit_attribute, self.1);
376 walk_list!(cx, visit_item, self.2);
380 pub fn check_ast_node<'a>(
383 lint_store: &LintStore,
384 registered_tools: &RegisteredTools,
385 lint_buffer: Option<LintBuffer>,
386 builtin_lints: impl EarlyLintPass + 'static,
387 check_node: impl EarlyCheckNode<'a>,
389 let context = EarlyContext::new(
394 lint_buffer.unwrap_or_default(),
397 // Note: `passes` is often empty. In that case, it's faster to run
398 // `builtin_lints` directly rather than bundling it up into the
399 // `RuntimeCombinedEarlyLintPass`.
401 if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
402 if passes.is_empty() {
403 check_ast_node_inner(sess, check_node, context, builtin_lints);
405 let mut passes: Vec<_> = passes.iter().map(|mk_pass| (mk_pass)()).collect();
406 passes.push(Box::new(builtin_lints));
407 let pass = RuntimeCombinedEarlyLintPass { passes: &mut passes[..] };
408 check_ast_node_inner(sess, check_node, context, pass);
412 pub fn check_ast_node_inner<'a, T: EarlyLintPass>(
414 check_node: impl EarlyCheckNode<'a>,
415 context: EarlyContext<'_>,
418 let mut cx = EarlyContextAndPass { context, pass };
420 cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
422 // All of the buffered lints should have been emitted at this point.
423 // If not, that means that we somehow buffered a lint for a node id
424 // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
425 for (id, lints) in cx.context.buffered.map {
426 for early_lint in lints {
430 "failed to process buffered lint here (dummy = {})",
431 id == ast::DUMMY_NODE_ID