Skip to content

Commit 75561c4

Browse files
committed
Port #[link_ordinal] to the new attribute parsing infrastructure.
1 parent bfc046a commit 75561c4

File tree

20 files changed

+159
-150
lines changed

20 files changed

+159
-150
lines changed

compiler/rustc_attr_data_structures/src/attributes.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,9 @@ pub enum AttributeKind {
294294
/// Represents `#[link_name]`.
295295
LinkName { name: Symbol, span: Span },
296296

297+
/// Represents `#[link_ordinal]`.
298+
LinkOrdinal { ordinal: u16, span: Span },
299+
297300
/// Represents [`#[link_section]`](https://doc.rust-lang.org/reference/abi.html#the-link_section-attribute)
298301
LinkSection { name: Symbol, span: Span },
299302

compiler/rustc_attr_data_structures/src/encode_cross_crate.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ impl AttributeKind {
4040
Ignore { .. } => No,
4141
Inline(..) => No,
4242
LinkName { .. } => Yes,
43+
LinkOrdinal { .. } => No,
4344
LinkSection { .. } => No,
4445
LoopMatch(..) => No,
4546
MacroTransparency(..) => Yes,

compiler/rustc_attr_parsing/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,9 @@ attr_parsing_invalid_repr_hint_no_value =
7878
attr_parsing_invalid_since =
7979
'since' must be a Rust version number, such as "1.31.0"
8080
81+
attr_parsing_link_ordinal_out_of_range = ordinal value in `link_ordinal` is too large: `{$ordinal}`
82+
.note = the value may not exceed `u16::MAX`
83+
8184
attr_parsing_missing_feature =
8285
missing 'feature'
8386

compiler/rustc_attr_parsing/src/attributes/link_attrs.rs

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
use rustc_attr_data_structures::AttributeKind;
2-
use rustc_attr_data_structures::AttributeKind::{LinkName, LinkSection};
2+
use rustc_attr_data_structures::AttributeKind::{LinkName, LinkOrdinal, LinkSection};
33
use rustc_feature::{AttributeTemplate, template};
44
use rustc_span::{Span, Symbol, sym};
55

66
use crate::attributes::{
77
AttributeOrder, NoArgsAttributeParser, OnDuplicate, SingleAttributeParser,
88
};
9-
use crate::context::{AcceptContext, Stage};
9+
use crate::context::{AcceptContext, Stage, parse_single_integer};
1010
use crate::parser::ArgParser;
11-
use crate::session_diagnostics::NullOnLinkSection;
11+
use crate::session_diagnostics::{LinkOrdinalOutOfRange, NullOnLinkSection};
1212

1313
pub(crate) struct LinkNameParser;
1414

@@ -87,3 +87,36 @@ impl<S: Stage> NoArgsAttributeParser<S> for StdInternalSymbolParser {
8787
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
8888
const CREATE: fn(Span) -> AttributeKind = AttributeKind::StdInternalSymbol;
8989
}
90+
91+
pub(crate) struct LinkOrdinalParser;
92+
93+
impl<S: Stage> SingleAttributeParser<S> for LinkOrdinalParser {
94+
const PATH: &[Symbol] = &[sym::link_ordinal];
95+
const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost;
96+
const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Error;
97+
const TEMPLATE: AttributeTemplate = template!(List: "ordinal");
98+
99+
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
100+
let ordinal = parse_single_integer(cx, args)?;
101+
102+
// According to the table at
103+
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header, the
104+
// ordinal must fit into 16 bits. Similarly, the Ordinal field in COFFShortExport (defined
105+
// in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import
106+
// information to LLVM for `#[link(kind = "raw-dylib"_])`, is also defined to be uint16_t.
107+
//
108+
// FIXME: should we allow an ordinal of 0? The MSVC toolchain has inconsistent support for
109+
// this: both LINK.EXE and LIB.EXE signal errors and abort when given a .DEF file that
110+
// specifies a zero ordinal. However, llvm-dlltool is perfectly happy to generate an import
111+
// library for such a .DEF file, and MSVC's LINK.EXE is also perfectly happy to consume an
112+
// import library produced by LLVM with an ordinal of 0, and it generates an .EXE. (I
113+
// don't know yet if the resulting EXE runs, as I haven't yet built the necessary DLL --
114+
// see earlier comment about LINK.EXE failing.)
115+
let Ok(ordinal) = ordinal.try_into() else {
116+
cx.emit_err(LinkOrdinalOutOfRange { span: cx.attr_span, ordinal });
117+
return None;
118+
};
119+
120+
Some(LinkOrdinal { ordinal, span: cx.attr_span })
121+
}
122+
}

compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
use rustc_ast::LitKind;
21
use rustc_attr_data_structures::AttributeKind;
32
use rustc_feature::{AttributeTemplate, template};
43
use rustc_span::{Symbol, sym};
54

65
use crate::attributes::{AttributeOrder, OnDuplicate, SingleAttributeParser};
7-
use crate::context::{AcceptContext, Stage};
6+
use crate::context::{AcceptContext, Stage, parse_single_integer};
87
use crate::parser::ArgParser;
98

109
pub(crate) struct RustcLayoutScalarValidRangeStart;
@@ -16,8 +15,8 @@ impl<S: Stage> SingleAttributeParser<S> for RustcLayoutScalarValidRangeStart {
1615
const TEMPLATE: AttributeTemplate = template!(List: "start");
1716

1817
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
19-
parse_rustc_layout_scalar_valid_range(cx, args)
20-
.map(|n| AttributeKind::RustcLayoutScalarValidRangeStart(n, cx.attr_span))
18+
parse_single_integer(cx, args)
19+
.map(|n| AttributeKind::RustcLayoutScalarValidRangeStart(Box::new(n), cx.attr_span))
2120
}
2221
}
2322

