Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3713,6 +3713,7 @@ dependencies = [
"rustc_ast_pretty",
"rustc_data_structures",
"rustc_error_messages",
"rustc_lint_defs",
"rustc_macros",
"rustc_serialize",
"rustc_span",
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
tcx.sess,
tcx.features(),
tcx.registered_attr_tools(()),
tcx.registered_lint_tools(()),
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
),
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_attr_ir/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ rustc_ast = { path = "../rustc_ast" }
rustc_ast_pretty = { path = "../rustc_ast_pretty" }
rustc_data_structures = { path = "../rustc_data_structures" }
rustc_error_messages = { path = "../rustc_error_messages" }
rustc_lint_defs = { path = "../rustc_lint_defs" }

@JonathanBrouwer JonathanBrouwer Nov 1, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already an indirect dependency via
rustc_abi -> rustc_errors -> rustc_lint_defs

View changes since the review

rustc_macros = { path = "../rustc_macros" }
rustc_serialize = { path = "../rustc_serialize" }
rustc_span = { path = "../rustc_span" }
Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_attr_ir/src/lint.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rustc_lint_defs::LintName;
use rustc_macros::{Decodable, Encodable, PrintAttribute, StableHash};
use rustc_span::{Span, Symbol, sym};
use rustc_structures::LintName;

use crate::{HashIgnoredAttrId, PrintAttribute};

Expand Down Expand Up @@ -45,7 +45,12 @@ impl LintCheckKind {
/// ```
#[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)]
pub struct LintCheck {
pub lint_name: LintName,
/// The full normalized lint name of an existing lint, including the tool name.
/// This may not be what the user wrote down, in case of renamed lints the new lint name is here.
/// The above implies that `LintStore::find_lints` is guaranteed to find this lint using this symbol.
///
/// For example, `single_use_lifetime` is changed to `single_use_lifetimes`.
pub lint_name_normalized: LintName,
pub kind: LintCheckKind,
pub reason: Option<Symbol>,
/// Needed by `LintExpectationId` to track fulfilled expectations
Expand All @@ -61,5 +66,4 @@ pub struct LintCheck {
/// #[deny(foo::bar::baz)]
/// ^^^^^^^^^^^^^
pub lint_span: Span,
pub tool_span: Option<Span>,
}
5 changes: 2 additions & 3 deletions compiler/rustc_attr_ir/src/pretty_printing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ use rustc_ast::token::{CommentKind, DocFragmentKind};
use rustc_ast::{AttrId, AttrStyle, IntTy, UintTy};
use rustc_ast_pretty::pp::Printer;
use rustc_data_structures::fx::FxIndexMap;
use rustc_lint_defs::LintName;
use rustc_span::def_id::DefId;
use rustc_span::hygiene::Transparency;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};
use rustc_structures::{
CollapseMacroDebuginfo, CrateType, Limit, LintName, NativeLibKind, SanitizerSet,
};
use rustc_structures::{CollapseMacroDebuginfo, CrateType, Limit, NativeLibKind, SanitizerSet};
use thin_vec::ThinVec;

use crate::HashIgnoredAttrId;
Expand Down
194 changes: 176 additions & 18 deletions compiler/rustc_attr_parsing/src/attributes/lint.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
use rustc_ast::join_path_syms;
use rustc_attr_ir::AttributeKind;
use rustc_attr_ir::lint::{LintCheck, LintCheckKind};
use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES;
use rustc_span::sym;
use rustc_structures::LintName;
use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES};
use rustc_lint_defs::{CheckLintNameResult, LintId, LintName};
use rustc_span::{Span, Symbol, sym};
use thin_vec::ThinVec;

