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_errors::{struct_span_err, Applicability, DiagnosticBuilder};
31 use rustc_hir::def_id::{CrateNum, DefId};
32 use rustc_session::lint::BuiltinLintDiagnostics;
33 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
34 use rustc_session::Session;
35 use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP};
37 use syntax::util::lev_distance::find_best_match_for_name;
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 let Some(_) = tool_name {
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_and_emit<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: Option<S>, msg: &str) {
477 self.lookup(lint, span, msg).emit();
480 fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(
485 diagnostic: BuiltinLintDiagnostics,
487 let mut db = self.lookup(lint, span, msg);
489 let sess = self.sess();
491 BuiltinLintDiagnostics::Normal => (),
492 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
493 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
494 Ok(s) if is_global => {
495 (format!("dyn ({})", s), Applicability::MachineApplicable)
497 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
498 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
500 db.span_suggestion(span, "use `dyn`", sugg, app);
502 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
503 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
505 // FIXME(Manishearth) ideally the emitting code
506 // can tell us whether or not this is global
507 let opt_colon = 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(span_def) => {
522 db.span_note(span_def, "the macro is defined here");
524 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
531 add_elided_lifetime_in_path_suggestion(
541 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
542 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
544 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
545 if !replaces.is_empty() {
546 db.tool_only_multipart_suggestion(
549 Applicability::MachineApplicable,
553 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
554 for (span, is_imported) in spans {
555 let introduced = if is_imported { "imported" } else { "defined" };
558 format!("the item `{}` is already {} here", ident, introduced),
562 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
563 stability::deprecation_suggestion(&mut db, suggestion, span)
570 fn lookup<S: Into<MultiSpan>>(
575 ) -> DiagnosticBuilder<'_>;
577 /// Emit a lint at the appropriate level, for a particular span.
578 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
579 self.lookup_and_emit(lint, Some(span), msg);
582 fn struct_span_lint<S: Into<MultiSpan>>(
587 ) -> DiagnosticBuilder<'_> {
588 self.lookup(lint, Some(span), msg)
591 /// Emit a lint and note at the appropriate level, for a particular span.
600 let mut err = self.lookup(lint, Some(span), msg);
601 if note_span == span {
604 err.span_note(note_span, note);
609 /// Emit a lint and help at the appropriate level, for a particular span.
610 fn span_lint_help(&self, lint: &'static Lint, span: Span, msg: &str, help: &str) {
611 let mut err = self.lookup(lint, Some(span), msg);
612 self.span_lint(lint, span, msg);
613 err.span_help(span, help);
617 /// Emit a lint at the appropriate level, with no associated span.
618 fn lint(&self, lint: &'static Lint, msg: &str) {
619 self.lookup_and_emit(lint, None as Option<Span>, msg);
623 impl<'a> EarlyContext<'a> {
626 lint_store: &'a LintStore,
627 krate: &'a ast::Crate,
628 buffered: LintBuffer,
629 warn_about_weird_lints: bool,
630 ) -> EarlyContext<'a> {
635 builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
641 impl LintContext for LateContext<'_, '_> {
642 type PassObject = LateLintPassObject;
644 /// Gets the overall compiler `Session` object.
645 fn sess(&self) -> &Session {
649 fn lints(&self) -> &LintStore {
653 fn lookup<S: Into<MultiSpan>>(
658 ) -> DiagnosticBuilder<'_> {
659 let hir_id = self.last_node_with_lint_attrs;
662 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg),
663 None => self.tcx.struct_lint_node(lint, hir_id, msg),
668 impl LintContext for EarlyContext<'_> {
669 type PassObject = EarlyLintPassObject;
671 /// Gets the overall compiler `Session` object.
672 fn sess(&self) -> &Session {
676 fn lints(&self) -> &LintStore {
680 fn lookup<S: Into<MultiSpan>>(
685 ) -> DiagnosticBuilder<'_> {
686 self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
690 impl<'a, 'tcx> LateContext<'a, 'tcx> {
691 pub fn current_lint_root(&self) -> hir::HirId {
692 self.last_node_with_lint_attrs
695 /// Check if a `DefId`'s path matches the given absolute type path usage.
697 /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
698 /// inherent `impl` blocks are matched with the name of the type.
702 /// ```rust,ignore (no context or def id available)
703 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
704 /// // The given `def_id` is that of an `Option` type
707 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
708 let names = self.get_def_path(def_id);
710 names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
713 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
717 /// ```rust,ignore (no context or def id available)
718 /// let def_path = cx.get_def_path(def_id);
719 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
720 /// // The given `def_id` is that of an `Option` type
723 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
724 pub struct AbsolutePathPrinter<'tcx> {
725 pub tcx: TyCtxt<'tcx>,
728 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
731 type Path = Vec<Symbol>;
734 type DynExistential = ();
737 fn tcx(&self) -> TyCtxt<'tcx> {
741 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
745 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
749 fn print_dyn_existential(
751 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
752 ) -> Result<Self::DynExistential, Self::Error> {
756 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
760 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
761 Ok(vec![self.tcx.original_crate_name(cnum)])
767 trait_ref: Option<ty::TraitRef<'tcx>>,
768 ) -> Result<Self::Path, Self::Error> {
769 if trait_ref.is_none() {
770 if let ty::Adt(def, substs) = self_ty.kind {
771 return self.print_def_path(def.did, substs);
775 // This shouldn't ever be needed, but just in case:
776 Ok(vec![match trait_ref {
777 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
778 None => Symbol::intern(&format!("<{}>", self_ty)),
784 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
785 _disambiguated_data: &DisambiguatedDefPathData,
787 trait_ref: Option<ty::TraitRef<'tcx>>,
788 ) -> Result<Self::Path, Self::Error> {
789 let mut path = print_prefix(self)?;
791 // This shouldn't ever be needed, but just in case:
792 path.push(match trait_ref {
793 Some(trait_ref) => Symbol::intern(&format!(
795 trait_ref.print_only_trait_path(),
798 None => Symbol::intern(&format!("<impl {}>", self_ty)),
806 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
807 disambiguated_data: &DisambiguatedDefPathData,
808 ) -> Result<Self::Path, Self::Error> {
809 let mut path = print_prefix(self)?;
811 // Skip `::{{constructor}}` on tuple/unit structs.
812 match disambiguated_data.data {
813 DefPathData::Ctor => return Ok(path),
817 path.push(disambiguated_data.data.as_symbol());
821 fn path_generic_args(
823 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
824 _args: &[GenericArg<'tcx>],
825 ) -> Result<Self::Path, Self::Error> {
830 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
834 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
836 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
838 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
839 self.tcx.layout_of(self.param_env.and(ty))