Skip to content

Commit 0baa9ff

Browse files
committed
Define static array of char[] generics
1 parent 79ffcde commit 0baa9ff

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
@@ -226,7 +226,6 @@ matchTemplate(const std::string &template_str,
226226
size_t si = 0;
227227

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

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

240241
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"))
@@ -307,9 +321,10 @@ void ExprRule::validate(const std::string &name) const {
307321
assert(0 && "Expr rule loaded from IR but has no src");
308322
}
309323

310-
// Check that both source and target use the same generics.
311-
for (unsigned i = 0; i < generics.size(); ++i) {
312-
auto placeholder = std::format("T{}", i + 1);
324+
assert(generics.size() <= kMaxGenerics &&
325+
"rule declares more generics than kMaxGenerics");
326+
for (unsigned i = 0, e = generics.size(); i < e; ++i) {
327+
const char *placeholder = kGenericPlaceholders.storage[i];
313328
if (src.find(placeholder) == std::string::npos) {
314329
llvm::errs() << name << '\n';
315330
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)