]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/early.rs
Rollup merge of #67948 - llogiq:gallop, r=Mark-Simulacrum
[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 rustc::lint::{EarlyContext, LintStore};
18 use rustc::lint::{EarlyLintPass, EarlyLintPassObject};
19 use rustc::lint::{LintContext, LintPass};
20 use rustc_session::lint::LintBuffer;
21 use rustc_session::Session;
22 use rustc_span::Span;
23 use syntax::ast;
24 use syntax::visit as ast_visit;
25
26 use log::debug;
27 use std::slice;
28
29 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
30     $cx.pass.$f(&$cx.context, $($args),*);
31 }) }
32
33 struct EarlyContextAndPass<'a, T: EarlyLintPass> {
34     context: EarlyContext<'a>,
35     pass: T,
36 }
37
38 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
39     fn check_id(&mut self, id: ast::NodeId) {
40         for early_lint in self.context.buffered.take(id) {
41             self.context.lookup_and_emit_with_diagnostics(
42                 early_lint.lint_id.lint,
43                 Some(early_lint.span.clone()),
44                 &early_lint.msg,
45                 early_lint.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(
121         &mut self,
122         fk: ast_visit::FnKind<'a>,
123         decl: &'a ast::FnDecl,
124         span: Span,
125         id: ast::NodeId,
126     ) {
127         run_early_pass!(self, check_fn, fk, decl, span, id);
128         self.check_id(id);
129         ast_visit::walk_fn(self, fk, decl, span);
130         run_early_pass!(self, check_fn_post, fk, decl, span, id);
131     }
132
133     fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
134         run_early_pass!(self, check_struct_def, s);
135         if let Some(ctor_hir_id) = s.ctor_id() {
136             self.check_id(ctor_hir_id);
137         }
138         ast_visit::walk_struct_def(self, s);
139         run_early_pass!(self, check_struct_def_post, s);
140     }
141
142     fn visit_struct_field(&mut self, s: &'a ast::StructField) {
143         self.with_lint_attrs(s.id, &s.attrs, |cx| {
144             run_early_pass!(cx, check_struct_field, s);
145             ast_visit::walk_struct_field(cx, s);
146         })
147     }
148
149     fn visit_variant(&mut self, v: &'a ast::Variant) {
150         self.with_lint_attrs(v.id, &v.attrs, |cx| {
151             run_early_pass!(cx, check_variant, v);
152             ast_visit::walk_variant(cx, v);
153             run_early_pass!(cx, check_variant_post, v);
154         })
155     }
156
157     fn visit_ty(&mut self, t: &'a ast::Ty) {
158         run_early_pass!(self, check_ty, t);
159         self.check_id(t.id);
160         ast_visit::walk_ty(self, t);
161     }
162
163     fn visit_ident(&mut self, ident: ast::Ident) {
164         run_early_pass!(self, check_ident, ident);
165     }
166
167     fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
168         run_early_pass!(self, check_mod, m, s, n);
169         self.check_id(n);
170         ast_visit::walk_mod(self, m);
171         run_early_pass!(self, check_mod_post, m, s, n);
172     }
173
174     fn visit_local(&mut self, l: &'a ast::Local) {
175         self.with_lint_attrs(l.id, &l.attrs, |cx| {
176             run_early_pass!(cx, check_local, l);
177             ast_visit::walk_local(cx, l);
178         })
179     }
180
181     fn visit_block(&mut self, b: &'a ast::Block) {
182         run_early_pass!(self, check_block, b);
183         self.check_id(b.id);
184         ast_visit::walk_block(self, b);
185         run_early_pass!(self, check_block_post, b);
186     }
187
188     fn visit_arm(&mut self, a: &'a ast::Arm) {
189         run_early_pass!(self, check_arm, a);
190         ast_visit::walk_arm(self, a);
191     }
192
193     fn visit_expr_post(&mut self, e: &'a ast::Expr) {
194         run_early_pass!(self, check_expr_post, e);
195     }
196
197     fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
198         run_early_pass!(self, check_generic_param, param);
199         ast_visit::walk_generic_param(self, param);
200     }
201
202     fn visit_generics(&mut self, g: &'a ast::Generics) {
203         run_early_pass!(self, check_generics, g);
204         ast_visit::walk_generics(self, g);
205     }
206
207     fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
208         run_early_pass!(self, check_where_predicate, p);
209         ast_visit::walk_where_predicate(self, p);
210     }
211
212     fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
213         run_early_pass!(self, check_poly_trait_ref, t, m);
214         ast_visit::walk_poly_trait_ref(self, t, m);
215     }
216
217     fn visit_trait_item(&mut self, trait_item: &'a ast::AssocItem) {
218         self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
219             run_early_pass!(cx, check_trait_item, trait_item);
220             ast_visit::walk_trait_item(cx, trait_item);
221             run_early_pass!(cx, check_trait_item_post, trait_item);
222         });
223     }
224
225     fn visit_impl_item(&mut self, impl_item: &'a ast::AssocItem) {
226         self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
227             run_early_pass!(cx, check_impl_item, impl_item);
228             ast_visit::walk_impl_item(cx, impl_item);
229             run_early_pass!(cx, check_impl_item_post, impl_item);
230         });
231     }
232
233     fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
234         run_early_pass!(self, check_lifetime, lt);
235         self.check_id(lt.id);
236     }
237
238     fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
239         run_early_pass!(self, check_path, p, id);
240         self.check_id(id);
241         ast_visit::walk_path(self, p);
242     }
243
244     fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
245         run_early_pass!(self, check_attribute, attr);
246     }
247
248     fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
249         run_early_pass!(self, check_mac_def, mac, id);
250         self.check_id(id);
251     }
252
253     fn visit_mac(&mut self, mac: &'a ast::Mac) {
254         // FIXME(#54110): So, this setup isn't really right. I think
255         // that (a) the libsyntax visitor ought to be doing this as
256         // part of `walk_mac`, and (b) we should be calling
257         // `visit_path`, *but* that would require a `NodeId`, and I
258         // want to get #53686 fixed quickly. -nmatsakis
259         ast_visit::walk_path(self, &mac.path);
260
261         run_early_pass!(self, check_mac, mac);
262     }
263 }
264
265 struct EarlyLintPassObjects<'a> {
266     lints: &'a mut [EarlyLintPassObject],
267 }
268
269 #[allow(rustc::lint_pass_impl_without_macro)]
270 impl LintPass for EarlyLintPassObjects<'_> {
271     fn name(&self) -> &'static str {
272         panic!()
273     }
274 }
275
276 macro_rules! expand_early_lint_pass_impl_methods {
277     ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
278         $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
279             for obj in self.lints.iter_mut() {
280                 obj.$name(context, $($param),*);
281             }
282         })*
283     )
284 }
285
286 macro_rules! early_lint_pass_impl {
287     ([], [$($methods:tt)*]) => (
288         impl EarlyLintPass for EarlyLintPassObjects<'_> {
289             expand_early_lint_pass_impl_methods!([$($methods)*]);
290         }
291     )
292 }
293
294 early_lint_methods!(early_lint_pass_impl, []);
295
296 fn early_lint_crate<T: EarlyLintPass>(
297     sess: &Session,
298     lint_store: &LintStore,
299     krate: &ast::Crate,
300     pass: T,
301     buffered: LintBuffer,
302     warn_about_weird_lints: bool,
303 ) -> LintBuffer {
304     let mut cx = EarlyContextAndPass {
305         context: EarlyContext::new(sess, lint_store, krate, buffered, warn_about_weird_lints),
306         pass,
307     };
308
309     // Visit the whole crate.
310     cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
311         // since the root module isn't visited as an item (because it isn't an
312         // item), warn for it here.
313         run_early_pass!(cx, check_crate, krate);
314
315         ast_visit::walk_crate(cx, krate);
316
317         run_early_pass!(cx, check_crate_post, krate);
318     });
319     cx.context.buffered
320 }
321
322 pub fn check_ast_crate<T: EarlyLintPass>(
323     sess: &Session,
324     lint_store: &LintStore,
325     krate: &ast::Crate,
326     pre_expansion: bool,
327     lint_buffer: Option<LintBuffer>,
328     builtin_lints: T,
329 ) {
330     let mut passes: Vec<_> = if pre_expansion {
331         lint_store.pre_expansion_passes.iter().map(|p| (p)()).collect()
332     } else {
333         lint_store.early_passes.iter().map(|p| (p)()).collect()
334     };
335     let mut buffered = lint_buffer.unwrap_or_default();
336
337     if !sess.opts.debugging_opts.no_interleave_lints {
338         buffered =
339             early_lint_crate(sess, lint_store, krate, builtin_lints, buffered, pre_expansion);
340
341         if !passes.is_empty() {
342             buffered = early_lint_crate(
343                 sess,
344                 lint_store,
345                 krate,
346                 EarlyLintPassObjects { lints: &mut passes[..] },
347                 buffered,
348                 pre_expansion,
349             );
350         }
351     } else {
352         for pass in &mut passes {
353             buffered = sess
354                 .prof
355                 .extra_verbose_generic_activity(&format!("running lint: {}", pass.name()))
356                 .run(|| {
357                     early_lint_crate(
358                         sess,
359                         lint_store,
360                         krate,
361                         EarlyLintPassObjects { lints: slice::from_mut(pass) },
362                         buffered,
363                         pre_expansion,
364                     )
365                 });
366         }
367     }
368
369     // All of the buffered lints should have been emitted at this point.
370     // If not, that means that we somehow buffered a lint for a node id
371     // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
372     //
373     // Rustdoc runs everybody-loops before the early lints and removes
374     // function bodies, so it's totally possible for linted
375     // node ids to not exist (e.g., macros defined within functions for the
376     // unused_macro lint) anymore. So we only run this check
377     // when we're not in rustdoc mode. (see issue #47639)
378     if !sess.opts.actually_rustdoc {
379         for (_id, lints) in buffered.map {
380             for early_lint in lints {
381                 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
382             }
383         }
384     }
385 }