Skip to content

Commit 5eeb075

Browse files
committed
Implement integer to pointer casts
1 parent 69d7991 commit 5eeb075

29 files changed

Lines changed: 2776 additions & 190 deletions

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -749,9 +749,14 @@ void ConverterRefCount::EmitRustUnion(clang::RecordDecl *decl) {
749749
}
750750

751751
void ConverterRefCount::EmitByteSizeAttr(const clang::RecordDecl *decl) {
752-
StrCat(std::format(
753-
"#[byte_size({})]",
754-
ctx_.getTypeSizeInChars(ctx_.getCanonicalTagType(decl)).getQuantity()));
752+
auto type = ctx_.getCanonicalTagType(decl);
753+
StrCat(std::format("#[byte_size({})]",
754+
ctx_.getTypeSizeInChars(type).getQuantity()));
755+
// The integers of pointers are aligned as malloc aligns them (see
756+
// libcc2rs/src/escape.rs), unless the type is over-aligned.
757+
if (auto align = ctx_.getTypeAlignInChars(type).getQuantity(); align > 16) {
758+
StrCat(std::format("#[byte_align({})]", align));
759+
}
755760
}
756761

757762
std::string
@@ -1462,6 +1467,38 @@ bool ConverterRefCount::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) {
14621467
EmitFresh(GetDefaultAsString(expr->getType()));
14631468
return false;
14641469
}
1470+
if (expr->getCastKind() == clang::CK_PointerToIntegral ||
1471+
expr->getCastKind() == clang::CK_IntegralToPointer) {
1472+
std::string dst_type;
1473+
{
1474+
PushConversionKind push(*this, ConversionKind::Unboxed);
1475+
dst_type = ToString(expr->getType());
1476+
}
1477+
// The integers of pointers are usize, which other integers are cast
1478+
// from and to.
1479+
auto sub_expr = ToString(expr->getSubExpr());
1480+
if (expr->getCastKind() == clang::CK_PointerToIntegral) {
1481+
bool cast = Mapper::Map(*this, expr->getType()) != "usize";
1482+
PushParen paren(*this, cast);
1483+
StrCat(sub_expr, ".to_int()");
1484+
if (cast) {
1485+
StrCat(keyword::kAs, dst_type);
1486+
}
1487+
} else {
1488+
bool cast = Mapper::Map(*this, expr->getSubExpr()->getType()) != "usize";
1489+
StrCat(std::format("<{}>::from_int", dst_type));
1490+
PushParen paren(*this);
1491+
{
1492+
PushParen value(*this, cast);
1493+
StrCat(sub_expr);
1494+
}
1495+
if (cast) {
1496+
StrCat(keyword::kAs, "usize");
1497+
}
1498+
}
1499+
MarkFresh();
1500+
return false;
1501+
}
14651502
switch (expr->getStmtClass()) {
14661503
case clang::Stmt::CXXReinterpretCastExprClass:
14671504
assert(expr->getType()->isPointerType() &&
@@ -1472,22 +1509,6 @@ bool ConverterRefCount::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) {
14721509
return false;
14731510
case clang::Stmt::CStyleCastExprClass:
14741511
case clang::Stmt::CXXStaticCastExprClass:
1475-
if (expr->getCastKind() == clang::CastKind::CK_PointerToIntegral ||
1476-
expr->getCastKind() == clang::CastKind::CK_IntegralToPointer) {
1477-
std::string dst_type;
1478-
{
1479-
PushConversionKind push(*this, ConversionKind::Unboxed);
1480-
dst_type = ToString(expr->getType());
1481-
}
1482-
if (expr->getCastKind() == clang::CastKind::CK_PointerToIntegral) {
1483-
EmitFresh(std::format("{}.to_int()", ToString(expr->getSubExpr())));
1484-
} else {
1485-
EmitFresh(std::format("<{}>::from_int({})", dst_type,
1486-
ToString(expr->getSubExpr())));
1487-
}
1488-
return false;
1489-
}
1490-
14911512
if (ConvertFunctionPointerCast(expr)) {
14921513
return false;
14931514
} else if (expr->getSubExpr()->getType()->isVoidPointerType() &&

‎libcc2rs-macros/Cargo.toml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@ quote = "1"
1212
syn = { version = "2", features = ["full", "visit-mut", "extra-traits"] }
1313

1414
[dev-dependencies]
15-
trybuild = "1"
15+
# trybuild 1.0.123 passes --diagnostic-width to rustc, which cargo also passes
16+
# when it knows the width of the terminal, and rustc rejects it twice.
17+
trybuild = ">=1, <1.0.123"

‎libcc2rs-macros/src/byte_repr.rs‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,17 @@ use proc_macro::TokenStream;
55
use quote::quote;
66
use syn::{Attribute, Data, DeriveInput, Expr, Fields, parse_macro_input};
77

8-
fn byte_size(attrs: &[Attribute]) -> Option<Expr> {
8+
fn attr_arg(attrs: &[Attribute], name: &str) -> Option<Expr> {
99
attrs
1010
.iter()
11-
.find(|attr| attr.path().is_ident("byte_size"))
11+
.find(|attr| attr.path().is_ident(name))
1212
.map(|attr| attr.parse_args().unwrap())
1313
}
1414

15+
fn byte_size(attrs: &[Attribute]) -> Option<Expr> {
16+
attr_arg(attrs, "byte_size")
17+
}
18+
1519
pub fn expand(input: TokenStream) -> TokenStream {
1620
let input = parse_macro_input!(input as DeriveInput);
1721
let name = &input.ident;
@@ -28,6 +32,14 @@ pub fn expand(input: TokenStream) -> TokenStream {
2832

2933
let size = byte_size(&input.attrs)
3034
.unwrap_or_else(|| panic!("struct `{name}` has no #[byte_size(...)]"));
35+
// Only over-aligned structs give their alignment.
36+
let align = attr_arg(&input.attrs, "byte_align").map(|align| {
37+
quote! {
38+
fn byte_align() -> usize {
39+
#align
40+
}
41+
}
42+
});
3143

3244
// The bytes of each field are at its offset, and span the byte size of
3345
// its type, unless given by its byte_size attribute.
@@ -53,6 +65,8 @@ pub fn expand(input: TokenStream) -> TokenStream {
5365
#size
5466
}
5567

68+
#align
69+
5670
#[allow(unused_variables)]
5771
fn to_bytes(&self, buf: &mut [u8]) {
5872
#(::libcc2rs::ByteRepr::to_bytes(&self.#idents, &mut buf[#ranges]);)*
@@ -64,6 +78,13 @@ pub fn expand(input: TokenStream) -> TokenStream {
6478
#(#idents: <#types as ::libcc2rs::ByteRepr>::from_bytes(&buf[#ranges]),)*
6579
}
6680
}
81+
82+
// Keeps the lengths of the arrays in the fields, which the bytes
83+
// of rows don't give.
84+
#[allow(unused_variables)]
85+
fn assign_bytes(&mut self, buf: &[u8]) {
86+
#(::libcc2rs::ByteRepr::assign_bytes(&mut self.#idents, &buf[#ranges]);)*
87+
}
6788
}
6889
}
6990
.into()

‎libcc2rs-macros/src/lib.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,9 @@ pub fn goto(_input: TokenStream) -> TokenStream {
114114
// offset given by its offset attribute (see derive(Record)). The byte_size
115115
// attribute gives the byte size of S in C, and of the fields whose size in C
116116
// differs from the byte_size() of their type (e.g., arrays and pointers).
117+
// Over-aligned structs also give their alignment in C, as #[byte_align(64)].
117118

118-
#[proc_macro_derive(ByteRepr, attributes(offset, byte_size))]
119+
#[proc_macro_derive(ByteRepr, attributes(offset, byte_size, byte_align))]
119120
pub fn derive_byte_repr(input: TokenStream) -> TokenStream {
120121
byte_repr::expand(input)
121122
}

0 commit comments

Comments
 (0)