Translate unions in unsafe#32
Merged
nunoplopes merged 19 commits intoCpp2Rust:masterfrom Apr 28, 2026
Merged
Conversation
0dde2eb to
6a4e8f9
Compare
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.
nunoplopes
reviewed
Apr 28, 2026
| if (auto *default_ctor = GetUserDefinedDefaultConstructor(cxx)) { | ||
| StrCat(keyword_unsafe_); | ||
| PushBrace unsafe_brace(*this); | ||
| Convert(clang::CXXConstructExpr::Create( |
Contributor
There was a problem hiding this comment.
won't this leak memory?
Contributor
Author
There was a problem hiding this comment.
It's created inside the allocator of ASTContext, the node is automatically freed when ASTContext is destroyed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
C/C++ unions are translated as Rust unions in unsafe. They manually implement default with
std::mem::zeroedsince unions cannot derive DefaultEach 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