Skip to content

Commit 708f45f

Browse files
Port #[used] to new attribute parsing infrastructure
Signed-off-by: Jonathan Brouwer <jonathantbrouwer@gmail.com>
1 parent a17780d commit 708f45f

File tree

14 files changed

+184
-125
lines changed

14 files changed

+184
-125
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
@@ -277,5 +288,8 @@ pub enum AttributeKind {
277288

278289
/// Represents `#[track_caller]`
279290
TrackCaller(Span),
291+
292+
/// Represents `#[used]`
293+
Used { used_by: UsedBy, span: Span },
280294
// tidy-alphabetical-end
281295
}

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr};
1+
use rustc_attr_data_structures::{AttributeKind, OptimizeAttr, UsedBy};
22
use rustc_feature::{AttributeTemplate, template};
33
use rustc_session::parse::feature_err;
44
use rustc_span::{Span, Symbol, sym};
@@ -201,3 +201,84 @@ impl<S: Stage> SingleAttributeParser<S> for NoMangleParser {
201201
Some(AttributeKind::NoMangle(cx.attr_span))
202202
}
203203
}
204+
205+
#[derive(Default)]
206+
pub(crate) struct UsedParser {
207+
first_compiler: Option<Span>,
208+
first_linker: Option<Span>,
209+
}
210+
211+
// A custom `AttributeParser` is used rather than a Simple attribute parser because
212+
// - Specifying two `#[used]` attributes is a warning (but will be an error in the future)
213+
// - But specifying two conflicting attributes: `#[used(compiler)]` and `#[used(linker)]` is already an error today
214+
// We can change this to a Simple parser once the warning becomes an error
215+
impl<S: Stage> AttributeParser<S> for UsedParser {
216+
const ATTRIBUTES: AcceptMapping<Self, S> = &[(
217+
&[sym::used],
218+
template!(Word, List: "compiler|linker"),
219+
|group: &mut Self, cx, args| {
220+
let used_by = match args {
221+
ArgParser::NoArgs => UsedBy::Linker,
222+
ArgParser::List(list) => {
223+
let Some(l) = list.single() else {
224+
cx.expected_single_argument(list.span);
225+
return;
226+
};
227+
228+
match l.meta_item().and_then(|i| i.path().word_sym()) {
229+
Some(sym::compiler) => {
230+
if !cx.features().used_with_arg() {
231+
feature_err(
232+
&cx.sess(),
233+
sym::used_with_arg,
234+
cx.attr_span,
235+
"`#[used(compiler)]` is currently unstable",
236+
)
237+
.emit();
238+
}
239+
UsedBy::Compiler
240+
}
241+
Some(sym::linker) => {
242+
if !cx.features().used_with_arg() {
243+
feature_err(
244+
&cx.sess(),
245+
sym::used_with_arg,
246+
cx.attr_span,
247+
"`#[used(linker)]` is currently unstable",
248+
)
249+
.emit();
250+
}
251+
UsedBy::Linker
252+
}
253+
_ => {
254+
cx.expected_specific_argument(l.span(), vec!["compiler", "linker"]);
255+
return;
256+
}
257+
}
258+
}
259+
ArgParser::NameValue(_) => return,
260+
};
261+
262+
let target = match used_by {
263+
UsedBy::Compiler => &mut group.first_compiler,
264+
UsedBy::Linker => &mut group.first_linker,
265+
};
266+
267+
let attr_span = cx.attr_span;
268+
if let Some(prev) = *target {
269+
cx.warn_unused_duplicate(prev, attr_span);
270+
} else {
271+
*target = Some(attr_span);
272+
}
273+
},
274+
)];
275+
276+
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
277+
// Ratcheting behaviour, if both `linker` and `compiler` are specified, use `linker`
278+
Some(match (self.first_compiler, self.first_linker) {
279+
(_, Some(span)) => AttributeKind::Used { used_by: UsedBy::Linker, span },
280+
(Some(span), _) => AttributeKind::Used { used_by: UsedBy::Compiler, span },
281+
(None, None) => return None,
282+
})
283+
}
284+
}

compiler/rustc_attr_parsing/src/context.rs

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

