Skip to content

Commit 2d73dfc

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 fd4780f commit 2d73dfc

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
@@ -1702,11 +1702,13 @@ std::string Converter::GetEscapedStringLiteral(clang::Expr *expr,
17021702
}
17031703

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

cpp2rust/converter/models/converter_refcount.cpp

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

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

0 commit comments

Comments
 (0)