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