Skip to content

Commit d34b78a

Browse files
committed
Define static array of char[] generics
1 parent 2aac34d commit d34b78a

3 files changed

Lines changed: 23 additions & 5 deletions

File tree

cpp2rust/converter/mapper.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,6 @@ matchTemplate(const std::string &template_str,
227227
size_t si = 0;
228228

229229
while (ti < template_str.size()) {
230-
// Match T{N}. TODO: currently only T0..9 are supported
231230
if (template_str[ti] == 'T' && ti + 1 < template_str.size() &&
232231
std::isdigit(template_str[ti + 1])) {
233232
size_t tj = ti + 2;
@@ -236,6 +235,8 @@ matchTemplate(const std::string &template_str,
236235
}
237236

238237
size_t type_idx = std::stoi(&template_str[ti + 1]) - 1;
238+
assert(type_idx < TranslationRule::kMaxGenerics &&
239+
"template placeholder exceeds kMaxGenerics");
239240
ti = tj;
240241

241242
std::string_view nextLit;

cpp2rust/converter/translation_rule.cpp

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
#include <llvm/Support/MemoryBuffer.h>
88

99
#include <algorithm>
10-
#include <format>
1110
#include <string>
1211
#include <vector>
1312

@@ -17,6 +16,21 @@ namespace cpp2rust::TranslationRule {
1716

1817
namespace {
1918

19+
struct GenericPlaceholders {
20+
char storage[kMaxGenerics][3]{};
21+
22+
constexpr GenericPlaceholders() {
23+
for (unsigned i = 0; i < kMaxGenerics; ++i) {
24+
storage[i][0] = 'T';
25+
storage[i][1] = static_cast<char>('1' + i);
26+
storage[i][2] = '\0';
27+
}
28+
}
29+
};
30+
static_assert(kMaxGenerics <= 9,
31+
"GenericPlaceholders assumes single-digit names");
32+
constexpr GenericPlaceholders kGenericPlaceholders{};
33+
2034
TypeInfo ParseTypeInfoJSON(const llvm::json::Object &obj) {
2135
TypeInfo info;
2236
if (auto ty = obj.getString("type"))
@@ -311,9 +325,10 @@ void ExprRule::validate(const std::string &name) const {
311325
assert(0 && "Expr rule loaded from IR but has no src");
312326
}
313327

314-
// Check that both source and target use the same generics.
315-
for (unsigned i = 0; i < generics.size(); ++i) {
316-
auto placeholder = std::format("T{}", i + 1);
328+
assert(generics.size() <= kMaxGenerics &&
329+
"rule declares more generics than kMaxGenerics");
330+
for (unsigned i = 0, e = generics.size(); i < e; ++i) {
331+
const char *placeholder = kGenericPlaceholders.storage[i];
317332
if (src.find(placeholder) == std::string::npos) {
318333
llvm::errs() << name << '\n';
319334
dump();

cpp2rust/converter/translation_rule.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515

1616
namespace cpp2rust::TranslationRule {
1717

18+
inline constexpr unsigned kMaxGenerics = 9;
19+
1820
struct TextFragment {
1921
std::string text;
2022

0 commit comments

Comments
 (0)