]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/early.rs
Auto merge of #98091 - Dylan-DPC:rollup-ueb6b5x, r=Dylan-DPC
[rust.git] / compiler / rustc_lint / src / early.rs
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_middle::ty::RegisteredTools;
23 use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
24 use rustc_session::Session;
25 use rustc_span::symbol::Ident;
26 use rustc_span::Span;
27
28 use std::slice;
29 use tracing::debug;
30
31 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
32     $cx.pass.$f(&$cx.context, $($args),*);
33 }) }
34
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     fn check_id(&mut self, id: ast::NodeId) {
42         for early_lint in self.context.buffered.take(id) {
43             let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
44             self.context.lookup_with_diagnostics(
45                 lint_id.lint,
46                 Some(span),
47                 |lint| {
48                     lint.build(&msg).emit();
49                 },
50                 diagnostic,
51             );
52         }
53     }
54
55     /// Merge the lints specified by any lint attributes into the
56     /// current lint context, call the provided function, then reset the
57     /// lints in effect to their previous state.
58     fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
59     where
60         F: FnOnce(&mut Self),
61     {
62         let is_crate_node = id == ast::CRATE_NODE_ID;
63         let push = self.context.builder.push(attrs, is_crate_node, None);
64
65         self.check_id(id);
66         self.enter_attrs(attrs);
67         f(self);
68         self.exit_attrs(attrs);
69         self.context.builder.pop(push);
70     }
71
72     fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
73         debug!("early context: enter_attrs({:?})", attrs);
74         run_early_pass!(self, enter_lint_attrs, attrs);
75     }
76
77     fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
78         debug!("early context: exit_attrs({:?})", attrs);
79         run_early_pass!(self, exit_lint_attrs, attrs);
80     }
81 }
82
83 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
84     fn visit_param(&mut self, param: &'a ast::Param) {
85         self.with_lint_attrs(param.id, &param.attrs, |cx| {
86             run_early_pass!(cx, check_param, param);
87             ast_visit::walk_param(cx, param);
88         });
89     }
90
91     fn visit_item(&mut self, it: &'a ast::Item) {
92         self.with_lint_attrs(it.id, &it.attrs, |cx| {
93             run_early_pass!(cx, check_item, it);
94             ast_visit::walk_item(cx, it);
95             run_early_pass!(cx, check_item_post, it);
96         })
97     }
98
99     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
100         self.with_lint_attrs(it.id, &it.attrs, |cx| {
101             run_early_pass!(cx, check_foreign_item, it);
102             ast_visit::walk_foreign_item(cx, it);
103             run_early_pass!(cx, check_foreign_item_post, it);
104         })
105     }
106
107     fn visit_pat(&mut self, p: &'a ast::Pat) {
108         run_early_pass!(self, check_pat, p);
109         self.check_id(p.id);
110         ast_visit::walk_pat(self, p);
111         run_early_pass!(self, check_pat_post, p);
112     }
113
114     fn visit_anon_const(&mut self, c: &'a ast::AnonConst) {
115         run_early_pass!(self, check_anon_const, c);
116         self.check_id(c.id);
117         ast_visit::walk_anon_const(self, c);
118     }
119
120     fn visit_expr(&mut self, e: &'a ast::Expr) {
121         self.with_lint_attrs(e.id, &e.attrs, |cx| {
122             run_early_pass!(cx, check_expr, e);
123             ast_visit::walk_expr(cx, e);
124         })
125     }
126
127     fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
128         self.with_lint_attrs(f.id, &f.attrs, |cx| {
129             ast_visit::walk_expr_field(cx, f);
130         })
131     }
132
133     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
134         // Add the statement's lint attributes to our
135         // current state when checking the statement itself.
136         // This allows us to handle attributes like
137         // `#[allow(unused_doc_comments)]`, which apply to
138         // sibling attributes on the same target
139         //
140         // Note that statements get their attributes from
141         // the AST struct that they wrap (e.g. an item)
142         self.with_lint_attrs(s.id, s.attrs(), |cx| {
143             run_early_pass!(cx, check_stmt, s);
144             cx.check_id(s.id);
145         });
146         // The visitor for the AST struct wrapped
147         // by the statement (e.g. `Item`) will call
148         // `with_lint_attrs`, so do this walk
149         // outside of the above `with_lint_attrs` call
150         ast_visit::walk_stmt(self, s);
151     }
152
153     fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) {
154         run_early_pass!(self, check_fn, fk, span, id);
155         self.check_id(id);
156         ast_visit::walk_fn(self, fk, span);
157
158         // Explicitly check for lints associated with 'closure_id', since
159         // it does not have a corresponding AST node
160         if let ast_visit::FnKind::Fn(_, _, sig, _, _, _) = fk {
161             if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness {
162                 self.check_id(closure_id);
163             }
164         }
165         run_early_pass!(self, check_fn_post, fk, span, id);
166     }
167
168     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
169         run_early_pass!(self, check_struct_def, s);
170         if let Some(ctor_hir_id) = s.ctor_id() {
171             self.check_id(ctor_hir_id);
172         }
173         ast_visit::walk_struct_def(self, s);
174         run_early_pass!(self, check_struct_def_post, s);
175     }
176
177     fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
178         self.with_lint_attrs(s.id, &s.attrs, |cx| {
179             run_early_pass!(cx, check_field_def, s);
180             ast_visit::walk_field_def(cx, s);
181         })
182     }
183
184     fn visit_variant(&mut self, v: &'a ast::Variant) {
185         self.with_lint_attrs(v.id, &v.attrs, |cx| {
186             run_early_pass!(cx, check_variant, v);
187             ast_visit::walk_variant(cx, v);
188             run_early_pass!(cx, check_variant_post, v);
189         })
190     }
191
192     fn visit_ty(&mut self, t: &'a ast::Ty) {
193         run_early_pass!(self, check_ty, t);
194         self.check_id(t.id);
195         ast_visit::walk_ty(self, t);
196     }
197
198     fn visit_ident(&mut self, ident: Ident) {
199         run_early_pass!(self, check_ident, ident);
200     }
201
202     fn visit_local(&mut self, l: &'a ast::Local) {
203         self.with_lint_attrs(l.id, &l.attrs, |cx| {
204             run_early_pass!(cx, check_local, l);
205             ast_visit::walk_local(cx, l);
206         })
207     }
208
209     fn visit_block(&mut self, b: &'a ast::Block) {
210         run_early_pass!(self, check_block, b);
211         self.check_id(b.id);
212         ast_visit::walk_block(self, b);
213         run_early_pass!(self, check_block_post, b);
214     }
215
216     fn visit_arm(&mut self, a: &'a ast::Arm) {
217         self.with_lint_attrs(a.id, &a.attrs, |cx| {
218             run_early_pass!(cx, check_arm, a);
219             ast_visit::walk_arm(cx, a);
220         })
221     }
222
223     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
224         run_early_pass!(self, check_expr_post, e);
225
226         // Explicitly check for lints associated with 'closure_id', since
227         // it does not have a corresponding AST node
228         match e.kind {
229             ast::ExprKind::Closure(_, ast::Async::Yes { closure_id, .. }, ..)
230             | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id),
231             _ => {}
232         }
233     }
234
235     fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) {
236         run_early_pass!(self, check_generic_arg, arg);
237         ast_visit::walk_generic_arg(self, arg);
238     }
239
240     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
241         run_early_pass!(self, check_generic_param, param);
242         self.check_id(param.id);
243         ast_visit::walk_generic_param(self, param);
244     }
245
246     fn visit_generics(&mut self, g: &'a ast::Generics) {
247         run_early_pass!(self, check_generics, g);
248         ast_visit::walk_generics(self, g);
249     }
250
251     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
252         run_early_pass!(self, check_where_predicate, p);
253         ast_visit::walk_where_predicate(self, p);
254     }
255
256     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
257         run_early_pass!(self, check_poly_trait_ref, t, m);
258         ast_visit::walk_poly_trait_ref(self, t, m);
259     }
260
261     fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
262         self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
263             ast_visit::AssocCtxt::Trait => {
264                 run_early_pass!(cx, check_trait_item, item);
265                 ast_visit::walk_assoc_item(cx, item, ctxt);
266                 run_early_pass!(cx, check_trait_item_post, item);
267             }
268             ast_visit::AssocCtxt::Impl => {
269                 run_early_pass!(cx, check_impl_item, item);
270                 ast_visit::walk_assoc_item(cx, item, ctxt);
271                 run_early_pass!(cx, check_impl_item_post, item);
272             }
273         });
274     }
275
276     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt) {
277         run_early_pass!(self, check_lifetime, lt);
278         self.check_id(lt.id);
279     }
280
281     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
282         run_early_pass!(self, check_path, p, id);
283         self.check_id(id);
284         ast_visit::walk_path(self, p);
285     }
286
287     fn visit_path_segment(&mut self, path_span: Span, s: &'a ast::PathSegment) {
288         self.check_id(s.id);
289         ast_visit::walk_path_segment(self, path_span, s);
290     }
291
292     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
293         run_early_pass!(self, check_attribute, attr);
294     }
295
296     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
297         run_early_pass!(self, check_mac_def, mac, id);
298         self.check_id(id);
299     }
300
301     fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
302         run_early_pass!(self, check_mac, mac);
303         ast_visit::walk_mac(self, mac);
304     }
305 }
306
307 struct EarlyLintPassObjects<'a> {
308     lints: &'a mut [EarlyLintPassObject],
309 }
310
311 #[allow(rustc::lint_pass_impl_without_macro)]
312 impl LintPass for EarlyLintPassObjects<'_> {
313     fn name(&self) -> &'static str {
314         panic!()
315     }
316 }
317
318 macro_rules! expand_early_lint_pass_impl_methods {
319     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
320         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
321             for obj in self.lints.iter_mut() {
322                 obj.$name(context, $($param),*);
323             }
324         })*
325     )
326 }
327
328 macro_rules! early_lint_pass_impl {
329     ([], [$($methods:tt)*]) => (
330         impl EarlyLintPass for EarlyLintPassObjects<'_> {
331             expand_early_lint_pass_impl_methods!([$($methods)*]);
332         }
333     )
334 }
335
336 crate::early_lint_methods!(early_lint_pass_impl, []);
337
338 /// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
339 /// This trait generalizes over those nodes.
340 pub trait EarlyCheckNode<'a>: Copy {
341     fn id(self) -> ast::NodeId;
342     fn attrs<'b>(self) -> &'b [ast::Attribute]
343     where
344         'a: 'b;
345     fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
346     where
347         'a: 'b;
348 }
349
350 impl<'a> EarlyCheckNode<'a> for &'a ast::Crate {
351     fn id(self) -> ast::NodeId {
352         ast::CRATE_NODE_ID
353     }
354     fn attrs<'b>(self) -> &'b [ast::Attribute]
355     where
356         'a: 'b,
357     {
358         &self.attrs
359     }
360     fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
361     where
362         'a: 'b,
363     {
364         run_early_pass!(cx, check_crate, self);
365         ast_visit::walk_crate(cx, self);
366         run_early_pass!(cx, check_crate_post, self);
367     }
368 }
369
370 impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
371     fn id(self) -> ast::NodeId {
372         self.0
373     }
374     fn attrs<'b>(self) -> &'b [ast::Attribute]
375     where
376         'a: 'b,
377     {
378         self.1
379     }
380     fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
381     where
382         'a: 'b,
383     {
384         walk_list!(cx, visit_attribute, self.1);
385         walk_list!(cx, visit_item, self.2);
386     }
387 }
388
389 fn early_lint_node<'a>(
390     sess: &Session,
391     warn_about_weird_lints: bool,
392     lint_store: &LintStore,
393     registered_tools: &RegisteredTools,
394     buffered: LintBuffer,
395     pass: impl EarlyLintPass,
396     check_node: impl EarlyCheckNode<'a>,
397 ) -> LintBuffer {
398     let mut cx = EarlyContextAndPass {
399         context: EarlyContext::new(
400             sess,
401             warn_about_weird_lints,
402             lint_store,
403             registered_tools,
404             buffered,
405         ),
406         pass,
407     };
408
409     cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
410     cx.context.buffered
411 }
412
413 pub fn check_ast_node<'a>(
414     sess: &Session,
415     pre_expansion: bool,
416     lint_store: &LintStore,
417     registered_tools: &RegisteredTools,
418     lint_buffer: Option<LintBuffer>,
419     builtin_lints: impl EarlyLintPass,
420     check_node: impl EarlyCheckNode<'a>,
421 ) {
422     let passes =
423         if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
424     let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
425     let mut buffered = lint_buffer.unwrap_or_default();
426
427     if sess.opts.debugging_opts.no_interleave_lints {
428         for (i, pass) in passes.iter_mut().enumerate() {
429             buffered =
430                 sess.prof.extra_verbose_generic_activity("run_lint", pass.name()).run(|| {
431                     early_lint_node(
432                         sess,
433                         !pre_expansion && i == 0,
434                         lint_store,
435                         registered_tools,
436                         buffered,
437                         EarlyLintPassObjects { lints: slice::from_mut(pass) },
438                         check_node,
439                     )
440                 });
441         }
442     } else {
443         buffered = early_lint_node(
444             sess,
445             !pre_expansion,
446             lint_store,
447             registered_tools,
448             buffered,
449             builtin_lints,
450             check_node,
451         );
452
453         if !passes.is_empty() {
454             buffered = early_lint_node(
455                 sess,
456                 false,
457                 lint_store,
458                 registered_tools,
459                 buffered,
460                 EarlyLintPassObjects { lints: &mut passes[..] },
461                 check_node,
462             );
463         }
464     }
465
466     // All of the buffered lints should have been emitted at this point.
467     // If not, that means that we somehow buffered a lint for a node id
468     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
469     for (id, lints) in buffered.map {
470         for early_lint in lints {
471             sess.delay_span_bug(
472                 early_lint.span,
473                 &format!(
474                     "failed to process buffered lint here (dummy = {})",
475                     id == ast::DUMMY_NODE_ID
476                 ),
477             );
478         }
479     }
480 }