Skip to content

Commit e70cbef

Browse files
Port #[used] to new attribute parsing infrastructure
Signed-off-by: Jonathan Brouwer <[email protected]>
1 parent 8051f01 commit e70cbef

File tree

14 files changed

+195
-128
lines changed

14 files changed

+195
-128
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,17 @@ impl Deprecation {
131131
}
132132
}
133133

134+
/// There are three valid forms of the attribute:
135+
/// `#[used]`, which is semantically equivalent to `#[used(linker)]` except that the latter is currently unstable.
136+
/// `#[used(compiler)]`
137+
/// `#[used(linker)]`
138+
#[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)]
139+
#[derive(HashStable_Generic, PrintAttribute)]
140+
pub enum UsedBy {
141+
Compiler,
142+
Linker,
143+
}
144+
134145
/// Represents parsed *built-in* inert attributes.
135146
///
136147
/// ## Overview
@@ -249,5 +260,8 @@ pub enum AttributeKind {
249260
/// Span of the attribute.
250261
span: Span,
251262
},
263+
264+
/// Represents `#[used]`
265+
Used { used_by: UsedBy, span: Span },
252266
// tidy-alphabetical-end
253267
}

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 93 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr};
1+
use rustc_attr_data_structures::lints::AttributeLintKind;
2+
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr, UsedBy};
23
use rustc_feature::{AttributeTemplate, template};
3-
use rustc_span::sym;
4+
use rustc_session::parse::feature_err;
5+
use rustc_span::{Span, sym};
46

5-
use super::{AttributeOrder, OnDuplicate, SingleAttributeParser};
6-
use crate::context::{AcceptContext, Stage};
7+
use super::{AcceptMapping, AttributeOrder, AttributeParser, OnDuplicate, SingleAttributeParser};
8+
use crate::context::{AcceptContext, FinalizeContext, Stage};
79
use crate::parser::ArgParser;
810

911
pub(crate) struct OptimizeParser;
@@ -56,3 +58,90 @@ impl<S: Stage> SingleAttributeParser<S> for ColdParser {
5658
Some(AttributeKind::Cold(cx.attr_span))
5759
}
5860
}
61+
62+
#[derive(Default)]
63+
pub(crate) struct UsedParser {
64+
first_compiler: Option<Span>,
65+
first_linker: Option<Span>,
66+
}
67+
68+
// A custom `AttributeParser` is used rather than a Simple attribute parser because
69+
// - Specifying two `#[used]` attributes is a warning (but will be an error in the future)
70+
// - But specifying two conflicting attributes: `#[used(compiler)]` and `#[used(linker)]` is already an error today
71+
// We can change this to a Simple parser once the warning becomes an error
72+
impl<S: Stage> AttributeParser<S> for UsedParser {
73+
const ATTRIBUTES: AcceptMapping<Self, S> = &[(
74+
&[sym::used],
75+
template!(Word, List: "compiler|linker"),
76+
|group: &mut Self, cx, args| {
77+
let used_by = match args {
78+
ArgParser::NoArgs => UsedBy::Linker,
79+
ArgParser::List(list) => {
80+
let Some(l) = list.single() else {
81+
cx.expected_single_argument(list.span);
82+
return;
83+
};
84+
85+
match l.meta_item().and_then(|i| i.path().word_sym()) {
86+
Some(sym::compiler) => {
87+
if !cx.features().used_with_arg() {
88+
feature_err(
89+
&cx.sess(),
90+
sym::used_with_arg,
91+
cx.attr_span,
92+
"`#[used(compiler)]` is currently unstable",
93+
)
94+
.emit();
95+
}
96+
UsedBy::Compiler
97+
}
98+
Some(sym::linker) => {
99+
if !cx.features().used_with_arg() {
100+
feature_err(
101+
&cx.sess(),
102+
sym::used_with_arg,
103+
cx.attr_span,
104+
"`#[used(linker)]` is currently unstable",
105+
)
106+
.emit();
107+
}
108+
UsedBy::Linker
109+
}
110+
_ => {
111+
cx.expected_specific_argument(l.span(), vec!["compiler", "linker"]);
112+
return;
113+
}
114+
}
115+
}
116+
ArgParser::NameValue(_) => return,
117+
};
118+
119+
let target = match used_by {
120+
UsedBy::Compiler => &mut group.first_compiler,
121+
UsedBy::Linker => &mut group.first_linker,
122+
};
123+
124+
if let Some(prev) = *target {
125+
cx.emit_lint(
126+
AttributeLintKind::UnusedDuplicate {
127+
this: cx.attr_span,
128+
other: prev,
129+
warning: false,
130+
},
131+
cx.attr_span,
132+
);
133+
} else {
134+
*target = Some(cx.attr_span);
135+
}
136+
},
137+
)];
138+
139+
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
140+
// Ratcheting behaviour, if both `linker` and `compiler` are specified, use `linker`
141+
Some(match (self.first_compiler, self.first_linker) {
142+
(_, Some(span)) => AttributeKind::Used { used_by: UsedBy::Linker, span },
143+
(Some(span), _) => AttributeKind::Used { used_by: UsedBy::Compiler, span },
144+
(None, None) => return None,
145+
})
146+
}
147+
}

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use rustc_session::Session;
1515
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
1616

