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_node_with_lint_attrs: hir::HirId,
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 {}
567 pub trait LintContext<'tcx>: Sized {
568 type PassObject: LintPassObject;
570 fn sess(&self) -> &Session;
571 fn lints(&self) -> &LintStore;
572 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject>;
573 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject>;
575 fn lookup_and_emit<S: Into<MultiSpan>>(&self,
579 self.lookup(lint, span, msg).emit();
582 fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(&self,
586 diagnostic: BuiltinLintDiagnostics) {
587 let mut db = self.lookup(lint, span, msg);
588 diagnostic.run(self.sess(), &mut db);
592 fn lookup<S: Into<MultiSpan>>(&self,
596 -> DiagnosticBuilder<'_>;
598 /// Emit a lint at the appropriate level, for a particular span.
599 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
600 self.lookup_and_emit(lint, Some(span), msg);
603 fn struct_span_lint<S: Into<MultiSpan>>(&self,
607 -> DiagnosticBuilder<'_> {
608 self.lookup(lint, Some(span), msg)
611 /// Emit a lint and note at the appropriate level, for a particular span.
612 fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
613 note_span: Span, note: &str) {
614 let mut err = self.lookup(lint, Some(span), msg);
615 if note_span == span {
618 err.span_note(note_span, note);
623 /// Emit a lint and help at the appropriate level, for a particular span.
624 fn span_lint_help(&self, lint: &'static Lint, span: Span,
625 msg: &str, help: &str) {
626 let mut err = self.lookup(lint, Some(span), msg);
627 self.span_lint(lint, span, msg);
628 err.span_help(span, help);
632 /// Emit a lint at the appropriate level, with no associated span.
633 fn lint(&self, lint: &'static Lint, msg: &str) {
634 self.lookup_and_emit(lint, None as Option<Span>, msg);
639 impl<'a> EarlyContext<'a> {
642 krate: &'a ast::Crate,
643 buffered: LintBuffer,
644 ) -> EarlyContext<'a> {
648 lint_sess: LintSession {
649 lints: sess.lint_store.borrow(),
652 builder: LintLevelSets::builder(sess),
658 macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
659 $cx.pass.$f(&$cx.context, $($args),*);
662 impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
663 fn check_id(&mut self, id: ast::NodeId) {
664 for early_lint in self.context.buffered.take(id) {
665 self.context.lookup_and_emit_with_diagnostics(
666 early_lint.lint_id.lint,
667 Some(early_lint.span.clone()),
669 early_lint.diagnostic
674 /// Merge the lints specified by any lint attributes into the
675 /// current lint context, call the provided function, then reset the
676 /// lints in effect to their previous state.
677 fn with_lint_attrs<F>(&mut self,
679 attrs: &'a [ast::Attribute],
681 where F: FnOnce(&mut Self)
683 let push = self.context.builder.push(attrs);
685 self.enter_attrs(attrs);
687 self.exit_attrs(attrs);
688 self.context.builder.pop(push);
691 fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
692 debug!("early context: enter_attrs({:?})", attrs);
693 run_early_pass!(self, enter_lint_attrs, attrs);
696 fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
697 debug!("early context: exit_attrs({:?})", attrs);
698 run_early_pass!(self, exit_lint_attrs, attrs);
702 impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
703 type PassObject = LateLintPassObject;
705 /// Gets the overall compiler `Session` object.
706 fn sess(&self) -> &Session {
710 fn lints(&self) -> &LintStore {
711 &*self.lint_sess.lints
714 fn lint_sess(&self) -> &LintSession<'tcx, Self::PassObject> {
718 fn lint_sess_mut(&mut self) -> &mut LintSession<'tcx, Self::PassObject> {
722 fn lookup<S: Into<MultiSpan>>(&self,
726 -> DiagnosticBuilder<'_> {
727 let hir_id = self.last_node_with_lint_attrs;
730 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg),
732 self.tcx.struct_lint_node(lint, hir_id, msg)
738 impl<'a> LintContext<'a> for EarlyContext<'a> {
739 type PassObject = EarlyLintPassObject;
741 /// Gets the overall compiler `Session` object.
742 fn sess(&self) -> &Session {
746 fn lints(&self) -> &LintStore {
747 &*self.lint_sess.lints
750 fn lint_sess(&self) -> &LintSession<'a, Self::PassObject> {
754 fn lint_sess_mut(&mut self) -> &mut LintSession<'a, Self::PassObject> {
758 fn lookup<S: Into<MultiSpan>>(&self,
762 -> DiagnosticBuilder<'_> {
763 self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
767 impl<'a, 'tcx> LateContext<'a, 'tcx> {
768 /// Merge the lints specified by any lint attributes into the
769 /// current lint context, call the provided function, then reset the
770 /// lints in effect to their previous state.
771 fn with_lint_attrs<F>(&mut self,
773 attrs: &'tcx [ast::Attribute],
775 where F: FnOnce(&mut Self)
777 let prev = self.last_node_with_lint_attrs;
778 self.last_node_with_lint_attrs = id;
779 self.enter_attrs(attrs);
781 self.exit_attrs(attrs);
782 self.last_node_with_lint_attrs = prev;
785 fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
786 debug!("late context: enter_attrs({:?})", attrs);
787 run_lints!(self, enter_lint_attrs, attrs);
790 fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
791 debug!("late context: exit_attrs({:?})", attrs);
792 run_lints!(self, exit_lint_attrs, attrs);
795 fn with_param_env<F>(&mut self, id: hir::HirId, f: F)
796 where F: FnOnce(&mut Self),
798 let old_param_env = self.param_env;
799 self.param_env = self.tcx.param_env(self.tcx.hir().local_def_id_from_hir_id(id));
801 self.param_env = old_param_env;
803 pub fn current_lint_root(&self) -> hir::HirId {
804 self.last_node_with_lint_attrs
808 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
810 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
812 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
813 self.tcx.layout_of(self.param_env.and(ty))
817 impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> {
818 /// Because lints are scoped lexically, we want to walk nested
819 /// items in the context of the outer item, so enable
821 fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
822 hir_visit::NestedVisitorMap::All(&self.tcx.hir())
825 fn visit_nested_body(&mut self, body: hir::BodyId) {
826 let old_tables = self.tables;
827 self.tables = self.tcx.body_tables(body);
828 let body = self.tcx.hir().body(body);
829 self.visit_body(body);
830 self.tables = old_tables;
833 fn visit_body(&mut self, body: &'tcx hir::Body) {
834 run_lints!(self, check_body, body);
835 hir_visit::walk_body(self, body);
836 run_lints!(self, check_body_post, body);
839 fn visit_item(&mut self, it: &'tcx hir::Item) {
840 let generics = self.generics.take();
841 self.generics = it.node.generics();
842 self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
843 cx.with_param_env(it.hir_id, |cx| {
844 run_lints!(cx, check_item, it);
845 hir_visit::walk_item(cx, it);
846 run_lints!(cx, check_item_post, it);
849 self.generics = generics;
852 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
853 self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
854 cx.with_param_env(it.hir_id, |cx| {
855 run_lints!(cx, check_foreign_item, it);
856 hir_visit::walk_foreign_item(cx, it);
857 run_lints!(cx, check_foreign_item_post, it);
862 fn visit_pat(&mut self, p: &'tcx hir::Pat) {
863 run_lints!(self, check_pat, p);
864 hir_visit::walk_pat(self, p);
867 fn visit_expr(&mut self, e: &'tcx hir::Expr) {
868 self.with_lint_attrs(e.hir_id, &e.attrs, |cx| {
869 run_lints!(cx, check_expr, e);
870 hir_visit::walk_expr(cx, e);
871 run_lints!(cx, check_expr_post, e);
875 fn visit_stmt(&mut self, s: &'tcx hir::Stmt) {
876 // statement attributes are actually just attributes on one of
880 // so we keep track of lint levels there
881 run_lints!(self, check_stmt, s);
882 hir_visit::walk_stmt(self, s);
885 fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl,
886 body_id: hir::BodyId, span: Span, id: hir::HirId) {
887 // Wrap in tables here, not just in visit_nested_body,
888 // in order for `check_fn` to be able to use them.
889 let old_tables = self.tables;
890 self.tables = self.tcx.body_tables(body_id);
891 let body = self.tcx.hir().body(body_id);
892 run_lints!(self, check_fn, fk, decl, body, span, id);
893 hir_visit::walk_fn(self, fk, decl, body_id, span, id);
894 run_lints!(self, check_fn_post, fk, decl, body, span, id);
895 self.tables = old_tables;
898 fn visit_variant_data(&mut self,
899 s: &'tcx hir::VariantData,
901 g: &'tcx hir::Generics,
904 run_lints!(self, check_struct_def, s, name, g, item_id);
905 hir_visit::walk_struct_def(self, s);
906 run_lints!(self, check_struct_def_post, s, name, g, item_id);
909 fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
910 self.with_lint_attrs(s.hir_id, &s.attrs, |cx| {
911 run_lints!(cx, check_struct_field, s);
912 hir_visit::walk_struct_field(cx, s);
916 fn visit_variant(&mut self,
917 v: &'tcx hir::Variant,
918 g: &'tcx hir::Generics,
919 item_id: hir::HirId) {
920 self.with_lint_attrs(v.node.data.hir_id(), &v.node.attrs, |cx| {
921 run_lints!(cx, check_variant, v, g);
922 hir_visit::walk_variant(cx, v, g, item_id);
923 run_lints!(cx, check_variant_post, v, g);
927 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
928 run_lints!(self, check_ty, t);
929 hir_visit::walk_ty(self, t);
932 fn visit_name(&mut self, sp: Span, name: ast::Name) {
933 run_lints!(self, check_name, sp, name);
936 fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: hir::HirId) {
937 run_lints!(self, check_mod, m, s, n);
938 hir_visit::walk_mod(self, m, n);
939 run_lints!(self, check_mod_post, m, s, n);
942 fn visit_local(&mut self, l: &'tcx hir::Local) {
943 self.with_lint_attrs(l.hir_id, &l.attrs, |cx| {
944 run_lints!(cx, check_local, l);
945 hir_visit::walk_local(cx, l);
949 fn visit_block(&mut self, b: &'tcx hir::Block) {
950 run_lints!(self, check_block, b);
951 hir_visit::walk_block(self, b);
952 run_lints!(self, check_block_post, b);
955 fn visit_arm(&mut self, a: &'tcx hir::Arm) {
956 run_lints!(self, check_arm, a);
957 hir_visit::walk_arm(self, a);
960 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) {
961 run_lints!(self, check_generic_param, p);
962 hir_visit::walk_generic_param(self, p);
965 fn visit_generics(&mut self, g: &'tcx hir::Generics) {
966 run_lints!(self, check_generics, g);
967 hir_visit::walk_generics(self, g);
970 fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate) {
971 run_lints!(self, check_where_predicate, p);
972 hir_visit::walk_where_predicate(self, p);
975 fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef,
976 m: hir::TraitBoundModifier) {
977 run_lints!(self, check_poly_trait_ref, t, m);
978 hir_visit::walk_poly_trait_ref(self, t, m);
981 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
982 let generics = self.generics.take();
983 self.generics = Some(&trait_item.generics);
984 self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |cx| {
985 cx.with_param_env(trait_item.hir_id, |cx| {
986 run_lints!(cx, check_trait_item, trait_item);
987 hir_visit::walk_trait_item(cx, trait_item);
988 run_lints!(cx, check_trait_item_post, trait_item);
991 self.generics = generics;
994 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
995 let generics = self.generics.take();
996 self.generics = Some(&impl_item.generics);
997 self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |cx| {
998 cx.with_param_env(impl_item.hir_id, |cx| {
999 run_lints!(cx, check_impl_item, impl_item);
1000 hir_visit::walk_impl_item(cx, impl_item);
1001 run_lints!(cx, check_impl_item_post, impl_item);
1004 self.generics = generics;
1007 fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) {
1008 run_lints!(self, check_lifetime, lt);
1009 hir_visit::walk_lifetime(self, lt);
1012 fn visit_path(&mut self, p: &'tcx hir::Path, id: hir::HirId) {
1013 run_lints!(self, check_path, p, id);
1014 hir_visit::walk_path(self, p);
1017 fn visit_attribute(&mut self, attr: &'tcx ast::Attribute) {
1018 run_lints!(self, check_attribute, attr);
1022 impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
1023 fn visit_item(&mut self, it: &'a ast::Item) {
1024 self.with_lint_attrs(it.id, &it.attrs, |cx| {
1025 run_early_pass!(cx, check_item, it);
1026 ast_visit::walk_item(cx, it);
1027 run_early_pass!(cx, check_item_post, it);
1031 fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
1032 self.with_lint_attrs(it.id, &it.attrs, |cx| {
1033 run_early_pass!(cx, check_foreign_item, it);
1034 ast_visit::walk_foreign_item(cx, it);
1035 run_early_pass!(cx, check_foreign_item_post, it);
1039 fn visit_pat(&mut self, p: &'a ast::Pat) {
1040 let mut visit_subpats = true;
1041 run_early_pass!(self, check_pat, p, &mut visit_subpats);
1042 self.check_id(p.id);
1044 ast_visit::walk_pat(self, p);
1048 fn visit_expr(&mut self, e: &'a ast::Expr) {
1049 self.with_lint_attrs(e.id, &e.attrs, |cx| {
1050 run_early_pass!(cx, check_expr, e);
1051 ast_visit::walk_expr(cx, e);
1055 fn visit_stmt(&mut self, s: &'a ast::Stmt) {
1056 run_early_pass!(self, check_stmt, s);
1057 self.check_id(s.id);
1058 ast_visit::walk_stmt(self, s);
1061 fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, decl: &'a ast::FnDecl,
1062 span: Span, id: ast::NodeId) {
1063 run_early_pass!(self, check_fn, fk, decl, span, id);
1065 ast_visit::walk_fn(self, fk, decl, span);
1066 run_early_pass!(self, check_fn_post, fk, decl, span, id);
1069 fn visit_variant_data(&mut self,
1070 s: &'a ast::VariantData,
1072 g: &'a ast::Generics,
1073 item_id: ast::NodeId,
1075 run_early_pass!(self, check_struct_def, s, ident, g, item_id);
1076 self.check_id(s.id());
1077 ast_visit::walk_struct_def(self, s);
1078 run_early_pass!(self, check_struct_def_post, s, ident, g, item_id);
1081 fn visit_struct_field(&mut self, s: &'a ast::StructField) {
1082 self.with_lint_attrs(s.id, &s.attrs, |cx| {
1083 run_early_pass!(cx, check_struct_field, s);
1084 ast_visit::walk_struct_field(cx, s);
1088 fn visit_variant(&mut self, v: &'a ast::Variant, g: &'a ast::Generics, item_id: ast::NodeId) {
1089 self.with_lint_attrs(item_id, &v.node.attrs, |cx| {
1090 run_early_pass!(cx, check_variant, v, g);
1091 ast_visit::walk_variant(cx, v, g, item_id);
1092 run_early_pass!(cx, check_variant_post, v, g);
1096 fn visit_ty(&mut self, t: &'a ast::Ty) {
1097 run_early_pass!(self, check_ty, t);
1098 self.check_id(t.id);
1099 ast_visit::walk_ty(self, t);
1102 fn visit_ident(&mut self, ident: ast::Ident) {
1103 run_early_pass!(self, check_ident, ident);
1106 fn visit_mod(&mut self, m: &'a ast::Mod, s: Span, _a: &[ast::Attribute], n: ast::NodeId) {
1107 run_early_pass!(self, check_mod, m, s, n);
1109 ast_visit::walk_mod(self, m);
1110 run_early_pass!(self, check_mod_post, m, s, n);
1113 fn visit_local(&mut self, l: &'a ast::Local) {
1114 self.with_lint_attrs(l.id, &l.attrs, |cx| {
1115 run_early_pass!(cx, check_local, l);
1116 ast_visit::walk_local(cx, l);
1120 fn visit_block(&mut self, b: &'a ast::Block) {
1121 run_early_pass!(self, check_block, b);
1122 self.check_id(b.id);
1123 ast_visit::walk_block(self, b);
1124 run_early_pass!(self, check_block_post, b);
1127 fn visit_arm(&mut self, a: &'a ast::Arm) {
1128 run_early_pass!(self, check_arm, a);
1129 ast_visit::walk_arm(self, a);
1132 fn visit_expr_post(&mut self, e: &'a ast::Expr) {
1133 run_early_pass!(self, check_expr_post, e);
1136 fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
1137 run_early_pass!(self, check_generic_param, param);
1138 ast_visit::walk_generic_param(self, param);
1141 fn visit_generics(&mut self, g: &'a ast::Generics) {
1142 run_early_pass!(self, check_generics, g);
1143 ast_visit::walk_generics(self, g);
1146 fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
1147 run_early_pass!(self, check_where_predicate, p);
1148 ast_visit::walk_where_predicate(self, p);
1151 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) {
1152 run_early_pass!(self, check_poly_trait_ref, t, m);
1153 ast_visit::walk_poly_trait_ref(self, t, m);
1156 fn visit_trait_item(&mut self, trait_item: &'a ast::TraitItem) {
1157 self.with_lint_attrs(trait_item.id, &trait_item.attrs, |cx| {
1158 run_early_pass!(cx, check_trait_item, trait_item);
1159 ast_visit::walk_trait_item(cx, trait_item);
1160 run_early_pass!(cx, check_trait_item_post, trait_item);
1164 fn visit_impl_item(&mut self, impl_item: &'a ast::ImplItem) {
1165 self.with_lint_attrs(impl_item.id, &impl_item.attrs, |cx| {
1166 run_early_pass!(cx, check_impl_item, impl_item);
1167 ast_visit::walk_impl_item(cx, impl_item);
1168 run_early_pass!(cx, check_impl_item_post, impl_item);
1172 fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) {
1173 run_early_pass!(self, check_lifetime, lt);
1174 self.check_id(lt.id);
1177 fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
1178 run_early_pass!(self, check_path, p, id);
1180 ast_visit::walk_path(self, p);
1183 fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
1184 run_early_pass!(self, check_attribute, attr);
1187 fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
1188 run_early_pass!(self, check_mac_def, mac, id);
1192 fn visit_mac(&mut self, mac: &'a ast::Mac) {
1193 // FIXME(#54110): So, this setup isn't really right. I think
1194 // that (a) the libsyntax visitor ought to be doing this as
1195 // part of `walk_mac`, and (b) we should be calling
1196 // `visit_path`, *but* that would require a `NodeId`, and I
1197 // want to get #53686 fixed quickly. -nmatsakis
1198 ast_visit::walk_path(self, &mac.node.path);
1200 run_early_pass!(self, check_mac, mac);
1205 /// Performs lint checking on a crate.
1207 /// Consumes the `lint_store` field of the `Session`.
1208 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1209 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
1211 let krate = tcx.hir().krate();
1212 let passes = tcx.sess.lint_store.borrow_mut().late_passes.take();
1215 let mut cx = LateContext {
1217 tables: &ty::TypeckTables::empty(None),
1218 param_env: ty::ParamEnv::empty(),
1220 lint_sess: LintSession {
1222 lints: tcx.sess.lint_store.borrow(),
1224 last_node_with_lint_attrs: hir::CRATE_HIR_ID,
1228 // Visit the whole crate.
1229 cx.with_lint_attrs(hir::CRATE_HIR_ID, &krate.attrs, |cx| {
1230 // since the root module isn't visited as an item (because it isn't an
1231 // item), warn for it here.
1232 run_lints!(cx, check_crate, krate);
1234 hir_visit::walk_crate(cx, krate);
1236 run_lints!(cx, check_crate_post, krate);
1241 // Put the lint store levels and passes back in the session.
1242 tcx.sess.lint_store.borrow_mut().late_passes = passes;
1245 struct EarlyLintPassObjects<'a> {
1246 lints: &'a mut [EarlyLintPassObject],
1249 impl LintPass for EarlyLintPassObjects<'_> {
1250 fn name(&self) -> &'static str {
1254 fn get_lints(&self) -> LintArray {
1259 macro_rules! expand_early_lint_pass_impl_methods {
1260 ([$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
1261 $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
1262 for obj in self.lints.iter_mut() {
1263 obj.$name(context, $($param),*);
1269 macro_rules! early_lint_pass_impl {
1270 ([], [$($methods:tt)*]) => (
1271 impl EarlyLintPass for EarlyLintPassObjects<'_> {
1272 expand_early_lint_pass_impl_methods!([$($methods)*]);
1277 early_lint_methods!(early_lint_pass_impl, []);
1280 fn early_lint_crate<T: EarlyLintPass>(
1284 buffered: LintBuffer,
1286 let mut cx = EarlyContextAndPass {
1287 context: EarlyContext::new(sess, krate, buffered),
1291 // Visit the whole crate.
1292 cx.with_lint_attrs(ast::CRATE_NODE_ID, &krate.attrs, |cx| {
1293 // since the root module isn't visited as an item (because it isn't an
1294 // item), warn for it here.
1295 run_early_pass!(cx, check_crate, krate);
1297 ast_visit::walk_crate(cx, krate);
1299 run_early_pass!(cx, check_crate_post, krate);
1304 pub fn check_ast_crate<T: EarlyLintPass>(
1307 pre_expansion: bool,
1310 let (mut passes, mut buffered) = if pre_expansion {
1312 sess.lint_store.borrow_mut().pre_expansion_passes.take().unwrap(),
1313 LintBuffer::default(),
1317 sess.lint_store.borrow_mut().early_passes.take().unwrap(),
1318 sess.buffered_lints.borrow_mut().take().unwrap(),
1322 if !sess.opts.debugging_opts.no_interleave_lints {
1323 buffered = early_lint_crate(sess, krate, builtin_lints, buffered);
1325 if !passes.is_empty() {
1326 buffered = early_lint_crate(
1329 EarlyLintPassObjects { lints: &mut passes[..] },
1334 for pass in &mut passes {
1335 buffered = time(sess, &format!("running lint: {}", pass.name()), || {
1339 EarlyLintPassObjects { lints: slice::from_mut(pass) },
1346 // Put the lint store levels and passes back in the session.
1348 sess.lint_store.borrow_mut().pre_expansion_passes = Some(passes);
1350 sess.lint_store.borrow_mut().early_passes = Some(passes);
1353 // All of the buffered lints should have been emitted at this point.
1354 // If not, that means that we somehow buffered a lint for a node id
1355 // that was not lint-checked (perhaps it doesn't exist?). This is a bug.
1357 // Rustdoc runs everybody-loops before the early lints and removes
1358 // function bodies, so it's totally possible for linted
1359 // node ids to not exist (e.g., macros defined within functions for the
1360 // unused_macro lint) anymore. So we only run this check
1361 // when we're not in rustdoc mode. (see issue #47639)
1362 if !sess.opts.actually_rustdoc {
1363 for (_id, lints) in buffered.map {
1364 for early_lint in lints {
1365 sess.delay_span_bug(early_lint.span, "failed to process buffered lint here");
1371 impl Encodable for LintId {
1372 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1373 s.emit_str(&self.lint.name.to_lowercase())
1377 impl Decodable for LintId {
1379 fn decode<D: Decoder>(d: &mut D) -> Result<LintId, D::Error> {
1380 let s = d.read_str()?;
1381 ty::tls::with(|tcx| {
1382 match tcx.sess.lint_store.borrow().find_lints(&s) {
1385 panic!("invalid lint-id `{}`", s);
1389 Err(_) => panic!("invalid lint-id `{}`", s),