Skip to content

repr(transparent) could accept singleton ZST with alignment > 1. #100954

Closed
@pnkfelix

Description

@pnkfelix

I tried this code:

#[repr(transparent)]
struct R([usize; 0]);

I expected to see this happen: That code could be accepted.

Instead, this happened: The code is rejected, with the diagnostic:

error[[E0691]](https://doc.rust-lang.org/nightly/error-index.html#E0691): zero-sized field in transparent struct has alignment larger than 1
 --> src/lib.rs:2:10
  |
2 | struct R([usize; 0]);
  |          ^^^^^^^^^^ has alignment larger than 1

For more information about this error, try `rustc --explain E0691`.

That is, we could loosen the repr(transparent) rules to say that it "requires at most one field that occupies memory"; this is a loosening of our current rules on two levels:

  • It would allow for there to be no non-ZST fields in the struct. Today we require exactly one non-ZST field in a repr(transparent) struct
  • It would replace the predicate "ZST/non-ZST" with "occupies/does-not-occupy memory" -- the distinction there being that a ZST with alignment > 1 can cause padding to be injected, and thus memory to be allocated.

Hat tip to @RalfJung for pointing this oddity out as part of PR #99972

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions