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