1717
use crate::attributes::allow_unstable::{AllowConstFnUnstableParser, AllowInternalUnstableParser};
1818
use crate::attributes::codegen_attrs::{
19-
ColdParser, NakedParser, NoMangleParser, OptimizeParser, TrackCallerParser,
19+
ColdParser, NakedParser, NoMangleParser, OptimizeParser, TrackCallerParser, UsedParser,
2020
};
2121
use crate::attributes::confusables::ConfusablesParser;
2222
use crate::attributes::deprecation::DeprecationParser;
@@ -103,6 +103,7 @@ attribute_parsers!(
103103
ConstStabilityParser,
104104
NakedParser,
105105
StabilityParser,
106+
UsedParser,
106107
// tidy-alphabetical-end
107108

108109
// 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};
@@ -163,6 +163,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
163163
}
164164
codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
165165
}
166+
AttributeKind::Used { used_by, .. } => match used_by {
167+
UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
168+
UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
169+
},
166170
_ => {}
167171
}
168172
}
@@ -184,44 +188,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
184188
sym::rustc_std_internal_symbol => {
185189
codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
186190
}
187-
sym::used => {
188-
let inner = attr.meta_item_list();
189-
match inner.as_deref() {
190-
Some([item]) if item.has_name(sym::linker) => {
191-
if !tcx.features().used_with_arg() {
192-
feature_err(
193-
&tcx.sess,
194-
sym::used_with_arg,
195-
attr.span(),
196-
"`#[used(linker)]` is currently unstable",
197-
)
198-
.emit();
199-
}
200-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
201-
}
202-
Some([item]) if item.has_name(sym::compiler) => {
203-
if !tcx.features().used_with_arg() {
204-
feature_err(
205-
&tcx.sess,
206-
sym::used_with_arg,
207-
attr.span(),
208-
"`#[used(compiler)]` is currently unstable",
209-
)
210-
.emit();
211-
}
212-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER;
213-
}
214-
Some(_) => {
215-
tcx.dcx().emit_err(errors::ExpectedUsedSymbol { span: attr.span() });
216-
}
217-
None => {
218-
// Unconditionally using `llvm.used` causes issues in handling
219-
// `.init_array` with the gold linker. Luckily gold has been
220-
// deprecated with GCC 15 and rustc now warns about using gold.
221-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER
222-
}
223-
}
224-
}
225191
sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
226192
sym::export_name => {
227193
if let Some(s) = attr.value_str() {

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
@@ -811,9 +811,6 @@ passes_unused_variable_try_prefix = unused variable: `{$name}`
811811
.suggestion = if this is intentional, prefix it with an underscore
812812
813813
814-
passes_used_compiler_linker =
815-
`used(compiler)` and `used(linker)` can't be used together
816-
817814
passes_used_static =
818815
attribute must be applied to a `static` variable
819816
.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
@@ -195,6 +195,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
195195
Attribute::Parsed(AttributeKind::NoMangle(attr_span)) => {
196196
self.check_no_mangle(hir_id, *attr_span, span, target)
197197
}
198+
Attribute::Parsed(AttributeKind::Used { span: attr_span, .. }) => {
199+
self.check_used(*attr_span, target, span);
200+
}
198201
Attribute::Unparsed(attr_item) => {
199202
style = Some(attr_item.style);
200203
match attr.path().as_slice() {
@@ -329,7 +332,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
329332
| sym::cfi_encoding // FIXME(cfi_encoding)
330333
| sym::pointee // FIXME(derive_coerce_pointee)
331334
| sym::omit_gdb_pretty_printer_section // FIXME(omit_gdb_pretty_printer_section)
332-
| sym::used // handled elsewhere to restrict to static items
333335
| sym::instruction_set // broken on stable!!!
334336
| sym::windows_subsystem // broken on stable!!!
335337
| sym::patchable_function_entry // FIXME(patchable_function_entry)
@@ -399,7 +401,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
399401
}
400402

401403
self.check_repr(attrs, span, target, item, hir_id);
402-
self.check_used(attrs, target, span);
403404
self.check_rustc_force_inline(hir_id, attrs, span, target);
404405
}
405406

@@ -2102,44 +2103,13 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
21022103
}
21032104
}
21042105

2105-
fn check_used(&self, attrs: &[Attribute], target: Target, target_span: Span) {
2106-
let mut used_linker_span = None;
2107-
let mut used_compiler_span = None;
2108-
for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
2109-
if target != Target::Static {
2110-
self.dcx().emit_err(errors::UsedStatic {
2111-
attr_span: attr.span(),
2112-
span: target_span,
2113-
target: target.name(),
2114-
});
2115-
}
2116-
let inner = attr.meta_item_list();
2117-
match inner.as_deref() {
2118-
Some([item]) if item.has_name(sym::linker) => {
2119-
if used_linker_span.is_none() {
2120-
used_linker_span = Some(attr.span());
2121-
}
2122-
}
2123-
Some([item]) if item.has_name(sym::compiler) => {
2124-
if used_compiler_span.is_none() {
2125-
used_compiler_span = Some(attr.span());
2126-
}
2127-
}
2128-
Some(_) => {
2129-
// This error case is handled in rustc_hir_analysis::collect.
2130-
}
2131-
None => {
2132-
// Default case (compiler) when arg isn't defined.
2133-
if used_compiler_span.is_none() {
2134-
used_compiler_span = Some(attr.span());
2135-
}
2136-
}
2137-
}
2138-
}
2139-
if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
2140-
self.tcx
2141-
.dcx()
2142-
.emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
2106+
fn check_used(&self, attr_span: Span, target: Target, target_span: Span) {
2107+
if target != Target::Static {
2108+
self.dcx().emit_err(errors::UsedStatic {
2109+
attr_span,
2110+
span: target_span,
2111+
target: target.name(),
2112+
});
21432113
}
21442114
}
21452115

compiler/rustc_passes/src/errors.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -629,13 +629,6 @@ pub(crate) struct UsedStatic {
629629
pub target: &'static str,
630630
}
631631

632-
#[derive(Diagnostic)]
633-
#[diag(passes_used_compiler_linker)]
634-
pub(crate) struct UsedCompilerLinker {
635-
#[primary_span]
636-
pub spans: Vec<Span>,
637-
}
638-
639632
#[derive(Diagnostic)]
640633
#[diag(passes_allow_internal_unstable)]
641634
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)