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