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 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
11 changes: 5 additions & 6 deletions compiler/rustc_attr_ir/src/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,12 @@ impl LintCheckKind {
pub struct LintCheck {
/// The lint's tool name, if present.
pub tool: Option<Ident>,
Comment thread
JonathanBrouwer marked this conversation as resolved.
/// The lint's name, minus the tool name if any.
/// The full normalized lint name of an existing lint, including the tool name.
/// This may not be what we user wrote down, in case of renamed lints the new lint name is here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Until #164607 this can also recover unknown lint names to a clippy lint even when it is not registered as renamed.

/// The above implies that `LintStore::find_lints` is guaranteed to find this lint using this symbol.
///
/// For example:
/// - `clippy::blah` -> `blah`
/// - `unstable_imports` -> `unstable_imports`
/// - `custom_tool::blah::bleh` -> `blah::bleh`
pub lint_name: Symbol,
/// For example, `single_use_lifetime` is changed to `single_use_lifetimes`.
pub lint_name_normalized: Symbol,

@JonathanBrouwer JonathanBrouwer Oct 25, 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.

My goal for a follow-up PR is to change this field from a Symbol that needs to be looked up in LintStore to a LintId. I think this should be possible, but encoding and decoding will be a challenge. I think this PR is already a good step forwards regardless.

View changes since the review

/// The span of the lint name.
///
/// For example `#[deny(foo, bar, reason = "reason")]`
Expand Down
156 changes: 153 additions & 3 deletions compiler/rustc_attr_parsing/src/attributes/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ 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::{Symbol, sym};
use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES};
use rustc_lint_defs::{CheckLintNameResult, LintId};
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
use thin_vec::ThinVec;

use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability};
use crate::context::{AcceptContext, ExpectStringLiteral, FinalizeContext};
use crate::diagnostics::{
DeprecatedLintName, 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 @@ -69,9 +74,18 @@ impl LintParser {
),
};

let lint_name_normalized = if let Some((_lint_ids, new_lint_name)) =

@JonathanBrouwer JonathanBrouwer Oct 25, 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.

Note that we already have the lint_ids here! We just need to figure out how to encode & decode them in a follow-up PR!

View changes since the review

Self::check_lint_name(lint_name, tool, p.span(), cx)
Comment thread
JonathanBrouwer marked this conversation as resolved.
{
new_lint_name
} else {
// Discard lint attributes with unknown lints in them
continue;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please cover this in a test, I think it would be best to have a hir pretty test showing that unknown lints and lints whose tool is inactive are dropped.

};

self.lints.push(LintCheck {
tool,
lint_name,
lint_name_normalized,
lint_span: p.span(),
kind,
attr_id,
Expand Down Expand Up @@ -130,6 +144,142 @@ impl LintParser {
}
}
}

fn check_lint_name<'a>(
lint_name: Symbol,
tool: Option<Ident>,
lint_span: Span,
cx: &mut AcceptContext<'_, 'a>,
) -> Option<(&'a [LintId], Symbol)> {
let lint_result = cx.sess.lint_store.as_ref().unwrap().check_lint_name(
lint_name.as_str(),
tool.map(|tool| tool.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 `target_span` will be `DUMMY_SP`, which we use to detect which instance we are.
// #164898 will fix this, after that PR this check can be removed
let should_lint = cx.target_span != DUMMY_SP;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think this is a good idea:

  • I would not accept this as a standalone PR (instead demanding a more rigorous fix)
  • Try to keep behavior changes to a minimum during refactors


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 => {
let complete_name = &format!("{}::{lint_name}", tool.unwrap().name);
Symbol::intern(complete_name)
}
Some(new_lint_name) => {
let symbol = Symbol::intern(&new_lint_name);
if should_lint {
cx.emit_lint(
RENAMED_AND_REMOVED_LINTS,
DeprecatedLintName {
name: lint_name.to_string(),
suggestion: lint_span,
replace: new_lint_name,
},
lint_span,
);
}
symbol
}
};
(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 => {
if should_lint {
cx.emit_err(UnknownToolInScopedLint {
span: Some(tool.unwrap().span),
tool_name: tool.unwrap().name,
lint_name: lint_name.to_string(),
is_nightly_build: cx.sess.is_nightly_build(),
});
}
return None;
}

CheckLintNameResult::Renamed(ref replace) => {
if should_lint {
let suggestion = RenamedLintSuggestion::WithSpan {
suggestion: lint_span,
replace: replace.clone(),
};
let name = tool
.map(|Ident { name, .. }| format!("{name}::{lint_name}"))
.unwrap_or_else(|| lint_name.to_string());
cx.emit_lint(
RENAMED_AND_REMOVED_LINTS,
RenamedLint { name, replace: replace.clone(), 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.
// NOTE: `new_name` already includes the tool name, so we don't
// have to add it again.
let CheckLintNameResult::Ok(ids) = cx
.sess
.lint_store
.as_ref()
.unwrap()
.check_lint_name(replace, None, cx.lint_tools.unwrap())
else {
panic!("renamed lint does not exist: {replace}");
};

(ids, Symbol::intern(&replace))
}

CheckLintNameResult::Removed(ref reason) => {
if should_lint {
let name = if let Some(Ident { name, .. }) = tool {
format!("{name}::{lint_name}")
} else {
lint_name.to_string()
};
cx.emit_lint(
RENAMED_AND_REMOVED_LINTS,
RemovedLint { name, reason: reason.clone() },
lint_span,
);
}
return None;
}

CheckLintNameResult::NoLint(suggestion) => {
if should_lint {
let name = tool
.map(|Ident { name, .. }| format!("{name}::{lint_name}"))
.unwrap_or_else(|| lint_name.to_string());
let suggestion =
suggestion.map(|(replace, from_rustc)| UnknownLintSuggestion::WithSpan {
suggestion: lint_span,
replace,
from_rustc,
});
cx.emit_lint(UNKNOWN_LINTS, UnknownLint { name, suggestion }, lint_span);
}
return None;
}
};
Some((ids, name))
}
}

impl AttributeParser for LintParser {
Expand Down
81 changes: 81 additions & 0 deletions compiler/rustc_attr_parsing/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2186,3 +2186,84 @@ pub(crate) struct Unused {
#[subdiagnostic]
pub note: UnusedNote,
}

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

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

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

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

#[derive(Diagnostic)]
#[diag("unknown lint: `{$name}`")]
pub(crate) struct UnknownLint {
pub name: String,
#[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 = "{replace}",
applicability = "maybe-incorrect"
)]
WithSpan {
#[primary_span]
suggestion: Span,
replace: Symbol,
from_rustc: bool,
},
#[help(
"{$from_rustc ->
[true] a lint with a similar name exists in `rustc` lints: `{$replace}`
*[false] did you mean: `{$replace}`
}"
)]
WithoutSpan { replace: Symbol, from_rustc: bool },
}

