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