Skip to content

Commit

Permalink
[NFC][TableGen] Refactor StringToOffsetTable
Browse files Browse the repository at this point in the history
- Make `EmitString` const by not mutating `AggregateString`.
- Use C++17 structured bindings in `GetOrAddStringOffset`.
- Use StringExtras version of isDigit instead of std::isdigit.
  • Loading branch information
jurahul committed Aug 22, 2024
1 parent 743e70b commit 0a01439
Showing 1 changed file with 16 additions and 20 deletions.
36 changes: 16 additions & 20 deletions llvm/include/llvm/TableGen/StringToOffsetTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
#include <optional>

namespace llvm {
Expand All @@ -31,16 +30,15 @@ class StringToOffsetTable {
size_t size() const { return AggregateString.size(); }

unsigned GetOrAddStringOffset(StringRef Str, bool appendZero = true) {
auto IterBool =
StringOffset.insert(std::make_pair(Str, AggregateString.size()));
if (IterBool.second) {
auto [II, Inserted] = StringOffset.insert({Str, size()});
if (Inserted) {
// Add the string to the aggregate if this is the first time found.
AggregateString.append(Str.begin(), Str.end());
if (appendZero)
AggregateString += '\0';
}

return IterBool.first->second;
return II->second;
}

// Returns the offset of `Str` in the table if its preset, else return
Expand All @@ -52,37 +50,35 @@ class StringToOffsetTable {
return II->second;
}

void EmitString(raw_ostream &O) {
void EmitString(raw_ostream &O) const {
// Escape the string.
SmallString<256> Str;
raw_svector_ostream(Str).write_escaped(AggregateString);
AggregateString = std::string(Str);
SmallString<256> EscapedStr;
raw_svector_ostream(EscapedStr).write_escaped(AggregateString);

O << " \"";
unsigned CharsPrinted = 0;
for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
for (unsigned i = 0, e = EscapedStr.size(); i != e; ++i) {
if (CharsPrinted > 70) {
O << "\"\n \"";
CharsPrinted = 0;
}
O << AggregateString[i];
O << EscapedStr[i];
++CharsPrinted;

// Print escape sequences all together.
if (AggregateString[i] != '\\')
if (EscapedStr[i] != '\\')
continue;

assert(i + 1 < AggregateString.size() && "Incomplete escape sequence!");
if (isdigit(AggregateString[i + 1])) {
assert(isdigit(AggregateString[i + 2]) &&
isdigit(AggregateString[i + 3]) &&
assert(i + 1 < EscapedStr.size() && "Incomplete escape sequence!");
if (isDigit(EscapedStr[i + 1])) {
assert(isDigit(EscapedStr[i + 2]) && isDigit(EscapedStr[i + 3]) &&
"Expected 3 digit octal escape!");
O << AggregateString[++i];
O << AggregateString[++i];
O << AggregateString[++i];
O << EscapedStr[++i];
O << EscapedStr[++i];
O << EscapedStr[++i];
CharsPrinted += 3;
} else {
O << AggregateString[++i];
O << EscapedStr[++i];
++CharsPrinted;
}
}
Expand Down

0 comments on commit 0a01439

Please sign in to comment.