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