@@ -30,34 +29,11 @@ impl<S: Stage> SingleAttributeParser<S> for RustcLayoutScalarValidRangeEnd {
3029
const TEMPLATE: AttributeTemplate = template!(List: "end");
3130

3231
fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser<'_>) -> Option<AttributeKind> {
33-
parse_rustc_layout_scalar_valid_range(cx, args)
34-
.map(|n| AttributeKind::RustcLayoutScalarValidRangeEnd(n, cx.attr_span))
32+
parse_single_integer(cx, args)
33+
.map(|n| AttributeKind::RustcLayoutScalarValidRangeEnd(Box::new(n), cx.attr_span))
3534
}
3635
}
3736

38-
fn parse_rustc_layout_scalar_valid_range<S: Stage>(
39-
cx: &mut AcceptContext<'_, '_, S>,
40-
args: &ArgParser<'_>,
41-
) -> Option<Box<u128>> {
42-
let Some(list) = args.list() else {
43-
cx.expected_list(cx.attr_span);
44-
return None;
45-
};
46-
let Some(single) = list.single() else {
47-
cx.expected_single_argument(list.span);
48-
return None;
49-
};
50-
let Some(lit) = single.lit() else {
51-
cx.expected_integer_literal(single.span());
52-
return None;
53-
};
54-
let LitKind::Int(num, _ty) = lit.kind else {
55-
cx.expected_integer_literal(single.span());
56-
return None;
57-
};
58-
Some(Box::new(num.0))
59-
}
60-
6137
pub(crate) struct RustcObjectLifetimeDefaultParser;
6238

