]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/early.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_lint / 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::ast;
20 use rustc_ast::visit as ast_visit;
21 use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
22 use rustc_session::Session;
23 use rustc_span::Span;
24
25 use log::debug;
26 use std::slice;
27
28 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
29     $cx.pass.$f(&$cx.context, $($args),*);
30 }) }
31
32 struct EarlyContextAndPass<'a, T: EarlyLintPass> {
33     context: EarlyContext<'a>,
34     pass: T,
35 }
36
37 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
38     fn check_id(&mut self, id: ast::NodeId) {
39         for early_lint in self.context.buffered.take(id) {
40             let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
41             self.context.lookup_with_diagnostics(
42                 lint_id.lint,
43                 Some(span),
44                 |lint| lint.build(&msg).emit(),
45                 diagnostic,
46             );
47         }
48     }
49
50     /// Merge the lints specified by any lint attributes into the
51     /// current lint context, call the provided function, then reset the
52     /// lints in effect to their previous state.
53     fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
54     where
55         F: FnOnce(&mut Self),
56     {
57         let push = self.context.builder.push(attrs, &self.context.lint_store);
58         self.check_id(id);
59         self.enter_attrs(attrs);
60         f(self);
61         self.exit_attrs(attrs);
62         self.context.builder.pop(push);
63     }
64
65     fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
66         debug!("early context: enter_attrs({:?})", attrs);
67         run_early_pass!(self, enter_lint_attrs, attrs);
68     }
69
70     fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
71         debug!("early context: exit_attrs({:?})", attrs);
72         run_early_pass!(self, exit_lint_attrs, attrs);
73     }
74 }
75
76 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
77     fn visit_param(&mut self, param: &'a ast::Param) {
78         self.with_lint_attrs(param.id, &param.attrs, |cx| {
79             run_early_pass!(cx, check_param, param);
80             ast_visit::walk_param(cx, param);
81         });
82     }
83
84     fn visit_item(&mut self, it: &'a ast::Item) {
85         self.with_lint_attrs(it.id, &it.attrs, |cx| {
86             run_early_pass!(cx, check_item, it);
87             ast_visit::walk_item(cx, it);
88             run_early_pass!(cx, check_item_post, it);
89         })
90     }
91
92     fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
93         self.with_lint_attrs(it.id, &it.attrs, |cx| {
94             run_early_pass!(cx, check_foreign_item, it);
95             ast_visit::walk_foreign_item(cx, it);
96             run_early_pass!(cx, check_foreign_item_post, it);
97         })
98     }
99
100     fn visit_pat(&mut self, p: &'a ast::Pat) {
101         run_early_pass!(self, check_pat, p);
102         self.check_id(p.id);
103         ast_visit::walk_pat(self, p);
104         run_early_pass!(self, check_pat_post, p);
105     }
106
107     fn visit_expr(&mut self, e: &'a ast::Expr) {
108         self.with_lint_attrs(e.id, &e.attrs, |cx| {
109             run_early_pass!(cx, check_expr, e);
110             ast_visit::walk_expr(cx, e);
111         })
112     }
113
114     fn visit_stmt(&mut self, s: &'a ast::Stmt) {
115         run_early_pass!(self, check_stmt, s);
116         self.check_id(s.id);
117         ast_visit::walk_stmt(self, s);
118     }
119
120     fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) {
121         run_early_pass!(self, check_fn, fk, span, id);
122         self.check_id(id);
123         ast_visit::walk_fn(self, fk, span);
124         run_early_pass!(self, check_fn_post, fk, span, id);
125     }
126
127     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
128         run_early_pass!(self, check_struct_def, s);
129         if let Some(ctor_hir_id) = s.ctor_id() {
130             self.check_id(ctor_hir_id);
131         }
132         ast_visit::walk_struct_def(self, s);
133         run_early_pass!(self, check_struct_def_post, s);
134     }
135
136     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
137         self.with_lint_attrs(s.id, &s.attrs, |cx| {
138             run_early_pass!(cx, check_struct_field, s);
139             ast_visit::walk_struct_field(cx, s);
140         })
141     }
142
143     fn visit_variant(&mut self, v: &'a ast::Variant) {
144         self.with_lint_attrs(v.id, &v.attrs, |cx| {
145             run_early_pass!(cx, check_variant, v);
146             ast_visit::walk_variant(cx, v);
147             run_early_pass!(cx, check_variant_post, v);
148         })
149     }
150
151     fn visit_ty(&mut self, t: &'a ast::Ty) {
152         run_early_pass!(self, check_ty, t);
153         self.check_id(t.id);
154         ast_visit::walk_ty(self, t);
155     }
156
157     fn visit_ident(&mut self, ident: ast::Ident) {
158         run_early_pass!(self, check_ident, ident);
159     }
160
161     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
162         run_early_pass!(self, check_mod, m, s, n);
163         self.check_id(n);
164         ast_visit::walk_mod(self, m);
165         run_early_pass!(self, check_mod_post, m, s, n);
166     }
167
168     fn visit_local(&mut self, l: &'a ast::Local) {
169         self.with_lint_attrs(l.id, &l.attrs, |cx| {
170             run_early_pass!(cx, check_local, l);
171             ast_visit::walk_local(cx, l);
172         })
173     }
174
175     fn visit_block(&mut self, b: &'a ast::Block) {
176         run_early_pass!(self, check_block, b);
177         self.check_id(b.id);
178         ast_visit::walk_block(self, b);
179         run_early_pass!(self, check_block_post, b);
180     }
181
182     fn visit_arm(&mut self, a: &'a ast::Arm) {
183         run_early_pass!(self, check_arm, a);
184         ast_visit::walk_arm(self, a);
185     }
186
187     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
188         run_early_pass!(self, check_expr_post, e);
189     }
190
191     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
192         run_early_pass!(self, check_generic_param, param);
193         ast_visit::walk_generic_param(self, param);
194     }
195
196     fn visit_generics(&mut self, g: &'a ast::Generics) {
197         run_early_pass!(self, check_generics, g);
198         ast_visit::walk_generics(self, g);
199     }
200
201     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
202         run_early_pass!(self, check_where_predicate, p);
203         ast_visit::walk_where_predicate(self, p);
204     }
205
206     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
207         run_early_pass!(self, check_poly_trait_ref, t, m);
208         ast_visit::walk_poly_trait_ref(self, t, m);
209     }
210
211     fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
212         self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
213             ast_visit::AssocCtxt::Trait => {
214                 run_early_pass!(cx, check_trait_item, item);
215                 ast_visit::walk_assoc_item(cx, item, ctxt);
216                 run_early_pass!(cx, check_trait_item_post, item);
217             }
218             ast_visit::AssocCtxt::Impl => {
219                 run_early_pass!(cx, check_impl_item, item);
220                 ast_visit::walk_assoc_item(cx, item, ctxt);
221                 run_early_pass!(cx, check_impl_item_post, item);
222             }
223         });
224     }
225
226     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
227         run_early_pass!(self, check_lifetime, lt);
228         self.check_id(lt.id);
229     }
230
231     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
232         run_early_pass!(self, check_path, p, id);
233         self.check_id(id);
234         ast_visit::walk_path(self, p);
235     }
236
237     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
238         run_early_pass!(self, check_attribute, attr);
239     }
240
241     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
242         run_early_pass!(self, check_mac_def, mac, id);
243         self.check_id(id);
244     }
245
246     fn visit_mac(&mut self, mac: &'a ast::MacCall) {
247         // FIXME(#54110): So, this setup isn't really right. I think
248         // that (a) the librustc_ast visitor ought to be doing this as
249         // part of `walk_mac`, and (b) we should be calling
250         // `visit_path`, *but* that would require a `NodeId`, and I
251         // want to get #53686 fixed quickly. -nmatsakis
252         ast_visit::walk_path(self, &mac.path);
253
254         run_early_pass!(self, check_mac, mac);
255     }
256 }
257
258 struct EarlyLintPassObjects<'a> {
259     lints: &'a mut [EarlyLintPassObject],
260 }
261
262 #[allow(rustc::lint_pass_impl_without_macro)]
263 impl LintPass for EarlyLintPassObjects<'_> {
264     fn name(&self) -> &'static str {
265         panic!()
266     }
267 }
268
269 macro_rules! expand_early_lint_pass_impl_methods {
270     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
271         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
272             for obj in self.lints.iter_mut() {
273                 obj.$name(context, $($param),*);
274             }
275         })*
276     )
277 }
278
279 macro_rules! early_lint_pass_impl {
280     ([], [$($methods:tt)*]) => (
281         impl EarlyLintPass for EarlyLintPassObjects<'_> {
282             expand_early_lint_pass_impl_methods!([$($methods)*]);
283         }
284     )
285 }
286
287 crate::early_lint_methods!(early_lint_pass_impl, []);
288
289 fn early_lint_crate<T: EarlyLintPass>(
290     sess: &Session,
291     lint_store: &LintStore,
292     krate: &ast::Crate,
293     pass: T,
294     buffered: LintBuffer,
295     warn_about_weird_lints: bool,
296 ) -> LintBuffer {
297     let mut cx = EarlyContextAndPass {
298         context: EarlyContext::new(sess, lint_store, krate, buffered, warn_about_weird_lints),
299         pass,
300     };
301
302     // Visit the whole crate.
303     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
304         // since the root module isn't visited as an item (because it isn't an
305         // item), warn for it here.
306         run_early_pass!(cx, check_crate, krate);
307
308         ast_visit::walk_crate(cx, krate);
309
310         run_early_pass!(cx, check_crate_post, krate);
311     });
312     cx.context.buffered
313 }
314
315 pub fn check_ast_crate<T: EarlyLintPass>(
316     sess: &Session,
317     lint_store: &LintStore,
318     krate: &ast::Crate,
319     pre_expansion: bool,
320     lint_buffer: Option<LintBuffer>,
321     builtin_lints: T,
322 ) {
323     let passes =
324         if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
325     let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
326     let mut buffered = lint_buffer.unwrap_or_default();
327
328     if !sess.opts.debugging_opts.no_interleave_lints {
329         buffered =
330             early_lint_crate(sess, lint_store, krate, builtin_lints, buffered, pre_expansion);
331
332         if !passes.is_empty() {
333             buffered = early_lint_crate(
334                 sess,
335                 lint_store,
336                 krate,
337                 EarlyLintPassObjects { lints: &mut passes[..] },
338                 buffered,
339                 pre_expansion,
340             );
341         }
342     } else {
343         for pass in &mut passes {
344             buffered =
345                 sess.prof.extra_verbose_generic_activity("run_lint", pass.name()).run(|| {
346                     early_lint_crate(
347                         sess,
348                         lint_store,
349                         krate,
350                         EarlyLintPassObjects { lints: slice::from_mut(pass) },
351                         buffered,
352                         pre_expansion,
353                     )
354                 });
355         }
356     }
357
358     // All of the buffered lints should have been emitted at this point.
359     // If not, that means that we somehow buffered a lint for a node id
360     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
361     //
362     // Rustdoc runs everybody-loops before the early lints and removes
363     // function bodies, so it's totally possible for linted
364     // node ids to not exist (e.g., macros defined within functions for the
365     // unused_macro lint) anymore. So we only run this check
366     // when we're not in rustdoc mode. (see issue #47639)
367     if !sess.opts.actually_rustdoc {
368         for (_id, lints) in buffered.map {
369             for early_lint in lints {
370                 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
371             }
372         }
373     }
374 }