Skip to content

Commit 0031aab

Browse files
Port #[used] to new attribute parsing infrastructure
Signed-off-by: Jonathan Brouwer <[email protected]>
1 parent 42245d3 commit 0031aab

File tree

14 files changed

+186
-125
lines changed

14 files changed

+186
-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
@@ -265,5 +276,8 @@ pub enum AttributeKind {
265276
/// Span of the attribute.
266277
span: Span,
267278
},
279+
280+
/// Represents `#[used]`
281+
Used { used_by: UsedBy, span: Span },
268282
// tidy-alphabetical-end
269283
}

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, sym};
@@ -183,3 +183,84 @@ impl<S: Stage> SingleAttributeParser<S> for NoMangleParser {
183183
Some(AttributeKind::NoMangle(cx.attr_span))
184184
}
185185
}
186+
187+
#[derive(Default)]
188+
pub(crate) struct UsedParser {
189+
first_compiler: Option<Span>,
190+
first_linker: Option<Span>,
191+
}
192+
193+
// A custom `AttributeParser` is used rather than a Simple attribute parser because
194+
// - Specifying two `#[used]` attributes is a warning (but will be an error in the future)
195+
// - But specifying two conflicting attributes: `#[used(compiler)]` and `#[used(linker)]` is already an error today
196+
// We can change this to a Simple parser once the warning becomes an error
197+
impl<S: Stage> AttributeParser<S> for UsedParser {
198+
const ATTRIBUTES: AcceptMapping<Self, S> = &[(
199+
&[sym::used],
200+
template!(Word, List: "compiler|linker"),
201+
|group: &mut Self, cx, args| {
202+
let used_by = match args {
203+
ArgParser::NoArgs => UsedBy::Linker,
204+
ArgParser::List(list) => {
205+
let Some(l) = list.single() else {
206+
cx.expected_single_argument(list.span);
207+
return;
208+
};
209+
210+
match l.meta_item().and_then(|i| i.path().word_sym()) {
211+
Some(sym::compiler) => {
212+
if !cx.features().used_with_arg() {
213+
feature_err(
214+
&cx.sess(),
215+
sym::used_with_arg,
216+
cx.attr_span,
217+
"`#[used(compiler)]` is currently unstable",
218+
)
219+
.emit();
220+
}
221+
UsedBy::Compiler
222+
}
223+
Some(sym::linker) => {
224+
if !cx.features().used_with_arg() {
225+
feature_err(
226+
&cx.sess(),
227+
sym::used_with_arg,
228+
cx.attr_span,
229+
"`#[used(linker)]` is currently unstable",
230+
)
231+
.emit();
232+
}
233+
UsedBy::Linker
234+
}
235+
_ => {
236+
cx.expected_specific_argument(l.span(), vec!["compiler", "linker"]);
237+
return;
238+
}
239+
}
240+
}
241+
ArgParser::NameValue(_) => return,
242+
};
243+
244+
let target = match used_by {
245+
UsedBy::Compiler => &mut group.first_compiler,
246+
UsedBy::Linker => &mut group.first_linker,
247+
};
248+
249+
let attr_span = cx.attr_span;
250+
if let Some(prev) = *target {
251+
cx.warn_unused_duplicate(prev, attr_span);
252+
} else {
253+
*target = Some(attr_span);
254+
}
255+
},
256+
)];
257+
258+
fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
259+
// Ratcheting behaviour, if both `linker` and `compiler` are specified, use `linker`
260+
Some(match (self.first_compiler, self.first_linker) {
261+
(_, Some(span)) => AttributeKind::Used { used_by: UsedBy::Linker, span },
262+
(Some(span), _) => AttributeKind::Used { used_by: UsedBy::Compiler, span },
263+
(None, None) => return None,
264+
})
265+
}
266+
}

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ 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, NakedParser, NoMangleParser, OptimizeParser};
18+
use crate::attributes::codegen_attrs::{
19+
ColdParser, NakedParser, NoMangleParser, OptimizeParser, UsedParser,
20+
};
1921
use crate::attributes::confusables::ConfusablesParser;
2022
use crate::attributes::deprecation::DeprecationParser;
2123
use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
@@ -99,6 +101,7 @@ attribute_parsers!(
99101
ConstStabilityParser,
100102
NakedParser,
101103
StabilityParser,
104+
UsedParser,
102105
// tidy-alphabetical-end
103106

104107
// 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};
@@ -142,6 +142,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
142142
});
143143
}
144144
}
145+
AttributeKind::Used { used_by, .. } => match used_by {
146+
UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
147+
UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
148+
},
145149
_ => {}
146150
}
147151
}
@@ -169,44 +173,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
169173
sym::rustc_std_internal_symbol => {
170174
codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
171175
}
172-
sym::used => {
173-
let inner = attr.meta_item_list();
174-
match inner.as_deref() {
175-
Some([item]) if item.has_name(sym::linker) => {
176-
if !tcx.features().used_with_arg() {
177-
feature_err(
178-
&tcx.sess,
179-
sym::used_with_arg,
180-
attr.span(),
181-
"`#[used(linker)]` is currently unstable",
182-
)
183-
.emit();
184-
}
185-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER;
186-
}
187-
Some([item]) if item.has_name(sym::compiler) => {
188-
if !tcx.features().used_with_arg() {
189-
feature_err(
190-
&tcx.sess,
191-
sym::used_with_arg,
192-
attr.span(),
193-
"`#[used(compiler)]` is currently unstable",
194-
)
195-
.emit();
196-
}
197-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER;
198-
}
199-
Some(_) => {
200-
tcx.dcx().emit_err(errors::ExpectedUsedSymbol { span: attr.span() });
201-
}
202-
None => {
203-
// Unconditionally using `llvm.used` causes issues in handling
204-
// `.init_array` with the gold linker. Luckily gold has been
205-
// deprecated with GCC 15 and rustc now warns about using gold.
206-
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER
207-
}
208-
}
209-
}
210176
sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
211177
sym::track_caller => {
212178
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
@@ -804,9 +804,6 @@ passes_unused_variable_try_prefix = unused variable: `{$name}`
804804
.suggestion = if this is intentional, prefix it with an underscore
805805
806806
807-
passes_used_compiler_linker =
808-
`used(compiler)` and `used(linker)` can't be used together
809-
810807
passes_used_static =
811808
attribute must be applied to a `static` variable
812809
.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
@@ -180,6 +180,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
180180
Attribute::Parsed(AttributeKind::NoMangle(attr_span)) => {
181181
self.check_no_mangle(hir_id, *attr_span, span, target)
182182
}
183+
Attribute::Parsed(AttributeKind::Used { span: attr_span, .. }) => {
184+
self.check_used(*attr_span, target, span);
185+
}
183186
Attribute::Unparsed(attr_item) => {
184187
style = Some(attr_item.style);
185188
match attr.path().as_slice() {
@@ -317,7 +320,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
317320
| sym::cfi_encoding // FIXME(cfi_encoding)
318321
| sym::pointee // FIXME(derive_coerce_pointee)
319322
| sym::omit_gdb_pretty_printer_section // FIXME(omit_gdb_pretty_printer_section)
320-
| sym::used // handled elsewhere to restrict to static items
321323
| sym::instruction_set // broken on stable!!!
322324
| sym::windows_subsystem // broken on stable!!!
323325
| sym::patchable_function_entry // FIXME(patchable_function_entry)
@@ -387,7 +389,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
387389
}
388390

389391
self.check_repr(attrs, span, target, item, hir_id);
390-
self.check_used(attrs, target, span);
391392
self.check_rustc_force_inline(hir_id, attrs, span, target);
392393
}
393394

@@ -2095,44 +2096,13 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
20952096
}
20962097
}
20972098

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

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)