Skip to content

Lang proposal: const expressions in #[repr(align)] and #[repr(packed)] and friends. #155390

Open

Description

@BarronKane

View all comments

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

  1. The argument must resolve to a const of the type the attribute already requires (for align and packed, a power-of-two usize).
  2. 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.)
  3. Macro calls (align(some_macro!())) are out of scope. Only paths to already-defined constants and expressions over such paths are permitted.
  4. 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

  1. 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.
  1. 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) carrying ast::AnonConst payloads, 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.

  1. Scope. Is #[repr(packed(N))] in scope alongside #[repr(align(N))] for the initial implementation, or should it be deferred?
  2. 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?
  3. 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

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

  1. added
    needs-triage
    on Apr 16, 2026
  2. programmerjake commented on Apr 16, 2026

    @programmerjake
    Member

    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.

  3. Paladynee commented on Apr 17, 2026

    @Paladynee
    Contributor

    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?

  4. BarronKane commented on Apr 17, 2026

    @BarronKane
    Author

    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?

    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.

  5. Paladynee commented on Apr 17, 2026

    @Paladynee
    Contributor

    ah sorry, i didnt see the zulip link.

  6. BarronKane commented on Apr 18, 2026

    @BarronKane
    Author

    ah sorry, i didnt see the zulip link.

    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.

  7. programmerjake commented on Apr 18, 2026

    @programmerjake
    Member

    more of what I was thinking is that we just extend repr(align(N)) and repr(packed(N)) (and other similar attributes) to allow putting the path to a constant there instead of a literal N, 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.

  8. BarronKane commented on Apr 18, 2026

    @BarronKane
    Author

    more of what I was thinking is that we just extend repr(align(N)) and repr(packed(N)) (and other similar attributes) to allow putting the path to a constant there instead of a literal N, 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.

    This is almost exactly the shape of my PR, honestly.

  9. BarronKane commented on Apr 18, 2026

    @BarronKane
    Author

    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.

    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.

  10. BarronKane commented on Apr 26, 2026

    @BarronKane
    Author

    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.

  11. added
    T-lang
    I-lang-nominated
    on Apr 26, 2026
  12. added
    P-lang-drag-1
    on Apr 29, 2026
  13. scottmcm commented on Apr 29, 2026

    @scottmcm
    Member

    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.

  14. theemathas commented on May 1, 2026

    @theemathas
    Contributor

    Prior discussion: #52840

  15. 2 remaining items

  16. tmandry commented on May 6, 2026

    @tmandry
    Member

    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.

  17. joshtriplett commented on May 6, 2026

    @joshtriplett
    Member

    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 Align field in initialization and pattern matching, and having it show up in derive(Debug), much like PhantomData).

    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.)

  18. mejrs commented on May 6, 2026

    @mejrs
    Member

    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.

    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.

  19. BarronKane commented on May 10, 2026

    @BarronKane
    Author

    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::Repr AST node with AnonConst payloads, 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 as cfg/cfg_attr. Surface stays #[repr(align(CONST))]. One behavioral change (validation moves to parse time, including inside cfg(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.

  20. programmerjake commented on May 10, 2026

    @programmerjake
    Member

    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.:

    #[repr(align(128)]
    #[derive(MyTrait)]
    pub struct S;

    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.

  21. mejrs commented on May 10, 2026

    @mejrs
    Member

    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),

    #[proc_macro_derive(PrintIt)]
    pub fn assert_return_type_copy(item: TokenStream) -> TokenStream {
        println!("proc_macro_derive: `{item}`");
        TokenStream::new()
    }
    
    #[proc_macro_attribute]
    pub fn print_it(_attr: proc_macro::TokenStream, item: proc_macro::TokenStream) -> TokenStream {
        println!("proc_macro_attr: `{item}`");
        item
    }

    Then

    #[repr(C)]
    #[print_it]
    #[derive(PrintIt)]
    pub struct Foo;

    prints

    proc_macro_attr: `#[repr(C)] #[derive(PrintIt)] pub struct Foo;` 
    proc_macro_derive: `#[repr(C)] pub struct Foo;`
    

    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:

    macro_rules! make_struct {
        ($name:ident) => { pub struct $name; }
    }
    
    #[repr(C)]
    make_struct!(Bar);

    Since a repr builtin 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 #153745

    If 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.

  22. mejrs commented on May 10, 2026

    @mejrs
    Member

    @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.

  23. petrochenkov commented on May 10, 2026

    @petrochenkov
    Contributor

    @BarronKane let me propose another option: create a new builtin attribute macro with a different name.

    That's exactly what I suggested on the PR - #154708 (comment).

  24. BarronKane commented on May 11, 2026

    @BarronKane
    Author

    @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.

    Indeed, let me try this route properly.

  25. added
    I-lang-radar
    and removed
    I-lang-nominated
    needs-triage
    P-lang-drag-1
    on May 13, 2026
  26. nikomatsakis commented on May 13, 2026

    @nikomatsakis
    Contributor

    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.

  27. BarronKane commented on May 20, 2026

    @BarronKane
    Author

    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.

    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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalA-reprI-lang-radarT-lang

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions