Pre-RFC: #[align] attribute

Ok, when it was phrased as "types" in the original post I thought it was still types in the rust sense.

Agreed that if it's just about the alignment of fields it's fine.

as i see it, the main utility of this sort of namespacing is preventing namespace pollution... which seems like it has dubious utility, i'm not sure what else #[align] could mean in this position exempt exactly this. i guess it's possible there's a proc macro out there that uses this already.

Well, it sort of is, because the ideal solution would be to have the ability to define a WgslVec3 type that will just do the right thing when used in a #[repr(C)] structure. But, as you pointed out, that would require breaking a fundamental Rust design choice.

Explicit field alignments like this are the next-best thing, but are still fundamentally a work-around for the impedance mismatch between the two languages.

2 Likes

another usecase for this would be to guarantee a struct's layout is the same for all architectures. could be useful if it doesn't have any non-u8 fields.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

I just learned about Tracking Issue for `#[repr(align(...))]` on function items (fn_align) · Issue #82232 · rust-lang/rust · GitHub. Perhaps that should use #[align] also?

2 Likes

As an extra bit of background/prior art: especially in an embedded context, sections are used to force the alignment of functions and statics.

For embedded projects, you typically define your own sections, and their alignment, explicitly in a linker file. Important functions/statics can get their own section, and the alignment of the item will be the alignment of the section. The section is specified with with #[link_section].

Note: this is not a good solution, but one that works today. It's easy to make mistakes with section names or sizes: the #[link_section] attribute is unsafe for good reasons. So having #[align] directly on statics and functions would be a big improvement.

1 Like

I asked some embedded folks, to try and find a concrete example, and there is one here:

/// Ethernet descriptor rings are a global singleton
#[link_section = ".sram3.eth"]
static mut DES_RING: MaybeUninit<ethernet::DesRing<4, 4>> =
    MaybeUninit::uninit();

Which uses the .sram3 linker section defined here:

  .sram3 (NOLOAD) : ALIGN(4) {
    *(.sram3 .sram3.*);
    . = ALIGN(4);
    } > SRAM3

This section performs double-duty: it puts the static in a special bit of ram, but also forces the alignment. With #[align], that alignment can be dropped from the linker file.


We should not get bogged down with syntax, but T-lang seemed to like #[align = N] instead of #[align(N)], So that's something to maybe touch on in an eventual RFC.

3 Likes

RFC is up: RFC: Add an attribute for raising the alignment of various items by Jules-Bertholet · Pull Request #3806 · rust-lang/rfcs · GitHub

1 Like