Skip to content

Commit 6e5caf5

Browse files
authored
Accept the j format specifier and escape braces in printf (#518)
1 parent 4024fe3 commit 6e5caf5

4 files changed

Lines changed: 17 additions & 0 deletions

File tree

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,6 +1137,14 @@ void ConverterRefCount::ConvertDeclRefValue(clang::Expr *expr,
11371137

11381138
static std::vector<const char *> printf2fmt(std::string &format) {
11391139
std::vector<const char *> types;
1140+
std::string escaped;
1141+
for (char c : format) {
1142+
escaped += c;
1143+
if (c == '{' || c == '}') {
1144+
escaped += c;
1145+
}
1146+
}
1147+
format = std::move(escaped);
11401148
size_t pos = 0;
11411149
while ((pos = format.find('%', pos)) != std::string::npos) {
11421150
if (pos + 1 >= format.size())
@@ -1181,6 +1189,7 @@ static std::vector<const char *> printf2fmt(std::string &format) {
11811189
continue;
11821190
}
11831191
break;
1192+
case 'j':
11841193
case 'z':
11851194
if (pos + 2 < format.size() &&
11861195
(format[pos + 2] == 'd' || format[pos + 2] == 'u')) {

‎tests/unit/out/refcount/printfs.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ fn main_0() -> i32 {
5353
"{}",
5454
(Ptr::<Vec<i8>>::decay(&({ fn2_1(s.as_pointer(),) })) as Ptr<i8>)
5555
);
56+
println!("{{}} {} {}", 5_u64, (-6_i32 as i64));
5657
return 0;
5758
}
5859
pub fn __cpp2rust_init_globals() {}

‎tests/unit/out/unsafe/printfs.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ unsafe fn main_0() -> i32 {
5656
c"%s\n".as_ptr() as *const i8,
5757
(*(unsafe { fn2_1(&s) })).as_ptr(),
5858
);
59+
printf(
60+
c"{} %ju %jd\n".as_ptr() as *const i8,
61+
5_u64,
62+
(-6_i32 as i64),
63+
);
5964
return 0;
6065
}
6166
pub unsafe fn __cpp2rust_init_globals() {}

‎tests/unit/printfs.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <cassert>
2+
#include <cstdint>
23
#include <cstdio>
34
#include <string>
45

@@ -18,5 +19,6 @@ int main() {
1819
printf("%s\n", s.data());
1920
printf("%s\n", fn("foo").c_str());
2021
printf("%s\n", fn2(s).c_str());
22+
printf("{} %ju %jd\n", (uintmax_t)5, (intmax_t)-6);
2123
return 0;
2224
}

0 commit comments

Comments
 (0)