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, DiagnosticBuilder, DiagnosticMessage};
29 use rustc_errors::{Applicability, DecorateLint, MultiSpan, SuggestionStyle};
31 use rustc_hir::def::Res;
32 use rustc_hir::def_id::{CrateNum, DefId};
33 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
34 use rustc_middle::middle::privacy::EffectiveVisibilities;
35 use rustc_middle::middle::stability;
36 use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout};
37 use rustc_middle::ty::print::with_no_trimmed_paths;
38 use rustc_middle::ty::{self, print::Printer, subst::GenericArg, RegisteredTools, Ty, TyCtxt};
39 use rustc_session::lint::{BuiltinLintDiagnostics, LintExpectationId};
40 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
41 use rustc_session::Session;
42 use rustc_span::lev_distance::find_best_match_for_name;
43 use rustc_span::symbol::{sym, Ident, Symbol};
44 use rustc_span::{BytePos, Span};
45 use rustc_target::abi;
51 type EarlyLintPassFactory = dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync;
52 type LateLintPassFactory =
53 dyn for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx> + sync::Send + sync::Sync;
55 /// Information about the registered lints.
57 /// This is basically the subset of `Context` that we can
58 /// build early in the compile pipeline.
59 pub struct LintStore {
61 lints: Vec<&'static Lint>,
63 /// Constructor functions for each variety of lint pass.
65 /// These should only be called once, but since we want to avoid locks or
66 /// interior mutability, we don't enforce this (and lints should, in theory,
67 /// be compatible with being constructed more than once, though not
68 /// necessarily in a sane manner. This is safe though.)
69 pub pre_expansion_passes: Vec<Box<EarlyLintPassFactory>>,
70 pub early_passes: Vec<Box<EarlyLintPassFactory>>,
71 pub late_passes: Vec<Box<LateLintPassFactory>>,
72 /// This is unique in that we construct them per-module, so not once.
73 pub late_module_passes: Vec<Box<LateLintPassFactory>>,
75 /// Lints indexed by name.
76 by_name: FxHashMap<String, TargetLint>,
78 /// Map of registered lint groups to what lints they expand to.
79 lint_groups: FxHashMap<&'static str, LintGroup>,
82 /// The target of the `by_name` map, which accounts for renaming/deprecation.
85 /// A direct lint target
88 /// Temporary renaming, used for easing migration pain; see #16545
89 Renamed(String, LintId),
91 /// Lint with this name existed previously, but has been removed/deprecated.
92 /// The string argument is the reason for removal.
95 /// A lint name that should give no warnings and have no effect.
97 /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
101 pub enum FindLintError {
108 /// Whether deprecation warnings should be suppressed for this alias.
113 lint_ids: Vec<LintId>,
115 depr: Option<LintAlias>,
119 pub enum CheckLintNameResult<'a> {
121 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
122 NoLint(Option<Symbol>),
123 /// The lint refers to a tool that has not been registered.
125 /// The lint is either renamed or removed. This is the warning
126 /// message, and an optional new name (`None` if removed).
127 Warning(String, Option<String>),
128 /// The lint is from a tool. If the Option is None, then either
129 /// the lint does not exist in the tool or the code was not
130 /// compiled with the tool and therefore the lint was never
131 /// added to the `LintStore`. Otherwise the `LintId` will be
132 /// returned as if it where a rustc lint.
133 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
137 pub fn new() -> LintStore {
140 pre_expansion_passes: vec![],
141 early_passes: vec![],
143 late_module_passes: vec![],
144 by_name: Default::default(),
145 lint_groups: Default::default(),
149 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
153 pub fn get_lint_groups<'t>(
155 ) -> impl Iterator<Item = (&'static str, Vec<LintId>, bool)> + 't {
156 // This function is not used in a way which observes the order of lints.
157 #[allow(rustc::potential_query_instability)]
160 .filter(|(_, LintGroup { depr, .. })| {
161 // Don't display deprecated lint groups.
164 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
165 (*k, lint_ids.clone(), *from_plugin)
169 pub fn register_early_pass(
171 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
173 self.early_passes.push(Box::new(pass));
176 /// This lint pass is softly deprecated. It misses expanded code and has caused a few
177 /// errors in the past. Currently, it is only used in Clippy. New implementations
178 /// should avoid using this interface, as it might be removed in the future.
180 /// * See [rust#69838](https://github.com/rust-lang/rust/pull/69838)
181 /// * See [rust-clippy#5518](https://github.com/rust-lang/rust-clippy/pull/5518)
182 pub fn register_pre_expansion_pass(
184 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
186 self.pre_expansion_passes.push(Box::new(pass));
189 pub fn register_late_pass(
191 pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
196 self.late_passes.push(Box::new(pass));
199 pub fn register_late_mod_pass(
201 pass: impl for<'tcx> Fn(TyCtxt<'tcx>) -> LateLintPassObject<'tcx>
206 self.late_module_passes.push(Box::new(pass));
209 // Helper method for register_early/late_pass
210 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
212 self.lints.push(lint);
214 let id = LintId::of(lint);
215 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
216 bug!("duplicate specification of lint {}", lint.name_lower())
219 if let Some(FutureIncompatibleInfo { reason, .. }) = lint.future_incompatible {
220 if let Some(edition) = reason.edition() {
222 .entry(edition.lint_name())
223 .or_insert(LintGroup {
225 from_plugin: lint.is_plugin,
231 // Lints belonging to the `future_incompatible` lint group are lints where a
232 // future version of rustc will cause existing code to stop compiling.
233 // Lints tied to an edition don't count because they are opt-in.
235 .entry("future_incompatible")
236 .or_insert(LintGroup {
238 from_plugin: lint.is_plugin,
248 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
249 self.lint_groups.insert(
254 depr: Some(LintAlias { name: lint_name, silent: true }),
259 pub fn register_group(
263 deprecated_name: Option<&'static str>,
268 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
270 if let Some(deprecated) = deprecated_name {
271 self.lint_groups.insert(
276 depr: Some(LintAlias { name, silent: false }),
282 bug!("duplicate specification of lint group {}", name);
286 /// This lint should give no warning and have no effect.
288 /// This is used by rustc to avoid warning about old rustdoc lints before rustdoc registers them as tool lints.
290 pub fn register_ignored(&mut self, name: &str) {
291 if self.by_name.insert(name.to_string(), Ignored).is_some() {
292 bug!("duplicate specification of lint {}", name);
296 /// This lint has been renamed; warn about using the new name and apply the lint.
298 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
299 let Some(&Id(target)) = self.by_name.get(new_name) else {
300 bug!("invalid lint renaming of {} to {}", old_name, new_name);
302 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
305 pub fn register_removed(&mut self, name: &str, reason: &str) {
306 self.by_name.insert(name.into(), Removed(reason.into()));
309 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
310 match self.by_name.get(lint_name) {
311 Some(&Id(lint_id)) => Ok(vec![lint_id]),
312 Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
313 Some(&Removed(_)) => Err(FindLintError::Removed),
314 Some(&Ignored) => Ok(vec![]),
316 return match self.lint_groups.get(lint_name) {
317 Some(LintGroup { lint_ids, depr, .. }) => {
318 if let Some(LintAlias { name, .. }) = depr {
324 None => Err(FindLintError::Removed),
330 /// Checks the validity of lint names derived from the command line.
331 pub fn check_lint_name_cmdline(
336 registered_tools: &RegisteredTools,
338 let (tool_name, lint_name_only) = parse_lint_and_tool_name(lint_name);
339 if lint_name_only == crate::WARNINGS.name_lower() && matches!(level, Level::ForceWarn(_)) {
340 sess.emit_err(UnsupportedGroup { lint_group: crate::WARNINGS.name_lower() });
343 let lint_name = lint_name.to_string();
344 match self.check_lint_name(lint_name_only, tool_name, registered_tools) {
345 CheckLintNameResult::Warning(msg, _) => {
346 sess.emit_warning(CheckNameWarning {
348 sub: RequestedLevel { level, lint_name },
351 CheckLintNameResult::NoLint(suggestion) => {
352 sess.emit_err(CheckNameUnknown {
353 lint_name: lint_name.clone(),
355 sub: RequestedLevel { level, lint_name },
358 CheckLintNameResult::Tool(result) => {
359 if let Err((Some(_), new_name)) = result {
360 sess.emit_warning(CheckNameDeprecated {
361 lint_name: lint_name.clone(),
363 sub: RequestedLevel { level, lint_name },
367 CheckLintNameResult::NoTool => {
368 sess.emit_err(CheckNameUnknownTool {
369 tool_name: tool_name.unwrap(),
370 sub: RequestedLevel { level, lint_name },
377 /// True if this symbol represents a lint group name.
378 pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
380 "is_lint_group(lint_name={:?}, lint_groups={:?})",
382 self.lint_groups.keys().collect::<Vec<_>>()
384 let lint_name_str = lint_name.as_str();
385 self.lint_groups.contains_key(lint_name_str) || {
386 let warnings_name_str = crate::WARNINGS.name_lower();
387 lint_name_str == warnings_name_str
391 /// Checks the name of a lint for its existence, and whether it was
392 /// renamed or removed. Generates a DiagnosticBuilder containing a
393 /// warning for renamed and removed lints. This is over both lint
394 /// names from attributes and those passed on the command line. Since
395 /// it emits non-fatal warnings and there are *two* lint passes that
396 /// inspect attributes, this is only run from the late pass to avoid
397 /// printing duplicate warnings.
398 pub fn check_lint_name(
401 tool_name: Option<Symbol>,
402 registered_tools: &RegisteredTools,
403 ) -> CheckLintNameResult<'_> {
404 if let Some(tool_name) = tool_name {
405 // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes.
406 if tool_name != sym::rustc
407 && tool_name != sym::rustdoc
408 && !registered_tools.contains(&Ident::with_dummy_span(tool_name))
410 return CheckLintNameResult::NoTool;
414 let complete_name = if let Some(tool_name) = tool_name {
415 format!("{}::{}", tool_name, lint_name)
417 lint_name.to_string()
419 // If the lint was scoped with `tool::` check if the tool lint exists
420 if let Some(tool_name) = tool_name {
421 match self.by_name.get(&complete_name) {
422 None => match self.lint_groups.get(&*complete_name) {
423 // If the lint isn't registered, there are two possibilities:
425 // 1. The tool is currently running, so this lint really doesn't exist.
426 // FIXME: should this handle tools that never register a lint, like rustfmt?
427 debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
428 let tool_prefix = format!("{}::", tool_name);
429 return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
430 self.no_lint_suggestion(&complete_name)
432 // 2. The tool isn't currently running, so no lints will be registered.
433 // To avoid giving a false positive, ignore all unknown lints.
434 CheckLintNameResult::Tool(Err((None, String::new())))
437 Some(LintGroup { lint_ids, .. }) => {
438 return CheckLintNameResult::Tool(Ok(&lint_ids));
441 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
442 // If the lint was registered as removed or renamed by the lint tool, we don't need
443 // to treat tool_lints and rustc lints different and can use the code below.
447 match self.by_name.get(&complete_name) {
448 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
449 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
450 Some(new_name.to_owned()),
452 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
453 format!("lint `{}` has been removed: {}", complete_name, reason),
456 None => match self.lint_groups.get(&*complete_name) {
457 // If neither the lint, nor the lint group exists check if there is a `clippy::`
458 // variant of this lint
459 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
460 Some(LintGroup { lint_ids, depr, .. }) => {
461 // Check if the lint group name is deprecated
462 if let Some(LintAlias { name, silent }) = depr {
463 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
465 CheckLintNameResult::Ok(&lint_ids)
467 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
470 CheckLintNameResult::Ok(&lint_ids)
473 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
474 Some(&Ignored) => CheckLintNameResult::Ok(&[]),
478 fn no_lint_suggestion(&self, lint_name: &str) -> CheckLintNameResult<'_> {
479 let name_lower = lint_name.to_lowercase();
481 if lint_name.chars().any(char::is_uppercase) && self.find_lints(&name_lower).is_ok() {
482 // First check if the lint name is (partly) in upper case instead of lower case...
483 return CheckLintNameResult::NoLint(Some(Symbol::intern(&name_lower)));
485 // ...if not, search for lints with a similar name
486 let groups = self.lint_groups.keys().copied().map(Symbol::intern);
487 let lints = self.lints.iter().map(|l| Symbol::intern(&l.name_lower()));
488 let names: Vec<Symbol> = groups.chain(lints).collect();
489 let suggestion = find_best_match_for_name(&names, Symbol::intern(&name_lower), None);
490 CheckLintNameResult::NoLint(suggestion)
493 fn check_tool_name_for_backwards_compat(
497 ) -> CheckLintNameResult<'_> {
498 let complete_name = format!("{}::{}", tool_name, lint_name);
499 match self.by_name.get(&complete_name) {
500 None => match self.lint_groups.get(&*complete_name) {
501 // Now we are sure, that this lint exists nowhere
502 None => self.no_lint_suggestion(lint_name),
503 Some(LintGroup { lint_ids, depr, .. }) => {
504 // Reaching this would be weird, but let's cover this case anyway
505 if let Some(LintAlias { name, silent }) = depr {
506 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
508 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
510 CheckLintNameResult::Tool(Err((Some(&lint_ids), (*name).to_string())))
513 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
516 Some(&Id(ref id)) => {
517 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
520 debug!("got renamed lint {:?}", other);
521 CheckLintNameResult::NoLint(None)
527 /// Context for lint checking outside of type inference.
528 pub struct LateContext<'tcx> {
529 /// Type context we're checking in.
530 pub tcx: TyCtxt<'tcx>,
532 /// Current body, or `None` if outside a body.
533 pub enclosing_body: Option<hir::BodyId>,
535 /// Type-checking results for the current body. Access using the `typeck_results`
536 /// and `maybe_typeck_results` methods, which handle querying the typeck results on demand.
537 // FIXME(eddyb) move all the code accessing internal fields like this,
538 // to this module, to avoid exposing it to lint logic.
539 pub(super) cached_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
541 /// Parameter environment for the item we are in.
542 pub param_env: ty::ParamEnv<'tcx>,
544 /// Items accessible from the crate being checked.
545 pub effective_visibilities: &'tcx EffectiveVisibilities,
547 /// The store of registered lints and the lint levels.
548 pub lint_store: &'tcx LintStore,
550 pub last_node_with_lint_attrs: hir::HirId,
552 /// Generic type parameters in scope for the item we are in.
553 pub generics: Option<&'tcx hir::Generics<'tcx>>,
555 /// We are only looking at one module
556 pub only_module: bool,
559 /// Context for lint checking of the AST, after expansion, before lowering to HIR.
560 pub struct EarlyContext<'a> {
561 pub builder: LintLevelsBuilder<'a, crate::levels::TopDown>,
562 pub buffered: LintBuffer,
565 pub trait LintPassObject: Sized {}
567 impl LintPassObject for EarlyLintPassObject {}
569 impl LintPassObject for LateLintPassObject<'_> {}
571 pub trait LintContext: Sized {
572 type PassObject: LintPassObject;
574 fn sess(&self) -> &Session;
575 fn lints(&self) -> &LintStore;
577 /// Emit a lint at the appropriate level, with an optional associated span and an existing diagnostic.
579 /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
581 /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
582 fn lookup_with_diagnostics(
585 span: Option<impl Into<MultiSpan>>,
586 msg: impl Into<DiagnosticMessage>,
587 decorate: impl for<'a, 'b> FnOnce(
588 &'b mut DiagnosticBuilder<'a, ()>,
589 ) -> &'b mut DiagnosticBuilder<'a, ()>,
590 diagnostic: BuiltinLintDiagnostics,
592 // We first generate a blank diagnostic.
593 self.lookup(lint, span, msg,|db| {
594 // Now, set up surrounding context.
595 let sess = self.sess();
597 BuiltinLintDiagnostics::UnicodeTextFlow(span, content) => {
598 let spans: Vec<_> = content
600 .filter_map(|(i, c)| {
601 TEXT_FLOW_CONTROL_CHARS.contains(&c).then(|| {
602 let lo = span.lo() + BytePos(2 + i as u32);
603 (c, span.with_lo(lo).with_hi(lo + BytePos(c.len_utf8() as u32)))
607 let (an, s) = match spans.len() {
611 db.span_label(span, &format!(
612 "this comment contains {}invisible unicode text flow control codepoint{}",
616 for (c, span) in &spans {
617 db.span_label(*span, format!("{:?}", c));
620 "these kind of unicode codepoints change the way text flows on \
621 applications that support them, but can cause confusion because they \
622 change the order of characters on the screen",
624 if !spans.is_empty() {
625 db.multipart_suggestion_with_style(
626 "if their presence wasn't intentional, you can remove them",
627 spans.into_iter().map(|(_, span)| (span, "".to_string())).collect(),
628 Applicability::MachineApplicable,
629 SuggestionStyle::HideCodeAlways,
633 BuiltinLintDiagnostics::Normal => (),
634 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
635 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
637 // FIXME(Manishearth) ideally the emitting code
638 // can tell us whether or not this is global
640 if s.trim_start().starts_with("::") { "" } else { "::" };
642 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
644 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
646 db.span_suggestion(span, "use `crate`", sugg, app);
648 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
651 "names from parent modules are not accessible without an explicit import",
654 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(
657 db.span_note(span_def, "the macro is defined here");
659 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
665 add_elided_lifetime_in_path_suggestion(
674 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
675 db.span_suggestion(span, ¬e, sugg, Applicability::MaybeIncorrect);
677 BuiltinLintDiagnostics::UnusedImports(message, replaces, in_test_module) => {
678 if !replaces.is_empty() {
679 db.tool_only_multipart_suggestion(
682 Applicability::MachineApplicable,
686 if let Some(span) = in_test_module {
688 self.sess().source_map().guess_head_span(span),
689 "consider adding a `#[cfg(test)]` to the containing module",
693 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
694 for (span, is_imported) in spans {
695 let introduced = if is_imported { "imported" } else { "defined" };
698 format!("the item `{}` is already {} here", ident, introduced),
702 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
703 stability::deprecation_suggestion(db, "macro", suggestion, span)
705 BuiltinLintDiagnostics::UnusedDocComment(span) => {
706 db.span_label(span, "rustdoc does not generate documentation for macro invocations");
707 db.help("to document an item produced by a macro, \
708 the macro must produce the documentation as part of its expansion");
710 BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident) => {
711 db.span_suggestion(span, "remove `mut` from the parameter", ident, Applicability::MachineApplicable);
713 BuiltinLintDiagnostics::MissingAbi(span, default_abi) => {
714 db.span_label(span, "ABI should be specified here");
715 db.help(&format!("the default ABI is {}", default_abi.name()));
717 BuiltinLintDiagnostics::LegacyDeriveHelpers(span) => {
718 db.span_label(span, "the attribute is introduced here");
720 BuiltinLintDiagnostics::ProcMacroBackCompat(note) => {
723 BuiltinLintDiagnostics::OrPatternsBackCompat(span,suggestion) => {
724 db.span_suggestion(span, "use pat_param to preserve semantics", suggestion, Applicability::MachineApplicable);
726 BuiltinLintDiagnostics::ReservedPrefix(span) => {
727 db.span_label(span, "unknown prefix");
728 db.span_suggestion_verbose(
730 "insert whitespace here to avoid this being parsed as a prefix in Rust 2021",
732 Applicability::MachineApplicable,
735 BuiltinLintDiagnostics::UnusedBuiltinAttribute {
742 &format!("the built-in attribute `{attr_name}` will be ignored, since it's applied to the macro invocation `{macro_name}`")
745 BuiltinLintDiagnostics::TrailingMacro(is_trailing, name) => {
747 db.note("macro invocations at the end of a block are treated as expressions");
748 db.note(&format!("to ignore the value produced by the macro, add a semicolon after the invocation of `{name}`"));
751 BuiltinLintDiagnostics::BreakWithLabelAndLoop(span) => {
752 db.multipart_suggestion(
753 "wrap this expression in parentheses",
754 vec![(span.shrink_to_lo(), "(".to_string()),
755 (span.shrink_to_hi(), ")".to_string())],
756 Applicability::MachineApplicable
759 BuiltinLintDiagnostics::NamedAsmLabel(help) => {
761 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");
763 BuiltinLintDiagnostics::UnexpectedCfg((name, name_span), None) => {
764 let Some(names_valid) = &sess.parse_sess.check_config.names_valid else {
765 bug!("it shouldn't be possible to have a diagnostic on a name if name checking is not enabled");
767 let possibilities: Vec<Symbol> = names_valid.iter().map(|s| *s).collect();
769 // Suggest the most probable if we found one
770 if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) {
771 db.span_suggestion(name_span, "did you mean", best_match, Applicability::MaybeIncorrect);
774 BuiltinLintDiagnostics::UnexpectedCfg((name, name_span), Some((value, value_span))) => {
775 let Some(values) = &sess.parse_sess.check_config.values_valid.get(&name) else {
776 bug!("it shouldn't be possible to have a diagnostic on a value whose name is not in values");
778 let possibilities: Vec<Symbol> = values.iter().map(|&s| s).collect();
780 // Show the full list if all possible values for a given name, but don't do it
781 // for names as the possibilities could be very long
782 if !possibilities.is_empty() {
784 let mut possibilities = possibilities.iter().map(Symbol::as_str).collect::<Vec<_>>();
785 possibilities.sort();
787 let possibilities = possibilities.join(", ");
788 db.note(&format!("expected values for `{name}` are: {possibilities}"));
791 // Suggest the most probable if we found one
792 if let Some(best_match) = find_best_match_for_name(&possibilities, value, None) {
793 db.span_suggestion(value_span, "did you mean", format!("\"{best_match}\""), Applicability::MaybeIncorrect);
796 db.note(&format!("no expected value for `{name}`"));
797 if name != sym::feature {
798 db.span_suggestion(name_span.shrink_to_hi().to(value_span), "remove the value", "", Applicability::MaybeIncorrect);
802 BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(new_span, suggestion) => {
803 db.multipart_suggestion(
804 "move it to the end of the type declaration",
805 vec![(db.span.primary_span().unwrap(), "".to_string()), (new_span, suggestion)],
806 Applicability::MachineApplicable,
809 "see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information",
812 BuiltinLintDiagnostics::SingleUseLifetime {
814 use_span: Some((use_span, elide)),
817 debug!(?param_span, ?use_span, ?deletion_span);
818 db.span_label(param_span, "this lifetime...");
819 db.span_label(use_span, "...is used only here");
820 let msg = "elide the single-use lifetime";
821 let (use_span, replace_lt) = if elide {
822 let use_span = sess.source_map().span_extend_while(
825 ).unwrap_or(use_span);
826 (use_span, String::new())
828 (use_span, "'_".to_owned())
830 db.multipart_suggestion(
832 vec![(deletion_span, String::new()), (use_span, replace_lt)],
833 Applicability::MachineApplicable,
836 BuiltinLintDiagnostics::SingleUseLifetime {
841 debug!(?deletion_span);
844 "elide the unused lifetime",
846 Applicability::MachineApplicable,
849 BuiltinLintDiagnostics::NamedArgumentUsedPositionally{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => {
850 db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string");
851 if let Some(positional_arg_for_msg) = position_sp_for_msg {
852 let msg = format!("this formatting argument uses named argument `{}` by position", named_arg_name);
853 db.span_label(positional_arg_for_msg, msg);
856 if let Some(positional_arg_to_replace) = position_sp_to_replace {
857 let name = if is_formatting_arg { named_arg_name + "$" } else { named_arg_name };
858 let span_to_replace = if let Ok(positional_arg_content) =
859 self.sess().source_map().span_to_snippet(positional_arg_to_replace) && positional_arg_content.starts_with(':') {
860 positional_arg_to_replace.shrink_to_lo()
862 positional_arg_to_replace
864 db.span_suggestion_verbose(
866 "use the named argument by name to avoid ambiguity",
868 Applicability::MaybeIncorrect,
873 // Rewrap `db`, and pass control to the user.
878 // FIXME: These methods should not take an Into<MultiSpan> -- instead, callers should need to
879 // set the span in their `decorate` function (preferably using set_span).
880 /// Emit a lint at the appropriate level, with an optional associated span.
882 /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
884 /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
885 fn lookup<S: Into<MultiSpan>>(
889 msg: impl Into<DiagnosticMessage>,
890 decorate: impl for<'a, 'b> FnOnce(
891 &'b mut DiagnosticBuilder<'a, ()>,
892 ) -> &'b mut DiagnosticBuilder<'a, ()>,
895 /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
896 /// typically generated by `#[derive(LintDiagnostic)]`).
897 fn emit_spanned_lint<S: Into<MultiSpan>>(
901 decorator: impl for<'a> DecorateLint<'a, ()>,
903 self.lookup(lint, Some(span), decorator.msg(), |diag| decorator.decorate_lint(diag));
906 /// Emit a lint at the appropriate level, with an associated span.
908 /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
910 /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
911 fn struct_span_lint<S: Into<MultiSpan>>(
915 msg: impl Into<DiagnosticMessage>,
916 decorate: impl for<'a, 'b> FnOnce(
917 &'b mut DiagnosticBuilder<'a, ()>,
918 ) -> &'b mut DiagnosticBuilder<'a, ()>,
920 self.lookup(lint, Some(span), msg, decorate);
923 /// Emit a lint from a lint struct (some type that implements `DecorateLint`, typically
924 /// generated by `#[derive(LintDiagnostic)]`).
925 fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> DecorateLint<'a, ()>) {
926 self.lookup(lint, None as Option<Span>, decorator.msg(), |diag| {
927 decorator.decorate_lint(diag)
931 /// Emit a lint at the appropriate level, with no associated span.
933 /// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
935 /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
939 msg: impl Into<DiagnosticMessage>,
940 decorate: impl for<'a, 'b> FnOnce(
941 &'b mut DiagnosticBuilder<'a, ()>,
942 ) -> &'b mut DiagnosticBuilder<'a, ()>,
944 self.lookup(lint, None as Option<Span>, msg, decorate);
947 /// This returns the lint level for the given lint at the current location.
948 fn get_lint_level(&self, lint: &'static Lint) -> Level;
950 /// This function can be used to manually fulfill an expectation. This can
951 /// be used for lints which contain several spans, and should be suppressed,
952 /// if either location was marked with an expectation.
954 /// Note that this function should only be called for [`LintExpectationId`]s
955 /// retrieved from the current lint pass. Buffered or manually created ids can
957 fn fulfill_expectation(&self, expectation: LintExpectationId) {
958 // We need to make sure that submitted expectation ids are correctly fulfilled suppressed
959 // and stored between compilation sessions. To not manually do these steps, we simply create
960 // a dummy diagnostic and emit is as usual, which will be suppressed and stored like a normal
961 // expected lint diagnostic.
964 "this is a dummy diagnostic, to submit and store an expectation",
971 impl<'a> EarlyContext<'a> {
974 warn_about_weird_lints: bool,
975 lint_store: &'a LintStore,
976 registered_tools: &'a RegisteredTools,
977 buffered: LintBuffer,
978 ) -> EarlyContext<'a> {
980 builder: LintLevelsBuilder::new(
982 warn_about_weird_lints,
991 impl<'tcx> LintContext for LateContext<'tcx> {
992 type PassObject = LateLintPassObject<'tcx>;
994 /// Gets the overall compiler `Session` object.
995 fn sess(&self) -> &Session {
999 fn lints(&self) -> &LintStore {
1003 fn lookup<S: Into<MultiSpan>>(
1005 lint: &'static Lint,
1007 msg: impl Into<DiagnosticMessage>,
1008 decorate: impl for<'a, 'b> FnOnce(
1009 &'b mut DiagnosticBuilder<'a, ()>,
1010 ) -> &'b mut DiagnosticBuilder<'a, ()>,
1012 let hir_id = self.last_node_with_lint_attrs;
1015 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg, decorate),
1016 None => self.tcx.struct_lint_node(lint, hir_id, msg, decorate),
1020 fn get_lint_level(&self, lint: &'static Lint) -> Level {
1021 self.tcx.lint_level_at_node(lint, self.last_node_with_lint_attrs).0
1025 impl LintContext for EarlyContext<'_> {
1026 type PassObject = EarlyLintPassObject;
1028 /// Gets the overall compiler `Session` object.
1029 fn sess(&self) -> &Session {
1030 &self.builder.sess()
1033 fn lints(&self) -> &LintStore {
1034 self.builder.lint_store()
1037 fn lookup<S: Into<MultiSpan>>(
1039 lint: &'static Lint,
1041 msg: impl Into<DiagnosticMessage>,
1042 decorate: impl for<'a, 'b> FnOnce(
1043 &'b mut DiagnosticBuilder<'a, ()>,
1044 ) -> &'b mut DiagnosticBuilder<'a, ()>,
1046 self.builder.struct_lint(lint, span.map(|s| s.into()), msg, decorate)
1049 fn get_lint_level(&self, lint: &'static Lint) -> Level {
1050 self.builder.lint_level(lint).0
1054 impl<'tcx> LateContext<'tcx> {
1055 /// Gets the type-checking results for the current body,
1056 /// or `None` if outside a body.
1057 pub fn maybe_typeck_results(&self) -> Option<&'tcx ty::TypeckResults<'tcx>> {
1058 self.cached_typeck_results.get().or_else(|| {
1059 self.enclosing_body.map(|body| {
1060 let typeck_results = self.tcx.typeck_body(body);
1061 self.cached_typeck_results.set(Some(typeck_results));
1067 /// Gets the type-checking results for the current body.
1068 /// As this will ICE if called outside bodies, only call when working with
1069 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1071 pub fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1072 self.maybe_typeck_results().expect("`LateContext::typeck_results` called outside of body")
1075 /// Returns the final resolution of a `QPath`, or `Res::Err` if unavailable.
1076 /// Unlike `.typeck_results().qpath_res(qpath, id)`, this can be used even outside
1077 /// bodies (e.g. for paths in `hir::Ty`), without any risk of ICE-ing.
1078 pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
1080 hir::QPath::Resolved(_, ref path) => path.res,
1081 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1082 .maybe_typeck_results()
1083 .filter(|typeck_results| typeck_results.hir_owner == id.owner)
1085 if self.tcx.has_typeck_results(id.owner.to_def_id()) {
1086 Some(self.tcx.typeck(id.owner.def_id))
1091 .and_then(|typeck_results| typeck_results.type_dependent_def(id))
1092 .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
1096 /// Check if a `DefId`'s path matches the given absolute type path usage.
1098 /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`;
1099 /// inherent `impl` blocks are matched with the name of the type.
1101 /// Instead of using this method, it is often preferable to instead use
1102 /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors
1103 /// as paths get invalidated if the target definition moves.
1107 /// ```rust,ignore (no context or def id available)
1108 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
1109 /// // The given `def_id` is that of an `Option` type
1113 /// Used by clippy, but should be replaced by diagnostic items eventually.
1114 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
1115 let names = self.get_def_path(def_id);
1117 names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b)
1120 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
1124 /// ```rust,ignore (no context or def id available)
1125 /// let def_path = cx.get_def_path(def_id);
1126 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
1127 /// // The given `def_id` is that of an `Option` type
1130 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
1131 pub struct AbsolutePathPrinter<'tcx> {
1132 pub tcx: TyCtxt<'tcx>,
1135 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
1138 type Path = Vec<Symbol>;
1141 type DynExistential = ();
1144 fn tcx(&self) -> TyCtxt<'tcx> {
1148 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1152 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1156 fn print_dyn_existential(
1158 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
1159 ) -> Result<Self::DynExistential, Self::Error> {
1163 fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1167 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1168 Ok(vec![self.tcx.crate_name(cnum)])
1174 trait_ref: Option<ty::TraitRef<'tcx>>,
1175 ) -> Result<Self::Path, Self::Error> {
1176 if trait_ref.is_none() {
1177 if let ty::Adt(def, substs) = self_ty.kind() {
1178 return self.print_def_path(def.did(), substs);
1182 // This shouldn't ever be needed, but just in case:
1183 with_no_trimmed_paths!({
1184 Ok(vec![match trait_ref {
1185 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1186 None => Symbol::intern(&format!("<{}>", self_ty)),
1191 fn path_append_impl(
1193 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1194 _disambiguated_data: &DisambiguatedDefPathData,
1196 trait_ref: Option<ty::TraitRef<'tcx>>,
1197 ) -> Result<Self::Path, Self::Error> {
1198 let mut path = print_prefix(self)?;
1200 // This shouldn't ever be needed, but just in case:
1201 path.push(match trait_ref {
1202 Some(trait_ref) => {
1203 with_no_trimmed_paths!(Symbol::intern(&format!(
1205 trait_ref.print_only_trait_path(),
1210 with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty)))
1219 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1220 disambiguated_data: &DisambiguatedDefPathData,
1221 ) -> Result<Self::Path, Self::Error> {
1222 let mut path = print_prefix(self)?;
1224 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1225 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
1229 path.push(Symbol::intern(&disambiguated_data.data.to_string()));
1233 fn path_generic_args(
1235 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1236 _args: &[GenericArg<'tcx>],
1237 ) -> Result<Self::Path, Self::Error> {
1242 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
1246 impl<'tcx> abi::HasDataLayout for LateContext<'tcx> {
1248 fn data_layout(&self) -> &abi::TargetDataLayout {
1249 &self.tcx.data_layout
1253 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for LateContext<'tcx> {
1255 fn tcx(&self) -> TyCtxt<'tcx> {
1260 impl<'tcx> ty::layout::HasParamEnv<'tcx> for LateContext<'tcx> {
1262 fn param_env(&self) -> ty::ParamEnv<'tcx> {
1267 impl<'tcx> LayoutOfHelpers<'tcx> for LateContext<'tcx> {
1268 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
1271 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
1276 pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) {
1277 match lint_name.split_once("::") {
1278 Some((tool_name, lint_name)) => {
1279 let tool_name = Symbol::intern(tool_name);
1281 (Some(tool_name), lint_name)
1283 None => (None, lint_name),