Skip to content

Commit d386600

Browse files
Rollup merge of #142986 - JonathanBrouwer:export_name_parser, r=jdonszelmann
Port `#[export_name]` to the new attribute parsing infrastructure This PR contains two changes, in separate commits for reviewability: - Ports `export_name` to the new attribute parsing infrastructure for #131229 (comment) - Moves the check for mixing export_name/no_mangle to check_attr.rs and improve the error message, which previously had a mix of 2021/2024 edition syntax r? ``@jdonszelmann``
2 parents c5ac143 + 3d1cee5 commit d386600

21 files changed

+215
-125
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,14 @@ pub enum AttributeKind {
231231
/// Represents [`#[doc]`](https://doc.rust-lang.org/stable/rustdoc/write-documentation/the-doc-attribute.html).
232232
DocComment { style: AttrStyle, kind: CommentKind, span: Span, comment: Symbol },
233233

234+
/// Represents [`#[export_name]`](https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute).
235+
ExportName {
236+
/// The name to export this item with.
237+
/// It may not contain \0 bytes as it will be converted to a null-terminated string.
238+
name: Symbol,
239+
span: Span,
240+
},
241+
234242
/// Represents `#[inline]` and `#[rustc_force_inline]`.
235243
Inline(InlineAttr, Span),
236244

compiler/rustc_attr_data_structures/src/encode_cross_crate.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ impl AttributeKind {
2222
ConstStabilityIndirect => No,
2323
Deprecation { .. } => Yes,
2424
DocComment { .. } => Yes,
25+
ExportName { .. } => Yes,
2526
Inline(..) => No,
2627
MacroTransparency(..) => Yes,
2728
Repr(..) => No,

compiler/rustc_attr_parsing/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,12 @@ attr_parsing_naked_functions_incompatible_attribute =
9393
attribute incompatible with `#[unsafe(naked)]`
9494
.label = the `{$attr}` attribute is incompatible with `#[unsafe(naked)]`
9595
.naked_attribute = function marked with `#[unsafe(naked)]` here
96+
9697
attr_parsing_non_ident_feature =
9798
'feature' is not an identifier
9899
100+
attr_parsing_null_on_export = `export_name` may not contain null characters
101+
99102
attr_parsing_repr_ident =
100103
meta item in `repr` must be an identifier
101104

compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rustc_span::{Span, Symbol, sym};
66
use super::{AcceptMapping, AttributeOrder, AttributeParser, OnDuplicate, SingleAttributeParser};
77
use crate::context::{AcceptContext, FinalizeContext, Stage};
88
use crate::parser::ArgParser;
9-
use crate::session_diagnostics::NakedFunctionIncompatibleAttribute;
9+
use crate::session_diagnostics::{NakedFunctionIncompatibleAttribute, NullOnExport};
1010

1111
pub(crate) struct OptimizeParser;
1212

@@ -59,6 +59,33 @@ impl<S: Stage> SingleAttributeParser<S> for ColdParser {
5959
}
6060
}
6161

62+
pub(crate) struct ExportNameParser;
63+
64+
impl<S: Stage> SingleAttributeParser<S> for ExportNameParser {
65+
const PATH: &[rustc_span::Symbol] = &[sym::export_name];
66+
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst;
67+
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::WarnButFutureError;
68+
const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name");
69+
70+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
71+
let Some(nv) = args.name_value() else {
72+
cx.expected_name_value(cx.attr_span, None);
73+
return None;
74+
};
75+
let Some(name) = nv.value_as_str() else {
76+
cx.expected_string_literal(nv.value_span, Some(nv.value_as_lit()));
77+
return None;
78+
};
79+
if name.as_str().contains('\0') {
80+
// `#[export_name = ...]` will be converted to a null-terminated string,
81+
// so it may not contain any null characters.
82+
cx.emit_err(NullOnExport { span: cx.attr_span });
83+
return None;
84+
}
85+
Some(AttributeKind::ExportName { name, span: cx.attr_span })
86+
}
87+
}
88+
6289
#[derive(Default)]
6390
pub(crate) struct NakedParser {
6491
span: Option<Span>,

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, ExportNameParser, NakedParser, NoMangleParser, OptimizeParser, TrackCallerParser,
2020
};
2121
use crate::attributes::confusables::ConfusablesParser;
2222
use crate::attributes::deprecation::DeprecationParser;
@@ -117,6 +117,7 @@ attribute_parsers!(
117117
Single<ConstContinueParser>,
118118
Single<ConstStabilityIndirectParser>,
119119
Single<DeprecationParser>,
120+
Single<ExportNameParser>,
120121
Single<InlineParser>,
121122
Single<LoopMatchParser>,
122123
Single<MayDangleParser>,

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,13 @@ pub(crate) struct MustUseIllFormedAttributeInput {
445445
pub suggestions: DiagArgValue,
446446
}
447447

448+
#[derive(Diagnostic)]
449+
#[diag(attr_parsing_null_on_export, code = E0648)]
450+
pub(crate) struct NullOnExport {
451+
#[primary_span]
452+
pub span: Span,
453+
}
454+
448455
#[derive(Diagnostic)]
449456
#[diag(attr_parsing_stability_outside_std, code = E0734)]
450457
pub(crate) struct StabilityOutsideStd {

compiler/rustc_codegen_ssa/messages.ftl

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -205,11 +205,6 @@ codegen_ssa_missing_features = add the missing features in a `target_feature` at
205205
codegen_ssa_missing_query_depgraph =
206206
found CGU-reuse attribute but `-Zquery-dep-graph` was not specified
207207
208-
codegen_ssa_mixed_export_name_and_no_mangle = `{$no_mangle_attr}` attribute may not be used in combination with `#[export_name]`
209-
.label = `{$no_mangle_attr}` is ignored
210-
.note = `#[export_name]` takes precedence
211-
.suggestion = remove the `{$no_mangle_attr}` attribute
212-
213208
codegen_ssa_msvc_missing_linker = the msvc targets depend on the msvc linker but `link.exe` was not found
214209
215210
codegen_ssa_multiple_external_func_decl = multiple declarations of external function `{$function}` from library `{$library_name}` have different calling conventions
@@ -230,8 +225,6 @@ codegen_ssa_no_natvis_directory = error enumerating natvis directory: {$error}
230225
231226
codegen_ssa_no_saved_object_file = cached cgu {$cgu_name} should have an object file, but doesn't
232227
233-
codegen_ssa_null_on_export = `export_name` may not contain null characters
234-
235228
codegen_ssa_out_of_range_integer = integer value out of range
236229
.label = value must be between `0` and `255`
237230

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 4 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use rustc_attr_data_structures::{
99
use rustc_hir::def::DefKind;
1010
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
1111
use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
12-
use rustc_hir::{self as hir, HirId, LangItem, lang_items};
12+
use rustc_hir::{self as hir, LangItem, lang_items};
1313
use rustc_middle::middle::codegen_fn_attrs::{
1414
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
1515
};
@@ -87,7 +87,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
8787

8888
let mut link_ordinal_span = None;
8989
let mut no_sanitize_span = None;
90-
let mut mixed_export_name_no_mangle_lint_state = MixedExportNameAndNoMangleState::default();
9190

9291
for attr in attrs.iter() {
9392
// In some cases, attribute are only valid on functions, but it's the `check_attr`
@@ -119,16 +118,14 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
119118
.max();
120119
}
121120
AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
121+
AttributeKind::ExportName { name, .. } => {
122+
codegen_fn_attrs.export_name = Some(*name);
123+
}
122124
AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
123125
AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
124126
AttributeKind::NoMangle(attr_span) => {
125127
if tcx.opt_item_name(did.to_def_id()).is_some() {
126128
codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
127-
mixed_export_name_no_mangle_lint_state.track_no_mangle(
128-
*attr_span,
129-
tcx.local_def_id_to_hir_id(did),
130-
attr,
131-
);
132129
} else {
133130
tcx.dcx().emit_err(NoMangleNameless {
134131
span: *attr_span,
@@ -223,17 +220,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
223220
}
224221
}
225222
sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
226-
sym::export_name => {
227-
if let Some(s) = attr.value_str() {
228-
if s.as_str().contains('\0') {
229-
// `#[export_name = ...]` will be converted to a null-terminated string,
230-
// so it may not contain any null characters.
231-
tcx.dcx().emit_err(errors::NullOnExport { span: attr.span() });
232-
}
233-
codegen_fn_attrs.export_name = Some(s);
234-
mixed_export_name_no_mangle_lint_state.track_export_name(attr.span());
235-
}
236-
}
237223
sym::target_feature => {
238224
let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
239225
tcx.dcx().span_delayed_bug(attr.span(), "target_feature applied to non-fn");
@@ -444,8 +430,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
444430
}
445431
}
446432

447-
mixed_export_name_no_mangle_lint_state.lint_if_mixed(tcx);
448-
449433
// Apply the minimum function alignment here, so that individual backends don't have to.
450434
codegen_fn_attrs.alignment =
451435
Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
@@ -672,49 +656,6 @@ fn check_link_name_xor_ordinal(
672656
}
673657
}
674658

675-
#[derive(Default)]
676-
struct MixedExportNameAndNoMangleState<'a> {
677-
export_name: Option<Span>,
678-
hir_id: Option<HirId>,
679-
no_mangle: Option<Span>,
680-
no_mangle_attr: Option<&'a hir::Attribute>,
681-
}
682-
683-
impl<'a> MixedExportNameAndNoMangleState<'a> {
684-
fn track_export_name(&mut self, span: Span) {
685-
self.export_name = Some(span);
686-
}
687-
688-
fn track_no_mangle(&mut self, span: Span, hir_id: HirId, attr_name: &'a hir::Attribute) {
689-
self.no_mangle = Some(span);
690-
self.hir_id = Some(hir_id);
691-
self.no_mangle_attr = Some(attr_name);
692-
}
693-
694-
/// Emit diagnostics if the lint condition is met.
695-
fn lint_if_mixed(self, tcx: TyCtxt<'_>) {
696-
if let Self {
697-
export_name: Some(export_name),
698-
no_mangle: Some(no_mangle),
699-
hir_id: Some(hir_id),
700-
no_mangle_attr: Some(_),
701-
} = self
702-
{
703-
tcx.emit_node_span_lint(
704-
lint::builtin::UNUSED_ATTRIBUTES,
705-
hir_id,
706-
no_mangle,
707-
errors::MixedExportNameAndNoMangle {
708-
no_mangle,
709-
no_mangle_attr: "#[unsafe(no_mangle)]".to_string(),
710-
export_name,
711-
removal_span: no_mangle,
712-
},
713-
);
714-
}
715-
}
716-
}
717-
718659
/// We now check the #\[rustc_autodiff\] attributes which we generated from the #[autodiff(...)]
719660
/// macros. There are two forms. The pure one without args to mark primal functions (the functions
720661
/// being differentiated). The other form is #[rustc_autodiff(Mode, ActivityList)] on top of the

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,6 @@ pub(crate) struct RequiresRustAbi {
140140
pub span: Span,
141141
}
142142

143-
#[derive(Diagnostic)]
144-
#[diag(codegen_ssa_null_on_export, code = E0648)]
145-
pub(crate) struct NullOnExport {
146-
#[primary_span]
147-
pub span: Span,
148-
}
149-
150143
#[derive(Diagnostic)]
151144
#[diag(codegen_ssa_unsupported_instruction_set, code = E0779)]
152145
pub(crate) struct UnsupportedInstructionSet {
@@ -1207,18 +1200,6 @@ pub(crate) struct ErrorCreatingImportLibrary<'a> {
12071200
#[diag(codegen_ssa_aix_strip_not_used)]
12081201
pub(crate) struct AixStripNotUsed;
12091202

1210-
#[derive(LintDiagnostic)]
1211-
#[diag(codegen_ssa_mixed_export_name_and_no_mangle)]
1212-
pub(crate) struct MixedExportNameAndNoMangle {
1213-
#[label]
1214-
pub no_mangle: Span,
1215-
pub no_mangle_attr: String,
1216-
#[note]
1217-
pub export_name: Span,
1218-
#[suggestion(style = "verbose", code = "", applicability = "machine-applicable")]
1219-
pub removal_span: Span,
1220-
}
1221-
12221203
#[derive(Diagnostic, Debug)]
12231204
pub(crate) enum XcrunError {
12241205
#[diag(codegen_ssa_xcrun_failed_invoking)]

compiler/rustc_lint/src/builtin.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -977,9 +977,9 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
977977
};
978978
match it.kind {
979979
hir::ItemKind::Fn { generics, .. } => {
980-
if let Some(attr_span) = attr::find_by_name(attrs, sym::export_name)
981-
.map(|at| at.span())
982-
.or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
980+
if let Some(attr_span) =
981+
find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
982+
.or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
983983
{
984984
check_no_mangle_on_generic_fn(attr_span, None, generics, it.span);
985985
}
@@ -1010,9 +1010,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
10101010
for it in *items {
10111011
if let hir::AssocItemKind::Fn { .. } = it.kind {
10121012
let attrs = cx.tcx.hir_attrs(it.id.hir_id());
1013-
if let Some(attr_span) = attr::find_by_name(attrs, sym::export_name)
1014-
.map(|at| at.span())
1015-
.or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
1013+
if let Some(attr_span) =
1014+
find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
1015+
.or_else(
1016+
|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span),
1017+
)
10161018
{
10171019
check_no_mangle_on_generic_fn(
10181020
attr_span,

compiler/rustc_passes/messages.ftl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,11 @@ passes_missing_panic_handler =
486486
passes_missing_stability_attr =
487487
{$descr} has missing stability attribute
488488
489+
passes_mixed_export_name_and_no_mangle = `{$no_mangle_attr}` attribute may not be used in combination with `{$export_name_attr}`
490+
.label = `{$no_mangle_attr}` is ignored
491+
.note = `{$export_name_attr}` takes precedence
492+
.suggestion = remove the `{$no_mangle_attr}` attribute
493+
489494
passes_multiple_rustc_main =
490495
multiple functions with a `#[rustc_main]` attribute
491496
.first = first `#[rustc_main]` function

0 commit comments

Comments
 (0)