]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/late.rs
Inline and remove `late_lint_mod_pass`.
[rust.git] / compiler / rustc_lint / src / 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 as ast;
19 use rustc_data_structures::sync::join;
20 use rustc_hir as hir;
21 use rustc_hir::def_id::LocalDefId;
22 use rustc_hir::intravisit as hir_visit;
23 use rustc_hir::intravisit::Visitor;
24 use rustc_middle::hir::nested_filter;
25 use rustc_middle::ty::{self, TyCtxt};
26 use rustc_session::lint::LintPass;
27 use rustc_span::Span;
28
29 use std::any::Any;
30 use std::cell::Cell;
31
32 /// Extract the `LintStore` from the query context.
33 /// This function exists because we've erased `LintStore` as `dyn Any` in the context.
34 pub fn unerased_lint_store(tcx: TyCtxt<'_>) -> &LintStore {
35     let store: &dyn Any = &*tcx.lint_store;
36     store.downcast_ref().unwrap()
37 }
38
39 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
40     $cx.pass.$f(&$cx.context, $($args),*);
41 }) }
42
43 struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> {
44     context: LateContext<'tcx>,
45     pass: T,
46 }
47
48 impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> {
49     /// Merge the lints specified by any lint attributes into the
50     /// current lint context, call the provided function, then reset the
51     /// lints in effect to their previous state.
52     fn with_lint_attrs<F>(&mut self, id: hir::HirId, f: F)
53     where
54         F: FnOnce(&mut Self),
55     {
56         let attrs = self.context.tcx.hir().attrs(id);
57         let prev = self.context.last_node_with_lint_attrs;
58         self.context.last_node_with_lint_attrs = id;
59         debug!("late context: enter_attrs({:?})", attrs);
60         lint_callback!(self, enter_lint_attrs, attrs);
61         f(self);
62         debug!("late context: exit_attrs({:?})", attrs);
63         lint_callback!(self, exit_lint_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>, n: hir::HirId) {
79         lint_callback!(self, check_mod, m, n);
80         hir_visit::walk_mod(self, m, n);
81     }
82 }
83
84 impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPass<'tcx, T> {
85     type NestedFilter = nested_filter::All;
86
87     /// Because lints are scoped lexically, we want to walk nested
88     /// items in the context of the outer item, so enable
89     /// deep-walking.
90     fn nested_visit_map(&mut self) -> Self::Map {
91         self.context.tcx.hir()
92     }
93
94     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
95         let old_enclosing_body = self.context.enclosing_body.replace(body_id);
96         let old_cached_typeck_results = self.context.cached_typeck_results.get();
97
98         // HACK(eddyb) avoid trashing `cached_typeck_results` when we're
99         // nested in `visit_fn`, which may have already resulted in them
100         // being queried.
101         if old_enclosing_body != Some(body_id) {
102             self.context.cached_typeck_results.set(None);
103         }
104
105         let body = self.context.tcx.hir().body(body_id);
106         self.visit_body(body);
107         self.context.enclosing_body = old_enclosing_body;
108
109         // See HACK comment above.
110         if old_enclosing_body != Some(body_id) {
111             self.context.cached_typeck_results.set(old_cached_typeck_results);
112         }
113     }
114
115     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
116         self.with_lint_attrs(param.hir_id, |cx| {
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         let old_cached_typeck_results = self.context.cached_typeck_results.take();
131         let old_enclosing_body = self.context.enclosing_body.take();
132         self.with_lint_attrs(it.hir_id(), |cx| {
133             cx.with_param_env(it.hir_id(), |cx| {
134                 lint_callback!(cx, check_item, it);
135                 hir_visit::walk_item(cx, it);
136                 lint_callback!(cx, check_item_post, it);
137             });
138         });
139         self.context.enclosing_body = old_enclosing_body;
140         self.context.cached_typeck_results.set(old_cached_typeck_results);
141         self.context.generics = generics;
142     }
143
144     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
145         self.with_lint_attrs(it.hir_id(), |cx| {
146             cx.with_param_env(it.hir_id(), |cx| {
147                 lint_callback!(cx, check_foreign_item, it);
148                 hir_visit::walk_foreign_item(cx, it);
149             });
150         })
151     }
152
153     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
154         lint_callback!(self, check_pat, p);
155         hir_visit::walk_pat(self, p);
156     }
157
158     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
159         self.with_lint_attrs(e.hir_id, |cx| {
160             lint_callback!(cx, check_expr, e);
161             hir_visit::walk_expr(cx, e);
162             lint_callback!(cx, check_expr_post, e);
163         })
164     }
165
166     fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
167         // See `EarlyContextAndPass::visit_stmt` for an explanation
168         // of why we call `walk_stmt` outside of `with_lint_attrs`
169         self.with_lint_attrs(s.hir_id, |cx| {
170             lint_callback!(cx, check_stmt, s);
171         });
172         hir_visit::walk_stmt(self, s);
173     }
174
175     fn visit_fn(
176         &mut self,
177         fk: hir_visit::FnKind<'tcx>,
178         decl: &'tcx hir::FnDecl<'tcx>,
179         body_id: hir::BodyId,
180         span: Span,
181         id: hir::HirId,
182     ) {
183         // Wrap in typeck results here, not just in visit_nested_body,
184         // in order for `check_fn` to be able to use them.
185         let old_enclosing_body = self.context.enclosing_body.replace(body_id);
186         let old_cached_typeck_results = self.context.cached_typeck_results.take();
187         let body = self.context.tcx.hir().body(body_id);
188         lint_callback!(self, check_fn, fk, decl, body, span, id);
189         hir_visit::walk_fn(self, fk, decl, body_id, id);
190         self.context.enclosing_body = old_enclosing_body;
191         self.context.cached_typeck_results.set(old_cached_typeck_results);
192     }
193
194     fn visit_variant_data(&mut self, s: &'tcx hir::VariantData<'tcx>) {
195         lint_callback!(self, check_struct_def, s);
196         hir_visit::walk_struct_def(self, s);
197     }
198
199     fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
200         self.with_lint_attrs(s.hir_id, |cx| {
201             lint_callback!(cx, check_field_def, s);
202             hir_visit::walk_field_def(cx, s);
203         })
204     }
205
206     fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
207         self.with_lint_attrs(v.hir_id, |cx| {
208             lint_callback!(cx, check_variant, v);
209             hir_visit::walk_variant(cx, v);
210         })
211     }
212
213     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
214         lint_callback!(self, check_ty, t);
215         hir_visit::walk_ty(self, t);
216     }
217
218     fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
219         hir_visit::walk_inf(self, inf);
220     }
221
222     fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _: Span, n: hir::HirId) {
223         if !self.context.only_module {
224             self.process_mod(m, n);
225         }
226     }
227
228     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
229         self.with_lint_attrs(l.hir_id, |cx| {
230             lint_callback!(cx, check_local, l);
231             hir_visit::walk_local(cx, l);
232         })
233     }
234
235     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
236         lint_callback!(self, check_block, b);
237         hir_visit::walk_block(self, b);
238         lint_callback!(self, check_block_post, b);
239     }
240
241     fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
242         lint_callback!(self, check_arm, a);
243         hir_visit::walk_arm(self, a);
244     }
245
246     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
247         lint_callback!(self, check_generic_param, p);
248         hir_visit::walk_generic_param(self, p);
249     }
250
251     fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) {
252         lint_callback!(self, check_generics, g);
253         hir_visit::walk_generics(self, g);
254     }
255
256     fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) {
257         hir_visit::walk_where_predicate(self, p);
258     }
259
260     fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
261         lint_callback!(self, check_poly_trait_ref, t);
262         hir_visit::walk_poly_trait_ref(self, t);
263     }
264
265     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
266         let generics = self.context.generics.take();
267         self.context.generics = Some(&trait_item.generics);
268         self.with_lint_attrs(trait_item.hir_id(), |cx| {
269             cx.with_param_env(trait_item.hir_id(), |cx| {
270                 lint_callback!(cx, check_trait_item, trait_item);
271                 hir_visit::walk_trait_item(cx, trait_item);
272             });
273         });
274         self.context.generics = generics;
275     }
276
277     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
278         let generics = self.context.generics.take();
279         self.context.generics = Some(&impl_item.generics);
280         self.with_lint_attrs(impl_item.hir_id(), |cx| {
281             cx.with_param_env(impl_item.hir_id(), |cx| {
282                 lint_callback!(cx, check_impl_item, impl_item);
283                 hir_visit::walk_impl_item(cx, impl_item);
284                 lint_callback!(cx, check_impl_item_post, impl_item);
285             });
286         });
287         self.context.generics = generics;
288     }
289
290     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
291         hir_visit::walk_lifetime(self, lt);
292     }
293
294     fn visit_path(&mut self, p: &'tcx hir::Path<'tcx>, id: hir::HirId) {
295         lint_callback!(self, check_path, p, id);
296         hir_visit::walk_path(self, p);
297     }
298
299     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
300         lint_callback!(self, check_attribute, attr);
301     }
302 }
303
304 struct LateLintPassObjects<'a, 'tcx> {
305     lints: &'a mut [LateLintPassObject<'tcx>],
306 }
307
308 #[allow(rustc::lint_pass_impl_without_macro)]
309 impl LintPass for LateLintPassObjects<'_, '_> {
310     fn name(&self) -> &'static str {
311         panic!()
312     }
313 }
314
315 macro_rules! late_lint_pass_impl {
316     ([], [$hir:tt], [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => {
317         impl<$hir> LateLintPass<$hir> for LateLintPassObjects<'_, $hir> {
318             $(fn $name(&mut self, context: &LateContext<$hir>, $($param: $arg),*) {
319                 for obj in self.lints.iter_mut() {
320                     obj.$name(context, $($param),*);
321                 }
322             })*
323         }
324     };
325 }
326
327 crate::late_lint_methods!(late_lint_pass_impl, [], ['tcx]);
328
329 pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>(
330     tcx: TyCtxt<'tcx>,
331     module_def_id: LocalDefId,
332     builtin_lints: T,
333 ) {
334     let context = LateContext {
335         tcx,
336         enclosing_body: None,
337         cached_typeck_results: Cell::new(None),
338         param_env: ty::ParamEnv::empty(),
339         effective_visibilities: &tcx.effective_visibilities(()),
340         lint_store: unerased_lint_store(tcx),
341         last_node_with_lint_attrs: tcx.hir().local_def_id_to_hir_id(module_def_id),
342         generics: None,
343         only_module: true,
344     };
345
346     let mut passes: Vec<_> =
347         unerased_lint_store(tcx).late_module_passes.iter().map(|pass| (pass)(tcx)).collect();
348     passes.push(Box::new(builtin_lints));
349     let pass = LateLintPassObjects { lints: &mut passes[..] };
350
351     let mut cx = LateContextAndPass { context, pass };
352
353     let (module, _span, hir_id) = tcx.hir().get_module(module_def_id);
354     cx.process_mod(module, hir_id);
355
356     // Visit the crate attributes
357     if hir_id == hir::CRATE_HIR_ID {
358         for attr in tcx.hir().attrs(hir::CRATE_HIR_ID).iter() {
359             cx.visit_attribute(attr)
360         }
361     }
362 }
363
364 fn late_lint_pass_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, pass: T) {
365     let effective_visibilities = &tcx.effective_visibilities(());
366
367     let context = LateContext {
368         tcx,
369         enclosing_body: None,
370         cached_typeck_results: Cell::new(None),
371         param_env: ty::ParamEnv::empty(),
372         effective_visibilities,
373         lint_store: unerased_lint_store(tcx),
374         last_node_with_lint_attrs: hir::CRATE_HIR_ID,
375         generics: None,
376         only_module: false,
377     };
378
379     let mut cx = LateContextAndPass { context, pass };
380
381     // Visit the whole crate.
382     cx.with_lint_attrs(hir::CRATE_HIR_ID, |cx| {
383         // since the root module isn't visited as an item (because it isn't an
384         // item), warn for it here.
385         lint_callback!(cx, check_crate,);
386         tcx.hir().walk_toplevel_module(cx);
387         tcx.hir().walk_attributes(cx);
388         lint_callback!(cx, check_crate_post,);
389     })
390 }
391
392 fn late_lint_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(tcx: TyCtxt<'tcx>, builtin_lints: T) {
393     let mut passes =
394         unerased_lint_store(tcx).late_passes.iter().map(|p| (p)(tcx)).collect::<Vec<_>>();
395     passes.push(Box::new(builtin_lints));
396
397     late_lint_pass_crate(tcx, LateLintPassObjects { lints: &mut passes[..] });
398 }
399
400 /// Performs lint checking on a crate.
401 pub fn check_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(
402     tcx: TyCtxt<'tcx>,
403     builtin_lints: impl FnOnce() -> T + Send,
404 ) {
405     join(
406         || {
407             tcx.sess.time("crate_lints", || {
408                 // Run whole crate non-incremental lints
409                 late_lint_crate(tcx, builtin_lints());
410             });
411         },
412         || {
413             tcx.sess.time("module_lints", || {
414                 // Run per-module lints
415                 tcx.hir().par_for_each_module(|module| tcx.ensure().lint_mod(module));
416             });
417         },
418     );
419 }