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::*;
19 use crate::levels::LintLevelsBuilder;
20 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
21 use rustc::hir::map::definitions::{DefPathData, DisambiguatedDefPathData};
22 use rustc::lint::add_elided_lifetime_in_path_suggestion;
23 use rustc::middle::privacy::AccessLevels;
24 use rustc::middle::stability;
25 use rustc::ty::layout::{LayoutError, LayoutOf, TyLayout};
26 use rustc::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_data_structures::sync;
29 use rustc_error_codes::*;
30 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
32 use rustc_hir::def_id::{CrateNum, DefId};
33 use rustc_session::lint::BuiltinLintDiagnostics;
34 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
35 use rustc_session::Session;
36 use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP};
38 use syntax::util::lev_distance::find_best_match_for_name;
42 /// Information about the registered lints.
44 /// This is basically the subset of `Context` that we can
45 /// build early in the compile pipeline.
46 pub struct LintStore {
48 lints: Vec<&'static Lint>,
50 /// Constructor functions for each variety of lint pass.
52 /// These should only be called once, but since we want to avoid locks or
53 /// interior mutability, we don't enforce this (and lints should, in theory,
54 /// be compatible with being constructed more than once, though not
55 /// necessarily in a sane manner. This is safe though.)
56 pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
57 pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
58 pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
59 /// This is unique in that we construct them per-module, so not once.
60 pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
62 /// Lints indexed by name.
63 by_name: FxHashMap<String, TargetLint>,
65 /// Map of registered lint groups to what lints they expand to.
66 lint_groups: FxHashMap<&'static str, LintGroup>,
69 /// The target of the `by_name` map, which accounts for renaming/deprecation.
71 /// A direct lint target
74 /// Temporary renaming, used for easing migration pain; see #16545
75 Renamed(String, LintId),
77 /// Lint with this name existed previously, but has been removed/deprecated.
78 /// The string argument is the reason for removal.
82 pub enum FindLintError {
89 /// Whether deprecation warnings should be suppressed for this alias.
94 lint_ids: Vec<LintId>,
96 depr: Option<LintAlias>,
99 pub enum CheckLintNameResult<'a> {
101 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
102 NoLint(Option<Symbol>),
103 /// The lint is either renamed or removed. This is the warning
104 /// message, and an optional new name (`None` if removed).
105 Warning(String, Option<String>),
106 /// The lint is from a tool. If the Option is None, then either
107 /// the lint does not exist in the tool or the code was not
108 /// compiled with the tool and therefore the lint was never
109 /// added to the `LintStore`. Otherwise the `LintId` will be
110 /// returned as if it where a rustc lint.
111 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
115 pub fn new() -> LintStore {
118 pre_expansion_passes: vec![],
119 early_passes: vec![],
121 late_module_passes: vec![],
122 by_name: Default::default(),
123 lint_groups: Default::default(),
127 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
131 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
134 .filter(|(_, LintGroup { depr, .. })| {
135 // Don't display deprecated lint groups.
138 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
139 (*k, lint_ids.clone(), *from_plugin)
144 pub fn register_early_pass(
146 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
148 self.early_passes.push(Box::new(pass));
151 pub fn register_pre_expansion_pass(
153 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
155 self.pre_expansion_passes.push(Box::new(pass));
158 pub fn register_late_pass(
160 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
162 self.late_passes.push(Box::new(pass));
165 pub fn register_late_mod_pass(
167 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
169 self.late_module_passes.push(Box::new(pass));
172 // Helper method for register_early/late_pass
173 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
175 self.lints.push(lint);
177 let id = LintId::of(lint);
178 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
179 bug!("duplicate specification of lint {}", lint.name_lower())
182 if let Some(FutureIncompatibleInfo { edition, .. }) = lint.future_incompatible {
183 if let Some(edition) = edition {
185 .entry(edition.lint_name())
186 .or_insert(LintGroup {
188 from_plugin: lint.is_plugin,
196 .entry("future_incompatible")
197 .or_insert(LintGroup {
199 from_plugin: lint.is_plugin,
208 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
209 self.lint_groups.insert(
214 depr: Some(LintAlias { name: lint_name, silent: true }),
219 pub fn register_group(
223 deprecated_name: Option<&'static str>,
228 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
230 if let Some(deprecated) = deprecated_name {
231 self.lint_groups.insert(
236 depr: Some(LintAlias { name, silent: false }),
242 bug!("duplicate specification of lint group {}", name);
246 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
247 let target = match self.by_name.get(new_name) {
248 Some(&Id(lint_id)) => lint_id.clone(),
249 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
251 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
254 pub fn register_removed(&mut self, name: &str, reason: &str) {
255 self.by_name.insert(name.into(), Removed(reason.into()));
258 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
259 match self.by_name.get(lint_name) {
260 Some(&Id(lint_id)) => Ok(vec![lint_id]),
261 Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
262 Some(&Removed(_)) => Err(FindLintError::Removed),
264 return match self.lint_groups.get(lint_name) {
265 Some(LintGroup { lint_ids, depr, .. }) => {
266 if let Some(LintAlias { name, .. }) = depr {
272 None => Err(FindLintError::Removed),
278 /// Checks the validity of lint names derived from the command line
279 pub fn check_lint_name_cmdline(&self, sess: &Session, lint_name: &str, level: Level) {
280 let db = match self.check_lint_name(lint_name, None) {
281 CheckLintNameResult::Ok(_) => None,
282 CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
283 CheckLintNameResult::NoLint(suggestion) => {
285 struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
287 if let Some(suggestion) = suggestion {
288 err.help(&format!("did you mean: `{}`", suggestion));
293 CheckLintNameResult::Tool(result) => match result {
294 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
295 "lint name `{}` is deprecated \
296 and does not have an effect anymore. \
304 if let Some(mut db) = db {
306 "requested on the command line with `{} {}`",
308 Level::Allow => "-A",
311 Level::Forbid => "-F",
320 /// Checks the name of a lint for its existence, and whether it was
321 /// renamed or removed. Generates a DiagnosticBuilder containing a
322 /// warning for renamed and removed lints. This is over both lint
323 /// names from attributes and those passed on the command line. Since
324 /// it emits non-fatal warnings and there are *two* lint passes that
325 /// inspect attributes, this is only run from the late pass to avoid
326 /// printing duplicate warnings.
327 pub fn check_lint_name(
330 tool_name: Option<Symbol>,
331 ) -> CheckLintNameResult<'_> {
332 let complete_name = if let Some(tool_name) = tool_name {
333 format!("{}::{}", tool_name, lint_name)
335 lint_name.to_string()
337 // If the lint was scoped with `tool::` check if the tool lint exists
338 if let Some(_) = tool_name {
339 match self.by_name.get(&complete_name) {
340 None => match self.lint_groups.get(&*complete_name) {
341 None => return CheckLintNameResult::Tool(Err((None, String::new()))),
342 Some(LintGroup { lint_ids, .. }) => {
343 return CheckLintNameResult::Tool(Ok(&lint_ids));
346 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
347 // If the lint was registered as removed or renamed by the lint tool, we don't need
348 // to treat tool_lints and rustc lints different and can use the code below.
352 match self.by_name.get(&complete_name) {
353 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
354 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
355 Some(new_name.to_owned()),
357 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
358 format!("lint `{}` has been removed: `{}`", complete_name, reason),
361 None => match self.lint_groups.get(&*complete_name) {
362 // If neither the lint, nor the lint group exists check if there is a `clippy::`
363 // variant of this lint
364 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
365 Some(LintGroup { lint_ids, depr, .. }) => {
366 // Check if the lint group name is deprecated
367 if let Some(LintAlias { name, silent }) = depr {
368 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
370 CheckLintNameResult::Ok(&lint_ids)
372 CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
375 CheckLintNameResult::Ok(&lint_ids)
378 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
382 fn check_tool_name_for_backwards_compat(
386 ) -> CheckLintNameResult<'_> {
387 let complete_name = format!("{}::{}", tool_name, lint_name);
388 match self.by_name.get(&complete_name) {
389 None => match self.lint_groups.get(&*complete_name) {
390 // Now we are sure, that this lint exists nowhere
393 self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
396 find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
398 CheckLintNameResult::NoLint(suggestion)
400 Some(LintGroup { lint_ids, depr, .. }) => {
401 // Reaching this would be weird, but let's cover this case anyway
402 if let Some(LintAlias { name, silent }) = depr {
403 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
405 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
407 CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
410 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
413 Some(&Id(ref id)) => {
414 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
416 _ => CheckLintNameResult::NoLint(None),
421 /// Context for lint checking after type checking.
422 pub struct LateContext<'a, 'tcx> {
423 /// Type context we're checking in.
424 pub tcx: TyCtxt<'tcx>,
426 /// Side-tables for the body we are in.
427 // FIXME: Make this lazy to avoid running the TypeckTables query?
428 pub tables: &'a ty::TypeckTables<'tcx>,
430 /// Parameter environment for the item we are in.
431 pub param_env: ty::ParamEnv<'tcx>,
433 /// Items accessible from the crate being checked.
434 pub access_levels: &'a AccessLevels,
436 /// The store of registered lints and the lint levels.
437 pub lint_store: &'tcx LintStore,
439 pub last_node_with_lint_attrs: hir::HirId,
441 /// Generic type parameters in scope for the item we are in.
442 pub generics: Option<&'tcx hir::Generics<'tcx>>,
444 /// We are only looking at one module
445 pub only_module: bool,
448 /// Context for lint checking of the AST, after expansion, before lowering to
450 pub struct EarlyContext<'a> {
451 /// Type context we're checking in.
452 pub sess: &'a Session,
454 /// The crate being checked.
455 pub krate: &'a ast::Crate,
457 pub builder: LintLevelsBuilder<'a>,
459 /// The store of registered lints and the lint levels.
460 pub lint_store: &'a LintStore,
462 pub buffered: LintBuffer,
465 pub trait LintPassObject: Sized {}
467 impl LintPassObject for EarlyLintPassObject {}
469 impl LintPassObject for LateLintPassObject {}
471 pub trait LintContext: Sized {
472 type PassObject: LintPassObject;
474 fn sess(&self) -> &Session;
475 fn lints(&self) -> &LintStore;
477 fn lookup_and_emit<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: Option<S>, msg: &str) {
478 self.lookup(lint, span, msg).emit();
481 fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(
486 diagnostic: BuiltinLintDiagnostics,
488 let mut db = self.lookup(lint, span, msg);
490 let sess = self.sess();
492 BuiltinLintDiagnostics::Normal => (),
493 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
494 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
495 Ok(s) if is_global => {
496 (format!("dyn ({})", s), Applicability::MachineApplicable)
498 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
499 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
501 db.span_suggestion(span, "use `dyn`", sugg, app);
503 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
504 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
506 // FIXME(Manishearth) ideally the emitting code
507 // can tell us whether or not this is global
508 let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" };
510 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
512 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
514 db.span_suggestion(span, "use `crate`", sugg, app);
516 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
519 "names from parent modules are not accessible without an explicit import",
522 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
523 db.span_note(span_def, "the macro is defined here");
525 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
532 add_elided_lifetime_in_path_suggestion(
542 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
543 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
545 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
546 if !replaces.is_empty() {
547 db.tool_only_multipart_suggestion(
550 Applicability::MachineApplicable,
554 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
555 for (span, is_imported) in spans {
556 let introduced = if is_imported { "imported" } else { "defined" };
559 format!("the item `{}` is already {} here", ident, introduced),
563 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
564 stability::deprecation_suggestion(&mut db, suggestion, span)
571 fn lookup<S: Into<MultiSpan>>(
576 ) -> DiagnosticBuilder<'_>;
578 /// Emit a lint at the appropriate level, for a particular span.
579 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
580 self.lookup_and_emit(lint, Some(span), msg);
583 fn struct_span_lint<S: Into<MultiSpan>>(
588 ) -> DiagnosticBuilder<'_> {
589 self.lookup(lint, Some(span), msg)
592 /// Emit a lint and note at the appropriate level, for a particular span.
601 let mut err = self.lookup(lint, Some(span), msg);
602 if note_span == span {
605 err.span_note(note_span, note);
610 /// Emit a lint and help at the appropriate level, for a particular span.
611 fn span_lint_help(&self, lint: &'static Lint, span: Span, msg: &str, help: &str) {
612 let mut err = self.lookup(lint, Some(span), msg);
613 self.span_lint(lint, span, msg);
614 err.span_help(span, help);
618 /// Emit a lint at the appropriate level, with no associated span.
619 fn lint(&self, lint: &'static Lint, msg: &str) {
620 self.lookup_and_emit(lint, None as Option<Span>, msg);
624 impl<'a> EarlyContext<'a> {
627 lint_store: &'a LintStore,
628 krate: &'a ast::Crate,
629 buffered: LintBuffer,
630 warn_about_weird_lints: bool,
631 ) -> EarlyContext<'a> {
636 builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
642 impl LintContext for LateContext<'_, '_> {
643 type PassObject = LateLintPassObject;
645 /// Gets the overall compiler `Session` object.
646 fn sess(&self) -> &Session {
650 fn lints(&self) -> &LintStore {
654 fn lookup<S: Into<MultiSpan>>(
659 ) -> DiagnosticBuilder<'_> {
660 let hir_id = self.last_node_with_lint_attrs;
663 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg),
664 None => self.tcx.struct_lint_node(lint, hir_id, msg),
669 impl LintContext for EarlyContext<'_> {
670 type PassObject = EarlyLintPassObject;
672 /// Gets the overall compiler `Session` object.
673 fn sess(&self) -> &Session {
677 fn lints(&self) -> &LintStore {
681 fn lookup<S: Into<MultiSpan>>(
686 ) -> DiagnosticBuilder<'_> {
687 self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
691 impl<'a, 'tcx> LateContext<'a, 'tcx> {
692 pub fn current_lint_root(&self) -> hir::HirId {
693 self.last_node_with_lint_attrs
696 /// Check if a `DefId`'s path matches the given absolute type path usage.
698 /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
699 /// inherent `impl` blocks are matched with the name of the type.
703 /// ```rust,ignore (no context or def id available)
704 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
705 /// // The given `def_id` is that of an `Option` type
708 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
709 let names = self.get_def_path(def_id);
711 names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
714 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
718 /// ```rust,ignore (no context or def id available)
719 /// let def_path = cx.get_def_path(def_id);
720 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
721 /// // The given `def_id` is that of an `Option` type
724 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
725 pub struct AbsolutePathPrinter<'tcx> {
726 pub tcx: TyCtxt<'tcx>,
729 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
732 type Path = Vec<Symbol>;
735 type DynExistential = ();
738 fn tcx(&self) -> TyCtxt<'tcx> {
742 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
746 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
750 fn print_dyn_existential(
752 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
753 ) -> Result<Self::DynExistential, Self::Error> {
757 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
761 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
762 Ok(vec![self.tcx.original_crate_name(cnum)])
768 trait_ref: Option<ty::TraitRef<'tcx>>,
769 ) -> Result<Self::Path, Self::Error> {
770 if trait_ref.is_none() {
771 if let ty::Adt(def, substs) = self_ty.kind {
772 return self.print_def_path(def.did, substs);
776 // This shouldn't ever be needed, but just in case:
777 Ok(vec![match trait_ref {
778 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
779 None => Symbol::intern(&format!("<{}>", self_ty)),
785 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
786 _disambiguated_data: &DisambiguatedDefPathData,
788 trait_ref: Option<ty::TraitRef<'tcx>>,
789 ) -> Result<Self::Path, Self::Error> {
790 let mut path = print_prefix(self)?;
792 // This shouldn't ever be needed, but just in case:
793 path.push(match trait_ref {
794 Some(trait_ref) => Symbol::intern(&format!(
796 trait_ref.print_only_trait_path(),
799 None => Symbol::intern(&format!("<impl {}>", self_ty)),
807 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
808 disambiguated_data: &DisambiguatedDefPathData,
809 ) -> Result<Self::Path, Self::Error> {
810 let mut path = print_prefix(self)?;
812 // Skip `::{{constructor}}` on tuple/unit structs.
813 match disambiguated_data.data {
814 DefPathData::Ctor => return Ok(path),
818 path.push(disambiguated_data.data.as_symbol());
822 fn path_generic_args(
824 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
825 _args: &[GenericArg<'tcx>],
826 ) -> Result<Self::Path, Self::Error> {
831 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
835 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
837 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
839 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
840 self.tcx.layout_of(self.param_env.and(ty))