1use std::any::Any;
7use std::cell::Cell;
8
9use rustc_data_structures::stack::ensure_sufficient_stack;
10use rustc_data_structures::sync::join;
11use rustc_hir::def_id::{LocalDefId, LocalModDefId};
12use rustc_hir::{self as hir, AmbigArg, HirId, intravisit as hir_visit};
13use rustc_middle::hir::nested_filter;
14use rustc_middle::ty::{self, TyCtxt};
15use rustc_session::Session;
16use rustc_session::lint::LintPass;
17use rustc_session::lint::builtin::HardwiredLints;
18use rustc_span::Span;
19use tracing::debug;
20
21use crate::passes::LateLintPassObject;
22use crate::{LateContext, LateLintPass, LintId, LintStore};
23
24pub fn unerased_lint_store(sess: &Session) -> &LintStore {
28 let store: &dyn Any = sess.lint_store.as_deref().unwrap();
29 store.downcast_ref().unwrap()
30}
31
32macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
33 $cx.pass.$f(&$cx.context, $($args),*);
34}) }
35
36struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> {
39 context: LateContext<'tcx>,
40 pass: T,
41}
42
43impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> {
44 fn with_lint_attrs<F>(&mut self, id: HirId, f: F)
48 where
49 F: FnOnce(&mut Self),
50 {
51 let attrs = self.context.tcx.hir_attrs(id);
52 let prev = self.context.last_node_with_lint_attrs;
53 self.context.last_node_with_lint_attrs = id;
54 debug!("late context: enter_attrs({:?})", attrs);
55 lint_callback!(self, check_attributes, attrs);
56 for attr in attrs {
57 lint_callback!(self, check_attribute, attr);
58 }
59 f(self);
60 debug!("late context: exit_attrs({:?})", attrs);
61 lint_callback!(self, check_attributes_post, attrs);
62 self.context.last_node_with_lint_attrs = prev;
63 }
64
65 fn with_param_env<F>(&mut self, id: hir::OwnerId, f: F)
66 where
67 F: FnOnce(&mut Self),
68 {
69 let old_param_env = self.context.param_env;
70 self.context.param_env = self.context.tcx.param_env(id);
71 f(self);
72 self.context.param_env = old_param_env;
73 }
74
75 fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, n: HirId) {
76 lint_callback!(self, check_mod, m, n);
77 hir_visit::walk_mod(self, m);
78 }
79}
80
81impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPass<'tcx, T> {
82 type NestedFilter = nested_filter::All;
83
84 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
88 self.context.tcx
89 }
90
91 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
92 let old_enclosing_body = self.context.enclosing_body.replace(body_id);
93 let old_cached_typeck_results = self.context.cached_typeck_results.get();
94
95 if old_enclosing_body != Some(body_id) {
99 self.context.cached_typeck_results.set(None);
100 }
101
102 let body = self.context.tcx.hir_body(body_id);
103 self.visit_body(body);
104 self.context.enclosing_body = old_enclosing_body;
105
106 if old_enclosing_body != Some(body_id) {
108 self.context.cached_typeck_results.set(old_cached_typeck_results);
109 }
110 }
111
112 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
113 self.with_lint_attrs(param.hir_id, |cx| {
114 hir_visit::walk_param(cx, param);
115 });
116 }
117
118 fn visit_body(&mut self, body: &hir::Body<'tcx>) {
119 lint_callback!(self, check_body, body);
120 hir_visit::walk_body(self, body);
121 lint_callback!(self, check_body_post, body);
122 }
123
124 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
125 let generics = self.context.generics.take();
126 self.context.generics = it.kind.generics();
127 let old_cached_typeck_results = self.context.cached_typeck_results.take();
128 let old_enclosing_body = self.context.enclosing_body.take();
129 self.with_lint_attrs(it.hir_id(), |cx| {
130 cx.with_param_env(it.owner_id, |cx| {
131 lint_callback!(cx, check_item, it);
132 hir_visit::walk_item(cx, it);
133 lint_callback!(cx, check_item_post, it);
134 });
135 });
136 self.context.enclosing_body = old_enclosing_body;
137 self.context.cached_typeck_results.set(old_cached_typeck_results);
138 self.context.generics = generics;
139 }
140
141 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
142 self.with_lint_attrs(it.hir_id(), |cx| {
143 cx.with_param_env(it.owner_id, |cx| {
144 lint_callback!(cx, check_foreign_item, it);
145 hir_visit::walk_foreign_item(cx, it);
146 });
147 })
148 }
149
150 fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
151 lint_callback!(self, check_pat, p);
152 hir_visit::walk_pat(self, p);
153 }
154
155 fn visit_lit(&mut self, hir_id: HirId, lit: &'tcx hir::Lit, negated: bool) {
156 lint_callback!(self, check_lit, hir_id, lit, negated);
157 }
158
159 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
160 self.with_lint_attrs(field.hir_id, |cx| hir_visit::walk_expr_field(cx, field))
161 }
162
163 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
164 ensure_sufficient_stack(|| {
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
173 fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
174 self.with_lint_attrs(s.hir_id, |cx| {
177 lint_callback!(cx, check_stmt, s);
178 });
179 hir_visit::walk_stmt(self, s);
180 }
181
182 fn visit_fn(
183 &mut self,
184 fk: hir_visit::FnKind<'tcx>,
185 decl: &'tcx hir::FnDecl<'tcx>,
186 body_id: hir::BodyId,
187 span: Span,
188 id: LocalDefId,
189 ) {
190 let old_enclosing_body = self.context.enclosing_body.replace(body_id);
193 let old_cached_typeck_results = self.context.cached_typeck_results.take();
194 let body = self.context.tcx.hir_body(body_id);
195 lint_callback!(self, check_fn, fk, decl, body, span, id);
196 hir_visit::walk_fn(self, fk, decl, body_id, 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(&mut self, s: &'tcx hir::VariantData<'tcx>) {
202 lint_callback!(self, check_struct_def, s);
203 hir_visit::walk_struct_def(self, s);
204 }
205
206 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
207 self.with_lint_attrs(s.hir_id, |cx| {
208 lint_callback!(cx, check_field_def, s);
209 hir_visit::walk_field_def(cx, s);
210 })
211 }
212
213 fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
214 self.with_lint_attrs(v.hir_id, |cx| {
215 lint_callback!(cx, check_variant, v);
216 hir_visit::walk_variant(cx, v);
217 })
218 }
219
220 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) {
221 lint_callback!(self, check_ty, t);
222 hir_visit::walk_ty(self, t);
223 }
224
225 fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _: Span, n: HirId) {
226 if !self.context.only_module {
227 self.process_mod(m, n);
228 }
229 }
230
231 fn visit_local(&mut self, l: &'tcx hir::LetStmt<'tcx>) {
232 self.with_lint_attrs(l.hir_id, |cx| {
233 lint_callback!(cx, check_local, l);
234 hir_visit::walk_local(cx, l);
235 })
236 }
237
238 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
239 lint_callback!(self, check_block, b);
240 hir_visit::walk_block(self, b);
241 lint_callback!(self, check_block_post, b);
242 }
243
244 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
245 self.with_lint_attrs(a.hir_id, |cx| {
246 lint_callback!(cx, check_arm, a);
247 hir_visit::walk_arm(cx, a);
248 })
249 }
250
251 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
252 lint_callback!(self, check_generic_param, p);
253 hir_visit::walk_generic_param(self, p);
254 }
255
256 fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) {
257 lint_callback!(self, check_generics, g);
258 hir_visit::walk_generics(self, g);
259 }
260
261 fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) {
262 hir_visit::walk_where_predicate(self, p);
263 }
264
265 fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
266 lint_callback!(self, check_poly_trait_ref, t);
267 hir_visit::walk_poly_trait_ref(self, t);
268 }
269
270 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
271 let generics = self.context.generics.take();
272 self.context.generics = Some(trait_item.generics);
273 self.with_lint_attrs(trait_item.hir_id(), |cx| {
274 cx.with_param_env(trait_item.owner_id, |cx| {
275 lint_callback!(cx, check_trait_item, trait_item);
276 hir_visit::walk_trait_item(cx, trait_item);
277 });
278 });
279 self.context.generics = generics;
280 }
281
282 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
283 let generics = self.context.generics.take();
284 self.context.generics = Some(impl_item.generics);
285 self.with_lint_attrs(impl_item.hir_id(), |cx| {
286 cx.with_param_env(impl_item.owner_id, |cx| {
287 lint_callback!(cx, check_impl_item, impl_item);
288 hir_visit::walk_impl_item(cx, impl_item);
289 lint_callback!(cx, check_impl_item_post, impl_item);
290 });
291 });
292 self.context.generics = generics;
293 }
294
295 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
296 hir_visit::walk_lifetime(self, lt);
297 }
298
299 fn visit_path(&mut self, p: &hir::Path<'tcx>, id: HirId) {
300 lint_callback!(self, check_path, p, id);
301 hir_visit::walk_path(self, p);
302 }
303}
304
305struct RuntimeCombinedLateLintPass<'a, 'tcx> {
310 passes: &'a mut [LateLintPassObject<'tcx>],
311}
312
313#[allow(rustc::lint_pass_impl_without_macro)]
314impl LintPass for RuntimeCombinedLateLintPass<'_, '_> {
315 fn name(&self) -> &'static str {
316 panic!()
317 }
318 fn get_lints(&self) -> crate::LintVec {
319 panic!()
320 }
321}
322
323macro_rules! impl_late_lint_pass {
324 ([], [$($(#[$attr:meta])* fn $f:ident($($param:ident: $arg:ty),*);)*]) => {
325 impl<'tcx> LateLintPass<'tcx> for RuntimeCombinedLateLintPass<'_, 'tcx> {
326 $(fn $f(&mut self, context: &LateContext<'tcx>, $($param: $arg),*) {
327 for pass in self.passes.iter_mut() {
328 pass.$f(context, $($param),*);
329 }
330 })*
331 }
332 };
333}
334
335crate::late_lint_methods!(impl_late_lint_pass, []);
336
337pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>(
338 tcx: TyCtxt<'tcx>,
339 module_def_id: LocalModDefId,
340 builtin_lints: T,
341) {
342 let context = LateContext {
343 tcx,
344 enclosing_body: None,
345 cached_typeck_results: Cell::new(None),
346 param_env: ty::ParamEnv::empty(),
347 effective_visibilities: tcx.effective_visibilities(()),
348 last_node_with_lint_attrs: tcx.local_def_id_to_hir_id(module_def_id),
349 generics: None,
350 only_module: true,
351 };
352
353 let store = unerased_lint_store(tcx.sess);
357
358 if store.late_module_passes.is_empty() {
359 late_lint_mod_inner(tcx, module_def_id, context, builtin_lints);
360 } else {
361 let builtin_lints = Box::new(builtin_lints) as Box<dyn LateLintPass<'tcx>>;
362 let mut binding = store
363 .late_module_passes
364 .iter()
365 .map(|mk_pass| (mk_pass)(tcx))
366 .chain(std::iter::once(builtin_lints))
367 .collect::<Vec<_>>();
368
369 let pass = RuntimeCombinedLateLintPass { passes: binding.as_mut_slice() };
370 late_lint_mod_inner(tcx, module_def_id, context, pass);
371 }
372}
373
374fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>(
375 tcx: TyCtxt<'tcx>,
376 module_def_id: LocalModDefId,
377 context: LateContext<'tcx>,
378 pass: T,
379) {
380 let mut cx = LateContextAndPass { context, pass };
381
382 let (module, _span, hir_id) = tcx.hir_get_module(module_def_id);
383
384 cx.with_lint_attrs(hir_id, |cx| {
385 if hir_id == hir::CRATE_HIR_ID {
387 lint_callback!(cx, check_crate,);
388 }
389
390 cx.process_mod(module, hir_id);
391
392 if hir_id == hir::CRATE_HIR_ID {
393 lint_callback!(cx, check_crate_post,);
394 }
395 });
396}
397
398fn late_lint_crate<'tcx>(tcx: TyCtxt<'tcx>) {
399 let passes: Vec<_> =
401 unerased_lint_store(tcx.sess).late_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect();
402
403 if passes.is_empty() {
404 return;
405 }
406
407 let context = LateContext {
408 tcx,
409 enclosing_body: None,
410 cached_typeck_results: Cell::new(None),
411 param_env: ty::ParamEnv::empty(),
412 effective_visibilities: tcx.effective_visibilities(()),
413 last_node_with_lint_attrs: hir::CRATE_HIR_ID,
414 generics: None,
415 only_module: false,
416 };
417
418 let lints_that_dont_need_to_run = tcx.lints_that_dont_need_to_run(());
419
420 let mut filtered_passes: Vec<Box<dyn LateLintPass<'tcx>>> = passes
421 .into_iter()
422 .filter(|pass| {
423 let lints = (**pass).get_lints();
424 lints.is_empty() ||
426 !lints.iter().all(|lint| lints_that_dont_need_to_run.contains(&LintId::of(lint)))
428 })
429 .collect();
430
431 filtered_passes.push(Box::new(HardwiredLints));
432 let pass = RuntimeCombinedLateLintPass { passes: &mut filtered_passes[..] };
433 late_lint_crate_inner(tcx, context, pass);
434}
435
436fn late_lint_crate_inner<'tcx, T: LateLintPass<'tcx>>(
437 tcx: TyCtxt<'tcx>,
438 context: LateContext<'tcx>,
439 pass: T,
440) {
441 let mut cx = LateContextAndPass { context, pass };
442
443 cx.with_lint_attrs(hir::CRATE_HIR_ID, |cx| {
445 lint_callback!(cx, check_crate,);
448 tcx.hir_walk_toplevel_module(cx);
449 lint_callback!(cx, check_crate_post,);
450 })
451}
452
453pub fn check_crate<'tcx>(tcx: TyCtxt<'tcx>) {
455 join(
456 || {
457 tcx.sess.time("crate_lints", || {
458 late_lint_crate(tcx);
460 });
461 },
462 || {
463 tcx.sess.time("module_lints", || {
464 tcx.par_hir_for_each_module(|module| tcx.ensure_ok().lint_mod(module));
466 });
467 },
468 );
469}