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