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 CheckNameDeprecated, CheckNameUnknown, CheckNameUnknownTool, CheckNameWarning, RequestedLevel,
23 use crate::levels::LintLevelsBuilder;
24 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
25 use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS;
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::sync;
28 use rustc_errors::add_elided_lifetime_in_path_suggestion;
30 Applicability, DecorateLint, LintDiagnosticBuilder, MultiSpan, SuggestionStyle,
33 use rustc_hir::def::Res;
34 use rustc_hir::def_id::{CrateNum, DefId};
35 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
36 use rustc_middle::middle::privacy::AccessLevels;
37 use rustc_middle::middle::stability;
38 use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout};
39 use rustc_middle::ty::print::with_no_trimmed_paths;
40 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, RegisteredTools, Ty, TyCtxt};
41 use rustc_session::lint::{BuiltinLintDiagnostics, LintExpectationId};
42 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
43 use rustc_session::Session;
44 use rustc_span::lev_distance::find_best_match_for_name;
45 use rustc_span::symbol::{sym, Ident, Symbol};
46 use rustc_span::{BytePos, Span};
47 use rustc_target::abi;
53 /// Information about the registered lints.
55 /// This is basically the subset of `Context` that we can
56 /// build early in the compile pipeline.
57 pub struct LintStore {
59 lints: Vec<&'static Lint>,
61 /// Constructor functions for each variety of lint pass.
63 /// These should only be called once, but since we want to avoid locks or
64 /// interior mutability, we don't enforce this (and lints should, in theory,
65 /// be compatible with being constructed more than once, though not
66 /// necessarily in a sane manner. This is safe though.)
67 pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
68 pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
69 pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
70 /// This is unique in that we construct them per-module, so not once.
71 pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
73 /// Lints indexed by name.
74 by_name: FxHashMap<String, TargetLint>,
76 /// Map of registered lint groups to what lints they expand to.
77 lint_groups: FxHashMap<&'static str, LintGroup>,
80 /// The target of the `by_name` map, which accounts for renaming/deprecation.
83 /// A direct lint target
86 /// Temporary renaming, used for easing migration pain; see #16545
87 Renamed(String, LintId),
89 /// Lint with this name existed previously, but has been removed/deprecated.
90 /// The string argument is the reason for removal.
93 /// A lint name that should give no warnings and have no effect.
95 /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
99 pub enum FindLintError {
106 /// Whether deprecation warnings should be suppressed for this alias.
111 lint_ids: Vec<LintId>,
113 depr: Option<LintAlias>,
117 pub enum CheckLintNameResult<'a> {
119 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
120 NoLint(Option<Symbol>),
121 /// The lint refers to a tool that has not been registered.
123 /// The lint is either renamed or removed. This is the warning
124 /// message, and an optional new name (`None` if removed).
125 Warning(String, Option<String>),
126 /// The lint is from a tool. If the Option is None, then either
127 /// the lint does not exist in the tool or the code was not
128 /// compiled with the tool and therefore the lint was never
129 /// added to the `LintStore`. Otherwise the `LintId` will be
130 /// returned as if it where a rustc lint.
131 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
135 pub fn new() -> LintStore {
138 pre_expansion_passes: vec![],
139 early_passes: vec![],
141 late_module_passes: vec![],
142 by_name: Default::default(),
143 lint_groups: Default::default(),
147 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
151 pub fn get_lint_groups<'t>(
153 ) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> + 't {
154 // This function is not used in a way which observes the order of lints.
155 #[allow(rustc::potential_query_instability)]
158 .filter(|(_, LintGroup { depr, .. })| {
159 // Don't display deprecated lint groups.
162 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
163 (*k, lint_ids.clone(), *from_plugin)
167 pub fn register_early_pass(
169 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
171 self.early_passes.push(Box::new(pass));
174 /// This lint pass is softly deprecated. It misses expanded code and has caused a few
175 /// errors in the past. Currently, it is only used in Clippy. New implementations
176 /// should avoid using this interface, as it might be removed in the future.
178 /// * See [rust#69838](https://github.com/rust-lang/rust/pull/69838)
179 /// * See [rust-clippy#5518](https://github.com/rust-lang/rust-clippy/pull/5518)
180 pub fn register_pre_expansion_pass(
182 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
184 self.pre_expansion_passes.push(Box::new(pass));
187 pub fn register_late_pass(
189 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
191 self.late_passes.push(Box::new(pass));
194 pub fn register_late_mod_pass(
196 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
198 self.late_module_passes.push(Box::new(pass));
201 // Helper method for register_early/late_pass
202 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
204 self.lints.push(lint);
206 let id = LintId::of(lint);
207 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
208 bug!("duplicate specification of lint {}", lint.name_lower())
211 if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
212 if let Some(edition) = reason.edition() {
214 .entry(edition.lint_name())
215 .or_insert(LintGroup {
217 from_plugin: lint.is_plugin,
223 // Lints belonging to the `future_incompatible` lint group are lints where a
224 // future version of rustc will cause existing code to stop compiling.
225 // Lints tied to an edition don't count because they are opt-in.
227 .entry("future_incompatible")
228 .or_insert(LintGroup {
230 from_plugin: lint.is_plugin,
240 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
241 self.lint_groups.insert(
246 depr: Some(LintAlias { name: lint_name, silent: true }),
251 pub fn register_group(
255 deprecated_name: Option<&'static str>,
260 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
262 if let Some(deprecated) = deprecated_name {
263 self.lint_groups.insert(
268 depr: Some(LintAlias { name, silent: false }),
274 bug!("duplicate specification of lint group {}", name);
278 /// This lint should give no warning and have no effect.
280 /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
282 pub fn register_ignored(&mut self, name: &str) {
283 if self.by_name.insert(name.to_string(), Ignored).is_some() {
284 bug!("duplicate specification of lint {}", name);
288 /// This lint has been renamed; warn about using the new name and apply the lint.
290 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
291 let Some(&Id(target)) = self.by_name.get(new_name) else {
292 bug!("invalid lint renaming of {} to {}", old_name, new_name);
294 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
297 pub fn register_removed(&mut self, name: &str, reason: &str) {
298 self.by_name.insert(name.into(), Removed(reason.into()));
301 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
302 match self.by_name.get(lint_name) {
303 Some(&Id(lint_id)) => Ok(vec![lint_id]),
304 Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
305 Some(&Removed(_)) => Err(FindLintError::Removed),
306 Some(&Ignored) => Ok(vec![]),
308 return match self.lint_groups.get(lint_name) {
309 Some(LintGroup { lint_ids, depr, .. }) => {
310 if let Some(LintAlias { name, .. }) = depr {
316 None => Err(FindLintError::Removed),
322 /// Checks the validity of lint names derived from the command line.
323 pub fn check_lint_name_cmdline(
328 registered_tools: &RegisteredTools,
330 let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
331 if lint_name_only == crate::WARNINGS.name_lower() && matches!(level, Level::ForceWarn(_)) {
332 sess.emit_err(UnsupportedGroup { lint_group: crate::WARNINGS.name_lower() });
335 let lint_name = lint_name.to_string();
336 match self.check_lint_name(lint_name_only, tool_name, registered_tools) {
337 CheckLintNameResult::Warning(msg, _) => {
338 sess.emit_warning(CheckNameWarning {
340 sub: RequestedLevel { level, lint_name },
343 CheckLintNameResult::NoLint(suggestion) => {
344 sess.emit_err(CheckNameUnknown {
345 lint_name: lint_name.clone(),
347 sub: RequestedLevel { level, lint_name },
350 CheckLintNameResult::Tool(result) => {
351 if let Err((Some(_), new_name)) = result {
352 sess.emit_warning(CheckNameDeprecated {
353 lint_name: lint_name.clone(),
355 sub: RequestedLevel { level, lint_name },
359 CheckLintNameResult::NoTool => {
360 sess.emit_err(CheckNameUnknownTool {
361 tool_name: tool_name.unwrap(),
362 sub: RequestedLevel { level, lint_name },
369 /// True if this symbol represents a lint group name.
370 pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
372 "is_lint_group(lint_name={:?}, lint_groups={:?})",
374 self.lint_groups.keys().collect::<Vec<_>>()
376 let lint_name_str = lint_name.as_str();
377 self.lint_groups.contains_key(lint_name_str) || {
378 let warnings_name_str = crate::WARNINGS.name_lower();
379 lint_name_str == warnings_name_str
383 /// Checks the name of a lint for its existence, and whether it was
384 /// renamed or removed. Generates a DiagnosticBuilder containing a
385 /// warning for renamed and removed lints. This is over both lint
386 /// names from attributes and those passed on the command line. Since
387 /// it emits non-fatal warnings and there are *two* lint passes that
388 /// inspect attributes, this is only run from the late pass to avoid
389 /// printing duplicate warnings.
390 pub fn check_lint_name(
393 tool_name: Option<Symbol>,
394 registered_tools: &RegisteredTools,
395 ) -> CheckLintNameResult<'_> {
396 if let Some(tool_name) = tool_name {
397 // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
398 if tool_name != sym::rustc
399 && tool_name != sym::rustdoc
400 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
402 return CheckLintNameResult::NoTool;
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) = tool_name {
413 match self.by_name.get(&complete_name) {
414 None => match self.lint_groups.get(&*complete_name) {
415 // If the lint isn't registered, there are two possibilities:
417 // 1. The tool is currently running, so this lint really doesn't exist.
418 // FIXME: should this handle tools that never register a lint, like rustfmt?
419 debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
420 let tool_prefix = format!("{}::", tool_name);
421 return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
422 self.no_lint_suggestion(&complete_name)
424 // 2. The tool isn't currently running, so no lints will be registered.
425 // To avoid giving a false positive, ignore all unknown lints.
426 CheckLintNameResult::Tool(Err((None, String::new())))
429 Some(LintGroup { lint_ids, .. }) => {
430 return CheckLintNameResult::Tool(Ok(&lint_ids));
433 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
434 // If the lint was registered as removed or renamed by the lint tool, we don't need
435 // to treat tool_lints and rustc lints different and can use the code below.
439 match self.by_name.get(&complete_name) {
440 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
441 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
442 Some(new_name.to_owned()),
444 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
445 format!("lint `{}` has been removed: {}", complete_name, reason),
448 None => match self.lint_groups.get(&*complete_name) {
449 // If neither the lint, nor the lint group exists check if there is a `clippy::`
450 // variant of this lint
451 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
452 Some(LintGroup { lint_ids, depr, .. }) => {
453 // Check if the lint group name is deprecated
454 if let Some(LintAlias { name, silent }) = depr {
455 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
457 CheckLintNameResult::Ok(&lint_ids)
459 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
462 CheckLintNameResult::Ok(&lint_ids)
465 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
466 Some(&Ignored) => CheckLintNameResult::Ok(&[]),
470 fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
471 let name_lower = lint_name.to_lowercase();
473 if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
474 // First check if the lint name is (partly) in upper case instead of lower case...
475 return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
477 // ...if not, search for lints with a similar name
478 let groups = self.lint_groups.keys().copied().map(Symbol::intern);
479 let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
480 let names: Vec<Symbol> = groups.chain(lints).collect();
481 let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
482 CheckLintNameResult::NoLint(suggestion)
485 fn check_tool_name_for_backwards_compat(
489 ) -> CheckLintNameResult<'_> {
490 let complete_name = format!("{}::{}", tool_name, lint_name);
491 match self.by_name.get(&complete_name) {
492 None => match self.lint_groups.get(&*complete_name) {
493 // Now we are sure, that this lint exists nowhere
494 None => self.no_lint_suggestion(lint_name),
495 Some(LintGroup { lint_ids, depr, .. }) => {
496 // Reaching this would be weird, but let's cover this case anyway
497 if let Some(LintAlias { name, silent }) = depr {
498 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
500 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
502 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
505 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
508 Some(&Id(ref id)) => {
509 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
512 debug!("got renamed lint {:?}", other);
513 CheckLintNameResult::NoLint(None)
519 /// Context for lint checking outside of type inference.
520 pub struct LateContext<'tcx> {
521 /// Type context we're checking in.
522 pub tcx: TyCtxt<'tcx>,
524 /// Current body, or `None` if outside a body.
525 pub enclosing_body: Option<hir::BodyId>,
527 /// Type-checking results for the current body. Access using the `typeck_results`
528 /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
529 // FIXME(eddyb) move all the code accessing internal fields like this,
530 // to this module, to avoid exposing it to lint logic.
531 pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
533 /// Parameter environment for the item we are in.
534 pub param_env: ty::ParamEnv<'tcx>,
536 /// Items accessible from the crate being checked.
537 pub access_levels: &'tcx AccessLevels,
539 /// The store of registered lints and the lint levels.
540 pub lint_store: &'tcx LintStore,
542 pub last_node_with_lint_attrs: hir::HirId,
544 /// Generic type parameters in scope for the item we are in.
545 pub generics: Option<&'tcx hir::Generics<'tcx>>,
547 /// We are only looking at one module
548 pub only_module: bool,
551 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
552 pub struct EarlyContext<'a> {
553 pub builder: LintLevelsBuilder<'a>,
554 pub buffered: LintBuffer,
557 pub trait LintPassObject: Sized {}
559 impl LintPassObject for EarlyLintPassObject {}
561 impl LintPassObject for LateLintPassObject {}
563 pub trait LintContext: Sized {
564 type PassObject: LintPassObject;
566 fn sess(&self) -> &Session;
567 fn lints(&self) -> &LintStore;
569 fn lookup_with_diagnostics(
572 span: Option<impl Into<MultiSpan>>,
573 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
574 diagnostic: BuiltinLintDiagnostics,
576 self.lookup(lint, span, |lint| {
577 // We first generate a blank diagnostic.
578 let mut db = lint.build("");
580 // Now, set up surrounding context.
581 let sess = self.sess();
583 BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
584 let spans: Vec<_> = content
586 .filter_map(|(i, c)| {
587 TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
588 let lo = span.lo() + BytePos(2 + i as u32);
589 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
593 let (an, s) = match spans.len() {
597 db.span_label(span, &format!(
598 "this comment contains {}invisible unicode text flow control codepoint{}",
602 for (c, span) in &spans {
603 db.span_label(*span, format!("{:?}", c));
606 "these kind of unicode codepoints change the way text flows on \
607 applications that support them, but can cause confusion because they \
608 change the order of characters on the screen",
610 if !spans.is_empty() {
611 db.multipart_suggestion_with_style(
612 "if their presence wasn't intentional, you can remove them",
613 spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
614 Applicability::MachineApplicable,
615 SuggestionStyle::HideCodeAlways,
619 BuiltinLintDiagnostics::Normal => (),
620 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
621 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
623 // FIXME(Manishearth) ideally the emitting code
624 // can tell us whether or not this is global
626 if s.trim_start().starts_with("::") { "" } else { "::" };
628 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
630 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
632 db.span_suggestion(span, "use `crate`", sugg, app);
634 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
637 "names from parent modules are not accessible without an explicit import",
640 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
643 db.span_note(span_def, "the macro is defined here");
645 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
651 add_elided_lifetime_in_path_suggestion(
660 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
661 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
663 BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
664 if !replaces.is_empty() {
665 db.tool_only_multipart_suggestion(
668 Applicability::MachineApplicable,
672 if let Some(span) = in_test_module {
674 self.sess().source_map().guess_head_span(span),
675 "consider adding a `#[cfg(test)]` to the containing module",
679 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
680 for (span, is_imported) in spans {
681 let introduced = if is_imported { "imported" } else { "defined" };
684 format!("the item `{}` is already {} here", ident, introduced),
688 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
689 stability::deprecation_suggestion(&mut db, "macro", suggestion, span)
691 BuiltinLintDiagnostics::UnusedDocComment(span) => {
692 db.span_label(span, "rustdoc does not generate documentation for macro invocations");
693 db.help("to document an item produced by a macro, \
694 the macro must produce the documentation as part of its expansion");
696 BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
697 db.span_suggestion(span, "remove `mut` from the parameter", ident, Applicability::MachineApplicable);
699 BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
700 db.span_label(span, "ABI should be specified here");
701 db.help(&format!("the default ABI is {}", default_abi.name()));
703 BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
704 db.span_label(span, "the attribute is introduced here");
706 BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
709 BuiltinLintDiagnostics::OrPatternsBackCompat(span,suggestion) => {
710 db.span_suggestion(span, "use pat_param to preserve semantics", suggestion, Applicability::MachineApplicable);
712 BuiltinLintDiagnostics::ReservedPrefix(span) => {
713 db.span_label(span, "unknown prefix");
714 db.span_suggestion_verbose(
716 "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
718 Applicability::MachineApplicable,
721 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
728 &format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
731 BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
733 db.note("macro invocations at the end of a block are treated as expressions");
734 db.note(&format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
737 BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
738 db.multipart_suggestion(
739 "wrap this expression in parentheses",
740 vec![(span.shrink_to_lo(), "(".to_string()),
741 (span.shrink_to_hi(), ")".to_string())],
742 Applicability::MachineApplicable
745 BuiltinLintDiagnostics::NamedAsmLabel(help) => {
747 db.note("see the asm section of Rust By Example <https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels> for more information");
749 BuiltinLintDiagnostics::UnexpectedCfg((name, name_span), None) => {
750 let Some(names_valid) = &sess.parse_sess.check_config.names_valid else {
751 bug!("it shouldn't be possible to have a diagnostic on a name if name checking is not enabled");
753 let possibilities: Vec<Symbol> = names_valid.iter().map(|s| *s).collect();
755 // Suggest the most probable if we found one
756 if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) {
757 db.span_suggestion(name_span, "did you mean", best_match, Applicability::MaybeIncorrect);
760 BuiltinLintDiagnostics::UnexpectedCfg((name, name_span), Some((value, value_span))) => {
761 let Some(values) = &sess.parse_sess.check_config.values_valid.get(&name) else {
762 bug!("it shouldn't be possible to have a diagnostic on a value whose name is not in values");
764 let possibilities: Vec<Symbol> = values.iter().map(|&s| s).collect();
766 // Show the full list if all possible values for a given name, but don't do it
767 // for names as the possibilities could be very long
768 if !possibilities.is_empty() {
770 let mut possibilities = possibilities.iter().map(Symbol::as_str).collect::<Vec<_>>();
771 possibilities.sort();
773 let possibilities = possibilities.join(", ");
774 db.note(&format!("expected values for `{name}` are: {possibilities}"));
777 // Suggest the most probable if we found one
778 if let Some(best_match) = find_best_match_for_name(&possibilities, value, None) {
779 db.span_suggestion(value_span, "did you mean", format!("\"{best_match}\""), Applicability::MaybeIncorrect);
782 db.note(&format!("no expected value for `{name}`"));
783 if name != sym::feature {
784 db.span_suggestion(name_span.shrink_to_hi().to(value_span), "remove the value", "", Applicability::MaybeIncorrect);
788 BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(new_span, suggestion) => {
789 db.multipart_suggestion(
790 "move it to the end of the type declaration",
791 vec![(db.span.primary_span().unwrap(), "".to_string()), (new_span, suggestion)],
792 Applicability::MachineApplicable,
795 "see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information",
798 BuiltinLintDiagnostics::SingleUseLifetime {
800 use_span: Some((use_span, elide)),
803 debug!(?param_span, ?use_span, ?deletion_span);
804 db.span_label(param_span, "this lifetime...");
805 db.span_label(use_span, "...is used only here");
806 let msg = "elide the single-use lifetime";
807 let (use_span, replace_lt) = if elide {
808 let use_span = sess.source_map().span_extend_while(
811 ).unwrap_or(use_span);
812 (use_span, String::new())
814 (use_span, "'_".to_owned())
816 db.multipart_suggestion(
818 vec![(deletion_span, String::new()), (use_span, replace_lt)],
819 Applicability::MachineApplicable,
822 BuiltinLintDiagnostics::SingleUseLifetime {
827 debug!(?deletion_span);
830 "elide the unused lifetime",
832 Applicability::MachineApplicable,
835 BuiltinLintDiagnostics::NamedArgumentUsedPositionally{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => {
836 db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string");
837 if let Some(positional_arg_for_msg) = position_sp_for_msg {
838 let msg = format!("this formatting argument uses named argument `{}` by position", named_arg_name);
839 db.span_label(positional_arg_for_msg, msg);
842 if let Some(positional_arg_to_replace) = position_sp_to_replace {
843 let name = if is_formatting_arg { named_arg_name + "$" } else { named_arg_name };
844 let span_to_replace = if let Ok(positional_arg_content) =
845 self.sess().source_map().span_to_snippet(positional_arg_to_replace) && positional_arg_content.starts_with(":") {
846 positional_arg_to_replace.shrink_to_lo()
848 positional_arg_to_replace
850 db.span_suggestion_verbose(
852 "use the named argument by name to avoid ambiguity",
854 Applicability::MaybeIncorrect,
859 // Rewrap `db`, and pass control to the user.
860 decorate(LintDiagnosticBuilder::new(db));
864 // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
865 // set the span in their `decorate` function (preferably using set_span).
866 fn lookup<S: Into<MultiSpan>>(
870 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
873 /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
874 /// typically generated by `#[derive(LintDiagnostic)]`).
875 fn emit_spanned_lint<S: Into<MultiSpan>>(
879 decorator: impl for<'a> DecorateLint<'a, ()>,
881 self.lookup(lint, Some(span), |diag| decorator.decorate_lint(diag));
884 fn struct_span_lint<S: Into<MultiSpan>>(
888 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
890 self.lookup(lint, Some(span), decorate);
893 /// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
894 /// generated by `#[derive(LintDiagnostic)]`).
895 fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> DecorateLint<'a, ()>) {
896 self.lookup(lint, None as Option<Span>, |diag| decorator.decorate_lint(diag));
899 /// Emit a lint at the appropriate level, with no associated span.
903 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
905 self.lookup(lint, None as Option<Span>, decorate);
908 /// This returns the lint level for the given lint at the current location.
909 fn get_lint_level(&self, lint: &'static Lint) -> Level;
911 /// This function can be used to manually fulfill an expectation. This can
912 /// be used for lints which contain several spans, and should be suppressed,
913 /// if either location was marked with an expectation.
915 /// Note that this function should only be called for [`LintExpectationId`]s
916 /// retrieved from the current lint pass. Buffered or manually created ids can
918 fn fulfill_expectation(&self, expectation: LintExpectationId) {
919 // We need to make sure that submitted expectation ids are correctly fulfilled suppressed
920 // and stored between compilation sessions. To not manually do these steps, we simply create
921 // a dummy diagnostic and emit is as usual, which will be suppressed and stored like a normal
922 // expected lint diagnostic.
925 "this is a dummy diagnostic, to submit and store an expectation",
932 impl<'a> EarlyContext<'a> {
935 warn_about_weird_lints: bool,
936 lint_store: &'a LintStore,
937 registered_tools: &'a RegisteredTools,
938 buffered: LintBuffer,
939 ) -> EarlyContext<'a> {
941 builder: LintLevelsBuilder::new(
943 warn_about_weird_lints,
952 impl LintContext for LateContext<'_> {
953 type PassObject = LateLintPassObject;
955 /// Gets the overall compiler `Session` object.
956 fn sess(&self) -> &Session {
960 fn lints(&self) -> &LintStore {
964 fn lookup<S: Into<MultiSpan>>(
968 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
970 let hir_id = self.last_node_with_lint_attrs;
973 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, decorate),
974 None => self.tcx.struct_lint_node(lint, hir_id, decorate),
978 fn get_lint_level(&self, lint: &'static Lint) -> Level {
979 self.tcx.lint_level_at_node(lint, self.last_node_with_lint_attrs).0
983 impl LintContext for EarlyContext<'_> {
984 type PassObject = EarlyLintPassObject;
986 /// Gets the overall compiler `Session` object.
987 fn sess(&self) -> &Session {
991 fn lints(&self) -> &LintStore {
992 self.builder.lint_store()
995 fn lookup<S: Into<MultiSpan>>(
999 decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>),
1001 self.builder.struct_lint(lint, span.map(|s| s.into()), decorate)
1004 fn get_lint_level(&self, lint: &'static Lint) -> Level {
1005 self.builder.lint_level(lint).0
1009 impl<'tcx> LateContext<'tcx> {
1010 /// Gets the type-checking results for the current body,
1011 /// or `None` if outside a body.
1012 pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
1013 self.cached_typeck_results.get().or_else(|| {
1014 self.enclosing_body.map(|body| {
1015 let typeck_results = self.tcx.typeck_body(body);
1016 self.cached_typeck_results.set(Some(typeck_results));
1022 /// Gets the type-checking results for the current body.
1023 /// As this will ICE if called outside bodies, only call when working with
1024 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1026 pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1027 self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
1030 /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
1031 /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
1032 /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
1033 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
1035 hir::QPath::Resolved(_, ref path) => path.res,
1036 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1037 .maybe_typeck_results()
1038 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
1040 if self.tcx.has_typeck_results(id.owner.to_def_id()) {
1041 Some(self.tcx.typeck(id.owner))
1046 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
1047 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
1051 /// Check if a `DefId`'s path matches the given absolute type path usage.
1053 /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
1054 /// inherent `impl` blocks are matched with the name of the type.
1056 /// Instead of using this method, it is often preferable to instead use
1057 /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
1058 /// as paths get invalidated if the target definition moves.
1062 /// ```rust,ignore (no context or def id available)
1063 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
1064 /// // The given `def_id` is that of an `Option` type
1068 /// Used by clippy, but should be replaced by diagnostic items eventually.
1069 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
1070 let names = self.get_def_path(def_id);
1072 names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
1075 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
1079 /// ```rust,ignore (no context or def id available)
1080 /// let def_path = cx.get_def_path(def_id);
1081 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
1082 /// // The given `def_id` is that of an `Option` type
1085 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
1086 pub struct AbsolutePathPrinter<'tcx> {
1087 pub tcx: TyCtxt<'tcx>,
1090 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
1093 type Path = Vec<Symbol>;
1096 type DynExistential = ();
1099 fn tcx(&self) -> TyCtxt<'tcx> {
1103 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1107 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1111 fn print_dyn_existential(
1113 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1114 ) -> Result<Self::DynExistential, Self::Error> {
1118 fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1122 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1123 Ok(vec![self.tcx.crate_name(cnum)])
1129 trait_ref: Option<ty::TraitRef<'tcx>>,
1130 ) -> Result<Self::Path, Self::Error> {
1131 if trait_ref.is_none() {
1132 if let ty::Adt(def, substs) = self_ty.kind() {
1133 return self.print_def_path(def.did(), substs);
1137 // This shouldn't ever be needed, but just in case:
1138 with_no_trimmed_paths!({
1139 Ok(vec![match trait_ref {
1140 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1141 None => Symbol::intern(&format!("<{}>", self_ty)),
1146 fn path_append_impl(
1148 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1149 _disambiguated_data: &DisambiguatedDefPathData,
1151 trait_ref: Option<ty::TraitRef<'tcx>>,
1152 ) -> Result<Self::Path, Self::Error> {
1153 let mut path = print_prefix(self)?;
1155 // This shouldn't ever be needed, but just in case:
1156 path.push(match trait_ref {
1157 Some(trait_ref) => {
1158 with_no_trimmed_paths!(Symbol::intern(&format!(
1160 trait_ref.print_only_trait_path(),
1165 with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
1174 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1175 disambiguated_data: &DisambiguatedDefPathData,
1176 ) -> Result<Self::Path, Self::Error> {
1177 let mut path = print_prefix(self)?;
1179 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1180 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1184 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1188 fn path_generic_args(
1190 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1191 _args: &[GenericArg<'tcx>],
1192 ) -> Result<Self::Path, Self::Error> {
1197 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1201 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1203 fn data_layout(&self) -> &abi::TargetDataLayout {
1204 &self.tcx.data_layout
1208 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1210 fn tcx(&self) -> TyCtxt<'tcx> {
1215 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1217 fn param_env(&self) -> ty::ParamEnv<'tcx> {
1222 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1223 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1226 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1231 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1232 match lint_name.split_once("::") {
1233 Some((tool_name, lint_name)) => {
1234 let tool_name = Symbol::intern(tool_name);
1236 (Some(tool_name), lint_name)
1238 None => (None, lint_name),