Skip to content

Commit dc53477

Browse files
committed
Change translation of string literal
In unsafe, they are translated as [u8; N] and in refcount they are translated as Box<[u8]>.
1 parent 1c052af commit dc53477

2 files changed

Lines changed: 13 additions & 4 deletions

File tree

‎cpp2rust/converter/converter.cpp‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1706,11 +1706,13 @@ std::string Converter::GetEscapedStringLiteral(clang::Expr *expr,
17061706
}
17071707

17081708
bool Converter::VisitStringLiteral(clang::StringLiteral *expr) {
1709-
StrCat(std::format("b{}.as_ptr()", GetEscapedStringLiteral(expr, true)));
1710-
// In C, string literals are char[], in C++ they are const char[]
1711-
if (!expr->getType().isConstQualified()) {
1712-
StrCat(".cast_mut()");
1709+
if (!curr_init_type_.empty() && curr_init_type_.top()->isArrayType()) {
1710+
// b"" has type &static [u8; N]. For translating char str[] =
1711+
// "string_literal"; we need an initializer of type [u8; N]. Dereferencing
1712+
// the &static [u8; N] achieves this.
1713+
StrCat(token::kStar);
17131714
}
1715+
StrCat(std::format("b{}", GetEscapedStringLiteral(expr, true)));
17141716
return false;
17151717
}
17161718

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -946,6 +946,13 @@ bool ConverterRefCount::VisitCallExpr(clang::CallExpr *expr) {
946946
}
947947

948948
bool ConverterRefCount::VisitStringLiteral(clang::StringLiteral *expr) {
949+
if (!curr_init_type_.empty() && curr_init_type_.top()->isArrayType()) {
950+
// b"" has type &static [u8; N]. For translating char str[] =
951+
// "string_literal"; we need an initializer of type Box<[u8]>
952+
StrCat(std::format("Box::<[u8]>::from(b{}.as_slice())",
953+
GetEscapedStringLiteral(expr, true)));
954+
return false;
955+
}
949956
StrCat(GetEscapedStringLiteral(expr));
950957
return false;
951958
}

0 commit comments

Comments
 (0)