#[repr(align(…))] should allow any constant expression, not just integer literals

Inspired by #[repr(align(…))] should allow arbitrary constant expressions, not just integer literals · Issue #52840 · rust-lang/rust · GitHub. Encountered while updating pyo3 to match upstream Python's _object layout: ci: Add 3.15 in CI by clin1234 · Pull Request #5518 · PyO3/pyo3 · GitHub

As someone who is very new in delving into how Rust's attributes are implemented, where would I start?

1 Like

Wouldn’t “any constant expression” potentially include 2 * align_of::<Self>() (perhaps indirectly)? The trait solver already has to handle (and emit errors for) cycles, but I don’t know if the part of the compiler responsible for choosing layouts can handle cycles.

More accurately, I think “any constant expression which could be used as the length of an array” would work. Not sure what the name for that sort of constant expression is, but (without const_generic_exprs or similar) those are more restricted.

Meanwhile, alignas can sort of be implemented with generics and zero-length arrays already, like [AlignAsThis; 0] (though it would also affect traits like Copy, so there’d be some benefit in an alignas attribute).

Good? Elain — Rust library // Lib.rs

2 Likes

TBH, I think that as an attribute putting an arbitrary const expression there is kinda icky. My instinct is that if it needs to be CTFE, it'd be easier to have a (probably-magic) struct Aligned<const ALIGNMENT: ptr::Alignment, T = ()>(pub T); that you could use, either as a wrapper or just add as a ZST field.

5 Likes