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
15 changes: 7 additions & 8 deletions compiler/rustc_attr_ir/src/lint.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use rustc_macros::{Decodable, Encodable, PrintAttribute, StableHash};
use rustc_span::{Ident, Span, Symbol, sym};
use rustc_span::{Span, Symbol, sym};

use crate::{HashIgnoredAttrId, PrintAttribute};
#[derive(Clone, Copy, Debug, StableHash, Encodable, Decodable, PrintAttribute)]
Expand Down Expand Up @@ -44,14 +44,13 @@ impl LintCheckKind {
#[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)]
pub struct LintCheck {
/// The lint's tool name, if present.
pub tool: Option<Ident>,
/// The lint's name, minus the tool name if any.
pub tool: Option<Symbol>,
/// 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.
Comment thread
JonathanBrouwer marked this conversation as resolved.
Resolved

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.

Suggested change
/// This may not be what we user wrote down, in case of renamed lints the new lint name is here.
/// 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:
/// - `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
163 changes: 159 additions & 4 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::{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)) =
Comment thread
JonathanBrouwer marked this conversation as resolved.
Resolved
LintParser::check_lint_name(lint_name, tool, p.span(), cx)
{
new_lint_name
} else {
// Discard lint attributes with unknown lints in them
continue;
Comment thread
JonathanBrouwer marked this conversation as resolved.
Resolved
};

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

fn check_lint_name<'a>(
lint_name: Symbol,
tool: Option<Ident>,
lint_span: Span,
cx: &mut AcceptContext<'_, 'a>,
Comment on lines +148 to +152

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.

Suggested change
fn check_lint_name<'a>(
lint_name: Symbol,
tool: Option<Ident>,
lint_span: Span,
cx: &mut AcceptContext<'_, 'a>,
fn check_lint_name<'sess>(
lint_name: Symbol,
tool: Option<Ident>,
lint_span: Span,
cx: &mut AcceptContext<'_, 'sess>,

) -> Option<(&'a [LintId], Symbol)> {
// FIXME For historic reasons these checks are not executed on macro calls

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.

More precisely, it's only ignored on macro calls produced by another macro's expansion. Prior to macro expansion it's still caught by the pre expansion pass collection.

That is:

macro_rules! identity { ($( $tt:tt )*) => { $( $tt )* } }

fn main() {
    #[expect(wat::doesnt_exist)] // ERROR
    println!();
    
    identity!{
        #[expect(wat::doesnt_exist)] // OK
        println!();
    }
}

I think that's maintained here, as we pass Crate as the pre-expansion target for that. Can you add a test, I don't believe one exists.

if cx.target == Target::MacroCall {
return None;
}

let lint_result = cx.sess.lint_store.as_ref().unwrap().check_attribute_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 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 => {
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_attribute_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 @@ -2199,3 +2199,84 @@ pub(crate) struct Unused {
#[derive(Diagnostic)]
#[diag("use of deprecated `no_link` attribute")]
pub(crate) struct NoLinkAttrUsed;

#[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,
}
19 changes: 16 additions & 3 deletions compiler/rustc_attr_parsing/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,15 @@ 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,

/// *Only* parse attributes that passes this filter.
///
/// Used in cases where we want the lowering infrastructure for parse just limited attributes.
parse_filter: Option<&'sess dyn Fn(&ast::Attribute) -> bool>,
pub(crate) parse_filter: Option<&'sess dyn Fn(&ast::Attribute) -> bool>,
}

impl<'sess> AttributeParser<'sess> {
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 @@ -2246,6 +2246,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
Loading
Loading