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