]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/late.rs
Auto merge of #68034 - Centril:rollup-3d9pq14, r=Centril
[rust.git] / src / librustc_lint / late.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::hir::map::Map;
18 use rustc::lint::LateContext;
19 use rustc::lint::LintPass;
20 use rustc::lint::{LateLintPass, LateLintPassObject};
21 use rustc::ty::{self, TyCtxt};
22 use rustc_data_structures::sync::{join, par_iter, ParallelIterator};
23 use rustc_hir as hir;
24 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
25 use rustc_hir::intravisit as hir_visit;
26 use rustc_hir::intravisit::Visitor;
27 use rustc_span::Span;
28 use std::slice;
29 use syntax::ast;
30
31 use log::debug;
32 use syntax::walk_list;
33
34 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
35     $cx.pass.$f(&$cx.context, $($args),*);
36 }) }
37
38 struct LateContextAndPass<'a, 'tcx, T: LateLintPass<'a, 'tcx>> {
39     context: LateContext<'a, 'tcx>,
40     pass: T,
41 }
42
43 impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> LateContextAndPass<'a, 'tcx, T> {
44     /// Merge the lints specified by any lint attributes into the
45     /// current lint context, call the provided function, then reset the
46     /// lints in effect to their previous state.
47     fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &'tcx [ast::Attribute], f: F)
48     where
49         F: FnOnce(&mut Self),
50     {
51         let prev = self.context.last_node_with_lint_attrs;
52         self.context.last_node_with_lint_attrs = id;
53         self.enter_attrs(attrs);
54         f(self);
55         self.exit_attrs(attrs);
56         self.context.last_node_with_lint_attrs = prev;
57     }
58
59     fn with_param_env<F>(&mut self, id: hir::HirId, f: F)
60     where
61         F: FnOnce(&mut Self),
62     {
63         let old_param_env = self.context.param_env;
64         self.context.param_env =
65             self.context.tcx.param_env(self.context.tcx.hir().local_def_id(id));
66         f(self);
67         self.context.param_env = old_param_env;
68     }
69
70     fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) {
71         lint_callback!(self, check_mod, m, s, n);
72         hir_visit::walk_mod(self, m, n);
73         lint_callback!(self, check_mod_post, m, s, n);
74     }
75
76     fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
77         debug!("late context: enter_attrs({:?})", attrs);
78         lint_callback!(self, enter_lint_attrs, attrs);
79     }
80
81     fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
82         debug!("late context: exit_attrs({:?})", attrs);
83         lint_callback!(self, exit_lint_attrs, attrs);
84     }
85 }
86
87 impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx>
88     for LateContextAndPass<'a, 'tcx, T>
89 {
90     type Map = Map<'tcx>;
91
92     /// Because lints are scoped lexically, we want to walk nested
93     /// items in the context of the outer item, so enable
94     /// deep-walking.
95     fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, Self::Map> {
96         hir_visit::NestedVisitorMap::All(&self.context.tcx.hir())
97     }
98
99     fn visit_nested_body(&mut self, body: hir::BodyId) {
100         let old_tables = self.context.tables;
101         self.context.tables = self.context.tcx.body_tables(body);
102         let body = self.context.tcx.hir().body(body);
103         self.visit_body(body);
104         self.context.tables = old_tables;
105     }
106
107     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
108         self.with_lint_attrs(param.hir_id, &param.attrs, |cx| {
109             lint_callback!(cx, check_param, param);
110             hir_visit::walk_param(cx, param);
111         });
112     }
113
114     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
115         lint_callback!(self, check_body, body);
116         hir_visit::walk_body(self, body);
117         lint_callback!(self, check_body_post, body);
118     }
119
120     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
121         let generics = self.context.generics.take();
122         self.context.generics = it.kind.generics();
123         self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
124             cx.with_param_env(it.hir_id, |cx| {
125                 lint_callback!(cx, check_item, it);
126                 hir_visit::walk_item(cx, it);
127                 lint_callback!(cx, check_item_post, it);
128             });
129         });
130         self.context.generics = generics;
131     }
132
133     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
134         self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
135             cx.with_param_env(it.hir_id, |cx| {
136                 lint_callback!(cx, check_foreign_item, it);
137                 hir_visit::walk_foreign_item(cx, it);
138                 lint_callback!(cx, check_foreign_item_post, it);
139             });
140         })
141     }
142
143     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
144         lint_callback!(self, check_pat, p);
145         hir_visit::walk_pat(self, p);
146     }
147
148     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
149         self.with_lint_attrs(e.hir_id, &e.attrs, |cx| {
150             lint_callback!(cx, check_expr, e);
151             hir_visit::walk_expr(cx, e);
152             lint_callback!(cx, check_expr_post, e);
153         })
154     }
155
156     fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
157         // statement attributes are actually just attributes on one of
158         // - item
159         // - local
160         // - expression
161         // so we keep track of lint levels there
162         lint_callback!(self, check_stmt, s);
163         hir_visit::walk_stmt(self, s);
164     }
165
166     fn visit_fn(
167         &mut self,
168         fk: hir_visit::FnKind<'tcx>,
169         decl: &'tcx hir::FnDecl<'tcx>,
170         body_id: hir::BodyId,
171         span: Span,
172         id: hir::HirId,
173     ) {
174         // Wrap in tables here, not just in visit_nested_body,
175         // in order for `check_fn` to be able to use them.
176         let old_tables = self.context.tables;
177         self.context.tables = self.context.tcx.body_tables(body_id);
178         let body = self.context.tcx.hir().body(body_id);
179         lint_callback!(self, check_fn, fk, decl, body, span, id);
180         hir_visit::walk_fn(self, fk, decl, body_id, span, id);
181         lint_callback!(self, check_fn_post, fk, decl, body, span, id);
182         self.context.tables = old_tables;
183     }
184
185     fn visit_variant_data(
186         &mut self,
187         s: &'tcx hir::VariantData<'tcx>,
188         _: ast::Name,
189         _: &'tcx hir::Generics<'tcx>,
190         _: hir::HirId,
191         _: Span,
192     ) {
193         lint_callback!(self, check_struct_def, s);
194         hir_visit::walk_struct_def(self, s);
195         lint_callback!(self, check_struct_def_post, s);
196     }
197
198     fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
199         self.with_lint_attrs(s.hir_id, &s.attrs, |cx| {
200             lint_callback!(cx, check_struct_field, s);
201             hir_visit::walk_struct_field(cx, s);
202         })
203     }
204
205     fn visit_variant(
206         &mut self,
207         v: &'tcx hir::Variant<'tcx>,
208         g: &'tcx hir::Generics<'tcx>,
209         item_id: hir::HirId,
210     ) {
211         self.with_lint_attrs(v.id, &v.attrs, |cx| {
212             lint_callback!(cx, check_variant, v);
213             hir_visit::walk_variant(cx, v, g, item_id);
214             lint_callback!(cx, check_variant_post, v);
215         })
216     }
217
218     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
219         lint_callback!(self, check_ty, t);
220         hir_visit::walk_ty(self, t);
221     }
222
223     fn visit_name(&mut self, sp: Span, name: ast::Name) {
224         lint_callback!(self, check_name, sp, name);
225     }
226
227     fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) {
228         if !self.context.only_module {
229             self.process_mod(m, s, n);
230         }
231     }
232
233     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
234         self.with_lint_attrs(l.hir_id, &l.attrs, |cx| {
235             lint_callback!(cx, check_local, l);
236             hir_visit::walk_local(cx, l);
237         })
238     }
239
240     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
241         lint_callback!(self, check_block, b);
242         hir_visit::walk_block(self, b);
243         lint_callback!(self, check_block_post, b);
244     }
245
246     fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
247         lint_callback!(self, check_arm, a);
248         hir_visit::walk_arm(self, a);
249     }
250
251     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
252         lint_callback!(self, check_generic_param, p);
253         hir_visit::walk_generic_param(self, p);
254     }
255
256     fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) {
257         lint_callback!(self, check_generics, g);
258         hir_visit::walk_generics(self, g);
259     }
260
261     fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) {
262         lint_callback!(self, check_where_predicate, p);
263         hir_visit::walk_where_predicate(self, p);
264     }
265
266     fn visit_poly_trait_ref(
267         &mut self,
268         t: &'tcx hir::PolyTraitRef<'tcx>,
269         m: hir::TraitBoundModifier,
270     ) {
271         lint_callback!(self, check_poly_trait_ref, t, m);
272         hir_visit::walk_poly_trait_ref(self, t, m);
273     }
274
275     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
276         let generics = self.context.generics.take();
277         self.context.generics = Some(&trait_item.generics);
278         self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |cx| {
279             cx.with_param_env(trait_item.hir_id, |cx| {
280                 lint_callback!(cx, check_trait_item, trait_item);
281                 hir_visit::walk_trait_item(cx, trait_item);
282                 lint_callback!(cx, check_trait_item_post, trait_item);
283             });
284         });
285         self.context.generics = generics;
286     }
287
288     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
289         let generics = self.context.generics.take();
290         self.context.generics = Some(&impl_item.generics);
291         self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |cx| {
292             cx.with_param_env(impl_item.hir_id, |cx| {
293                 lint_callback!(cx, check_impl_item, impl_item);
294                 hir_visit::walk_impl_item(cx, impl_item);
295                 lint_callback!(cx, check_impl_item_post, impl_item);
296             });
297         });
298         self.context.generics = generics;
299     }
300
301     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
302         lint_callback!(self, check_lifetime, lt);
303         hir_visit::walk_lifetime(self, lt);
304     }
305
306     fn visit_path(&mut self, p: &'tcx hir::Path<'tcx>, id: hir::HirId) {
307         lint_callback!(self, check_path, p, id);
308         hir_visit::walk_path(self, p);
309     }
310
311     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
312         lint_callback!(self, check_attribute, attr);
313     }
314 }
315
316 struct LateLintPassObjects<'a> {
317     lints: &'a mut [LateLintPassObject],
318 }
319
320 #[allow(rustc::lint_pass_impl_without_macro)]
321 impl LintPass for LateLintPassObjects<'_> {
322     fn name(&self) -> &'static str {
323         panic!()
324     }
325 }
326
327 macro_rules! expand_late_lint_pass_impl_methods {
328     ([$a:tt, $hir:tt], [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
329         $(fn $name(&mut self, context: &LateContext<$a, $hir>, $($param: $arg),*) {
330             for obj in self.lints.iter_mut() {
331                 obj.$name(context, $($param),*);
332             }
333         })*
334     )
335 }
336
337 macro_rules! late_lint_pass_impl {
338     ([], [$hir:tt], $methods:tt) => (
339         impl<'a, $hir> LateLintPass<'a, $hir> for LateLintPassObjects<'_> {
340             expand_late_lint_pass_impl_methods!(['a, $hir], $methods);
341         }
342     )
343 }
344
345 late_lint_methods!(late_lint_pass_impl, [], ['tcx]);
346
347 fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
348     tcx: TyCtxt<'tcx>,
349     module_def_id: DefId,
350     pass: T,
351 ) {
352     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
353
354     let context = LateContext {
355         tcx,
356         tables: &ty::TypeckTables::empty(None),
357         param_env: ty::ParamEnv::empty(),
358         access_levels,
359         lint_store: &tcx.lint_store,
360         last_node_with_lint_attrs: tcx.hir().as_local_hir_id(module_def_id).unwrap(),
361         generics: None,
362         only_module: true,
363     };
364
365     let mut cx = LateContextAndPass { context, pass };
366
367     let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
368     cx.process_mod(module, span, hir_id);
369
370     // Visit the crate attributes
371     if hir_id == hir::CRATE_HIR_ID {
372         walk_list!(cx, visit_attribute, tcx.hir().attrs(hir::CRATE_HIR_ID));
373     }
374 }
375
376 pub fn late_lint_mod<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
377     tcx: TyCtxt<'tcx>,
378     module_def_id: DefId,
379     builtin_lints: T,
380 ) {
381     if tcx.sess.opts.debugging_opts.no_interleave_lints {
382         // These passes runs in late_lint_crate with -Z no_interleave_lints
383         return;
384     }
385
386     late_lint_mod_pass(tcx, module_def_id, builtin_lints);
387
388     let mut passes: Vec<_> =
389         tcx.lint_store.late_module_passes.iter().map(|pass| (pass)()).collect();
390
391     if !passes.is_empty() {
392         late_lint_mod_pass(tcx, module_def_id, LateLintPassObjects { lints: &mut passes[..] });
393     }
394 }
395
396 fn late_lint_pass_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tcx>, pass: T) {
397     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
398
399     let krate = tcx.hir().krate();
400
401     let context = LateContext {
402         tcx,
403         tables: &ty::TypeckTables::empty(None),
404         param_env: ty::ParamEnv::empty(),
405         access_levels,
406         lint_store: &tcx.lint_store,
407         last_node_with_lint_attrs: hir::CRATE_HIR_ID,
408         generics: None,
409         only_module: false,
410     };
411
412     let mut cx = LateContextAndPass { context, pass };
413
414     // Visit the whole crate.
415     cx.with_lint_attrs(hir::CRATE_HIR_ID, &krate.attrs, |cx| {
416         // since the root module isn't visited as an item (because it isn't an
417         // item), warn for it here.
418         lint_callback!(cx, check_crate, krate);
419
420         hir_visit::walk_crate(cx, krate);
421
422         lint_callback!(cx, check_crate_post, krate);
423     })
424 }
425
426 fn late_lint_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tcx>, builtin_lints: T) {
427     let mut passes = tcx.lint_store.late_passes.iter().map(|p| (p)()).collect::<Vec<_>>();
428
429     if !tcx.sess.opts.debugging_opts.no_interleave_lints {
430         if !passes.is_empty() {
431             late_lint_pass_crate(tcx, LateLintPassObjects { lints: &mut passes[..] });
432         }
433
434         late_lint_pass_crate(tcx, builtin_lints);
435     } else {
436         for pass in &mut passes {
437             tcx.sess.time(&format!("running late lint: {}", pass.name()), || {
438                 late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) });
439             });
440         }
441
442         let mut passes: Vec<_> =
443             tcx.lint_store.late_module_passes.iter().map(|pass| (pass)()).collect();
444
445         for pass in &mut passes {
446             tcx.sess.time(&format!("running late module lint: {}", pass.name()), || {
447                 late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) });
448             });
449         }
450     }
451 }
452
453 /// Performs lint checking on a crate.
454 pub fn check_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
455     tcx: TyCtxt<'tcx>,
456     builtin_lints: impl FnOnce() -> T + Send,
457 ) {
458     join(
459         || {
460             tcx.sess.time("crate lints", || {
461                 // Run whole crate non-incremental lints
462                 late_lint_crate(tcx, builtin_lints());
463             });
464         },
465         || {
466             tcx.sess.time("module lints", || {
467                 // Run per-module lints
468                 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
469                     tcx.ensure().lint_mod(tcx.hir().local_def_id(module));
470                 });
471             });
472         },
473     );
474 }