1 //! Implementation of lint checking.
2 //!
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.
9 //!
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.
16
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;
27 use rustc_span::Span;
28
29 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
30 $cx.pass.$f(&$cx.context, $($args),*);
31 }) }
32
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>,
37 pass: T,
38 }
39
40 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
41 // This always-inlined function is for the hot call site.
42 #[inline(always)]
43 #[allow(rustc::diagnostic_outside_of_impl)]
inlined_check_id(&mut self, id: ast::NodeId)44 fn inlined_check_id(&mut self, id: ast::NodeId) {
45 for early_lint in self.context.buffered.take(id) {
46 let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
47 self.context.lookup_with_diagnostics(
48 lint_id.lint,
49 Some(span),
50 msg,
51 |lint| lint,
52 diagnostic,
53 );
54 }
55 }
56
57 // This non-inlined function is for the cold call sites.
check_id(&mut self, id: ast::NodeId)58 fn check_id(&mut self, id: ast::NodeId) {
59 self.inlined_check_id(id)
60 }
61
62 /// Merge the lints specified by any lint attributes into the
63 /// current lint context, call the provided function, then reset the
64 /// lints in effect to their previous state.
with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F) where F: FnOnce(&mut Self),65 fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
66 where
67 F: FnOnce(&mut Self),
68 {
69 let is_crate_node = id == ast::CRATE_NODE_ID;
70 debug!(?id);
71 let push = self.context.builder.push(attrs, is_crate_node, None);
72
73 self.inlined_check_id(id);
74 debug!("early context: enter_attrs({:?})", attrs);
75 lint_callback!(self, enter_lint_attrs, attrs);
76 ensure_sufficient_stack(|| f(self));
77 debug!("early context: exit_attrs({:?})", attrs);
78 lint_callback!(self, exit_lint_attrs, attrs);
79 self.context.builder.pop(push);
80 }
81 }
82
83 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
visit_param(&mut self, param: &'a ast::Param)84 fn visit_param(&mut self, param: &'a ast::Param) {
85 self.with_lint_attrs(param.id, ¶m.attrs, |cx| {
86 lint_callback!(cx, check_param, param);
87 ast_visit::walk_param(cx, param);
88 });
89 }
90
visit_item(&mut self, it: &'a ast::Item)91 fn visit_item(&mut self, it: &'a ast::Item) {
92 self.with_lint_attrs(it.id, &it.attrs, |cx| {
93 lint_callback!(cx, check_item, it);
94 ast_visit::walk_item(cx, it);
95 lint_callback!(cx, check_item_post, it);
96 })
97 }
98
visit_foreign_item(&mut self, it: &'a ast::ForeignItem)99 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
100 self.with_lint_attrs(it.id, &it.attrs, |cx| {
101 ast_visit::walk_foreign_item(cx, it);
102 })
103 }
104
visit_pat(&mut self, p: &'a ast::Pat)105 fn visit_pat(&mut self, p: &'a ast::Pat) {
106 lint_callback!(self, check_pat, p);
107 self.check_id(p.id);
108 ast_visit::walk_pat(self, p);
109 lint_callback!(self, check_pat_post, p);
110 }
111
visit_pat_field(&mut self, field: &'a ast::PatField)112 fn visit_pat_field(&mut self, field: &'a ast::PatField) {
113 self.with_lint_attrs(field.id, &field.attrs, |cx| {
114 ast_visit::walk_pat_field(cx, field);
115 });
116 }
117
visit_anon_const(&mut self, c: &'a ast::AnonConst)118 fn visit_anon_const(&mut self, c: &'a ast::AnonConst) {
119 self.check_id(c.id);
120 ast_visit::walk_anon_const(self, c);
121 }
122
visit_expr(&mut self, e: &'a ast::Expr)123 fn visit_expr(&mut self, e: &'a ast::Expr) {
124 self.with_lint_attrs(e.id, &e.attrs, |cx| {
125 lint_callback!(cx, check_expr, e);
126 ast_visit::walk_expr(cx, e);
127 })
128 }
129
visit_expr_field(&mut self, f: &'a ast::ExprField)130 fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
131 self.with_lint_attrs(f.id, &f.attrs, |cx| {
132 ast_visit::walk_expr_field(cx, f);
133 })
134 }
135
visit_stmt(&mut self, s: &'a ast::Stmt)136 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
137 // Add the statement's lint attributes to our
138 // current state when checking the statement itself.
139 // This allows us to handle attributes like
140 // `#[allow(unused_doc_comments)]`, which apply to
141 // sibling attributes on the same target
142 //
143 // Note that statements get their attributes from
144 // the AST struct that they wrap (e.g. an item)
145 self.with_lint_attrs(s.id, s.attrs(), |cx| {
146 lint_callback!(cx, check_stmt, s);
147 cx.check_id(s.id);
148 });
149 // The visitor for the AST struct wrapped
150 // by the statement (e.g. `Item`) will call
151 // `with_lint_attrs`, so do this walk
152 // outside of the above `with_lint_attrs` call
153 ast_visit::walk_stmt(self, s);
154 }
155
visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId)156 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) {
157 lint_callback!(self, check_fn, fk, span, id);
158 self.check_id(id);
159 ast_visit::walk_fn(self, fk);
160
161 // Explicitly check for lints associated with 'closure_id', since
162 // it does not have a corresponding AST node
163 if let ast_visit::FnKind::Fn(_, _, sig, _, _, _) = fk {
164 if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness {
165 self.check_id(closure_id);
166 }
167 }
168 }
169
visit_variant_data(&mut self, s: &'a ast::VariantData)170 fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
171 if let Some(ctor_node_id) = s.ctor_node_id() {
172 self.check_id(ctor_node_id);
173 }
174 ast_visit::walk_struct_def(self, s);
175 }
176
visit_field_def(&mut self, s: &'a ast::FieldDef)177 fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
178 self.with_lint_attrs(s.id, &s.attrs, |cx| {
179 ast_visit::walk_field_def(cx, s);
180 })
181 }
182
visit_variant(&mut self, v: &'a ast::Variant)183 fn visit_variant(&mut self, v: &'a ast::Variant) {
184 self.with_lint_attrs(v.id, &v.attrs, |cx| {
185 lint_callback!(cx, check_variant, v);
186 ast_visit::walk_variant(cx, v);
187 })
188 }
189
visit_ty(&mut self, t: &'a ast::Ty)190 fn visit_ty(&mut self, t: &'a ast::Ty) {
191 lint_callback!(self, check_ty, t);
192 self.check_id(t.id);
193 ast_visit::walk_ty(self, t);
194 }
195
visit_ident(&mut self, ident: Ident)196 fn visit_ident(&mut self, ident: Ident) {
197 lint_callback!(self, check_ident, ident);
198 }
199
visit_local(&mut self, l: &'a ast::Local)200 fn visit_local(&mut self, l: &'a ast::Local) {
201 self.with_lint_attrs(l.id, &l.attrs, |cx| {
202 lint_callback!(cx, check_local, l);
203 ast_visit::walk_local(cx, l);
204 })
205 }
206
visit_block(&mut self, b: &'a ast::Block)207 fn visit_block(&mut self, b: &'a ast::Block) {
208 lint_callback!(self, check_block, b);
209 self.check_id(b.id);
210 ast_visit::walk_block(self, b);
211 }
212
visit_arm(&mut self, a: &'a ast::Arm)213 fn visit_arm(&mut self, a: &'a ast::Arm) {
214 self.with_lint_attrs(a.id, &a.attrs, |cx| {
215 lint_callback!(cx, check_arm, a);
216 ast_visit::walk_arm(cx, a);
217 })
218 }
219
visit_expr_post(&mut self, e: &'a ast::Expr)220 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
221 // Explicitly check for lints associated with 'closure_id', since
222 // it does not have a corresponding AST node
223 match e.kind {
224 ast::ExprKind::Closure(box ast::Closure {
225 asyncness: ast::Async::Yes { closure_id, .. },
226 ..
227 }) => self.check_id(closure_id),
228 _ => {}
229 }
230 }
231
visit_generic_arg(&mut self, arg: &'a ast::GenericArg)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);
235 }
236
visit_generic_param(&mut self, param: &'a ast::GenericParam)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);
241 });
242 }
243
visit_generics(&mut self, g: &'a ast::Generics)244 fn visit_generics(&mut self, g: &'a ast::Generics) {
245 lint_callback!(self, check_generics, g);
246 ast_visit::walk_generics(self, g);
247 }
248
visit_where_predicate(&mut self, p: &'a ast::WherePredicate)249 fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
250 lint_callback!(self, enter_where_predicate, p);
251 ast_visit::walk_where_predicate(self, p);
252 lint_callback!(self, exit_where_predicate, p);
253 }
254
visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef)255 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
256 lint_callback!(self, check_poly_trait_ref, t);
257 ast_visit::walk_poly_trait_ref(self, t);
258 }
259
visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt)260 fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
261 self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
262 ast_visit::AssocCtxt::Trait => {
263 lint_callback!(cx, check_trait_item, item);
264 ast_visit::walk_assoc_item(cx, item, ctxt);
265 }
266 ast_visit::AssocCtxt::Impl => {
267 lint_callback!(cx, check_impl_item, item);
268 ast_visit::walk_assoc_item(cx, item, ctxt);
269 }
270 });
271 }
272
visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt)273 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt) {
274 self.check_id(lt.id);
275 }
276
visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId)277 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
278 self.check_id(id);
279 ast_visit::walk_path(self, p);
280 }
281
visit_path_segment(&mut self, s: &'a ast::PathSegment)282 fn visit_path_segment(&mut self, s: &'a ast::PathSegment) {
283 self.check_id(s.id);
284 ast_visit::walk_path_segment(self, s);
285 }
286
visit_attribute(&mut self, attr: &'a ast::Attribute)287 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
288 lint_callback!(self, check_attribute, attr);
289 }
290
visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId)291 fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
292 lint_callback!(self, check_mac_def, mac);
293 self.check_id(id);
294 }
295
visit_mac_call(&mut self, mac: &'a ast::MacCall)296 fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
297 lint_callback!(self, check_mac, mac);
298 ast_visit::walk_mac(self, mac);
299 }
300 }
301
302 // Combines multiple lint passes into a single pass, at runtime. Each
303 // `check_foo` method in `$methods` within this pass simply calls `check_foo`
304 // once per `$pass`. Compare with `declare_combined_early_lint_pass`, which is
305 // similar, but combines lint passes at compile time.
306 struct RuntimeCombinedEarlyLintPass<'a> {
307 passes: &'a mut [EarlyLintPassObject],
308 }
309
310 #[allow(rustc::lint_pass_impl_without_macro)]
311 impl LintPass for RuntimeCombinedEarlyLintPass<'_> {
name(&self) -> &'static str312 fn name(&self) -> &'static str {
313 panic!()
314 }
315 }
316
317 macro_rules! impl_early_lint_pass {
318 ([], [$($(#[$attr:meta])* fn $f:ident($($param:ident: $arg:ty),*);)*]) => (
319 impl EarlyLintPass for RuntimeCombinedEarlyLintPass<'_> {
320 $(fn $f(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
321 for pass in self.passes.iter_mut() {
322 pass.$f(context, $($param),*);
323 }
324 })*
325 }
326 )
327 }
328
329 crate::early_lint_methods!(impl_early_lint_pass, []);
330
331 /// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
332 /// This trait generalizes over those nodes.
333 pub trait EarlyCheckNode<'a>: Copy {
id(self) -> ast::NodeId334 fn id(self) -> ast::NodeId;
attrs<'b>(self) -> &'b [ast::Attribute] where 'a: 'b335 fn attrs<'b>(self) -> &'b [ast::Attribute]
336 where
337 'a: 'b;
check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>) where 'a: 'b338 fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>)
339 where
340 'a: 'b;
341 }
342
343 impl<'a> EarlyCheckNode<'a> for (&'a ast::Crate, &'a [ast::Attribute]) {
id(self) -> ast::NodeId344 fn id(self) -> ast::NodeId {
345 ast::CRATE_NODE_ID
346 }
attrs<'b>(self) -> &'b [ast::Attribute] where 'a: 'b,347 fn attrs<'b>(self) -> &'b [ast::Attribute]
348 where
349 'a: 'b,
350 {
351 &self.1
352 }
check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>) where 'a: 'b,353 fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>)
354 where
355 'a: 'b,
356 {
357 lint_callback!(cx, check_crate, self.0);
358 ast_visit::walk_crate(cx, self.0);
359 lint_callback!(cx, check_crate_post, self.0);
360 }
361 }
362
363 impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
id(self) -> ast::NodeId364 fn id(self) -> ast::NodeId {
365 self.0
366 }
attrs<'b>(self) -> &'b [ast::Attribute] where 'a: 'b,367 fn attrs<'b>(self) -> &'b [ast::Attribute]
368 where
369 'a: 'b,
370 {
371 self.1
372 }
check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>) where 'a: 'b,373 fn check<'b, T: EarlyLintPass>(self, cx: &mut EarlyContextAndPass<'b, T>)
374 where
375 'a: 'b,
376 {
377 walk_list!(cx, visit_attribute, self.1);
378 walk_list!(cx, visit_item, self.2);
379 }
380 }
381
check_ast_node<'a>( sess: &Session, pre_expansion: bool, lint_store: &LintStore, registered_tools: &RegisteredTools, lint_buffer: Option<LintBuffer>, builtin_lints: impl EarlyLintPass + 'static, check_node: impl EarlyCheckNode<'a>, )382 pub fn check_ast_node<'a>(
383 sess: &Session,
384 pre_expansion: bool,
385 lint_store: &LintStore,
386 registered_tools: &RegisteredTools,
387 lint_buffer: Option<LintBuffer>,
388 builtin_lints: impl EarlyLintPass + 'static,
389 check_node: impl EarlyCheckNode<'a>,
390 ) {
391 let context = EarlyContext::new(
392 sess,
393 !pre_expansion,
394 lint_store,
395 registered_tools,
396 lint_buffer.unwrap_or_default(),
397 );
398
399 // Note: `passes` is often empty. In that case, it's faster to run
400 // `builtin_lints` directly rather than bundling it up into the
401 // `RuntimeCombinedEarlyLintPass`.
402 let passes =
403 if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
404 if passes.is_empty() {
405 check_ast_node_inner(sess, check_node, context, builtin_lints);
406 } else {
407 let mut passes: Vec<_> = passes.iter().map(|mk_pass| (mk_pass)()).collect();
408 passes.push(Box::new(builtin_lints));
409 let pass = RuntimeCombinedEarlyLintPass { passes: &mut passes[..] };
410 check_ast_node_inner(sess, check_node, context, pass);
411 }
412 }
413
check_ast_node_inner<'a, T: EarlyLintPass>( sess: &Session, check_node: impl EarlyCheckNode<'a>, context: EarlyContext<'_>, pass: T, )414 pub fn check_ast_node_inner<'a, T: EarlyLintPass>(
415 sess: &Session,
416 check_node: impl EarlyCheckNode<'a>,
417 context: EarlyContext<'_>,
418 pass: T,
419 ) {
420 let mut cx = EarlyContextAndPass { context, pass };
421
422 cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
423
424 // All of the buffered lints should have been emitted at this point.
425 // If not, that means that we somehow buffered a lint for a node id
426 // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
427 for (id, lints) in cx.context.buffered.map {
428 for early_lint in lints {
429 sess.delay_span_bug(
430 early_lint.span,
431 format!(
432 "failed to process buffered lint here (dummy = {})",
433 id == ast::DUMMY_NODE_ID
434 ),
435 );
436 }
437 }
438 }
439