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