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