use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability};
use crate::context::{AcceptContext, ExpectStringLiteral, FinalizeContext};
use crate::diagnostics::{MalformedLintAttributeInput, MalformedLintAttributeInputHelp};
use crate::diagnostics::{
DeprecatedLintName, MalformedLintAttributeInput, MalformedLintAttributeInputHelp, RemovedLint,
RenamedLint, RenamedLintSuggestion, UnknownLint, UnknownLintSuggestion,
UnknownToolInScopedLint,
};
use crate::parser::{ArgParser, MetaItemOrLitParser};
use crate::target_checking::AllowedTargets;
use crate::target_checking::Policy::{Allow, Warn};
Expand Down Expand Up @@ -55,21 +60,47 @@ impl LintParser {
match item {
MetaItemOrLitParser::MetaItemParser(p) => {
match p.args() {
ArgParser::NoArgs => self.lints.push(LintCheck {
lint_name: LintName::new(
p.path().0.segments.iter().map(|s| s.ident.name),
),
kind,
attr_id,
reason,
attr_span,
lint_span: p.span(),
tool_span: if let [tool, _, ..] = &*p.path().0.segments {
Some(tool.span())
ArgParser::NoArgs => {
let (tool, lint_name) = match &*p.path().0.segments {
[] => unreachable!(),
[lint_name] => (None, lint_name.ident.name),
[tool, lint_name] => (Some(tool.ident), lint_name.ident.name),
// Not reachable for any builtin lints,
// but reachable using `register_tool`.
[tool, multi_segment_lint_name @ ..] => (
Some(tool.ident),
Symbol::intern(&join_path_syms(
multi_segment_lint_name
.iter()
.map(|seg| seg.ident.name),
)),
),
};
let lint_name =
LintName { tool: tool.map(|tool| tool.name), name: lint_name };

let lint_name_normalized = if let Some((_lint_ids, new_lint_name)) =
Comment thread
JonathanBrouwer marked this conversation as resolved.
Resolved
LintParser::check_lint_name(
lint_name,
tool.map(|tool| tool.span),
p.span(),
cx,
) {
new_lint_name
} else {
None
},
}),
// Discard lint attributes with unknown lints in them
continue;
Comment thread
JonathanBrouwer marked this conversation as resolved.
Resolved
};

self.lints.push(LintCheck {
lint_name_normalized,
lint_span: p.span(),
kind,
attr_id,
reason,
attr_span,
})
}
// We've found a `reason = "reason"` but we're not the last element.
ArgParser::NameValue(nv) if p.path().word_is(sym::reason) => {
cx.emit_err(diagnostics::MalformedAttribute {
Expand Down Expand Up @@ -123,6 +154,133 @@ impl LintParser {
}
}
}

fn check_lint_name<'sess>(
lint_name: LintName,
tool_span: Option<Span>,
lint_span: Span,
cx: &mut AcceptContext<'_, 'sess>,
) -> Option<(&'sess [LintId], LintName)> {
let lint_result = cx
.sess
.lint_store
.as_ref()
.unwrap()
.check_attribute_lint_name(lint_name, cx.lint_tools.unwrap());

// FIXME(164898) Lint attributes are parsed twice, once on the AST and once on the HIR
// Both times emit diagnostics, for historic reasons
// We only want to emit these lints once, on the HIR.
// On the AST the parse filter will be `Some` (since we're only parsing lint attributes then)
// #164898 will fix this, after that PR this check can be removed
let should_lint = cx.parse_filter.is_none();

let (ids, name) = match lint_result {
CheckLintNameResult::Ok(ids) => (ids, lint_name),

CheckLintNameResult::Tool(ids, new_lint_name) => {
let name = match new_lint_name {
None => lint_name,
Some(replacement) => {
if should_lint {
cx.emit_lint(
RENAMED_AND_REMOVED_LINTS,
DeprecatedLintName {
lint_name,
suggestion: lint_span,
replacement,
},
lint_span,
);
}
replacement
}
};
(ids, name)
}

CheckLintNameResult::MissingTool => {
// If `MissingTool` is returned, then either the lint does not
// exist in the tool or the code was not compiled with the tool and
// therefore the lint was never added to the `LintStore`. To detect
// this is the responsibility of the lint tool.
return None;
}

CheckLintNameResult::NoTool(tool_name) => {
if should_lint {
cx.emit_err(UnknownToolInScopedLint {
span: Some(tool_span.unwrap()),
tool_name,
lint_name,
is_nightly_build: cx.sess.is_nightly_build(),
});
}
return None;
}

CheckLintNameResult::Renamed(replacement) => {
if should_lint {
let suggestion =
RenamedLintSuggestion::WithSpan { suggestion: lint_span, replacement };
cx.emit_lint(
RENAMED_AND_REMOVED_LINTS,
RenamedLint { name: lint_name, replacement, suggestion },
lint_span,
);
}

// If this lint was renamed, apply the new lint instead of ignoring the
// attribute. Ignore any errors or warnings that happen because the new
// name is inaccurate.
let replace_check = cx
.sess
.lint_store
.as_ref()
.unwrap()
.check_attribute_lint_name(replacement, cx.lint_tools.unwrap());
let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) =
replace_check
else {
panic!(
"renamed lint does not exist: {lint_name} => {replacement}\n{replace_check:?}"
);
};

(ids, replacement)
}

CheckLintNameResult::Removed(reason) => {
if should_lint {
cx.emit_lint(
RENAMED_AND_REMOVED_LINTS,
RemovedLint { name: lint_name, reason },
lint_span,
);
}
return None;
}

CheckLintNameResult::NoLint(suggestion) => {
if should_lint {
let suggestion = suggestion.map(|(replacement, from_rustc)| {
UnknownLintSuggestion::WithSpan {
suggestion: lint_span,
replacement,
from_rustc,
}
});
cx.emit_lint(
UNKNOWN_LINTS,
UnknownLint { name: lint_name, suggestion },
lint_span,
);
}
return None;
}
};
Some((ids, name))
}
}

impl AttributeParser for LintParser {
Expand Down
82 changes: 82 additions & 0 deletions compiler/rustc_attr_parsing/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustc_errors::codes::*;
use rustc_errors::{
Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, E0264, Level, MultiSpan,
};
use rustc_lint_defs::LintName;
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{Ident, Span, Symbol};
use rustc_target::spec::TargetTuple;
Expand Down Expand Up @@ -2255,3 +2256,84 @@ pub(crate) struct UnknownLintHelper {
pub span: Span,
pub unknown: Symbol,
}

#[derive(Diagnostic)]
#[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")]
pub(crate) struct DeprecatedLintName {
pub lint_name: LintName,
#[suggestion("change it to", code = "{replacement}", applicability = "machine-applicable")]
pub suggestion: Span,
pub replacement: LintName,
}

#[derive(Diagnostic)]
#[diag("unknown tool name `{$tool_name}` found in scoped lint: `{$lint_name}`", code = E0710)]
pub(crate) struct UnknownToolInScopedLint {
#[primary_span]
pub span: Option<Span>,
pub tool_name: Symbol,
pub lint_name: LintName,
#[help("add `#![register_tool({$tool_name})]` to the crate root")]
pub is_nightly_build: bool,
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been renamed to `{$replacement}`")]
pub(crate) struct RenamedLint {
pub name: LintName,
pub replacement: LintName,
#[subdiagnostic]
pub suggestion: RenamedLintSuggestion,
}

#[derive(Subdiagnostic)]
pub enum RenamedLintSuggestion {
#[suggestion("use the new name", code = "{replacement}", applicability = "machine-applicable")]
WithSpan {
#[primary_span]
suggestion: Span,
replacement: LintName,
},
#[help("use the new name `{$replacement}`")]
WithoutSpan { replacement: LintName },
}

#[derive(Diagnostic)]
#[diag("unknown lint: `{$name}`")]
pub(crate) struct UnknownLint {
pub name: LintName,
#[subdiagnostic]
pub suggestion: Option<UnknownLintSuggestion>,
}

#[derive(Subdiagnostic)]
pub enum UnknownLintSuggestion {
#[suggestion(
"{$from_rustc ->
[true] a lint with a similar name exists in `rustc` lints
*[false] did you mean
}",
code = "{replacement}",
applicability = "maybe-incorrect"
)]
WithSpan {
#[primary_span]
suggestion: Span,
replacement: LintName,
from_rustc: bool,
},
#[help(
"{$from_rustc ->
[true] a lint with a similar name exists in `rustc` lints: `{$replacement}`
*[false] did you mean: `{$replacement}`
}"
)]
WithoutSpan { replacement: LintName, from_rustc: bool },
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been removed: {$reason}")]
pub(crate) struct RemovedLint {
pub name: LintName,
pub reason: String,
}
Loading
Loading