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