6339
impl<S: Stage> SingleAttributeParser<S> for RustcObjectLifetimeDefaultParser {

compiler/rustc_attr_parsing/src/context.rs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::ops::{Deref, DerefMut};
55
use std::sync::LazyLock;
66

77
use private::Sealed;
8-
use rustc_ast::{self as ast, MetaItemLit, NodeId};
8+
use rustc_ast::{self as ast, LitKind, MetaItemLit, NodeId};
99
use rustc_attr_data_structures::AttributeKind;
1010
use rustc_attr_data_structures::lints::{AttributeLint, AttributeLintKind};
1111
use rustc_errors::{DiagCtxtHandle, Diagnostic};
@@ -24,8 +24,8 @@ use crate::attributes::deprecation::DeprecationParser;
2424
use crate::attributes::dummy::DummyParser;
2525
use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
2626
use crate::attributes::link_attrs::{
27-
ExportStableParser, FfiConstParser, FfiPureParser, LinkNameParser, LinkSectionParser,
28-
StdInternalSymbolParser,
27+
ExportStableParser, FfiConstParser, FfiPureParser, LinkNameParser, LinkOrdinalParser,
28+
LinkSectionParser, StdInternalSymbolParser,
2929
};
3030
use crate::attributes::lint_helpers::{AsPtrParser, PassByValueParser, PubTransparentParser};
3131
use crate::attributes::loop_match::{ConstContinueParser, LoopMatchParser};
@@ -141,6 +141,7 @@ attribute_parsers!(
141141
Single<IgnoreParser>,
142142
Single<InlineParser>,
143143
Single<LinkNameParser>,
144+
Single<LinkOrdinalParser>,
144145
Single<LinkSectionParser>,
145146
Single<MustUseParser>,
146147
Single<OptimizeParser>,
@@ -767,3 +768,32 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
767768
}
768769
}
769770
}
771+
772+
/// Parse a single integer.
773+
///
774+
/// Used by attributes that take a single integer as argument, such as
775+
/// `#[link_ordinal]` and `#[rustc_layout_scalar_valid_range_start]`.
776+
/// `cx` is the context given to the attribute.
777+
/// `args` is the parser for the attribute arguments.
778+
pub(crate) fn parse_single_integer<S: Stage>(
779+
cx: &mut AcceptContext<'_, '_, S>,
780+
args: &ArgParser<'_>,
781+
) -> Option<u128> {
782+
let Some(list) = args.list() else {
783+
cx.expected_list(cx.attr_span);
784+
return None;
785+
};
786+
let Some(single) = list.single() else {
787+
cx.expected_single_argument(list.span);
788+
return None;
789+
};
790+
let Some(lit) = single.lit() else {
791+
cx.expected_integer_literal(single.span());
792+
return None;
793+
};
794+
let LitKind::Int(num, _ty) = lit.kind else {
795+
cx.expected_integer_literal(single.span());
796+
return None;
797+
};
798+
Some(num.0)
799+
}

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -514,6 +514,15 @@ pub(crate) struct NakedFunctionIncompatibleAttribute {
514514
pub attr: String,
515515
}
516516

