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