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::lint::LintDiagnosticBuilder;
22 use rustc::middle::privacy::AccessLevels;
23 use rustc::middle::stability;
24 use rustc::ty::layout::{LayoutError, LayoutOf, TyAndLayout};
25 use rustc::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
27 use rustc_ast::util::lev_distance::find_best_match_for_name;
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_data_structures::sync;
30 use rustc_errors::{struct_span_err, Applicability};
32 use rustc_hir::def_id::{CrateNum, DefId};
33 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
34 use rustc_session::lint::{add_elided_lifetime_in_path_suggestion, BuiltinLintDiagnostics};
35 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
36 use rustc_session::Session;
37 use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP};
41 /// Information about the registered lints.
43 /// This is basically the subset of `Context` that we can
44 /// build early in the compile pipeline.
45 pub struct LintStore {
47 lints: Vec<&'static Lint>,
49 /// Constructor functions for each variety of lint pass.
51 /// These should only be called once, but since we want to avoid locks or
52 /// interior mutability, we don't enforce this (and lints should, in theory,
53 /// be compatible with being constructed more than once, though not
54 /// necessarily in a sane manner. This is safe though.)
55 pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
56 pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
57 pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
58 /// This is unique in that we construct them per-module, so not once.
59 pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
61 /// Lints indexed by name.
62 by_name: FxHashMap<String, TargetLint>,
64 /// Map of registered lint groups to what lints they expand to.
65 lint_groups: FxHashMap<&'static str, LintGroup>,
68 /// The target of the `by_name` map, which accounts for renaming/deprecation.
70 /// A direct lint target
73 /// Temporary renaming, used for easing migration pain; see #16545
74 Renamed(String, LintId),
76 /// Lint with this name existed previously, but has been removed/deprecated.
77 /// The string argument is the reason for removal.
81 pub enum FindLintError {
88 /// Whether deprecation warnings should be suppressed for this alias.
93 lint_ids: Vec<LintId>,
95 depr: Option<LintAlias>,
98 pub enum CheckLintNameResult<'a> {
100 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
101 NoLint(Option<Symbol>),
102 /// The lint is either renamed or removed. This is the warning
103 /// message, and an optional new name (`None` if removed).
104 Warning(String, Option<String>),
105 /// The lint is from a tool. If the Option is None, then either
106 /// the lint does not exist in the tool or the code was not
107 /// compiled with the tool and therefore the lint was never
108 /// added to the `LintStore`. Otherwise the `LintId` will be
109 /// returned as if it where a rustc lint.
110 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
114 pub fn new() -> LintStore {
117 pre_expansion_passes: vec![],
118 early_passes: vec![],
120 late_module_passes: vec![],
121 by_name: Default::default(),
122 lint_groups: Default::default(),
126 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
130 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
133 .filter(|(_, LintGroup { depr, .. })| {
134 // Don't display deprecated lint groups.
137 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
138 (*k, lint_ids.clone(), *from_plugin)
143 pub fn register_early_pass(
145 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
147 self.early_passes.push(Box::new(pass));
150 pub fn register_pre_expansion_pass(
152 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
154 self.pre_expansion_passes.push(Box::new(pass));
157 pub fn register_late_pass(
159 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
161 self.late_passes.push(Box::new(pass));
164 pub fn register_late_mod_pass(
166 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
168 self.late_module_passes.push(Box::new(pass));
171 // Helper method for register_early/late_pass
172 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
174 self.lints.push(lint);
176 let id = LintId::of(lint);
177 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
178 bug!("duplicate specification of lint {}", lint.name_lower())
181 if let Some(FutureIncompatibleInfo { edition, .. }) = lint.future_incompatible {
182 if let Some(edition) = edition {
184 .entry(edition.lint_name())
185 .or_insert(LintGroup {
187 from_plugin: lint.is_plugin,
195 .entry("future_incompatible")
196 .or_insert(LintGroup {
198 from_plugin: lint.is_plugin,
207 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
208 self.lint_groups.insert(
213 depr: Some(LintAlias { name: lint_name, silent: true }),
218 pub fn register_group(
222 deprecated_name: Option<&'static str>,
227 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
229 if let Some(deprecated) = deprecated_name {
230 self.lint_groups.insert(
235 depr: Some(LintAlias { name, silent: false }),
241 bug!("duplicate specification of lint group {}", name);
245 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
246 let target = match self.by_name.get(new_name) {
247 Some(&Id(lint_id)) => lint_id,
248 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
250 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
253 pub fn register_removed(&mut self, name: &str, reason: &str) {
254 self.by_name.insert(name.into(), Removed(reason.into()));
257 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
258 match self.by_name.get(lint_name) {
259 Some(&Id(lint_id)) => Ok(vec![lint_id]),
260 Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
261 Some(&Removed(_)) => Err(FindLintError::Removed),
263 return match self.lint_groups.get(lint_name) {
264 Some(LintGroup { lint_ids, depr, .. }) => {
265 if let Some(LintAlias { name, .. }) = depr {
271 None => Err(FindLintError::Removed),
277 /// Checks the validity of lint names derived from the command line
278 pub fn check_lint_name_cmdline(&self, sess: &Session, lint_name: &str, level: Level) {
279 let db = match self.check_lint_name(lint_name, None) {
280 CheckLintNameResult::Ok(_) => None,
281 CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
282 CheckLintNameResult::NoLint(suggestion) => {
284 struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
286 if let Some(suggestion) = suggestion {
287 err.help(&format!("did you mean: `{}`", suggestion));
292 CheckLintNameResult::Tool(result) => match result {
293 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
294 "lint name `{}` is deprecated \
295 and does not have an effect anymore. \
303 if let Some(mut db) = db {
305 "requested on the command line with `{} {}`",
307 Level::Allow => "-A",
310 Level::Forbid => "-F",
319 /// Checks the name of a lint for its existence, and whether it was
320 /// renamed or removed. Generates a DiagnosticBuilder containing a
321 /// warning for renamed and removed lints. This is over both lint
322 /// names from attributes and those passed on the command line. Since
323 /// it emits non-fatal warnings and there are *two* lint passes that
324 /// inspect attributes, this is only run from the late pass to avoid
325 /// printing duplicate warnings.
326 pub fn check_lint_name(
329 tool_name: Option<Symbol>,
330 ) -> CheckLintNameResult<'_> {
331 let complete_name = if let Some(tool_name) = tool_name {
332 format!("{}::{}", tool_name, lint_name)
334 lint_name.to_string()
336 // If the lint was scoped with `tool::` check if the tool lint exists
337 if tool_name.is_some() {
338 match self.by_name.get(&complete_name) {
339 None => match self.lint_groups.get(&*complete_name) {
340 None => return CheckLintNameResult::Tool(Err((None, String::new()))),
341 Some(LintGroup { lint_ids, .. }) => {
342 return CheckLintNameResult::Tool(Ok(&lint_ids));
345 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
346 // If the lint was registered as removed or renamed by the lint tool, we don't need
347 // to treat tool_lints and rustc lints different and can use the code below.
351 match self.by_name.get(&complete_name) {
352 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
353 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
354 Some(new_name.to_owned()),
356 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
357 format!("lint `{}` has been removed: `{}`", complete_name, reason),
360 None => match self.lint_groups.get(&*complete_name) {
361 // If neither the lint, nor the lint group exists check if there is a `clippy::`
362 // variant of this lint
363 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
364 Some(LintGroup { lint_ids, depr, .. }) => {
365 // Check if the lint group name is deprecated
366 if let Some(LintAlias { name, silent }) = depr {
367 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
369 CheckLintNameResult::Ok(&lint_ids)
371 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
374 CheckLintNameResult::Ok(&lint_ids)
377 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
381 fn check_tool_name_for_backwards_compat(
385 ) -> CheckLintNameResult<'_> {
386 let complete_name = format!("{}::{}", tool_name, lint_name);
387 match self.by_name.get(&complete_name) {
388 None => match self.lint_groups.get(&*complete_name) {
389 // Now we are sure, that this lint exists nowhere
392 self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
395 find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
397 CheckLintNameResult::NoLint(suggestion)
399 Some(LintGroup { lint_ids, depr, .. }) => {
400 // Reaching this would be weird, but let's cover this case anyway
401 if let Some(LintAlias { name, silent }) = depr {
402 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
404 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
406 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
409 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
412 Some(&Id(ref id)) => {
413 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
415 _ => CheckLintNameResult::NoLint(None),
420 /// Context for lint checking after type checking.
421 pub struct LateContext<'a, 'tcx> {
422 /// Type context we're checking in.
423 pub tcx: TyCtxt<'tcx>,
425 /// Side-tables for the body we are in.
426 // FIXME: Make this lazy to avoid running the TypeckTables query?
427 pub tables: &'a ty::TypeckTables<'tcx>,
429 /// Parameter environment for the item we are in.
430 pub param_env: ty::ParamEnv<'tcx>,
432 /// Items accessible from the crate being checked.
433 pub access_levels: &'a AccessLevels,
435 /// The store of registered lints and the lint levels.
436 pub lint_store: &'tcx LintStore,
438 pub last_node_with_lint_attrs: hir::HirId,
440 /// Generic type parameters in scope for the item we are in.
441 pub generics: Option<&'tcx hir::Generics<'tcx>>,
443 /// We are only looking at one module
444 pub only_module: bool,
447 /// Context for lint checking of the AST, after expansion, before lowering to
449 pub struct EarlyContext<'a> {
450 /// Type context we're checking in.
451 pub sess: &'a Session,
453 /// The crate being checked.
454 pub krate: &'a ast::Crate,
456 pub builder: LintLevelsBuilder<'a>,
458 /// The store of registered lints and the lint levels.
459 pub lint_store: &'a LintStore,
461 pub buffered: LintBuffer,
464 pub trait LintPassObject: Sized {}
466 impl LintPassObject for EarlyLintPassObject {}
468 impl LintPassObject for LateLintPassObject {}
470 pub trait LintContext: Sized {
471 type PassObject: LintPassObject;
473 fn sess(&self) -> &Session;
474 fn lints(&self) -> &LintStore;
476 fn lookup_with_diagnostics(
479 span: Option<impl Into<MultiSpan>>,
480 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
481 diagnostic: BuiltinLintDiagnostics,
483 self.lookup(lint, span, |lint| {
484 // We first generate a blank diagnostic.
485 let mut db = lint.build("");
487 // Now, set up surrounding context.
488 let sess = self.sess();
490 BuiltinLintDiagnostics::Normal => (),
491 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
492 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
493 Ok(s) if is_global => {
494 (format!("dyn ({})", s), Applicability::MachineApplicable)
496 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
497 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
499 db.span_suggestion(span, "use `dyn`", sugg, app);
501 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
502 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
504 // FIXME(Manishearth) ideally the emitting code
505 // can tell us whether or not this is global
507 if s.trim_start().starts_with("::") { "" } else { "::" };
509 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
511 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
513 db.span_suggestion(span, "use `crate`", sugg, app);
515 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
518 "names from parent modules are not accessible without an explicit import",
521 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
524 db.span_note(span_def, "the macro is defined here");
526 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
533 add_elided_lifetime_in_path_suggestion(
543 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
544 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
546 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
547 if !replaces.is_empty() {
548 db.tool_only_multipart_suggestion(
551 Applicability::MachineApplicable,
555 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
556 for (span, is_imported) in spans {
557 let introduced = if is_imported { "imported" } else { "defined" };
560 format!("the item `{}` is already {} here", ident, introduced),
564 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
565 stability::deprecation_suggestion(&mut db, suggestion, span)
567 BuiltinLintDiagnostics::UnusedDocComment(span) => {
568 db.span_label(span, "rustdoc does not generate documentation for macros");
569 db.help("to document an item produced by a macro, \
570 the macro must produce the documentation as part of its expansion");
573 // Rewrap `db`, and pass control to the user.
574 decorate(LintDiagnosticBuilder::new(db));
578 // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
579 // set the span in their `decorate` function (preferably using set_span).
580 fn lookup<S: Into<MultiSpan>>(
584 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
587 fn struct_span_lint<S: Into<MultiSpan>>(
591 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
593 self.lookup(lint, Some(span), decorate);
595 /// Emit a lint at the appropriate level, with no associated span.
596 fn lint(&self, lint: &'static Lint, decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>)) {
597 self.lookup(lint, None as Option<Span>, decorate);
601 impl<'a> EarlyContext<'a> {
604 lint_store: &'a LintStore,
605 krate: &'a ast::Crate,
606 buffered: LintBuffer,
607 warn_about_weird_lints: bool,
608 ) -> EarlyContext<'a> {
613 builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
619 impl LintContext for LateContext<'_, '_> {
620 type PassObject = LateLintPassObject;
622 /// Gets the overall compiler `Session` object.
623 fn sess(&self) -> &Session {
627 fn lints(&self) -> &LintStore {
631 fn lookup<S: Into<MultiSpan>>(
635 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
637 let hir_id = self.last_node_with_lint_attrs;
640 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
641 None => self.tcx.struct_lint_node(lint, hir_id, decorate),
646 impl LintContext for EarlyContext<'_> {
647 type PassObject = EarlyLintPassObject;
649 /// Gets the overall compiler `Session` object.
650 fn sess(&self) -> &Session {
654 fn lints(&self) -> &LintStore {
658 fn lookup<S: Into<MultiSpan>>(
662 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>),
664 self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
668 impl<'a, 'tcx> LateContext<'a, 'tcx> {
669 pub fn current_lint_root(&self) -> hir::HirId {
670 self.last_node_with_lint_attrs
673 /// Check if a `DefId`'s path matches the given absolute type path usage.
675 /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
676 /// inherent `impl` blocks are matched with the name of the type.
680 /// ```rust,ignore (no context or def id available)
681 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
682 /// // The given `def_id` is that of an `Option` type
685 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
686 let names = self.get_def_path(def_id);
688 names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
691 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
695 /// ```rust,ignore (no context or def id available)
696 /// let def_path = cx.get_def_path(def_id);
697 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
698 /// // The given `def_id` is that of an `Option` type
701 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
702 pub struct AbsolutePathPrinter<'tcx> {
703 pub tcx: TyCtxt<'tcx>,
706 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
709 type Path = Vec<Symbol>;
712 type DynExistential = ();
715 fn tcx(&self) -> TyCtxt<'tcx> {
719 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
723 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
727 fn print_dyn_existential(
729 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
730 ) -> Result<Self::DynExistential, Self::Error> {
734 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
738 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
739 Ok(vec![self.tcx.original_crate_name(cnum)])
745 trait_ref: Option<ty::TraitRef<'tcx>>,
746 ) -> Result<Self::Path, Self::Error> {
747 if trait_ref.is_none() {
748 if let ty::Adt(def, substs) = self_ty.kind {
749 return self.print_def_path(def.did, substs);
753 // This shouldn't ever be needed, but just in case:
754 Ok(vec![match trait_ref {
755 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
756 None => Symbol::intern(&format!("<{}>", self_ty)),
762 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
763 _disambiguated_data: &DisambiguatedDefPathData,
765 trait_ref: Option<ty::TraitRef<'tcx>>,
766 ) -> Result<Self::Path, Self::Error> {
767 let mut path = print_prefix(self)?;
769 // This shouldn't ever be needed, but just in case:
770 path.push(match trait_ref {
771 Some(trait_ref) => Symbol::intern(&format!(
773 trait_ref.print_only_trait_path(),
776 None => Symbol::intern(&format!("<impl {}>", self_ty)),
784 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
785 disambiguated_data: &DisambiguatedDefPathData,
786 ) -> Result<Self::Path, Self::Error> {
787 let mut path = print_prefix(self)?;
789 // Skip `::{{constructor}}` on tuple/unit structs.
790 match disambiguated_data.data {
791 DefPathData::Ctor => return Ok(path),
795 path.push(disambiguated_data.data.as_symbol());
799 fn path_generic_args(
801 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
802 _args: &[GenericArg<'tcx>],
803 ) -> Result<Self::Path, Self::Error> {
808 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
812 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
814 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
816 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
817 self.tcx.layout_of(self.param_env.and(ty))