517+
#[derive(Diagnostic)]
518+
#[diag(attr_parsing_link_ordinal_out_of_range)]
519+
#[note]
520+
pub(crate) struct LinkOrdinalOutOfRange {
521+
#[primary_span]
522+
pub span: Span,
523+
pub ordinal: u128,
524+
}
525+
517526
pub(crate) enum AttributeParseErrorReason {
518527
ExpectedNoArgs,
519528
ExpectedStringLiteral { byte_string: Option<Span> },

compiler/rustc_codegen_ssa/messages.ftl

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,6 @@ codegen_ssa_ignoring_emit_path = ignoring emit path because multiple .{$extensio
8080
8181
codegen_ssa_ignoring_output = ignoring -o because multiple .{$extension} files were produced
8282
83-
codegen_ssa_illegal_link_ordinal_format = illegal ordinal format in `link_ordinal`
84-
.note = an unsuffixed integer value, e.g., `1`, is expected
85-
8683
codegen_ssa_incorrect_cgu_reuse_type =
8784
CGU-reuse for `{$cgu_user_name}` is `{$actual_reuse}` but should be {$at_least ->
8885
[one] {"at least "}
@@ -93,9 +90,6 @@ codegen_ssa_insufficient_vs_code_product = VS Code is a different product, and i
9390
9491
codegen_ssa_invalid_instruction_set = invalid instruction set specified
9592
96-
codegen_ssa_invalid_link_ordinal_nargs = incorrect number of arguments to `#[link_ordinal]`
97-
.note = the attribute requires exactly one argument
98-
9993
codegen_ssa_invalid_literal_value = invalid literal value
10094
.label = value must be an integer between `0` and `255`
10195

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 4 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
116116
AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
117117
AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
118118
AttributeKind::LinkName { name, .. } => codegen_fn_attrs.link_name = Some(*name),
119+
AttributeKind::LinkOrdinal { ordinal, span } => {
120+
codegen_fn_attrs.link_ordinal = Some(*ordinal);
121+
link_ordinal_span = Some(*span);
122+
}
119123
AttributeKind::LinkSection { name, .. } => {
120124
codegen_fn_attrs.link_section = Some(*name)
121125
}
@@ -250,12 +254,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
250254
}
251255
}
252256
}
253-
sym::link_ordinal => {
254-
link_ordinal_span = Some(attr.span());
255-
if let ordinal @ Some(_) = check_link_ordinal(tcx, attr) {
256-
codegen_fn_attrs.link_ordinal = ordinal;
257-
}
258-
}
259257
sym::no_sanitize => {
260258
no_sanitize_span = Some(attr.span());
261259
if let Some(list) = attr.meta_item_list() {
@@ -568,45 +566,6 @@ fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
568566
tcx.codegen_fn_attrs(opt_trait_item(tcx, def_id)?).alignment
569567
}
570568

571-
fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &hir::Attribute) -> Option<u16> {
572-
use rustc_ast::{LitIntType, LitKind, MetaItemLit};
573-
let meta_item_list = attr.meta_item_list()?;
574-
let [sole_meta_list] = &meta_item_list[..] else {
575-
tcx.dcx().emit_err(errors::InvalidLinkOrdinalNargs { span: attr.span() });
576-
return None;
577-
};
578-
if let Some(MetaItemLit { kind: LitKind::Int(ordinal, LitIntType::Unsuffixed), .. }) =
579-
sole_meta_list.lit()
580-
{
581-
// According to the table at
582-
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-header, the
583-
// ordinal must fit into 16 bits. Similarly, the Ordinal field in COFFShortExport (defined
584-
// in llvm/include/llvm/Object/COFFImportFile.h), which we use to communicate import
585-
// information to LLVM for `#[link(kind = "raw-dylib"_])`, is also defined to be uint16_t.
586-
//
587-
// FIXME: should we allow an ordinal of 0? The MSVC toolchain has inconsistent support for
588-
// this: both LINK.EXE and LIB.EXE signal errors and abort when given a .DEF file that
589-
// specifies a zero ordinal. However, llvm-dlltool is perfectly happy to generate an import
590-
// library for such a .DEF file, and MSVC's LINK.EXE is also perfectly happy to consume an
591-
// import library produced by LLVM with an ordinal of 0, and it generates an .EXE. (I
592-
// don't know yet if the resulting EXE runs, as I haven't yet built the necessary DLL --
593-
// see earlier comment about LINK.EXE failing.)
594-
if *ordinal <= u16::MAX as u128 {
595-
Some(ordinal.get() as u16)
596-
} else {
597-
let msg = format!("ordinal value in `link_ordinal` is too large: `{ordinal}`");
598-
tcx.dcx()
599-
.struct_span_err(attr.span(), msg)
600-
.with_note("the value may not exceed `u16::MAX`")
601-
.emit();
602-
None
603-
}
604-
} else {
605-
tcx.dcx().emit_err(errors::InvalidLinkOrdinalFormat { span: attr.span() });
606-
None
607-
}
608-
}
609-
610569
fn check_link_name_xor_ordinal(
611570
tcx: TyCtxt<'_>,
612571
codegen_fn_attrs: &CodegenFnAttrs,

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1108,22 +1108,6 @@ pub(crate) struct InvalidNoSanitize {
11081108
pub span: Span,
11091109
}
11101110

1111-
#[derive(Diagnostic)]
1112-
#[diag(codegen_ssa_invalid_link_ordinal_nargs)]
1113-
#[note]
1114-
pub(crate) struct InvalidLinkOrdinalNargs {
1115-
#[primary_span]
1116-
pub span: Span,
1117-
}
1118-
1119-
#[derive(Diagnostic)]
1120-
#[diag(codegen_ssa_illegal_link_ordinal_format)]
1121-
#[note]
1122-
pub(crate) struct InvalidLinkOrdinalFormat {
1123-
#[primary_span]
1124-
pub span: Span,
1125-
}
1126-
11271111
#[derive(Diagnostic)]
11281112
#[diag(codegen_ssa_target_feature_safe_trait)]
11291113
pub(crate) struct TargetFeatureSafeTrait {

0 commit comments

Comments
 (0)