Skip to content

Translate unions in unsafe#32

Merged
nunoplopes merged 19 commits intoCpp2Rust:masterfrom
lucic71:union-unsafe
Apr 28, 2026
Merged

Translate unions in unsafe#32
nunoplopes merged 19 commits intoCpp2Rust:masterfrom
lucic71:union-unsafe

Conversation

@lucic71
Copy link
Copy Markdown
Contributor

@lucic71 lucic71 commented Apr 27, 2026

C/C++ unions are translated as Rust unions in unsafe. They manually implement default with std::mem::zeroed since unions cannot derive Default

Each struct and union is decorated with the repr(C) attribute to make sure that the C layout is preserved. We need this because Rust is free to reorder fields for optimal struct layout

@lucic71 lucic71 marked this pull request as draft April 27, 2026 21:10
@lucic71 lucic71 force-pushed the union-unsafe branch 4 times, most recently from 0dde2eb to 6a4e8f9 Compare April 28, 2026 14:10
lucic71 added 17 commits April 28, 2026 15:11
Rename EmitRustStruct as EmitRustStructOrUnion since the logic for
emitting a struct or a union is very similar, the only thing that is
really different is whether are are emitting the struct or union
keyword.

All structs and unions have now repr(C). The Rust compiler is allowed to
reorder fields. This is undesirable for unions where order of fields is
strict. Since a struct that is defined outside an union can be used
inside an union, we have to be pessimstic and consider all structs as
having repr(C).

Unions cannot derive the Default trait, so implement Default as the 0
bit pattern, which should be enough for the current usages of union
fields.
@lucic71 lucic71 marked this pull request as ready for review April 28, 2026 14:40
@lucic71 lucic71 marked this pull request as draft April 28, 2026 14:42
@lucic71 lucic71 marked this pull request as ready for review April 28, 2026 15:37
if (auto *default_ctor = GetUserDefinedDefaultConstructor(cxx)) {
StrCat(keyword_unsafe_);
PushBrace unsafe_brace(*this);
Convert(clang::CXXConstructExpr::Create(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

won't this leak memory?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's created inside the allocator of ASTContext, the node is automatically freed when ASTContext is destroyed

@nunoplopes nunoplopes merged commit 81ca488 into Cpp2Rust:master Apr 28, 2026
9 checks passed
@lucic71 lucic71 deleted the union-unsafe branch April 29, 2026 13:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants