1 //! Implementation of lint checking.
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.
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.
17 use crate::{passes::LateLintPassObject, LateContext, LateLintPass, LintStore};
18 use rustc::hir::map::Map;
19 use rustc::ty::{self, TyCtxt};
20 use rustc_data_structures::sync::{join, par_iter, ParallelIterator};
22 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
23 use rustc_hir::intravisit as hir_visit;
24 use rustc_hir::intravisit::Visitor;
25 use rustc_session::lint::LintPass;
28 use syntax::walk_list;
33 /// Extract the `LintStore` from the query context.
34 /// This function exists because we've erased `LintStore` as `dyn Any` in the context.
35 crate fn unerased_lint_store<'tcx>(tcx: TyCtxt<'tcx>) -> &'tcx LintStore {
36 tcx.lint_store.downcast_ref().unwrap()
39 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
40 $cx.pass.$f(&$cx.context, $($args),*);
43 struct LateContextAndPass<'a, 'tcx, T: LateLintPass<'a, 'tcx>> {
44 context: LateContext<'a, 'tcx>,
48 impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> LateContextAndPass<'a, 'tcx, T> {
49 /// Merge the lints specified by any lint attributes into the
50 /// current lint context, call the provided function, then reset the
51 /// lints in effect to their previous state.
52 fn with_lint_attrs<F>(&mut self, id: hir::HirId, attrs: &'tcx [ast::Attribute], f: F)
56 let prev = self.context.last_node_with_lint_attrs;
57 self.context.last_node_with_lint_attrs = id;
58 self.enter_attrs(attrs);
60 self.exit_attrs(attrs);
61 self.context.last_node_with_lint_attrs = prev;
64 fn with_param_env<F>(&mut self, id: hir::HirId, f: F)
68 let old_param_env = self.context.param_env;
69 self.context.param_env =
70 self.context.tcx.param_env(self.context.tcx.hir().local_def_id(id));
72 self.context.param_env = old_param_env;
75 fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) {
76 lint_callback!(self, check_mod, m, s, n);
77 hir_visit::walk_mod(self, m, n);
78 lint_callback!(self, check_mod_post, m, s, n);
81 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
82 debug!("late context: enter_attrs({:?})", attrs);
83 lint_callback!(self, enter_lint_attrs, attrs);
86 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
87 debug!("late context: exit_attrs({:?})", attrs);
88 lint_callback!(self, exit_lint_attrs, attrs);
92 impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx>
93 for LateContextAndPass<'a, 'tcx, T>
97 /// Because lints are scoped lexically, we want to walk nested
98 /// items in the context of the outer item, so enable
100 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, Self::Map> {
101 hir_visit::NestedVisitorMap::All(&self.context.tcx.hir())
104 fn visit_nested_body(&mut self, body: hir::BodyId) {
105 let old_tables = self.context.tables;
106 self.context.tables = self.context.tcx.body_tables(body);
107 let body = self.context.tcx.hir().body(body);
108 self.visit_body(body);
109 self.context.tables = old_tables;
112 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
113 self.with_lint_attrs(param.hir_id, ¶m.attrs, |cx| {
114 lint_callback!(cx, check_param, param);
115 hir_visit::walk_param(cx, param);
119 fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) {
120 lint_callback!(self, check_body, body);
121 hir_visit::walk_body(self, body);
122 lint_callback!(self, check_body_post, body);
125 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
126 let generics = self.context.generics.take();
127 self.context.generics = it.kind.generics();
128 self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
129 cx.with_param_env(it.hir_id, |cx| {
130 lint_callback!(cx, check_item, it);
131 hir_visit::walk_item(cx, it);
132 lint_callback!(cx, check_item_post, it);
135 self.context.generics = generics;
138 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
139 self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
140 cx.with_param_env(it.hir_id, |cx| {
141 lint_callback!(cx, check_foreign_item, it);
142 hir_visit::walk_foreign_item(cx, it);
143 lint_callback!(cx, check_foreign_item_post, it);
148 fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
149 lint_callback!(self, check_pat, p);
150 hir_visit::walk_pat(self, p);
153 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
154 self.with_lint_attrs(e.hir_id, &e.attrs, |cx| {
155 lint_callback!(cx, check_expr, e);
156 hir_visit::walk_expr(cx, e);
157 lint_callback!(cx, check_expr_post, e);
161 fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
162 // statement attributes are actually just attributes on one of
166 // so we keep track of lint levels there
167 lint_callback!(self, check_stmt, s);
168 hir_visit::walk_stmt(self, s);
173 fk: hir_visit::FnKind<'tcx>,
174 decl: &'tcx hir::FnDecl<'tcx>,
175 body_id: hir::BodyId,
179 // Wrap in tables here, not just in visit_nested_body,
180 // in order for `check_fn` to be able to use them.
181 let old_tables = self.context.tables;
182 self.context.tables = self.context.tcx.body_tables(body_id);
183 let body = self.context.tcx.hir().body(body_id);
184 lint_callback!(self, check_fn, fk, decl, body, span, id);
185 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
186 lint_callback!(self, check_fn_post, fk, decl, body, span, id);
187 self.context.tables = old_tables;
190 fn visit_variant_data(
192 s: &'tcx hir::VariantData<'tcx>,
194 _: &'tcx hir::Generics<'tcx>,
198 lint_callback!(self, check_struct_def, s);
199 hir_visit::walk_struct_def(self, s);
200 lint_callback!(self, check_struct_def_post, s);
203 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
204 self.with_lint_attrs(s.hir_id, &s.attrs, |cx| {
205 lint_callback!(cx, check_struct_field, s);
206 hir_visit::walk_struct_field(cx, s);
212 v: &'tcx hir::Variant<'tcx>,
213 g: &'tcx hir::Generics<'tcx>,
216 self.with_lint_attrs(v.id, &v.attrs, |cx| {
217 lint_callback!(cx, check_variant, v);
218 hir_visit::walk_variant(cx, v, g, item_id);
219 lint_callback!(cx, check_variant_post, v);
223 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
224 lint_callback!(self, check_ty, t);
225 hir_visit::walk_ty(self, t);
228 fn visit_name(&mut self, sp: Span, name: ast::Name) {
229 lint_callback!(self, check_name, sp, name);
232 fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) {
233 if !self.context.only_module {
234 self.process_mod(m, s, n);
238 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
239 self.with_lint_attrs(l.hir_id, &l.attrs, |cx| {
240 lint_callback!(cx, check_local, l);
241 hir_visit::walk_local(cx, l);
245 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
246 lint_callback!(self, check_block, b);
247 hir_visit::walk_block(self, b);
248 lint_callback!(self, check_block_post, b);
251 fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
252 lint_callback!(self, check_arm, a);
253 hir_visit::walk_arm(self, a);
256 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
257 lint_callback!(self, check_generic_param, p);
258 hir_visit::walk_generic_param(self, p);
261 fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) {
262 lint_callback!(self, check_generics, g);
263 hir_visit::walk_generics(self, g);
266 fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) {
267 lint_callback!(self, check_where_predicate, p);
268 hir_visit::walk_where_predicate(self, p);
271 fn visit_poly_trait_ref(
273 t: &'tcx hir::PolyTraitRef<'tcx>,
274 m: hir::TraitBoundModifier,
276 lint_callback!(self, check_poly_trait_ref, t, m);
277 hir_visit::walk_poly_trait_ref(self, t, m);
280 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
281 let generics = self.context.generics.take();
282 self.context.generics = Some(&trait_item.generics);
283 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |cx| {
284 cx.with_param_env(trait_item.hir_id, |cx| {
285 lint_callback!(cx, check_trait_item, trait_item);
286 hir_visit::walk_trait_item(cx, trait_item);
287 lint_callback!(cx, check_trait_item_post, trait_item);
290 self.context.generics = generics;
293 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
294 let generics = self.context.generics.take();
295 self.context.generics = Some(&impl_item.generics);
296 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |cx| {
297 cx.with_param_env(impl_item.hir_id, |cx| {
298 lint_callback!(cx, check_impl_item, impl_item);
299 hir_visit::walk_impl_item(cx, impl_item);
300 lint_callback!(cx, check_impl_item_post, impl_item);
303 self.context.generics = generics;
306 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
307 lint_callback!(self, check_lifetime, lt);
308 hir_visit::walk_lifetime(self, lt);
311 fn visit_path(&mut self, p: &'tcx hir::Path<'tcx>, id: hir::HirId) {
312 lint_callback!(self, check_path, p, id);
313 hir_visit::walk_path(self, p);
316 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
317 lint_callback!(self, check_attribute, attr);
321 struct LateLintPassObjects<'a> {
322 lints: &'a mut [LateLintPassObject],
325 #[allow(rustc::lint_pass_impl_without_macro)]
326 impl LintPass for LateLintPassObjects<'_> {
327 fn name(&self) -> &'static str {
332 macro_rules! expand_late_lint_pass_impl_methods {
333 ([$a:tt, $hir:tt], [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
334 $(fn $name(&mut self, context: &LateContext<$a, $hir>, $($param: $arg),*) {
335 for obj in self.lints.iter_mut() {
336 obj.$name(context, $($param),*);
342 macro_rules! late_lint_pass_impl {
343 ([], [$hir:tt], $methods:tt) => (
344 impl<'a, $hir> LateLintPass<'a, $hir> for LateLintPassObjects<'_> {
345 expand_late_lint_pass_impl_methods!(['a, $hir], $methods);
350 crate::late_lint_methods!(late_lint_pass_impl, [], ['tcx]);
352 fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
354 module_def_id: DefId,
357 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
359 let context = LateContext {
361 tables: &ty::TypeckTables::empty(None),
362 param_env: ty::ParamEnv::empty(),
364 lint_store: unerased_lint_store(tcx),
365 last_node_with_lint_attrs: tcx.hir().as_local_hir_id(module_def_id).unwrap(),
370 let mut cx = LateContextAndPass { context, pass };
372 let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
373 cx.process_mod(module, span, hir_id);
375 // Visit the crate attributes
376 if hir_id == hir::CRATE_HIR_ID {
377 walk_list!(cx, visit_attribute, tcx.hir().attrs(hir::CRATE_HIR_ID));
381 pub fn late_lint_mod<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
383 module_def_id: DefId,
386 if tcx.sess.opts.debugging_opts.no_interleave_lints {
387 // These passes runs in late_lint_crate with -Z no_interleave_lints
391 late_lint_mod_pass(tcx, module_def_id, builtin_lints);
393 let mut passes: Vec<_> =
394 unerased_lint_store(tcx).late_module_passes.iter().map(|pass| (pass)()).collect();
396 if !passes.is_empty() {
397 late_lint_mod_pass(tcx, module_def_id, LateLintPassObjects { lints: &mut passes[..] });
401 fn late_lint_pass_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tcx>, pass: T) {
402 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
404 let krate = tcx.hir().krate();
406 let context = LateContext {
408 tables: &ty::TypeckTables::empty(None),
409 param_env: ty::ParamEnv::empty(),
411 lint_store: unerased_lint_store(tcx),
412 last_node_with_lint_attrs: hir::CRATE_HIR_ID,
417 let mut cx = LateContextAndPass { context, pass };
419 // Visit the whole crate.
420 cx.with_lint_attrs(hir::CRATE_HIR_ID, &krate.attrs, |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, krate);
425 hir_visit::walk_crate(cx, krate);
427 lint_callback!(cx, check_crate_post, krate);
431 fn late_lint_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tcx>, builtin_lints: T) {
432 let mut passes = unerased_lint_store(tcx).late_passes.iter().map(|p| (p)()).collect::<Vec<_>>();
434 if !tcx.sess.opts.debugging_opts.no_interleave_lints {
435 if !passes.is_empty() {
436 late_lint_pass_crate(tcx, LateLintPassObjects { lints: &mut passes[..] });
439 late_lint_pass_crate(tcx, builtin_lints);
441 for pass in &mut passes {
444 .extra_verbose_generic_activity(&format!("running late lint: {}", pass.name()))
446 late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) });
450 let mut passes: Vec<_> =
451 unerased_lint_store(tcx).late_module_passes.iter().map(|pass| (pass)()).collect();
453 for pass in &mut passes {
456 .extra_verbose_generic_activity(&format!(
457 "running late module lint: {}",
461 late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) });
467 /// Performs lint checking on a crate.
468 pub fn check_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
470 builtin_lints: impl FnOnce() -> T + Send,
474 tcx.sess.time("crate_lints", || {
475 // Run whole crate non-incremental lints
476 late_lint_crate(tcx, builtin_lints());
480 tcx.sess.time("module_lints", || {
481 // Run per-module lints
482 par_iter(&tcx.hir().krate().modules).for_each(|(&module, _)| {
483 tcx.ensure().lint_mod(tcx.hir().local_def_id(module));