• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::stack::ensure_sufficient_stack;
20 use rustc_data_structures::sync::{join, DynSend};
21 use rustc_hir as hir;
22 use rustc_hir::def_id::LocalDefId;
23 use rustc_hir::intravisit as hir_visit;
24 use rustc_hir::intravisit::Visitor;
25 use rustc_middle::hir::nested_filter;
26 use rustc_middle::ty::{self, TyCtxt};
27 use rustc_session::lint::LintPass;
28 use rustc_span::Span;
29 
30 use std::any::Any;
31 use std::cell::Cell;
32 
33 /// Extract the `LintStore` from the query context.
34 /// This function exists because we've erased `LintStore` as `dyn Any` in the context.
unerased_lint_store(tcx: TyCtxt<'_>) -> &LintStore35 pub fn unerased_lint_store(tcx: TyCtxt<'_>) -> &LintStore {
36     let store: &dyn Any = &*tcx.lint_store;
37     store.downcast_ref().unwrap()
38 }
39 
40 macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
41     $cx.pass.$f(&$cx.context, $($args),*);
42 }) }
43 
44 /// Implements the AST traversal for late lint passes. `T` provides the
45 /// `check_*` methods.
46 pub 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.
with_lint_attrs<F>(&mut self, id: hir::HirId, f: F) where F: FnOnce(&mut Self),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 
with_param_env<F>(&mut self, id: hir::OwnerId, f: F) where F: FnOnce(&mut Self),70     fn with_param_env<F>(&mut self, id: hir::OwnerId, f: F)
71     where
72         F: FnOnce(&mut Self),
73     {
74         let old_param_env = self.context.param_env;
75         self.context.param_env = self.context.tcx.param_env(id);
76         f(self);
77         self.context.param_env = old_param_env;
78     }
79 
process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, n: hir::HirId)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.
nested_visit_map(&mut self) -> Self::Map92     fn nested_visit_map(&mut self) -> Self::Map {
93         self.context.tcx.hir()
94     }
95 
visit_nested_body(&mut self, body_id: hir::BodyId)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 
visit_param(&mut self, param: &'tcx hir::Param<'tcx>)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 
visit_body(&mut self, body: &'tcx hir::Body<'tcx>)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 
visit_item(&mut self, it: &'tcx hir::Item<'tcx>)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.owner_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 
visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>)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.owner_id, |cx| {
149                 lint_callback!(cx, check_foreign_item, it);
150                 hir_visit::walk_foreign_item(cx, it);
151             });
152         })
153     }
154 
visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>)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 
visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>)160     fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
161         ensure_sufficient_stack(|| {
162             self.with_lint_attrs(e.hir_id, |cx| {
163                 lint_callback!(cx, check_expr, e);
164                 hir_visit::walk_expr(cx, e);
165                 lint_callback!(cx, check_expr_post, e);
166             })
167         })
168     }
169 
visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>)170     fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) {
171         // See `EarlyContextAndPass::visit_stmt` for an explanation
172         // of why we call `walk_stmt` outside of `with_lint_attrs`
173         self.with_lint_attrs(s.hir_id, |cx| {
174             lint_callback!(cx, check_stmt, s);
175         });
176         hir_visit::walk_stmt(self, s);
177     }
178 
visit_fn( &mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, span: Span, id: LocalDefId, )179     fn visit_fn(
180         &mut self,
181         fk: hir_visit::FnKind<'tcx>,
182         decl: &'tcx hir::FnDecl<'tcx>,
183         body_id: hir::BodyId,
184         span: Span,
185         id: LocalDefId,
186     ) {
187         // Wrap in typeck results here, not just in visit_nested_body,
188         // in order for `check_fn` to be able to use them.
189         let old_enclosing_body = self.context.enclosing_body.replace(body_id);
190         let old_cached_typeck_results = self.context.cached_typeck_results.take();
191         let body = self.context.tcx.hir().body(body_id);
192         lint_callback!(self, check_fn, fk, decl, body, span, id);
193         hir_visit::walk_fn(self, fk, decl, body_id, id);
194         self.context.enclosing_body = old_enclosing_body;
195         self.context.cached_typeck_results.set(old_cached_typeck_results);
196     }
197 
visit_variant_data(&mut self, s: &'tcx hir::VariantData<'tcx>)198     fn visit_variant_data(&mut self, s: &'tcx hir::VariantData<'tcx>) {
199         lint_callback!(self, check_struct_def, s);
200         hir_visit::walk_struct_def(self, s);
201     }
202 
visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>)203     fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
204         self.with_lint_attrs(s.hir_id, |cx| {
205             lint_callback!(cx, check_field_def, s);
206             hir_visit::walk_field_def(cx, s);
207         })
208     }
209 
visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>)210     fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
211         self.with_lint_attrs(v.hir_id, |cx| {
212             lint_callback!(cx, check_variant, v);
213             hir_visit::walk_variant(cx, v);
214         })
215     }
216 
visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>)217     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
218         lint_callback!(self, check_ty, t);
219         hir_visit::walk_ty(self, t);
220     }
221 
visit_infer(&mut self, inf: &'tcx hir::InferArg)222     fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
223         hir_visit::walk_inf(self, inf);
224     }
225 
visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _: Span, n: hir::HirId)226     fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _: Span, n: hir::HirId) {
227         if !self.context.only_module {
228             self.process_mod(m, n);
229         }
230     }
231 
visit_local(&mut self, l: &'tcx hir::Local<'tcx>)232     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
233         self.with_lint_attrs(l.hir_id, |cx| {
234             lint_callback!(cx, check_local, l);
235             hir_visit::walk_local(cx, l);
236         })
237     }
238 
visit_block(&mut self, b: &'tcx hir::Block<'tcx>)239     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
240         lint_callback!(self, check_block, b);
241         hir_visit::walk_block(self, b);
242         lint_callback!(self, check_block_post, b);
243     }
244 
visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>)245     fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) {
246         self.with_lint_attrs(a.hir_id, |cx| {
247             lint_callback!(cx, check_arm, a);
248             hir_visit::walk_arm(cx, a);
249         })
250     }
251 
visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>)252     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
253         lint_callback!(self, check_generic_param, p);
254         hir_visit::walk_generic_param(self, p);
255     }
256 
visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>)257     fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) {
258         lint_callback!(self, check_generics, g);
259         hir_visit::walk_generics(self, g);
260     }
261 
visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>)262     fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) {
263         hir_visit::walk_where_predicate(self, p);
264     }
265 
visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>)266     fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
267         lint_callback!(self, check_poly_trait_ref, t);
268         hir_visit::walk_poly_trait_ref(self, t);
269     }
270 
visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>)271     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
272         let generics = self.context.generics.take();
273         self.context.generics = Some(&trait_item.generics);
274         self.with_lint_attrs(trait_item.hir_id(), |cx| {
275             cx.with_param_env(trait_item.owner_id, |cx| {
276                 lint_callback!(cx, check_trait_item, trait_item);
277                 hir_visit::walk_trait_item(cx, trait_item);
278             });
279         });
280         self.context.generics = generics;
281     }
282 
visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>)283     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
284         let generics = self.context.generics.take();
285         self.context.generics = Some(&impl_item.generics);
286         self.with_lint_attrs(impl_item.hir_id(), |cx| {
287             cx.with_param_env(impl_item.owner_id, |cx| {
288                 lint_callback!(cx, check_impl_item, impl_item);
289                 hir_visit::walk_impl_item(cx, impl_item);
290                 lint_callback!(cx, check_impl_item_post, impl_item);
291             });
292         });
293         self.context.generics = generics;
294     }
295 
visit_lifetime(&mut self, lt: &'tcx hir::Lifetime)296     fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
297         hir_visit::walk_lifetime(self, lt);
298     }
299 
visit_path(&mut self, p: &hir::Path<'tcx>, id: hir::HirId)300     fn visit_path(&mut self, p: &hir::Path<'tcx>, id: hir::HirId) {
301         lint_callback!(self, check_path, p, id);
302         hir_visit::walk_path(self, p);
303     }
304 
visit_attribute(&mut self, attr: &'tcx ast::Attribute)305     fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
306         lint_callback!(self, check_attribute, attr);
307     }
308 }
309 
310 // Combines multiple lint passes into a single pass, at runtime. Each
311 // `check_foo` method in `$methods` within this pass simply calls `check_foo`
312 // once per `$pass`. Compare with `declare_combined_late_lint_pass`, which is
313 // similar, but combines lint passes at compile time.
314 struct RuntimeCombinedLateLintPass<'a, 'tcx> {
315     passes: &'a mut [LateLintPassObject<'tcx>],
316 }
317 
318 #[allow(rustc::lint_pass_impl_without_macro)]
319 impl LintPass for RuntimeCombinedLateLintPass<'_, '_> {
name(&self) -> &'static str320     fn name(&self) -> &'static str {
321         panic!()
322     }
323 }
324 
325 macro_rules! impl_late_lint_pass {
326     ([], [$($(#[$attr:meta])* fn $f:ident($($param:ident: $arg:ty),*);)*]) => {
327         impl<'tcx> LateLintPass<'tcx> for RuntimeCombinedLateLintPass<'_, 'tcx> {
328             $(fn $f(&mut self, context: &LateContext<'tcx>, $($param: $arg),*) {
329                 for pass in self.passes.iter_mut() {
330                     pass.$f(context, $($param),*);
331                 }
332             })*
333         }
334     };
335 }
336 
337 crate::late_lint_methods!(impl_late_lint_pass, []);
338 
late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>( tcx: TyCtxt<'tcx>, module_def_id: LocalDefId, builtin_lints: T, )339 pub(super) fn late_lint_mod<'tcx, T: LateLintPass<'tcx> + 'tcx>(
340     tcx: TyCtxt<'tcx>,
341     module_def_id: LocalDefId,
342     builtin_lints: T,
343 ) {
344     let context = LateContext {
345         tcx,
346         enclosing_body: None,
347         cached_typeck_results: Cell::new(None),
348         param_env: ty::ParamEnv::empty(),
349         effective_visibilities: &tcx.effective_visibilities(()),
350         lint_store: unerased_lint_store(tcx),
351         last_node_with_lint_attrs: tcx.hir().local_def_id_to_hir_id(module_def_id),
352         generics: None,
353         only_module: true,
354     };
355 
356     // Note: `passes` is often empty. In that case, it's faster to run
357     // `builtin_lints` directly rather than bundling it up into the
358     // `RuntimeCombinedLateLintPass`.
359     let mut passes: Vec<_> =
360         unerased_lint_store(tcx).late_module_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect();
361     if passes.is_empty() {
362         late_lint_mod_inner(tcx, module_def_id, context, builtin_lints);
363     } else {
364         passes.push(Box::new(builtin_lints));
365         let pass = RuntimeCombinedLateLintPass { passes: &mut passes[..] };
366         late_lint_mod_inner(tcx, module_def_id, context, pass);
367     }
368 }
369 
late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>( tcx: TyCtxt<'tcx>, module_def_id: LocalDefId, context: LateContext<'tcx>, pass: T, )370 fn late_lint_mod_inner<'tcx, T: LateLintPass<'tcx>>(
371     tcx: TyCtxt<'tcx>,
372     module_def_id: LocalDefId,
373     context: LateContext<'tcx>,
374     pass: T,
375 ) {
376     let mut cx = LateContextAndPass { context, pass };
377 
378     let (module, _span, hir_id) = tcx.hir().get_module(module_def_id);
379     cx.process_mod(module, hir_id);
380 
381     // Visit the crate attributes
382     if hir_id == hir::CRATE_HIR_ID {
383         for attr in tcx.hir().attrs(hir::CRATE_HIR_ID).iter() {
384             cx.visit_attribute(attr)
385         }
386     }
387 }
388 
late_lint_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(tcx: TyCtxt<'tcx>, builtin_lints: T)389 fn late_lint_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(tcx: TyCtxt<'tcx>, builtin_lints: T) {
390     let context = LateContext {
391         tcx,
392         enclosing_body: None,
393         cached_typeck_results: Cell::new(None),
394         param_env: ty::ParamEnv::empty(),
395         effective_visibilities: &tcx.effective_visibilities(()),
396         lint_store: unerased_lint_store(tcx),
397         last_node_with_lint_attrs: hir::CRATE_HIR_ID,
398         generics: None,
399         only_module: false,
400     };
401 
402     // Note: `passes` is often empty. In that case, it's faster to run
403     // `builtin_lints` directly rather than bundling it up into the
404     // `RuntimeCombinedLateLintPass`.
405     let mut passes: Vec<_> =
406         unerased_lint_store(tcx).late_passes.iter().map(|mk_pass| (mk_pass)(tcx)).collect();
407     if passes.is_empty() {
408         late_lint_crate_inner(tcx, context, builtin_lints);
409     } else {
410         passes.push(Box::new(builtin_lints));
411         let pass = RuntimeCombinedLateLintPass { passes: &mut passes[..] };
412         late_lint_crate_inner(tcx, context, pass);
413     }
414 }
415 
late_lint_crate_inner<'tcx, T: LateLintPass<'tcx>>( tcx: TyCtxt<'tcx>, context: LateContext<'tcx>, pass: T, )416 fn late_lint_crate_inner<'tcx, T: LateLintPass<'tcx>>(
417     tcx: TyCtxt<'tcx>,
418     context: LateContext<'tcx>,
419     pass: T,
420 ) {
421     let mut cx = LateContextAndPass { context, pass };
422 
423     // Visit the whole crate.
424     cx.with_lint_attrs(hir::CRATE_HIR_ID, |cx| {
425         // Since the root module isn't visited as an item (because it isn't an
426         // item), warn for it here.
427         lint_callback!(cx, check_crate,);
428         tcx.hir().walk_toplevel_module(cx);
429         tcx.hir().walk_attributes(cx);
430         lint_callback!(cx, check_crate_post,);
431     })
432 }
433 
434 /// Performs lint checking on a crate.
check_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>( tcx: TyCtxt<'tcx>, builtin_lints: impl FnOnce() -> T + Send + DynSend, )435 pub fn check_crate<'tcx, T: LateLintPass<'tcx> + 'tcx>(
436     tcx: TyCtxt<'tcx>,
437     builtin_lints: impl FnOnce() -> T + Send + DynSend,
438 ) {
439     join(
440         || {
441             tcx.sess.time("crate_lints", || {
442                 // Run whole crate non-incremental lints
443                 late_lint_crate(tcx, builtin_lints());
444             });
445         },
446         || {
447             tcx.sess.time("module_lints", || {
448                 // Run per-module lints
449                 tcx.hir().par_for_each_module(|module| tcx.ensure().lint_mod(module));
450             });
451         },
452     );
453 }
454