1717
use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
18-
use crate::attributes::codegen_attrs::{ColdParser, OptimizeParser};
18+
use crate::attributes::codegen_attrs::{ColdParser, OptimizeParser, UsedParser};
1919
use crate::attributes::confusables::ConfusablesParser;
2020
use crate::attributes::deprecation::DeprecationParser;
2121
use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
@@ -97,6 +97,7 @@ attribute_parsers!(
9797
ConfusablesParser,
9898
ConstStabilityParser,
9999
StabilityParser,
100+
UsedParser,
100101
// tidy-alphabetical-end
101102

102103
// tidy-alphabetical-start

compiler/rustc_codegen_ssa/messages.ftl

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,6 @@ codegen_ssa_error_writing_def_file =
4848
4949
codegen_ssa_expected_name_value_pair = expected name value pair
5050
51-
codegen_ssa_expected_used_symbol = expected `used`, `used(compiler)` or `used(linker)`
52-
5351
codegen_ssa_extern_funcs_not_found = some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
5452
5553
codegen_ssa_extract_bundled_libs_archive_member = failed to get data from archive member '{$rlib}': {$error}

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 5 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_abi::ExternAbi;
44
use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
55
use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr};
66
use rustc_attr_data_structures::{
7-
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, ReprAttr, find_attr,
7+
AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr, ReprAttr, UsedBy, find_attr,
88
};
99
use rustc_hir::def::DefKind;
1010
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
@@ -122,6 +122,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
122122
}
123123
AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
124124
AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
125+
AttributeKind::Used { used_by, .. } => match used_by {
126+
UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
127+
UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
128+
},
125129
_ => {}
126130
}
127131
}
@@ -166,44 +170,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
166170
sym::rustc_std_internal_symbol => {
167171
codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
168172
}
169-
sym::used => {
170-
let inner = attr.meta_item_list();
171-
match inner.as_deref() {
172-
Some([item]) if item.has_name(sym::linker) => {
173-
if !tcx.features().used_with_arg() {
174-
feature_err(
175-
&tcx.sess,
176-
sym::used_with_arg,
177-
attr.span(),
178-
"`#[used(linker)]` is currently unstable",
179-
)
180-
.emit();
181-
}
182-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
183-
}
184-
Some([item]) if item.has_name(sym::compiler) => {
185-
if !tcx.features().used_with_arg() {
186-
feature_err(
187-
&tcx.sess,
188-
sym::used_with_arg,
189-
attr.span(),
190-
"`#[used(compiler)]` is currently unstable",
191-
)
192-
.emit();
193-
}
194-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER;
195-
}
196-
Some(_) => {
197-
tcx.dcx().emit_err(errors::ExpectedUsedSymbol { span: attr.span() });
198-
}
199-
None => {
200-
// Unconditionally using `llvm.used` causes issues in handling
201-
// `.init_array` with the gold linker. Luckily gold has been
202-
// deprecated with GCC 15 and rustc now warns about using gold.
203-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER
204-
}
205-
}
206-
}
207173
sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
208174
sym::track_caller => {
209175
let is_closure = tcx.is_closure_like(did.to_def_id());

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -733,13 +733,6 @@ pub struct UnknownArchiveKind<'a> {
733733
pub kind: &'a str,
734734
}
735735

736-
#[derive(Diagnostic)]
737-
#[diag(codegen_ssa_expected_used_symbol)]
738-
pub(crate) struct ExpectedUsedSymbol {
739-
#[primary_span]
740-
pub span: Span,
741-
}
742-
743736
#[derive(Diagnostic)]
744737
#[diag(codegen_ssa_multiple_main_functions)]
745738
#[help]

compiler/rustc_passes/messages.ftl

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -809,9 +809,6 @@ passes_unused_variable_try_prefix = unused variable: `{$name}`
809809
.suggestion = if this is intentional, prefix it with an underscore
810810
811811
812-
passes_used_compiler_linker =
813-
`used(compiler)` and `used(linker)` can't be used together
814-
815812
passes_used_static =
816813
attribute must be applied to a `static` variable
817814
.label = but this is a {$target}

