The pass moved out of tests/tape_opt.cc into src/tape_opt.cc with a header (rot8_optimize(tape, cell_size)), so both entry points share one implementation: r8forge --opt file.r8asm > t.rot8 assemble, then optimise in memory r8forge_tape_opt t.rot8 t2.rot8 optimise a tape assembled earlier --opt is peeled off argv before the rest of the parsing, so it can appear anywhere and the existing flags are untouched; without it the output is byte for byte what it was (flagship 64513). Measured: flagship 64513 -> 58060 (-10.0%), calculator 62585 -> 54863 (-12.3%), and "12 34 + ." still prints the same out stream from the optimised calculator. ctest 8/8 still green.
63 lines
1.3 KiB
C++
63 lines
1.3 KiB
C++
#include "r8forge/tape_opt.hh"
|
|
|
|
#include <cstring>
|
|
|
|
namespace {
|
|
|
|
constexpr char kGt = '>';
|
|
constexpr char kLt = '<';
|
|
constexpr char kRor = '+';
|
|
constexpr char kFlb = '-';
|
|
|
|
bool is_ins(char c) { return c != 0 && std::strchr("><+-[].,", c) != nullptr; }
|
|
|
|
} // namespace
|
|
|
|
std::string rot8_optimize(const std::string &tape, size_t cell_size) {
|
|
const size_t width = cell_size == 0 ? 1 : cell_size;
|
|
const size_t n = tape.size();
|
|
std::string out;
|
|
out.reserve(n);
|
|
for (size_t i = 0; i < n;) {
|
|
const char c = tape[i];
|
|
if (!is_ins(c)) {
|
|
i++; // a stray byte (newline, comment) does nothing; drop it
|
|
continue;
|
|
}
|
|
if (c == kGt || c == kLt) {
|
|
long net = 0;
|
|
while (i < n && (tape[i] == kGt || tape[i] == kLt)) {
|
|
net += tape[i] == kGt ? 1 : -1;
|
|
i++;
|
|
}
|
|
const char dir = net >= 0 ? kGt : kLt;
|
|
const long count = net >= 0 ? net : -net;
|
|
for (long k = 0; k < count; k++) {
|
|
out += dir;
|
|
}
|
|
continue;
|
|
}
|
|
if (c == kRor) {
|
|
size_t run = 0;
|
|
while (i < n && tape[i] == kRor) {
|
|
run++;
|
|
i++;
|
|
}
|
|
out.append(run % width, kRor);
|
|
continue;
|
|
}
|
|
if (c == kFlb) {
|
|
size_t run = 0;
|
|
while (i < n && tape[i] == kFlb) {
|
|
run++;
|
|
i++;
|
|
}
|
|
out.append(run % 2, kFlb);
|
|
continue;
|
|
}
|
|
out += c;
|
|
i++;
|
|
}
|
|
return out;
|
|
}
|