Skip to content

Commit a10a9da

Browse files
Rollup merge of #166037 - Tess4552:reflection-register-reflecting-tools, r=oli-obk
reflection: enable tool attributes to be reflectable Adds an option to the `register_tool` crate level attribute to allow the option to be reflective. Tool attributes of these registered tools are queryable from a `TypeId` object. Encoded the reflectivity of an attribute in `Attribute::Tool` because the attributes can come from another crate and tools are reflective at the crate level. Addresses the FIXME introduced in #165810 Maybe we should run a perf run for it, not sure if the change to `Attribute::Tool` would impact it. r? @oli-obk cc @mejrs
2 parents 6c587fd + 48e98b4 commit a10a9da

37 files changed

Lines changed: 434 additions & 112 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3713,6 +3713,7 @@ dependencies = [
37133713
"rustc_ast_pretty",
37143714
"rustc_data_structures",
37153715
"rustc_error_messages",
3716+
"rustc_lint_defs",
37163717
"rustc_macros",
37173718
"rustc_serialize",
37183719
"rustc_span",

‎compiler/rustc_attr_ir/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ rustc_ast = { path = "../rustc_ast" }
1010
rustc_ast_pretty = { path = "../rustc_ast_pretty" }
1111
rustc_data_structures = { path = "../rustc_data_structures" }
1212
rustc_error_messages = { path = "../rustc_error_messages" }
13+
rustc_lint_defs = { path = "../rustc_lint_defs" }
1314
rustc_macros = { path = "../rustc_macros" }
1415
rustc_serialize = { path = "../rustc_serialize" }
1516
rustc_span = { path = "../rustc_span" }

‎compiler/rustc_attr_ir/src/attr.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use rustc_ast::token::DocFragmentKind;
55
use rustc_ast::{AttrStyle, DelimArgs, MetaItemLit, ast, join_path_idents};
66
use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
77
use rustc_error_messages::{DiagArgValue, IntoDiagArg};
8+
use rustc_lint_defs::ToolOptions;
89
use rustc_macros::{Decodable, Encodable, StableHash};
910
use rustc_span::{AttrId, DUMMY_SP, Ident, Span, Symbol};
1011

@@ -112,7 +113,7 @@ pub enum Attribute {
112113
///
113114
/// Tool attributes, with the exception of diagnostic attributes, are not converted into a
114115
/// parsed form.
115-
Tool(Box<AttrItem>),
116+
Tool { item: Box<AttrItem>, opts: ToolOptions },
116117

117118
/// A derive helper attribute.
118119
///
@@ -125,7 +126,7 @@ pub enum Attribute {
125126
impl Attribute {
126127
pub fn value_lit(&self) -> Option<&MetaItemLit> {
127128
match &self {
128-
Attribute::Tool(n) | Attribute::DeriveHelper(n) => match n.as_ref() {
129+
Attribute::Tool { item: n, .. } | Attribute::DeriveHelper(n) => match n.as_ref() {
129130
AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
130131
_ => None,
131132
},
@@ -135,7 +136,7 @@ impl Attribute {
135136

136137
pub fn is_prefix_attr_for_suggestions(&self) -> bool {
137138
match self {
138-
Attribute::Tool(attr) | Attribute::DeriveHelper(attr) => {
139+
Attribute::Tool { item: attr, .. } | Attribute::DeriveHelper(attr) => {
139140
attr.span.desugaring_kind().is_none()
140141
}
141142
// Other parsed attributes that can appear on expressions originate from source and

‎compiler/rustc_attr_ir/src/data_structures.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_ast::token::DocFragmentKind;
1212
use rustc_ast::{AttrStyle, Path, ast};
1313
use rustc_data_structures::fx::FxIndexMap;
1414
use rustc_error_messages::{DiagArgValue, IntoDiagArg};
15+
use rustc_lint_defs::ToolOptions;
1516
use rustc_macros::{
1617
Decodable, Decodable_NoContext, Encodable, Encodable_NoContext, PrintAttribute, StableHash,
1718
};
@@ -1167,8 +1168,8 @@ pub enum AttributeKind {
11671168

11681169
/// Represents `#[register_attribute_tool]`, `#[register_lint_tool]` and `#[register_tool]`
11691170
RegisterTool {
1170-
attr_tools: ThinVec<Ident>,
1171-
lint_tools: ThinVec<Ident>,
1171+
attr_tools: ThinVec<(Ident, ToolOptions)>,
1172+
lint_tools: ThinVec<(Ident, ToolOptions)>,
11721173
},
11731174

11741175
/// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations).

‎compiler/rustc_attr_ir/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ macro_rules! find_attr {
132132
$crate::Attribute::Parsed($pattern) $(if $guard)? => {
133133
break 'done Some($e);
134134
}
135-
$crate::Attribute::Tool(..) | $crate::Attribute::DeriveHelper(..) => {}
135+
$crate::Attribute::Tool {..} | $crate::Attribute::DeriveHelper(..) => {}
136136
// In lint emitting, there's a specific exception for this warning.
137137
// It's not usually emitted from inside macros from other crates
138138
// (see https://github.com/rust-lang/rust/issues/110613)

‎compiler/rustc_attr_ir/src/pretty_printing.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use rustc_ast::token::{CommentKind, DocFragmentKind};
1111
use rustc_ast::{AttrId, AttrStyle, IntTy, UintTy};
1212
use rustc_ast_pretty::pp::Printer;
1313
use rustc_data_structures::fx::FxIndexMap;
14+
use rustc_lint_defs::{Reflectiveness, ToolOptions};
1415
use rustc_span::def_id::DefId;
1516
use rustc_span::hygiene::Transparency;
1617
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};
@@ -226,4 +227,6 @@ print_debug!(
226227
NativeLibKind,
227228
CollapseMacroDebuginfo,
228229
LintName,
230+
ToolOptions,
231+
Reflectiveness,
229232
);

‎compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ impl AttributeParser for NakedParser {
294294
if other_attr
295295
.segments()
296296
.next()
297-
.is_some_and(|i| tools.iter().any(|tool| tool.name == i.name))
297+
.is_some_and(|i| tools.iter().any(|(tool, _)| tool.name == i.name))
298298
{
299299
// effectively skips the error message being emitted below
300300
// if it's a tool attribute

‎compiler/rustc_attr_parsing/src/attributes/crate_level.rs‎

Lines changed: 74 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
use rustc_attr_ir::WindowsSubsystemKind;
2-
use rustc_data_structures::fx::FxIndexSet;
2+
use rustc_data_structures::fx::FxIndexMap;
33
use rustc_feature::AttributeStability;
4+
use rustc_lint_defs::Reflectiveness::{NonReflective, Reflective};
5+
use rustc_lint_defs::ToolOptions;
46
use rustc_lint_defs::builtin::{DUPLICATE_TOOLS, UNKNOWN_CRATE_TYPES};
7+
use rustc_session::diagnostics::feature_err;
58
use rustc_span::Symbol;
69
use rustc_span::edit_distance::find_best_match_for_name_with_substrings;
710
use rustc_structures::CrateType;
811

912
use super::prelude::*;
1013
use crate::diagnostics::{
11-
DuplicateTool, ToolReserved, UnknownCrateTypes, UnknownCrateTypesSuggestion,
14+
DuplicateTool, PredefinedToolReflective, ToolReserved, UnknownCrateTypes,
15+
UnknownCrateTypesSuggestion, UnrecognizedToolOption,
1216
};
1317

1418
pub(crate) struct CrateNameParser;
@@ -323,12 +327,15 @@ impl CombineAttributeParser for FeatureParser {
323327

324328
#[derive(Default)]
325329
pub(crate) struct RegisterToolParser {
326-
attr_tools: FxIndexSet<Ident>,
327-
lint_tools: FxIndexSet<Ident>,
330+
attr_tools: FxIndexMap<Ident, ToolOptions>,
331+
lint_tools: FxIndexMap<Ident, ToolOptions>,
328332
}
329333

334+
pub const PREDEFINED_TOOLS: &[Symbol] =
335+
&[sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer];
336+
330337
fn parse_register_tool(
331-
tools: &mut [&mut FxIndexSet<Ident>],
338+
tools: &mut [&mut FxIndexMap<Ident, ToolOptions>],
332339
cx: &mut AcceptContext<'_, '_>,
333340
args: &ArgParser,
334341
) {
@@ -346,9 +353,6 @@ fn parse_register_tool(
346353
cx.adcx().expected_identifier(elem.span());
347354
continue;
348355
};
349-
let Some(()) = cx.expect_no_args(elem.args()) else {
350-
continue;
351-
};
352356

353357
let path = elem.path();
354358
let Some(ident) = path.word() else {
@@ -366,9 +370,60 @@ fn parse_register_tool(
366370
continue;
367371
}
368372

373+
let reflectiveness =
374+
match elem.args() {
375+
ArgParser::NoArgs => NonReflective,
376+
ArgParser::List(list) => 'reflect: {
377+
// features are not available during first pass, gate is emitted during second pass
378+
if cx.features.is_some_and(|f| !f.type_info()) {
379+
feature_err(
380+
cx.sess(),
381+
sym::type_info,
382+
elem.span(),
383+
"tool attribute options are currently unstable",
384+
)
385+
.emit();
386+
break 'reflect NonReflective;
387+
}
388+
389+
let Some(itm) = cx.expect_single(list) else {
390+
break 'reflect NonReflective;
391+
};
392+
393+
let Some(itm) = itm.meta_item_no_args() else {
394+
cx.adcx().expected_no_args(itm.span());
395+
break 'reflect NonReflective;
396+
};
397+
398+
if !itm.path().word_is(sym::reflect) {
399+
cx.should_emit.emit_err(cx.dcx().create_err(UnrecognizedToolOption {
400+
span: itm.span(),
401+
option: itm.path().get_attribute_path(),
402+
}));
403+
404+
break 'reflect NonReflective;
405+
}
406+
407+
if PREDEFINED_TOOLS.iter().any(|t| t == &ident.name) {
408+
cx.should_emit.emit_err(cx.dcx().create_err(PredefinedToolReflective {
409+
span: elem.span(),
410+
tool: ident,
411+
}));
412+
413+
break 'reflect NonReflective;
414+
}
415+
416+
Reflective
417+
}
418+
ArgParser::NameValue(_) => {
419+
cx.adcx().expected_list_or_no_args(elem.span());
420+
NonReflective
421+
}
422+
};
423+
369424
let mut lint_emitted = false;
370425
for tools in tools.iter_mut() {
371-
if let Some(old_ident) = tools.replace(ident)
426+
let opts = if let Some((old_ident, old_opts)) = tools.get_key_value(&ident)
372427
&& !lint_emitted
373428
{
374429
lint_emitted = true;
@@ -377,7 +432,13 @@ fn parse_register_tool(
377432
DuplicateTool { span: ident.span, tool: ident, old_ident_span: old_ident.span },
378433
ident.span,
379434
);
380-
}
435+
436+
old_opts.union(ToolOptions { reflectiveness })
437+
} else {
438+
ToolOptions { reflectiveness }
439+
};
440+
441+
tools.insert(ident, opts);
381442
}
382443
}
383444
}
@@ -386,21 +447,21 @@ impl AttributeParser for RegisterToolParser {
386447
const ATTRIBUTES: AcceptMapping<Self> = &[
387448
(
388449
&[sym::register_tool],
389-
template!(List: &["tool1, tool2, ..."]),
450+
template!(List: &["tool1, tool2(reflect), ..."]),
390451
unstable!(register_tool),
391452
|this, cx, args| {
392453
parse_register_tool(&mut [&mut this.attr_tools, &mut this.lint_tools], cx, args)
393454
},
394455
),
395456
(
396457
&[sym::register_attribute_tool],
397-
template!(List: &["tool1, tool2, ..."]),
458+
template!(List: &["tool1, tool2(reflect), ..."]),
398459
unstable!(register_tool),
399460
|this, cx, args| parse_register_tool(&mut [&mut this.attr_tools], cx, args),
400461
),
401462
(
402463
&[sym::register_lint_tool],
403-
template!(List: &["tool1, tool2, ..."]),
464+
template!(List: &["tool1, tool2(reflect), ..."]),
404465
unstable!(register_tool),
405466
|this, cx, args| parse_register_tool(&mut [&mut this.lint_tools], cx, args),
406467
),

‎compiler/rustc_attr_parsing/src/diagnostics.rs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,24 @@ pub(crate) struct ToolReserved {
948948
pub(crate) tool: Ident,
949949
}
950950

951+
#[derive(Diagnostic)]
952+
#[diag("unrecognized tool option `{$option}`")]
953+
pub(crate) struct UnrecognizedToolOption {
954+
#[primary_span]
955+
pub(crate) span: Span,
956+
pub(crate) option: AttrPath,
957+
}
958+
959+
#[derive(Diagnostic)]
960+
#[diag(
961+
"the tool attribute `{$tool}` is predefined and cannot be marked as being available for reflection"
962+
)]
963+
pub(crate) struct PredefinedToolReflective {
964+
#[primary_span]
965+
pub(crate) span: Span,
966+
pub(crate) tool: Ident,
967+
}
968+
951969
#[derive(Diagnostic)]
952970
#[diag("unknown diagnostic attribute")]
953971
pub(crate) struct UnknownDiagnosticAttribute {

‎compiler/rustc_attr_parsing/src/interface.rs‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ use rustc_attr_ir::{AttrArgs, AttrItem, AttrPath, Attribute, AttributeKind, Hash
1010
use rustc_data_structures::sync::{DynSend, DynSync};
1111
use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
1212
use rustc_feature::{BUILTIN_ATTRIBUTE_SET, Features};
13-
use rustc_lint_defs::{LintId, RegisteredTools};
13+
use rustc_lint_defs::Reflectiveness::NonReflective;
14+
use rustc_lint_defs::{LintId, RegisteredTools, ToolOptions};
1415
use rustc_session::Session;
15-
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
16+
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, sym};
1617

1718
use crate::attributes::AttributeSafety;
1819
use crate::attributes::doc_comment::target_check_doc_comment;
@@ -470,7 +471,7 @@ impl<'sess> AttributeParser<'sess> {
470471
// we could be here in the `#[lint::attribute_macro] not found` case,
471472
// which recovers with a `NonMacroAttr` res.
472473
if let Some(tools) = self.attr_tools
473-
&& tools.iter().any(|i| i.name == sym::lint)
474+
&& tools.iter().any(|(i, _)| i.name == sym::lint)
474475
{
475476
self.emit_err(diagnostics::UnknownLintHelper {
476477
span: n.item.span,
@@ -507,7 +508,19 @@ impl<'sess> AttributeParser<'sess> {
507508
let attr = match attr_path.segments.len() {
508509
0 => unreachable!("no path for {attr:?}"),
509510
1 => Attribute::DeriveHelper(Box::new(attr)),
510-
_ => Attribute::Tool(Box::new(attr)),
511+
_ => {
512+
if let Some(tools) = self.attr_tools
513+
&& let Some(opts) =
514+
tools.get(&Ident::with_dummy_span(attr_path.segments[0]))
515+
{
516+
Attribute::Tool { item: Box::new(attr), opts: opts.clone() }
517+
} else {
518+
Attribute::Tool {
519+
item: Box::new(attr),
520+
opts: ToolOptions { reflectiveness: NonReflective },
521+
}
522+
}
523+
}
511524
};
512525

513526
attributes.push(attr);

0 commit comments

Comments
 (0)