]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/early.rs
Merge commit 'b40ea209e7f14c8193ddfc98143967b6a2f4f5c9' 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         ast_visit::walk_anon_const(self, c);
113     }
114
115     fn visit_expr(&mut self, e: &'a ast::Expr) {
116         self.with_lint_attrs(e.id, &e.attrs, |cx| {
117             run_early_pass!(cx, check_expr, e);
118             ast_visit::walk_expr(cx, e);
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         run_early_pass!(self, check_fn_post, fk, span, id);
155     }
156
157     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
158         run_early_pass!(self, check_struct_def, s);
159         if let Some(ctor_hir_id) = s.ctor_id() {
160             self.check_id(ctor_hir_id);
161         }
162         ast_visit::walk_struct_def(self, s);
163         run_early_pass!(self, check_struct_def_post, s);
164     }
165
166     fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
167         self.with_lint_attrs(s.id, &s.attrs, |cx| {
168             run_early_pass!(cx, check_field_def, s);
169             ast_visit::walk_field_def(cx, s);
170         })
171     }
172
173     fn visit_variant(&mut self, v: &'a ast::Variant) {
174         self.with_lint_attrs(v.id, &v.attrs, |cx| {
175             run_early_pass!(cx, check_variant, v);
176             ast_visit::walk_variant(cx, v);
177             run_early_pass!(cx, check_variant_post, v);
178         })
179     }
180
181     fn visit_ty(&mut self, t: &'a ast::Ty) {
182         run_early_pass!(self, check_ty, t);
183         self.check_id(t.id);
184         ast_visit::walk_ty(self, t);
185     }
186
187     fn visit_ident(&mut self, ident: Ident) {
188         run_early_pass!(self, check_ident, ident);
189     }
190
191     fn visit_local(&mut self, l: &'a ast::Local) {
192         self.with_lint_attrs(l.id, &l.attrs, |cx| {
193             run_early_pass!(cx, check_local, l);
194             ast_visit::walk_local(cx, l);
195         })
196     }
197
198     fn visit_block(&mut self, b: &'a ast::Block) {
199         run_early_pass!(self, check_block, b);
200         self.check_id(b.id);
201         ast_visit::walk_block(self, b);
202         run_early_pass!(self, check_block_post, b);
203     }
204
205     fn visit_arm(&mut self, a: &'a ast::Arm) {
206         run_early_pass!(self, check_arm, a);
207         ast_visit::walk_arm(self, a);
208     }
209
210     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
211         run_early_pass!(self, check_expr_post, e);
212
213         // Explicitly check for lints associated with 'closure_id', since
214         // it does not have a corresponding AST node
215         match e.kind {
216             ast::ExprKind::Closure(_, ast::Async::Yes { closure_id, .. }, ..)
217             | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id),
218             _ => {}
219         }
220     }
221
222     fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) {
223         run_early_pass!(self, check_generic_arg, arg);
224         ast_visit::walk_generic_arg(self, arg);
225     }
226
227     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
228         run_early_pass!(self, check_generic_param, param);
229         ast_visit::walk_generic_param(self, param);
230     }
231
232     fn visit_generics(&mut self, g: &'a ast::Generics) {
233         run_early_pass!(self, check_generics, g);
234         ast_visit::walk_generics(self, g);
235     }
236
237     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
238         run_early_pass!(self, check_where_predicate, p);
239         ast_visit::walk_where_predicate(self, p);
240     }
241
242     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
243         run_early_pass!(self, check_poly_trait_ref, t, m);
244         ast_visit::walk_poly_trait_ref(self, t, m);
245     }
246
247     fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
248         self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
249             ast_visit::AssocCtxt::Trait => {
250                 run_early_pass!(cx, check_trait_item, item);
251                 ast_visit::walk_assoc_item(cx, item, ctxt);
252                 run_early_pass!(cx, check_trait_item_post, item);
253             }
254             ast_visit::AssocCtxt::Impl => {
255                 run_early_pass!(cx, check_impl_item, item);
256                 ast_visit::walk_assoc_item(cx, item, ctxt);
257                 run_early_pass!(cx, check_impl_item_post, item);
258             }
259         });
260     }
261
262     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
263         run_early_pass!(self, check_lifetime, lt);
264         self.check_id(lt.id);
265     }
266
267     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
268         run_early_pass!(self, check_path, p, id);
269         self.check_id(id);
270         ast_visit::walk_path(self, p);
271     }
272
273     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
274         run_early_pass!(self, check_attribute, attr);
275     }
276
277     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
278         run_early_pass!(self, check_mac_def, mac, id);
279         self.check_id(id);
280     }
281
282     fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
283         run_early_pass!(self, check_mac, mac);
284         ast_visit::walk_mac(self, mac);
285     }
286 }
287
288 struct EarlyLintPassObjects<'a> {
289     lints: &'a mut [EarlyLintPassObject],
290 }
291
292 #[allow(rustc::lint_pass_impl_without_macro)]
293 impl LintPass for EarlyLintPassObjects<'_> {
294     fn name(&self) -> &'static str {
295         panic!()
296     }
297 }
298
299 macro_rules! expand_early_lint_pass_impl_methods {
300     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
301         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
302             for obj in self.lints.iter_mut() {
303                 obj.$name(context, $($param),*);
304             }
305         })*
306     )
307 }
308
309 macro_rules! early_lint_pass_impl {
310     ([], [$($methods:tt)*]) => (
311         impl EarlyLintPass for EarlyLintPassObjects<'_> {
312             expand_early_lint_pass_impl_methods!([$($methods)*]);
313         }
314     )
315 }
316
317 crate::early_lint_methods!(early_lint_pass_impl, []);
318
319 fn early_lint_crate<T: EarlyLintPass>(
320     sess: &Session,
321     lint_store: &LintStore,
322     krate: &ast::Crate,
323     pass: T,
324     buffered: LintBuffer,
325     warn_about_weird_lints: bool,
326 ) -> LintBuffer {
327     let mut cx = EarlyContextAndPass {
328         context: EarlyContext::new(sess, lint_store, krate, buffered, warn_about_weird_lints),
329         pass,
330     };
331
332     // Visit the whole crate.
333     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
334         // since the root module isn't visited as an item (because it isn't an
335         // item), warn for it here.
336         run_early_pass!(cx, check_crate, krate);
337
338         ast_visit::walk_crate(cx, krate);
339
340         run_early_pass!(cx, check_crate_post, krate);
341     });
342     cx.context.buffered
343 }
344
345 pub fn check_ast_crate<T: EarlyLintPass>(
346     sess: &Session,
347     lint_store: &LintStore,
348     krate: &ast::Crate,
349     pre_expansion: bool,
350     lint_buffer: Option<LintBuffer>,
351     builtin_lints: T,
352 ) {
353     let passes =
354         if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
355     let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
356     let mut buffered = lint_buffer.unwrap_or_default();
357
358     if !sess.opts.debugging_opts.no_interleave_lints {
359         buffered =
360             early_lint_crate(sess, lint_store, krate, builtin_lints, buffered, pre_expansion);
361
362         if !passes.is_empty() {
363             buffered = early_lint_crate(
364                 sess,
365                 lint_store,
366                 krate,
367                 EarlyLintPassObjects { lints: &mut passes[..] },
368                 buffered,
369                 pre_expansion,
370             );
371         }
372     } else {
373         for pass in &mut passes {
374             buffered =
375                 sess.prof.extra_verbose_generic_activity("run_lint", pass.name()).run(|| {
376                     early_lint_crate(
377                         sess,
378                         lint_store,
379                         krate,
380                         EarlyLintPassObjects { lints: slice::from_mut(pass) },
381                         buffered,
382                         pre_expansion,
383                     )
384                 });
385         }
386     }
387
388     // All of the buffered lints should have been emitted at this point.
389     // If not, that means that we somehow buffered a lint for a node id
390     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
391     for (_id, lints) in buffered.map {
392         for early_lint in lints {
393             sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
394         }
395     }
396 }