#[derive(Diagnostic)]
#[diag("lint `{$name}` has been removed: {$reason}")]
pub(crate) struct RemovedLint {
pub name: String,
pub reason: String,
}
17 changes: 15 additions & 2 deletions compiler/rustc_attr_parsing/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub struct EmitAttribute(
/// context, through which all attributes can be lowered.
pub struct AttributeParser<'sess> {
pub(crate) attr_tools: Option<&'sess RegisteredTools>,
pub(crate) lint_tools: Option<&'sess RegisteredTools>,
pub(crate) features: Option<&'sess Features>,
pub(crate) sess: &'sess Session,
pub(crate) should_emit: ShouldEmit,
Expand Down Expand Up @@ -114,6 +115,7 @@ impl<'sess> AttributeParser<'sess> {
features,
should_emit,
None,
None,
);
assert!(parsed.len() <= 1);
parsed.pop()
Expand Down Expand Up @@ -156,8 +158,10 @@ impl<'sess> AttributeParser<'sess> {
features: Option<&'sess Features>,
should_emit: ShouldEmit,
attr_tools: Option<&'sess RegisteredTools>,
lint_tools: Option<&'sess RegisteredTools>,
) -> Vec<Attribute> {
let mut p = AttributeParser { features, attr_tools, parse_filter, sess, should_emit };
let mut p =
AttributeParser { features, attr_tools, lint_tools, parse_filter, sess, should_emit };
p.parse_attribute_list(
attrs,
target_span,
Expand Down Expand Up @@ -236,7 +240,14 @@ impl<'sess> AttributeParser<'sess> {
parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T,
template: &AttributeTemplate,
) -> T {
let mut parser = Self { features, attr_tools: None, parse_filter: None, sess, should_emit };
let mut parser = Self {
features,
attr_tools: None,
lint_tools: None,
parse_filter: None,
sess,
should_emit,
};
let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| {
sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
};
Expand Down Expand Up @@ -278,11 +289,13 @@ impl<'sess> AttributeParser<'sess> {
sess: &'sess Session,
features: &'sess Features,
attr_tools: &'sess RegisteredTools,
lint_tools: &'sess RegisteredTools,
should_emit: ShouldEmit,
) -> Self {
Self {
features: Some(features),
attr_tools: Some(attr_tools),
lint_tools: Some(lint_tools),
parse_filter: None,
sess,
should_emit,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_attr_parsing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ pub use attributes::cfg::{
pub use attributes::cfg_select::*;
pub use attributes::util::{is_builtin_attr, parse_version};
pub use context::ShouldEmit;
pub use diagnostics::ParsedDescription;
pub use diagnostics::{ParsedDescription, RenamedLintSuggestion, UnknownLintSuggestion};

@JonathanBrouwer JonathanBrouwer Oct 25, 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.

I'm not sure if people find it cursed to export diagnostic structs such that they can be re-used. I like it

View changes since the review

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't, it can hide unused diagnostics 😅

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.

While unused diagnostics are bad, the alternative is duplicating the suggestion structs which risks them diverging when someone edits one but not the other. I think that's worse

pub use interface::{AttributeParser, EmitAttribute};
pub use rustc_parse::parser::Recovery;
pub use template::AttributeTemplate;
1 change: 1 addition & 0 deletions compiler/rustc_expand/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2255,6 +2255,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
Some(self.cx.ecfg.features),
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
Some(self.cx.resolver.registered_attr_tools()),
Some(self.cx.resolver.registered_lint_tools()),
);

let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_interface/src/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub fn get_limits(krate_attrs: &[ast::Attribute], sess: &Session, features: &Fea
// So, no lints here to avoid duplicates.
ShouldEmit::EarlyFatal { also_emit_lints: false },
None,
None,
);
let attrs = &attrs;
Limits {
Expand Down
Loading
Loading