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