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 self::TargetLint::*;
20 use rustc_data_structures::sync::ReadGuard;
21 use crate::lint::{EarlyLintPass, EarlyLintPassObject, LateLintPassObject};
22 use crate::lint::{LintArray, Level, Lint, LintId, LintPass, LintBuffer};
23 use crate::lint::builtin::BuiltinLintDiagnostics;
24 use crate::lint::levels::{LintLevelSets, LintLevelsBuilder};
25 use crate::middle::privacy::AccessLevels;
26 use crate::rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
27 use crate::session::{config, early_error, Session};
28 use crate::ty::{self, TyCtxt, Ty};
29 use crate::ty::layout::{LayoutError, LayoutOf, TyLayout};
30 use crate::util::nodemap::FxHashMap;
31 use crate::util::common::time;
33 use std::default::Default as StdDefault;
36 use syntax_pos::{MultiSpan, Span, symbol::{LocalInternedString, Symbol}};
37 use errors::DiagnosticBuilder;
39 use crate::hir::def_id::LOCAL_CRATE;
40 use crate::hir::intravisit as hir_visit;
41 use syntax::util::lev_distance::find_best_match_for_name;
42 use syntax::visit as ast_visit;
44 /// Information about the registered lints.
46 /// This is basically the subset of `Context` that we can
47 /// build early in the compile pipeline.
48 pub struct LintStore {
49 /// Registered lints. The bool is true if the lint was
50 /// added by a plugin.
51 lints: Vec<(&'static Lint, bool)>,
53 /// Trait objects for each lint pass.
54 /// This is only `None` while performing a lint pass.
55 pre_expansion_passes: Option<Vec<EarlyLintPassObject>>,
56 early_passes: Option<Vec<EarlyLintPassObject>>,
57 late_passes: Option<Vec<LateLintPassObject>>,
59 /// Lints indexed by name.
60 by_name: FxHashMap<String, TargetLint>,
62 /// Map of registered lint groups to what lints they expand to.
63 lint_groups: FxHashMap<&'static str, LintGroup>,
65 /// Extra info for future incompatibility lints, describing the
66 /// issue or RFC that caused the incompatibility.
67 future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
70 pub struct LintSession<'a, PassObject> {
71 /// Reference to the store of registered lints.
72 lints: ReadGuard<'a, LintStore>,
74 /// Trait objects for each lint pass.
75 passes: Option<Vec<PassObject>>,
78 /// Lints that are buffered up early on in the `Session` before the
79 /// `LintLevels` is calculated
80 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
81 pub struct BufferedEarlyLint {
83 pub ast_id: ast::NodeId,
86 pub diagnostic: BuiltinLintDiagnostics,
89 /// Extra information for a future incompatibility lint. See the call
90 /// to `register_future_incompatible` in `librustc_lint/lib.rs` for
92 pub struct FutureIncompatibleInfo {
94 /// e.g., a URL for an issue/PR/RFC or error code
95 pub reference: &'static str,
96 /// If this is an edition fixing lint, the edition in which
97 /// this lint becomes obsolete
98 pub edition: Option<edition::Edition>,
101 /// The target of the `by_name` map, which accounts for renaming/deprecation.
103 /// A direct lint target
106 /// Temporary renaming, used for easing migration pain; see #16545
107 Renamed(String, LintId),
109 /// Lint with this name existed previously, but has been removed/deprecated.
110 /// The string argument is the reason for removal.
114 pub enum FindLintError {
121 /// Whether deprecation warnings should be suppressed for this alias.
126 lint_ids: Vec<LintId>,
128 depr: Option<LintAlias>,
131 pub enum CheckLintNameResult<'a> {
133 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
134 NoLint(Option<Symbol>),
135 /// The lint is either renamed or removed. This is the warning
136 /// message, and an optional new name (`None` if removed).
137 Warning(String, Option<String>),
138 /// The lint is from a tool. If the Option is None, then either
139 /// the lint does not exist in the tool or the code was not
140 /// compiled with the tool and therefore the lint was never
141 /// added to the `LintStore`. Otherwise the `LintId` will be
142 /// returned as if it where a rustc lint.
143 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
147 pub fn new() -> LintStore {
150 pre_expansion_passes: Some(vec![]),
151 early_passes: Some(vec![]),
152 late_passes: Some(vec![]),
153 by_name: Default::default(),
154 future_incompatible: Default::default(),
155 lint_groups: Default::default(),
159 pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
163 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
164 self.lint_groups.iter()
165 .filter(|(_, LintGroup { depr, .. })| {
166 // Don't display deprecated lint groups.
169 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
170 (*k, lint_ids.clone(), *from_plugin)
175 pub fn register_early_pass(&mut self,
176 sess: Option<&Session>,
179 pass: EarlyLintPassObject) {
180 self.push_pass(sess, from_plugin, &pass);
182 self.early_passes.as_mut().unwrap().push(pass);
186 pub fn register_pre_expansion_pass(
188 sess: Option<&Session>,
191 pass: EarlyLintPassObject,
193 self.push_pass(sess, from_plugin, &pass);
195 self.pre_expansion_passes.as_mut().unwrap().push(pass);
199 pub fn register_late_pass(&mut self,
200 sess: Option<&Session>,
202 pass: LateLintPassObject) {
203 self.push_pass(sess, from_plugin, &pass);
204 self.late_passes.as_mut().unwrap().push(pass);
207 // Helper method for register_early/late_pass
208 fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
209 sess: Option<&Session>,
212 for lint in pass.get_lints() {
213 self.lints.push((lint, from_plugin));
215 let id = LintId::of(lint);
216 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
217 let msg = format!("duplicate specification of lint {}", lint.name_lower());
218 match (sess, from_plugin) {
219 // We load builtin lints first, so a duplicate is a compiler bug.
220 // Use early_error when handling -W help with no crate.
221 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
222 (Some(_), false) => bug!("{}", msg),
224 // A duplicate name from a plugin is a user error.
225 (Some(sess), true) => sess.err(&msg[..]),
231 pub fn register_future_incompatible(&mut self,
232 sess: Option<&Session>,
233 lints: Vec<FutureIncompatibleInfo>) {
235 for edition in edition::ALL_EDITIONS {
236 let lints = lints.iter().filter(|f| f.edition == Some(*edition)).map(|f| f.id)
237 .collect::<Vec<_>>();
238 if !lints.is_empty() {
239 self.register_group(sess, false, edition.lint_name(), None, lints)
243 let mut future_incompatible = Vec::with_capacity(lints.len());
245 future_incompatible.push(lint.id);
246 self.future_incompatible.insert(lint.id, lint);
252 "future_incompatible",
258 pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
259 self.future_incompatible.get(&id)
262 pub fn register_group_alias(
264 lint_name: &'static str,
267 self.lint_groups.insert(alias, LintGroup {
270 depr: Some(LintAlias { name: lint_name, silent: true }),
274 pub fn register_group(
276 sess: Option<&Session>,
279 deprecated_name: Option<&'static str>,
284 .insert(name, LintGroup {
290 if let Some(deprecated) = deprecated_name {
291 self.lint_groups.insert(deprecated, LintGroup {
294 depr: Some(LintAlias { name, silent: false }),
299 let msg = format!("duplicate specification of lint group {}", name);
300 match (sess, from_plugin) {
301 // We load builtin lints first, so a duplicate is a compiler bug.
302 // Use early_error when handling -W help with no crate.
303 (None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
304 (Some(_), false) => bug!("{}", msg),
306 // A duplicate name from a plugin is a user error.
307 (Some(sess), true) => sess.err(&msg[..]),
312 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
313 let target = match self.by_name.get(new_name) {
314 Some(&Id(lint_id)) => lint_id.clone(),
315 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
317 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
320 pub fn register_removed(&mut self, name: &str, reason: &str) {
321 self.by_name.insert(name.into(), Removed(reason.into()));
324 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
325 match self.by_name.get(lint_name) {
326 Some(&Id(lint_id)) => Ok(vec![lint_id]),
327 Some(&Renamed(_, lint_id)) => {
330 Some(&Removed(_)) => {
331 Err(FindLintError::Removed)
335 return match self.lint_groups.get(lint_name) {
336 Some(LintGroup {lint_ids, depr, .. }) => {
337 if let Some(LintAlias { name, .. }) = depr {
343 None => Err(FindLintError::Removed)
350 /// Checks the validity of lint names derived from the command line
351 pub fn check_lint_name_cmdline(&self,
355 let db = match self.check_lint_name(lint_name, None) {
356 CheckLintNameResult::Ok(_) => None,
357 CheckLintNameResult::Warning(ref msg, _) => {
358 Some(sess.struct_warn(msg))
360 CheckLintNameResult::NoLint(suggestion) => {
361 let mut err = struct_err!(sess, E0602, "unknown lint: `{}`", lint_name);
363 if let Some(suggestion) = suggestion {
364 err.help(&format!("did you mean: `{}`", suggestion));
369 CheckLintNameResult::Tool(result) => match result {
370 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
371 "lint name `{}` is deprecated \
372 and does not have an effect anymore. \
380 if let Some(mut db) = db {
381 let msg = format!("requested on the command line with `{} {}`",
383 Level::Allow => "-A",
386 Level::Forbid => "-F",
394 /// Checks the name of a lint for its existence, and whether it was
395 /// renamed or removed. Generates a DiagnosticBuilder containing a
396 /// warning for renamed and removed lints. This is over both lint
397 /// names from attributes and those passed on the command line. Since
398 /// it emits non-fatal warnings and there are *two* lint passes that
399 /// inspect attributes, this is only run from the late pass to avoid
400 /// printing duplicate warnings.
401 pub fn check_lint_name(
404 tool_name: Option<LocalInternedString>,
405 ) -> CheckLintNameResult<'_> {
406 let complete_name = if let Some(tool_name) = tool_name {
407 format!("{}::{}", tool_name, lint_name)
409 lint_name.to_string()
411 // If the lint was scoped with `tool::` check if the tool lint exists
412 if let Some(_) = tool_name {
413 match self.by_name.get(&complete_name) {
414 None => match self.lint_groups.get(&*complete_name) {
415 None => return CheckLintNameResult::Tool(Err((None, String::new()))),
416 Some(LintGroup { lint_ids, .. }) => {
417 return CheckLintNameResult::Tool(Ok(&lint_ids));
420 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
421 // If the lint was registered as removed or renamed by the lint tool, we don't need
422 // to treat tool_lints and rustc lints different and can use the code below.
426 match self.by_name.get(&complete_name) {
427 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
429 "lint `{}` has been renamed to `{}`",
430 complete_name, new_name
432 Some(new_name.to_owned()),
434 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
435 format!("lint `{}` has been removed: `{}`", complete_name, reason),
438 None => match self.lint_groups.get(&*complete_name) {
439 // If neither the lint, nor the lint group exists check if there is a `clippy::`
440 // variant of this lint
441 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
442 Some(LintGroup { lint_ids, depr, .. }) => {
443 // Check if the lint group name is deprecated
444 if let Some(LintAlias { name, silent }) = depr {
445 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
447 CheckLintNameResult::Ok(&lint_ids)
449 CheckLintNameResult::Tool(Err((
455 CheckLintNameResult::Ok(&lint_ids)
458 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
462 fn check_tool_name_for_backwards_compat(
466 ) -> CheckLintNameResult<'_> {
467 let complete_name = format!("{}::{}", tool_name, lint_name);
468 match self.by_name.get(&complete_name) {
469 None => match self.lint_groups.get(&*complete_name) {
470 // Now we are sure, that this lint exists nowhere
472 let symbols = self.by_name.keys()
473 .map(|name| Symbol::intern(&name))
474 .collect::<Vec<_>>();
477 find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
479 CheckLintNameResult::NoLint(suggestion)
481 Some(LintGroup { lint_ids, depr, .. }) => {
482 // Reaching this would be weird, but let's cover this case anyway
483 if let Some(LintAlias { name, silent }) = depr {
484 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
486 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
488 CheckLintNameResult::Tool(Err((
494 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
497 Some(&Id(ref id)) => {
498 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
500 _ => CheckLintNameResult::NoLint(None),
505 /// Context for lint checking after type checking.
506 pub struct LateContext<'a, 'tcx: 'a> {
507 /// Type context we're checking in.
508 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
510 /// Side-tables for the body we are in.
511 pub tables: &'a ty::TypeckTables<'tcx>,
513 /// Parameter environment for the item we are in.
514 pub param_env: ty::ParamEnv<'tcx>,
516 /// Items accessible from the crate being checked.
517 pub access_levels: &'a AccessLevels,
519 /// The store of registered lints and the lint levels.
520 lint_sess: LintSession<'tcx, LateLintPassObject>,
522 last_ast_node_with_lint_attrs: ast::NodeId,
524 /// Generic type parameters in scope for the item we are in.
525 pub generics: Option<&'tcx hir::Generics>,
528 /// Context for lint checking of the AST, after expansion, before lowering to
530 pub struct EarlyContext<'a> {
531 /// Type context we're checking in.
532 pub sess: &'a Session,
534 /// The crate being checked.
535 pub krate: &'a ast::Crate,
537 builder: LintLevelsBuilder<'a>,
539 /// The store of registered lints and the lint levels.
540 lint_sess: LintSession<'a, EarlyLintPassObject>,
542 buffered: LintBuffer,
545 pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
546 context: EarlyContext<'a>,
550 /// Convenience macro for calling a `LintPass` method on every pass in the context.
551 macro_rules! run_lints { ($cx:expr, $f:ident, $($args:expr),*) => ({
552 // Move the vector of passes out of `$cx` so that we can
553 // iterate over it mutably while passing `$cx` to the methods.
554 let mut passes = $cx.lint_sess_mut().passes.take().unwrap();
555 for obj in &mut passes {
556 obj.$f($cx, $($args),*);
558 $cx.lint_sess_mut().passes = Some(passes);
561 pub trait LintPassObject: Sized {}
563 impl LintPassObject for EarlyLintPassObject {}
565 impl LintPassObject for LateLintPassObject {}
568 pub trait LintContext<'tcx>: Sized {
569 type PassObject: LintPassObject;
571 fn sess(&self) -> &Session;
572 fn lints(&self) -> &LintStore;
573 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
574 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
576 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
580 self.lookup(lint, span, msg).emit();
583 fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(&self,
587 diagnostic: BuiltinLintDiagnostics) {
588 let mut db = self.lookup(lint, span, msg);
589 diagnostic.run(self.sess(), &mut db);
593 fn lookup<S: Into<MultiSpan>>(&self,
597 -> DiagnosticBuilder<'_>;
599 /// Emit a lint at the appropriate level, for a particular span.
600 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
601 self.lookup_and_emit(lint, Some(span), msg);
604 fn struct_span_lint<S: Into<MultiSpan>>(&self,
608 -> DiagnosticBuilder<'_> {
609 self.lookup(lint, Some(span), msg)
612 /// Emit a lint and note at the appropriate level, for a particular span.
613 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
614 note_span: Span, note: &str) {
615 let mut err = self.lookup(lint, Some(span), msg);
616 if note_span == span {
619 err.span_note(note_span, note);
624 /// Emit a lint and help at the appropriate level, for a particular span.
625 fn span_lint_help(&self, lint: &'static Lint, span: Span,
626 msg: &str, help: &str) {
627 let mut err = self.lookup(lint, Some(span), msg);
628 self.span_lint(lint, span, msg);
629 err.span_help(span, help);
633 /// Emit a lint at the appropriate level, with no associated span.
634 fn lint(&self, lint: &'static Lint, msg: &str) {
635 self.lookup_and_emit(lint, None as Option<Span>, msg);
640 impl<'a> EarlyContext<'a> {
643 krate: &'a ast::Crate,
644 buffered: LintBuffer,
645 ) -> EarlyContext<'a> {
649 lint_sess: LintSession {
650 lints: sess.lint_store.borrow(),
653 builder: LintLevelSets::builder(sess),
659 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
660 $cx.pass.$f(&$cx.context, $($args),*);
663 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
664 fn check_id(&mut self, id: ast::NodeId) {
665 for early_lint in self.context.buffered.take(id) {
666 self.context.lookup_and_emit_with_diagnostics(
667 early_lint.lint_id.lint,
668 Some(early_lint.span.clone()),
670 early_lint.diagnostic
675 /// Merge the lints specified by any lint attributes into the
676 /// current lint context, call the provided function, then reset the
677 /// lints in effect to their previous state.
678 fn with_lint_attrs<F>(&mut self,
680 attrs: &'a [ast::Attribute],
682 where F: FnOnce(&mut Self)
684 let push = self.context.builder.push(attrs);
686 self.enter_attrs(attrs);
688 self.exit_attrs(attrs);
689 self.context.builder.pop(push);
692 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
693 debug!("early context: enter_attrs({:?})", attrs);
694 run_early_pass!(self, enter_lint_attrs, attrs);
697 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
698 debug!("early context: exit_attrs({:?})", attrs);
699 run_early_pass!(self, exit_lint_attrs, attrs);
703 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
704 type PassObject = LateLintPassObject;
706 /// Gets the overall compiler `Session` object.
707 fn sess(&self) -> &Session {
711 fn lints(&self) -> &LintStore {
712 &*self.lint_sess.lints
715 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
719 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
723 fn lookup<S: Into<MultiSpan>>(&self,
727 -> DiagnosticBuilder<'_> {
728 let id = self.last_ast_node_with_lint_attrs;
730 Some(s) => self.tcx.struct_span_lint_node(lint, id, s, msg),
731 None => self.tcx.struct_lint_node(lint, id, msg),
736 impl<'a> LintContext<'a> for EarlyContext<'a> {
737 type PassObject = EarlyLintPassObject;
739 /// Gets the overall compiler `Session` object.
740 fn sess(&self) -> &Session {
744 fn lints(&self) -> &LintStore {
745 &*self.lint_sess.lints
748 fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
752 fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
756 fn lookup<S: Into<MultiSpan>>(&self,
760 -> DiagnosticBuilder<'_> {
761 self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
765 impl<'a, 'tcx> LateContext<'a, 'tcx> {
766 /// Merge the lints specified by any lint attributes into the
767 /// current lint context, call the provided function, then reset the
768 /// lints in effect to their previous state.
769 fn with_lint_attrs<F>(&mut self,
771 attrs: &'tcx [ast::Attribute],
773 where F: FnOnce(&mut Self)
775 let prev = self.last_ast_node_with_lint_attrs;
776 self.last_ast_node_with_lint_attrs = id;
777 self.enter_attrs(attrs);
779 self.exit_attrs(attrs);
780 self.last_ast_node_with_lint_attrs = prev;
783 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
784 debug!("late context: enter_attrs({:?})", attrs);
785 run_lints!(self, enter_lint_attrs, attrs);
788 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
789 debug!("late context: exit_attrs({:?})", attrs);
790 run_lints!(self, exit_lint_attrs, attrs);
793 fn with_param_env<F>(&mut self, id: ast::NodeId, f: F)
794 where F: FnOnce(&mut Self),
796 let old_param_env = self.param_env;
797 self.param_env = self.tcx.param_env(self.tcx.hir().local_def_id(id));
799 self.param_env = old_param_env;
801 pub fn current_lint_root(&self) -> ast::NodeId {
802 self.last_ast_node_with_lint_attrs
806 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
808 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
810 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
811 self.tcx.layout_of(self.param_env.and(ty))
815 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
816 /// Because lints are scoped lexically, we want to walk nested
817 /// items in the context of the outer item, so enable
819 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
820 hir_visit::NestedVisitorMap::All(&self.tcx.hir())
823 fn visit_nested_body(&mut self, body: hir::BodyId) {
824 let old_tables = self.tables;
825 self.tables = self.tcx.body_tables(body);
826 let body = self.tcx.hir().body(body);
827 self.visit_body(body);
828 self.tables = old_tables;
831 fn visit_body(&mut self, body: &'tcx hir::Body) {
832 run_lints!(self, check_body, body);
833 hir_visit::walk_body(self, body);
834 run_lints!(self, check_body_post, body);
837 fn visit_item(&mut self, it: &'tcx hir::Item) {
838 let generics = self.generics.take();
839 self.generics = it.node.generics();
840 self.with_lint_attrs(it.id, &it.attrs, |cx| {
841 cx.with_param_env(it.id, |cx| {
842 run_lints!(cx, check_item, it);
843 hir_visit::walk_item(cx, it);
844 run_lints!(cx, check_item_post, it);
847 self.generics = generics;
850 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
851 self.with_lint_attrs(it.id, &it.attrs, |cx| {
852 cx.with_param_env(it.id, |cx| {
853 run_lints!(cx, check_foreign_item, it);
854 hir_visit::walk_foreign_item(cx, it);
855 run_lints!(cx, check_foreign_item_post, it);
860 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
861 run_lints!(self, check_pat, p);
862 hir_visit::walk_pat(self, p);
865 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
866 self.with_lint_attrs(e.id, &e.attrs, |cx| {
867 run_lints!(cx, check_expr, e);
868 hir_visit::walk_expr(cx, e);
869 run_lints!(cx, check_expr_post, e);
873 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
874 // statement attributes are actually just attributes on one of
878 // so we keep track of lint levels there
879 run_lints!(self, check_stmt, s);
880 hir_visit::walk_stmt(self, s);
883 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
884 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
885 // Wrap in tables here, not just in visit_nested_body,
886 // in order for `check_fn` to be able to use them.
887 let old_tables = self.tables;
888 self.tables = self.tcx.body_tables(body_id);
889 let body = self.tcx.hir().body(body_id);
890 run_lints!(self, check_fn, fk, decl, body, span, id);
891 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
892 run_lints!(self, check_fn_post, fk, decl, body, span, id);
893 self.tables = old_tables;
896 fn visit_variant_data(&mut self,
897 s: &'tcx hir::VariantData,
899 g: &'tcx hir::Generics,
900 item_id: ast::NodeId,
902 run_lints!(self, check_struct_def, s, name, g, item_id);
903 hir_visit::walk_struct_def(self, s);
904 run_lints!(self, check_struct_def_post, s, name, g, item_id);
907 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
908 self.with_lint_attrs(s.id, &s.attrs, |cx| {
909 run_lints!(cx, check_struct_field, s);
910 hir_visit::walk_struct_field(cx, s);
914 fn visit_variant(&mut self,
915 v: &'tcx hir::Variant,
916 g: &'tcx hir::Generics,
917 item_id: ast::NodeId) {
918 self.with_lint_attrs(v.node.data.id(), &v.node.attrs, |cx| {
919 run_lints!(cx, check_variant, v, g);
920 hir_visit::walk_variant(cx, v, g, item_id);
921 run_lints!(cx, check_variant_post, v, g);
925 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
926 run_lints!(self, check_ty, t);
927 hir_visit::walk_ty(self, t);
930 fn visit_name(&mut self, sp: Span, name: ast::Name) {
931 run_lints!(self, check_name, sp, name);
934 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: ast::NodeId) {
935 run_lints!(self, check_mod, m, s, n);
936 hir_visit::walk_mod(self, m, n);
937 run_lints!(self, check_mod_post, m, s, n);
940 fn visit_local(&mut self, l: &'tcx hir::Local) {
941 self.with_lint_attrs(l.id, &l.attrs, |cx| {
942 run_lints!(cx, check_local, l);
943 hir_visit::walk_local(cx, l);
947 fn visit_block(&mut self, b: &'tcx hir::Block) {
948 run_lints!(self, check_block, b);
949 hir_visit::walk_block(self, b);
950 run_lints!(self, check_block_post, b);
953 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
954 run_lints!(self, check_arm, a);
955 hir_visit::walk_arm(self, a);
958 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) {
959 run_lints!(self, check_generic_param, p);
960 hir_visit::walk_generic_param(self, p);
963 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
964 run_lints!(self, check_generics, g);
965 hir_visit::walk_generics(self, g);
968 fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate) {
969 run_lints!(self, check_where_predicate, p);
970 hir_visit::walk_where_predicate(self, p);
973 fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef,
974 m: hir::TraitBoundModifier) {
975 run_lints!(self, check_poly_trait_ref, t, m);
976 hir_visit::walk_poly_trait_ref(self, t, m);
979 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
980 let generics = self.generics.take();
981 self.generics = Some(&trait_item.generics);
982 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
983 cx.with_param_env(trait_item.id, |cx| {
984 run_lints!(cx, check_trait_item, trait_item);
985 hir_visit::walk_trait_item(cx, trait_item);
986 run_lints!(cx, check_trait_item_post, trait_item);
989 self.generics = generics;
992 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
993 let generics = self.generics.take();
994 self.generics = Some(&impl_item.generics);
995 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
996 cx.with_param_env(impl_item.id, |cx| {
997 run_lints!(cx, check_impl_item, impl_item);
998 hir_visit::walk_impl_item(cx, impl_item);
999 run_lints!(cx, check_impl_item_post, impl_item);
1002 self.generics = generics;
1005 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1006 run_lints!(self, check_lifetime, lt);
1007 hir_visit::walk_lifetime(self, lt);
1010 fn visit_path(&mut self, p: &'tcx hir::Path, id: hir::HirId) {
1011 run_lints!(self, check_path, p, id);
1012 hir_visit::walk_path(self, p);
1015 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
1016 run_lints!(self, check_attribute, attr);
1020 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
1021 fn visit_item(&mut self, it: &'a ast::Item) {
1022 self.with_lint_attrs(it.id, &it.attrs, |cx| {
1023 run_early_pass!(cx, check_item, it);
1024 ast_visit::walk_item(cx, it);
1025 run_early_pass!(cx, check_item_post, it);
1029 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
1030 self.with_lint_attrs(it.id, &it.attrs, |cx| {
1031 run_early_pass!(cx, check_foreign_item, it);
1032 ast_visit::walk_foreign_item(cx, it);
1033 run_early_pass!(cx, check_foreign_item_post, it);
1037 fn visit_pat(&mut self, p: &'a ast::Pat) {
1038 let mut visit_subpats = true;
1039 run_early_pass!(self, check_pat, p, &mut visit_subpats);
1040 self.check_id(p.id);
1042 ast_visit::walk_pat(self, p);
1046 fn visit_expr(&mut self, e: &'a ast::Expr) {
1047 self.with_lint_attrs(e.id, &e.attrs, |cx| {
1048 run_early_pass!(cx, check_expr, e);
1049 ast_visit::walk_expr(cx, e);
1053 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1054 run_early_pass!(self, check_stmt, s);
1055 self.check_id(s.id);
1056 ast_visit::walk_stmt(self, s);
1059 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1060 span: Span, id: ast::NodeId) {
1061 run_early_pass!(self, check_fn, fk, decl, span, id);
1063 ast_visit::walk_fn(self, fk, decl, span);
1064 run_early_pass!(self, check_fn_post, fk, decl, span, id);
1067 fn visit_variant_data(&mut self,
1068 s: &'a ast::VariantData,
1070 g: &'a ast::Generics,
1071 item_id: ast::NodeId,
1073 run_early_pass!(self, check_struct_def, s, ident, g, item_id);
1074 self.check_id(s.id());
1075 ast_visit::walk_struct_def(self, s);
1076 run_early_pass!(self, check_struct_def_post, s, ident, g, item_id);
1079 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1080 self.with_lint_attrs(s.id, &s.attrs, |cx| {
1081 run_early_pass!(cx, check_struct_field, s);
1082 ast_visit::walk_struct_field(cx, s);
1086 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1087 self.with_lint_attrs(item_id, &v.node.attrs, |cx| {
1088 run_early_pass!(cx, check_variant, v, g);
1089 ast_visit::walk_variant(cx, v, g, item_id);
1090 run_early_pass!(cx, check_variant_post, v, g);
1094 fn visit_ty(&mut self, t: &'a ast::Ty) {
1095 run_early_pass!(self, check_ty, t);
1096 self.check_id(t.id);
1097 ast_visit::walk_ty(self, t);
1100 fn visit_ident(&mut self, ident: ast::Ident) {
1101 run_early_pass!(self, check_ident, ident);
1104 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1105 run_early_pass!(self, check_mod, m, s, n);
1107 ast_visit::walk_mod(self, m);
1108 run_early_pass!(self, check_mod_post, m, s, n);
1111 fn visit_local(&mut self, l: &'a ast::Local) {
1112 self.with_lint_attrs(l.id, &l.attrs, |cx| {
1113 run_early_pass!(cx, check_local, l);
1114 ast_visit::walk_local(cx, l);
1118 fn visit_block(&mut self, b: &'a ast::Block) {
1119 run_early_pass!(self, check_block, b);
1120 self.check_id(b.id);
1121 ast_visit::walk_block(self, b);
1122 run_early_pass!(self, check_block_post, b);
1125 fn visit_arm(&mut self, a: &'a ast::Arm) {
1126 run_early_pass!(self, check_arm, a);
1127 ast_visit::walk_arm(self, a);
1130 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1131 run_early_pass!(self, check_expr_post, e);
1134 fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
1135 run_early_pass!(self, check_generic_param, param);
1136 ast_visit::walk_generic_param(self, param);
1139 fn visit_generics(&mut self, g: &'a ast::Generics) {
1140 run_early_pass!(self, check_generics, g);
1141 ast_visit::walk_generics(self, g);
1144 fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
1145 run_early_pass!(self, check_where_predicate, p);
1146 ast_visit::walk_where_predicate(self, p);
1149 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
1150 run_early_pass!(self, check_poly_trait_ref, t, m);
1151 ast_visit::walk_poly_trait_ref(self, t, m);
1154 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1155 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
1156 run_early_pass!(cx, check_trait_item, trait_item);
1157 ast_visit::walk_trait_item(cx, trait_item);
1158 run_early_pass!(cx, check_trait_item_post, trait_item);
1162 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1163 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
1164 run_early_pass!(cx, check_impl_item, impl_item);
1165 ast_visit::walk_impl_item(cx, impl_item);
1166 run_early_pass!(cx, check_impl_item_post, impl_item);
1170 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1171 run_early_pass!(self, check_lifetime, lt);
1172 self.check_id(lt.id);
1175 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1176 run_early_pass!(self, check_path, p, id);
1178 ast_visit::walk_path(self, p);
1181 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1182 run_early_pass!(self, check_attribute, attr);
1185 fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
1186 run_early_pass!(self, check_mac_def, mac, id);
1190 fn visit_mac(&mut self, mac: &'a ast::Mac) {
1191 // FIXME(#54110): So, this setup isn't really right. I think
1192 // that (a) the libsyntax visitor ought to be doing this as
1193 // part of `walk_mac`, and (b) we should be calling
1194 // `visit_path`, *but* that would require a `NodeId`, and I
1195 // want to get #53686 fixed quickly. -nmatsakis
1196 ast_visit::walk_path(self, &mac.node.path);
1198 run_early_pass!(self, check_mac, mac);
1203 /// Performs lint checking on a crate.
1205 /// Consumes the `lint_store` field of the `Session`.
1206 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1207 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1209 let krate = tcx.hir().krate();
1210 let passes = tcx.sess.lint_store.borrow_mut().late_passes.take();
1213 let mut cx = LateContext {
1215 tables: &ty::TypeckTables::empty(None),
1216 param_env: ty::ParamEnv::empty(),
1218 lint_sess: LintSession {
1220 lints: tcx.sess.lint_store.borrow(),
1222 last_ast_node_with_lint_attrs: ast::CRATE_NODE_ID,
1226 // Visit the whole crate.
1227 cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1228 // since the root module isn't visited as an item (because it isn't an
1229 // item), warn for it here.
1230 run_lints!(cx, check_crate, krate);
1232 hir_visit::walk_crate(cx, krate);
1234 run_lints!(cx, check_crate_post, krate);
1239 // Put the lint store levels and passes back in the session.
1240 tcx.sess.lint_store.borrow_mut().late_passes = passes;
1243 struct EarlyLintPassObjects<'a> {
1244 lints: &'a mut [EarlyLintPassObject],
1247 impl LintPass for EarlyLintPassObjects<'_> {
1248 fn name(&self) -> &'static str {
1252 fn get_lints(&self) -> LintArray {
1257 macro_rules! expand_early_lint_pass_impl_methods {
1258 ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
1259 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
1260 for obj in self.lints.iter_mut() {
1261 obj.$name(context, $($param),*);
1267 macro_rules! early_lint_pass_impl {
1268 ([], [$($methods:tt)*]) => (
1269 impl EarlyLintPass for EarlyLintPassObjects<'_> {
1270 expand_early_lint_pass_impl_methods!([$($methods)*]);
1275 early_lint_methods!(early_lint_pass_impl, []);
1278 fn early_lint_crate<T: EarlyLintPass>(
1282 buffered: LintBuffer,
1284 let mut cx = EarlyContextAndPass {
1285 context: EarlyContext::new(sess, krate, buffered),
1289 // Visit the whole crate.
1290 cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1291 // since the root module isn't visited as an item (because it isn't an
1292 // item), warn for it here.
1293 run_early_pass!(cx, check_crate, krate);
1295 ast_visit::walk_crate(cx, krate);
1297 run_early_pass!(cx, check_crate_post, krate);
1302 pub fn check_ast_crate<T: EarlyLintPass>(
1305 pre_expansion: bool,
1308 let (mut passes, mut buffered) = if pre_expansion {
1310 sess.lint_store.borrow_mut().pre_expansion_passes.take().unwrap(),
1311 LintBuffer::default(),
1315 sess.lint_store.borrow_mut().early_passes.take().unwrap(),
1316 sess.buffered_lints.borrow_mut().take().unwrap(),
1320 if !sess.opts.debugging_opts.no_interleave_lints {
1321 buffered = early_lint_crate(sess, krate, builtin_lints, buffered);
1323 if !passes.is_empty() {
1324 buffered = early_lint_crate(
1327 EarlyLintPassObjects { lints: &mut passes[..] },
1332 for pass in &mut passes {
1333 buffered = time(sess, &format!("running lint: {}", pass.name()), || {
1337 EarlyLintPassObjects { lints: slice::from_mut(pass) },
1344 // Put the lint store levels and passes back in the session.
1346 sess.lint_store.borrow_mut().pre_expansion_passes = Some(passes);
1348 sess.lint_store.borrow_mut().early_passes = Some(passes);
1351 // All of the buffered lints should have been emitted at this point.
1352 // If not, that means that we somehow buffered a lint for a node id
1353 // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
1355 // Rustdoc runs everybody-loops before the early lints and removes
1356 // function bodies, so it's totally possible for linted
1357 // node ids to not exist (e.g., macros defined within functions for the
1358 // unused_macro lint) anymore. So we only run this check
1359 // when we're not in rustdoc mode. (see issue #47639)
1360 if !sess.opts.actually_rustdoc {
1361 for (_id, lints) in buffered.map {
1362 for early_lint in lints {
1363 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
1369 impl Encodable for LintId {
1370 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1371 s.emit_str(&self.lint.name.to_lowercase())
1375 impl Decodable for LintId {
1377 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1378 let s = d.read_str()?;
1379 ty::tls::with(|tcx| {
1380 match tcx.sess.lint_store.borrow().find_lints(&s) {
1383 panic!("invalid lint-id `{}`", s);
1387 Err(_) => panic!("invalid lint-id `{}`", s),