Repository navigation
Description
Background
Several built-in attributes accept only integer literals where the argument is semantically a compile-time constant. The most common case is #[repr(align(N))], where N must be a literal even when the appropriate value is target-dependent and already exists as a const somewherein the crate graph.
Today this forces duplication across cfg branches:
#[cfg(target_arch = "x86_64")]
#[repr(align(64))]
pub struct CachePadded<T>(T);
#[cfg(target_arch = "aarch64")]
#[repr(align(128))]
pub struct CachePadded<T>(T);
#[cfg(any(target_arch = "arm", target_arch = "riscv32"))]
#[repr(align(32))]
pub struct CachePadded<T>(T);The same cfg ladder appears across the ecosystem with concurrency primitives (cache-line padding), crypto (side-channel hardening), embedded HALs (DMA buffer alignment), and any crate that aligns to a target-dependent value. The constant is known at compile time; the attribute just refuses to accept it in non-literal form.
C and C++ already support this via _Alignas(expr) / alignas(expr). Zig supports it via align(expr).
Proposal
Allow #[repr(align(N))] and #[repr(packed(N))] to accept paths to const items and constant expressions composed of such paths, in addition to integer literals.
pub const CACHELINE: usize = {
#[cfg(target_arch = "x86_64")] { 64 }
#[cfg(target_arch = "aarch64")] { 128 }
#[cfg(any(target_arch = "arm", target_arch =
"riscv32"))] { 32 }
};
#[repr(align(CACHELINE))]
pub struct CachePadded<T>(T);Proposed rules
- The argument must resolve to a const of the type the attribute already requires (for align and packed, a power-of-two usize).
- Resolution happens at attribute-processing time. The path must be visible in the dependency graph already established at that point — using a path that would require pulling in a new crate is an error. (I think this one is standard, I'm still learning the limitations of cargo dependency resolution.)
- Macro calls (align(some_macro!())) are out of scope. Only paths to already-defined constants and expressions over such paths are permitted.
- Errors at the attribute site (non-power-of-two, type mismatch, unresolved path) render at the attribute, not at the constant's definition.
Whatever form the backend machinery takes, the idea is to keep the semantics open and compatible with potential future expression resolution. I think it's important to be forward looking here.
Questions
- Syntactic vehicle. Should the surface syntax remain
#[repr(align(N))](with N resolving to a constant), or should the feature land through a different syntactic form?
Options raised so far in PR #154708
- Keep
#[repr(align(N))]as-is, with N extended to accept constant paths and expressions. Argued for by me and @programmerjake on the grounds that existing attribute syntax extends naturally - Treat the affected built-in attributes as active built-in attributes hardcoded in
rustc_expand(the model used by cfg / cfg_attr). - Implement as a built-in proc macro modeled on
#[define_opaque], with the surface attribute
preserved as the macro's invocation form. Suggested by @petrochenkov - A new dedicated syntax (e.g.,
align(CACHELINE) struct Foo;) — significantly larger scope, mentioned only for completeness.
- Backend mechanism. Independent of the syntactic vehicle, how should the constant payload be represented and resolved internally?
- (A) Extend the existing attribute IR to resolve constant paths during attribute lowering
- (B) Introduce a proper AST node (e.g.,
ast::Repr) carryingast::AnonConstpayloads, lowered through the usual AST → HIR → MIR pipeline.
The choice constrains and is constrained by the syntactic vehicle, which is why both questions appear here together.
- Scope. Is
#[repr(packed(N))]in scope alongside#[repr(align(N))]for the initial implementation, or should it be deferred? - String-valued attributes.
#[link_section = "..."]and#[export_name = "..."]have analogous motivation (target-dependent values forced into cfg ladders). Should they be considered in the same proposal, a follow-up, or deliberately left out? - Process. Is this an experiment-gated feature, or does it need a full RFC before implementation? @nnethercote raised this at the start of the PR review.
Prior Art
- RFC 3659 —
repr(tag = TypeAlias), currently S-waiting-on-team. Same tension between attributes-as-tokens and attributes-carrying-real-code, broader scope #[define_opaque](compiler/rustc_builtin_macros/src/define_opaque.rs) — existing built-in attribute that produces a proper AST node through a built-in proc macro. Reference implementation
patterncfg/cfg_attr— existing precedent for active built-in attributes producing AST inrustc_expand.- Implementation discussion: PR Add gated const item paths support for selected builtin attributes. #154708.
- Zulip Thread: #t-lang > #[repr(align(cacheline))] Support
cc @rust-lang/lang
Note: This is my first PR/Issue in rust itself, though I've used it and many other languages all my life, I'm very new to contributing to projects of this scale. I've been told a couple times that this is unreasonable as a first-time contribution, but this started as just a private "what if?" purely at parse time, and it just exploded from there after discussions were had. Regardless, I'm happy to do the leg work, and I'm learning a hell of a lot in the process, so I appreciate all the insight I've been given by everyone!
Activity
programmerjake commentedon Apr 16, 2026
I was thinking of
#[doc = path::to::CONST]as another place you could want arbitrary expressions, AFAIK it currently only supports macros that expand to a single string literal. Otoh we might want to exclude that as making tooling for docs too complex since it would require const-eval in addition to macro expansion.Paladynee commentedon Apr 17, 2026
wouldn't it be more feasible to provide the target "cacheline size" as a reliable cfg value instead of having to shoehorn consteval into attribute macros? or would that be too much to ask for if "cacheline size" is not really a stable thing to depend on?
BarronKane commentedon Apr 17, 2026
This was my original solution, being target based. Something like
repr(align(cacheline)), however this was received poorly for adding more complexity to the system as a whole and multiple devs and members reflected that they desired proper resolution rather than more parsing machinery.Paladynee commentedon Apr 17, 2026
ah sorry, i didnt see the zulip link.
BarronKane commentedon Apr 18, 2026
Yea I keep trying to find the MVP slice here, but the scope that would be seemingly acceptable to that keeps expanding, but there are two sides to it.
One one hand, if we can get the syntax side down, then the backend can be built piecemeal over time.
I.E. if
align(EXPR)was acceptable, or if the language side can be established at any level, then the backend can evolve slowly and attribute refactors can be done as needed rather than all at once.That was the original intention of my PR. Defend the semantics, shim the backend towards an eventual refactor.
There's multiple routes to the same endgame here, so this issue is meant to service the larger discussion, but I wanted to lay out my intentions here.
programmerjake commentedon Apr 18, 2026
more of what I was thinking is that we just extend
repr(align(N))andrepr(packed(N))(and other similar attributes) to allow putting the path to a constant there instead of a literalN, this would allow us to keep syntactical space for extending that to arbitrary expressions in the future but would also be simple enough that it wouldn't require major refactoring effort now.if this was done for
#[doc = ...], that already stably supports expanding macros, so that would need to be retained.BarronKane commentedon Apr 18, 2026
This is almost exactly the shape of my PR, honestly.
BarronKane commentedon Apr 18, 2026
Never responded to this, but I did want to note that I really like this. If we're going to go down the path of attribute level resolution at all, it would be extremely beneficial to consider a roadmap of everything that can make use of it.
Consts was always just a starting point, but it does mark the most practical case that fits 95% of needs for attribute level resolution.
BarronKane commentedon Apr 26, 2026
It's been about a week, so I'm going to go ahead and work on a prospective backend path for explicit lowering and introduce it into #154708 as a first step.
scottmcm commentedon Apr 29, 2026
cc also the alternative of putting this stuff into "real" const generics, like proposed in #154730
Personally I think I'd prefer that, since resolution in attributes always feels a bit awkward.
theemathas commentedon May 1, 2026
Prior discussion: #52840
2 remaining items
tmandry commentedon May 6, 2026
My vibe is positive from a lang perspective, though I predict that there will be implementation issues. I recall that resolving item paths in attributes was problematic.
I like the
#[repr(align(CONST_PATH))]syntax if we can implement it.joshtriplett commentedon May 6, 2026
This looks great to me, and I'd love to see the ability to set alignment using const expressions.
The alternative approach in #154730 is interesting, but seems like it'll need substantial additional design to address usability (e.g. having to handle the
Alignfield in initialization and pattern matching, and having it show up inderive(Debug), much likePhantomData).I think it's important that we work towards usability of the alignment mechanism we have,
repr(align(...)). And making const paths, and ideally const expressions, work in that would be a huge improvement that I've regularly seen people request. (That would allow factoring out common alignments, for instance.)mejrs commentedon May 6, 2026
If it's OK to migrate repr from an inert attribute to a builtin macro then the implementation is reasonably easy. This would look similar to define_opaque.I don't know if that is a breaking change and/or could be done across an edition.
We might be able to have repr be a builtin macro and have it masquerade as an attribute, too.
BarronKane commentedon May 10, 2026
Great input, all.
Should I create a new PR or rework the existing? Either's fine.
I see two options that satisfy the concerns and opinions put forward. Both options share the same backend: a new
ast::ReprAST node withAnonConstpayloads, lowered through the normal AST → HIR → MIR pipeline, modeled on#[define_opaque].They differ only in the surface vehicle:
Option 1 (@petrochenkov's first preference): Migrate
#[repr]to a built-in proc macro across an edition. Cleanest semantically; probably needs edition coordination as stated.Option 2 (his second listed option): Active built-in attribute materialized in
rustc_expand, same model ascfg/cfg_attr. Surface stays#[repr(align(CONST))]. One behavioral change (validation moves to parse time, including insidecfg(FALSE)— flagged in RFC #3659, worth a crater run).cc @joshtriplett @tmandry @programmerjake for the directly related input they gave.
I've done some testing with the above to good success, about ready to clean it up if it is desired. Or if anyone else has a criticism to be explored, I think I like option 1 better as it will open the door for any other attributes that may be desired in this process later.
Both options defend the existing attribute syntax.
programmerjake commentedon May 10, 2026
I'm not exactly sure how it works, but I'm worried a proc-macro or something similar will end up removing the
#[repr(...)]in later macro inputs, which would be a breaking change, e.g.:the
#[derive(MyTrait)]needs to be able to see the#[repr(...)]on the struct definition (I'm assuming that's what currently happens but haven't verified), but if it's a proc-macro I expect the attribute will get removed before the derives run.mejrs commentedon May 10, 2026
Then
prints
So the repr attribute indeed remains visible. When we try to "expand"
NonMacroAttrs we just insert it back and mark it as inert so that it is not expanded again. But replacing it by a macro would not have that behavior.We'll also have to handle things like this correctly:
Since a
reprbuiltin macro would change a field on ast items, this field would also need to survive any expansion steps following it. Otherwise we will run into problems like #153745If we want to have it "masquerade as an inert attribute", then likely we will need to something similar to regular inert attributes; mark it as inert but actually set it aside to expand it later when everything else has expanded.
mejrs commentedon May 10, 2026
@BarronKane let me propose another option: create a new builtin attribute macro with a different name.
That's the easiest way to get a WIP out there and figure out any bugs and other issues without having to think about the existing repr attribute too much. Then once it matures a bit we can have that discussion about whether it should be its own thing or subsume
#[repr]and how.petrochenkov commentedon May 10, 2026
That's exactly what I suggested on the PR - #154708 (comment).
BarronKane commentedon May 11, 2026
Indeed, let me try this route properly.
nikomatsakis commentedon May 13, 2026
Hi all, we discussed this in our lang-team call today. There was general meeting consensus that this seems like a "obviously desirable" feature in the abstract. From a lang perspective, as long as the const expressions are largely the same as const expressions elsewhere, this seems straightforward. The complexity lies on the implementation side (types, compiler team). So our general take is that we'd be happy with this work moving forward if there's a champion from types/compiler who wants to take it on!
Notes from Zulip.
BarronKane commentedon May 20, 2026
I'll have a PR ready this week! I've been working on this on the side from my jobs and college, so took a bit longer than anticipated. Thanks for the note!