compiler/rustc_passes/src/check_attr.rs

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
166166
&Attribute::Parsed(AttributeKind::MayDangle(attr_span)) => {
167167
self.check_may_dangle(hir_id, attr_span)
168168
}
169+
Attribute::Parsed(AttributeKind::Used { span: attr_span, .. }) => {
170+
self.check_used(*attr_span, target, span);
171+
}
169172
Attribute::Unparsed(_) => {
170173
match attr.path().as_slice() {
171174
[sym::diagnostic, sym::do_not_recommend, ..] => {
@@ -305,7 +308,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
305308
| sym::cfi_encoding // FIXME(cfi_encoding)
306309
| sym::pointee // FIXME(derive_coerce_pointee)
307310
| sym::omit_gdb_pretty_printer_section // FIXME(omit_gdb_pretty_printer_section)
308-
| sym::used // handled elsewhere to restrict to static items
309311
| sym::instruction_set // broken on stable!!!
310312
| sym::windows_subsystem // broken on stable!!!
311313
| sym::patchable_function_entry // FIXME(patchable_function_entry)
@@ -375,7 +377,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
375377
}
376378

377379
self.check_repr(attrs, span, target, item, hir_id);
378-
self.check_used(attrs, target, span);
379380
self.check_rustc_force_inline(hir_id, attrs, span, target);
380381
}
381382

@@ -2191,44 +2192,13 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
21912192
}
21922193
}
21932194

2194-
fn check_used(&self, attrs: &[Attribute], target: Target, target_span: Span) {
2195-
let mut used_linker_span = None;
2196-
let mut used_compiler_span = None;
2197-
for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
2198-
if target != Target::Static {
2199-
self.dcx().emit_err(errors::UsedStatic {
2200-
attr_span: attr.span(),
2201-
span: target_span,
2202-
target: target.name(),
2203-
});
2204-
}
2205-
let inner = attr.meta_item_list();
2206-
match inner.as_deref() {
2207-
Some([item]) if item.has_name(sym::linker) => {
2208-
if used_linker_span.is_none() {
2209-
used_linker_span = Some(attr.span());
2210-
}
2211-
}
2212-
Some([item]) if item.has_name(sym::compiler) => {
2213-
if used_compiler_span.is_none() {
2214-
used_compiler_span = Some(attr.span());
2215-
}
2216-
}
2217-
Some(_) => {
2218-
// This error case is handled in rustc_hir_analysis::collect.
2219-
}
2220-
None => {
2221-
// Default case (compiler) when arg isn't defined.
2222-
if used_compiler_span.is_none() {
2223-
used_compiler_span = Some(attr.span());
2224-
}
2225-
}
2226-
}
2227-
}
2228-
if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
2229-
self.tcx
2230-
.dcx()
2231-
.emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
2195+
fn check_used(&self, attr_span: Span, target: Target, target_span: Span) {
2196+
if target != Target::Static {
2197+
self.dcx().emit_err(errors::UsedStatic {
2198+
attr_span,
2199+
span: target_span,
2200+
target: target.name(),
2201+
});
22322202
}
22332203
}
22342204

compiler/rustc_passes/src/errors.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -611,13 +611,6 @@ pub(crate) struct UsedStatic {
611611
pub target: &'static str,
612612
}
613613

614-
#[derive(Diagnostic)]
615-
#[diag(passes_used_compiler_linker)]
616-
pub(crate) struct UsedCompilerLinker {
617-
#[primary_span]
618-
pub spans: Vec<Span>,
619-
}
620-
621614
#[derive(Diagnostic)]
622615
#[diag(passes_allow_internal_unstable)]
623616
pub(crate) struct AllowInternalUnstable {

tests/ui/attributes/used_with_arg.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![deny(unused_attributes)]
12
#![feature(used_with_arg)]
23

34
#[used(linker)]
@@ -6,14 +7,22 @@ static mut USED_LINKER: [usize; 1] = [0];
67
#[used(compiler)]
78
static mut USED_COMPILER: [usize; 1] = [0];
89

9-
#[used(compiler)] //~ ERROR `used(compiler)` and `used(linker)` can't be used together
10+
#[used(compiler)]
1011
#[used(linker)]
1112
static mut USED_COMPILER_LINKER2: [usize; 1] = [0];
1213

13-
#[used(compiler)] //~ ERROR `used(compiler)` and `used(linker)` can't be used together
14-
#[used(linker)]
1514
#[used(compiler)]
1615
#[used(linker)]
16+
#[used(compiler)] //~ ERROR unused attribute
17+
#[used(linker)] //~ ERROR unused attribute
1718
static mut USED_COMPILER_LINKER3: [usize; 1] = [0];
1819

20+
#[used(compiler)]
21+
#[used]
22+
static mut USED_WITHOUT_ATTR1: [usize; 1] = [0];
23+
24+
#[used(linker)]
25+
#[used] //~ ERROR unused attribute
26+
static mut USED_WITHOUT_ATTR2: [usize; 1] = [0];
27+
1928
fn main() {}

0 commit comments

Comments
 (0)