]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/late.rs
Rollup merge of #106113 - krasimirgg:llvm-16-ext-tyid, r=nikic
[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::Span;
28
29 use std::any::Any;
30 use std::cell::Cell;
31
32 /// Extract the `LintStore` from the query context.
33 /// This function exists because we've erased `LintStore` as `dyn Any` in the context.
34 pub fn unerased_lint_store(tcx: TyCtxt<'_>) -> &LintStore {
35     let store: &dyn Any = &*tcx.lint_store;
36     store.downcast_ref().unwrap()
37 }
38
39 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
40     $cx.pass.$f(&$cx.context, $($args),*);
41 }) }
42
43 /// Implements the AST traversal for late lint passes. `T` provides the
44 /// `check_*` methods.
45 pub struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> {
46     context: LateContext<'tcx>,
47     pass: T,
48 }
49
50 impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> {
51     /// Merge the lints specified by any lint attributes into the
52     /// current lint context, call the provided function, then reset the
53     /// lints in effect to their previous state.
54     fn with_lint_attrs<F>(&mut self, id: hir::HirId, f: F)
55     where
56         F: FnOnce(&mut Self),
57     {
58         let attrs = self.context.tcx.hir().attrs(id);
59         let prev = self.context.last_node_with_lint_attrs;
60         self.context.last_node_with_lint_attrs = id;
61         debug!("late context: enter_attrs({:?})", attrs);
62         lint_callback!(self, enter_lint_attrs, attrs);
63         f(self);
64         debug!("late context: exit_attrs({:?})", attrs);
65         lint_callback!(self, exit_lint_attrs, attrs);
66         self.context.last_node_with_lint_attrs = prev;
67     }
68
69     fn with_param_env<F>(&mut self, id: hir::HirId, f: F)
70     where
71         F: FnOnce(&mut Self),
72     {
73         let old_param_env = self.context.param_env;
74         self.context.param_env =
75             self.context.tcx.param_env(self.context.tcx.hir().local_def_id(id));
76         f(self);
77         self.context.param_env = old_param_env;
78     }
79
80     fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, n: hir::HirId) {
81         lint_callback!(self, check_mod, m, n);
82         hir_visit::walk_mod(self, m, n);
83     }
84 }
85
86 impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPass<'tcx, T> {
87     type NestedFilter = nested_filter::All;
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(&mut self) -> Self::Map {
93         self.context.tcx.hir()
94     }
95
96     fn visit_nested_body(&mut self, body_id: hir::BodyId) {
97         let old_enclosing_body = self.context.enclosing_body.replace(body_id);
98         let old_cached_typeck_results = self.context.cached_typeck_results.get();
99
100         // HACK(eddyb) avoid trashing `cached_typeck_results` when we're
101         // nested in `visit_fn`, which may have already resulted in them
102         // being queried.
103         if old_enclosing_body != Some(body_id) {
104             self.context.cached_typeck_results.set(None);
105         }
106
107         let body = self.context.tcx.hir().body(body_id);
108         self.visit_body(body);
109         self.context.enclosing_body = old_enclosing_body;
110
111         // See HACK comment above.
112         if old_enclosing_body != Some(body_id) {
113             self.context.cached_typeck_results.set(old_cached_typeck_results);
114         }
115     }
116
117     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
118         self.with_lint_attrs(param.hir_id, |cx| {
119             hir_visit::walk_param(cx, param);
120         });
121     }
122
123     fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
124         lint_callback!(self, check_body, body);
125         hir_visit::walk_body(self, body);
126         lint_callback!(self, check_body_post, body);
127     }
128
129     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
130         let generics = self.context.generics.take();
131         self.context.generics = it.kind.generics();
132         let old_cached_typeck_results = self.context.cached_typeck_results.take();
133         let old_enclosing_body = self.context.enclosing_body.take();
134         self.with_lint_attrs(it.hir_id(), |cx| {
135             cx.with_param_env(it.hir_id(), |cx| {
136                 lint_callback!(cx, check_item, it);
137                 hir_visit::walk_item(cx, it);
138                 lint_callback!(cx, check_item_post, it);
139             });
140         });
141         self.context.enclosing_body = old_enclosing_body;
142         self.context.cached_typeck_results.set(old_cached_typeck_results);
143         self.context.generics = generics;
144     }
145
146     fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
147         self.with_lint_attrs(it.hir_id(), |cx| {
148             cx.with_param_env(it.hir_id(), |cx| {
149                 lint_callback!(cx, check_foreign_item, it);
150                 hir_visit::walk_foreign_item(cx, it);
151             });
152         })
153     }
154
155     fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
156         lint_callback!(self, check_pat, p);
157         hir_visit::walk_pat(self, p);
158     }
159
160     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
161         self.with_lint_attrs(e.hir_id, |cx| {
162             lint_callback!(cx, check_expr, e);
163             hir_visit::walk_expr(cx, e);
164             lint_callback!(cx, check_expr_post, e);
165         })
166     }
167
168     fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
169         // See `EarlyContextAndPass::visit_stmt` for an explanation
170         // of why we call `walk_stmt` outside of `with_lint_attrs`
171         self.with_lint_attrs(s.hir_id, |cx| {
172             lint_callback!(cx, check_stmt, s);
173         });
174         hir_visit::walk_stmt(self, s);
175     }
176
177     fn visit_fn(
178         &mut self,
179         fk: hir_visit::FnKind<'tcx>,
180         decl: &'tcx hir::FnDecl<'tcx>,
181         body_id: hir::BodyId,
182         span: Span,
183         id: hir::HirId,
184     ) {
185         // Wrap in typeck results here, not just in visit_nested_body,
186         // in order for `check_fn` to be able to use them.
187         let old_enclosing_body = self.context.enclosing_body.replace(body_id);
188         let old_cached_typeck_results = self.context.cached_typeck_results.take();
189         let body = self.context.tcx.hir().body(body_id);
190         lint_callback!(self, check_fn, fk, decl, body, span, id);
191         hir_visit::walk_fn(self, fk, decl, body_id, id);
192         self.context.enclosing_body = old_enclosing_body;
193         self.context.cached_typeck_results.set(old_cached_typeck_results);
194     }
195
196     fn visit_variant_data(&mut self, s: &'tcx hir::VariantData<'tcx>) {
197         lint_callback!(self, check_struct_def, s);
198         hir_visit::walk_struct_def(self, s);
199     }
200
201     fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
202         self.with_lint_attrs(s.hir_id, |cx| {
203             lint_callback!(cx, check_field_def, s);
204             hir_visit::walk_field_def(cx, s);
205         })
206     }
207
208     fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
209         self.with_lint_attrs(v.hir_id, |cx| {
210             lint_callback!(cx, check_variant, v);
211             hir_visit::walk_variant(cx, 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_infer(&mut self, inf: &'tcx hir::InferArg) {
221         hir_visit::walk_inf(self, inf);
222     }
223
224     fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _: Span, n: hir::HirId) {
225         if !self.context.only_module {
226             self.process_mod(m, n);
227         }
228     }
229
230     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
231         self.with_lint_attrs(l.hir_id, |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         hir_visit::walk_where_predicate(self, p);
260     }
261
262     fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
263         lint_callback!(self, check_poly_trait_ref, t);
264         hir_visit::walk_poly_trait_ref(self, t);
265     }
266
267     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
268         let generics = self.context.generics.take();
269         self.context.generics = Some(&trait_item.generics);
270         self.with_lint_attrs(trait_item.hir_id(), |cx| {
271             cx.with_param_env(trait_item.hir_id(), |cx| {
272                 lint_callback!(cx, check_trait_item, trait_item);
273                 hir_visit::walk_trait_item(cx, trait_item);
274             });
275         });
276         self.context.generics = generics;
277     }
278
279     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
280         let generics = self.context.generics.take();
281         self.context.generics = Some(&impl_item.generics);
282         self.with_lint_attrs(impl_item.hir_id(), |cx| {
283             cx.with_param_env(impl_item.hir_id(), |cx| {
284                 lint_callback!(cx, check_impl_item, impl_item);
285                 hir_visit::walk_impl_item(cx, impl_item);
286                 lint_callback!(cx, check_impl_item_post, impl_item);
287             });
288         });
289         self.context.generics = generics;
290     }
291
292     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
293         hir_visit::walk_lifetime(self, lt);
294     }
295
296     fn visit_path(&mut self, p: &hir::Path<'tcx>, id: hir::HirId) {
297         lint_callback!(self, check_path, p, id);
298         hir_visit::walk_path(self, p);
299     }
300
301     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
302         lint_callback!(self, check_attribute, attr);
303     }
304 }
305
306 // Combines multiple lint passes into a single pass, at runtime. Each
307 // `check_foo` method in `$methods` within this pass simply calls `check_foo`
308 // once per `$pass`. Compare with `declare_combined_late_lint_pass`, which is
309 // similar, but combines lint passes at compile time.
310 struct RuntimeCombinedLateLintPass<'a, 'tcx> {
311     passes: &'a mut [LateLintPassObject<'tcx>],
312 }
313
314 #[allow(rustc::lint_pass_impl_without_macro)]
315 impl LintPass for RuntimeCombinedLateLintPass<'_, '_> {
316     fn name(&self) -> &'static str {
317         panic!()
318     }
319 }
320
321 macro_rules! impl_late_lint_pass {
322     ([], [$($(#[$attr:meta])* fn $f:ident($($param:ident: $arg:ty),*);)*]) => {
323         impl<'tcx> LateLintPass<'tcx> for RuntimeCombinedLateLintPass<'_, 'tcx> {
324             $(fn $f(&mut self, context: &LateContext<'tcx>, $($param: $arg),*) {
325                 for pass in self.passes.iter_mut() {
326                     pass.$f(context, $($param),*);
327                 }
328             })*
329         }
330     };
331 }
332
333 crate::late_lint_methods!(impl_late_lint_pass, []);
334
335 pub(super) fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>(
336     tcx: TyCtxt<'tcx>,
337     module_def_id: LocalDefId,
338     builtin_lints: T,
339 ) {
340     let context = LateContext {
341         tcx,
342         enclosing_body: None,
343         cached_typeck_results: Cell::new(None),
344         param_env: ty::ParamEnv::empty(),
345         effective_visibilities: &tcx.effective_visibilities(()),
346         lint_store: unerased_lint_store(tcx),
347         last_node_with_lint_attrs: tcx.hir().local_def_id_to_hir_id(module_def_id),
348         generics: None,
349         only_module: true,
350     };
351
352     // Note: `passes` is often empty. In that case, it's faster to run
353     // `builtin_lints` directly rather than bundling it up into the
354     // `RuntimeCombinedLateLintPass`.
355     let mut passes: Vec<_> =
356         unerased_lint_store(tcx).late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect();
357     if passes.is_empty() {
358         late_lint_mod_inner(tcx, module_def_id, context, builtin_lints);
359     } else {
360         passes.push(Box::new(builtin_lints));
361         let pass = RuntimeCombinedLateLintPass { passes: &mut passes[..] };
362         late_lint_mod_inner(tcx, module_def_id, context, pass);
363     }
364 }
365
366 fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>(
367     tcx: TyCtxt<'tcx>,
368     module_def_id: LocalDefId,
369     context: LateContext<'tcx>,
370     pass: T,
371 ) {
372     let mut cx = LateContextAndPass { context, pass };
373
374     let (module, _span, hir_id) = tcx.hir().get_module(module_def_id);
375     cx.process_mod(module, hir_id);
376
377     // Visit the crate attributes
378     if hir_id == hir::CRATE_HIR_ID {
379         for attr in tcx.hir().attrs(hir::CRATE_HIR_ID).iter() {
380             cx.visit_attribute(attr)
381         }
382     }
383 }
384
385 fn late_lint_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(tcx: TyCtxt<'tcx>, builtin_lints: T) {
386     let context = LateContext {
387         tcx,
388         enclosing_body: None,
389         cached_typeck_results: Cell::new(None),
390         param_env: ty::ParamEnv::empty(),
391         effective_visibilities: &tcx.effective_visibilities(()),
392         lint_store: unerased_lint_store(tcx),
393         last_node_with_lint_attrs: hir::CRATE_HIR_ID,
394         generics: None,
395         only_module: false,
396     };
397
398     // Note: `passes` is often empty. In that case, it's faster to run
399     // `builtin_lints` directly rather than bundling it up into the
400     // `RuntimeCombinedLateLintPass`.
401     let mut passes: Vec<_> =
402         unerased_lint_store(tcx).late_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect();
403     if passes.is_empty() {
404         late_lint_crate_inner(tcx, context, builtin_lints);
405     } else {
406         passes.push(Box::new(builtin_lints));
407         let pass = RuntimeCombinedLateLintPass { passes: &mut passes[..] };
408         late_lint_crate_inner(tcx, context, pass);
409     }
410 }
411
412 fn late_lint_crate_inner<'tcx, T: LateLintPass<'tcx>>(
413     tcx: TyCtxt<'tcx>,
414     context: LateContext<'tcx>,
415     pass: T,
416 ) {
417     let mut cx = LateContextAndPass { context, pass };
418
419     // Visit the whole crate.
420     cx.with_lint_attrs(hir::CRATE_HIR_ID, |cx| {
421         // Since the root module isn't visited as an item (because it isn't an
422         // item), warn for it here.
423         lint_callback!(cx, check_crate,);
424         tcx.hir().walk_toplevel_module(cx);
425         tcx.hir().walk_attributes(cx);
426         lint_callback!(cx, check_crate_post,);
427     })
428 }
429
430 /// Performs lint checking on a crate.
431 pub fn check_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(
432     tcx: TyCtxt<'tcx>,
433     builtin_lints: impl FnOnce() -> T + Send,
434 ) {
435     join(
436         || {
437             tcx.sess.time("crate_lints", || {
438                 // Run whole crate non-incremental lints
439                 late_lint_crate(tcx, builtin_lints());
440             });
441         },
442         || {
443             tcx.sess.time("module_lints", || {
444                 // Run per-module lints
445                 tcx.hir().par_for_each_module(|module| tcx.ensure().lint_mod(module));
446             });
447         },
448     );
449 }