Files
dsh a56a12f132 r8forge --opt: the peephole pass is part of the assembler now
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.
2026-11-18 10:34:30 +08:00

48 lines
1.3 KiB
C++

// r8forge_tape_opt -- the peephole pass as a filter for an existing .rot8 file.
//
// r8forge_tape_opt <in.rot8> [out.rot8]
//
// `r8forge --opt file.r8asm` does the same thing one step earlier; this exists
// for tapes that were assembled before, or by something else.
#include "r8forge/geometry.hh"
#include "r8forge/tape_opt.hh"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iterator>
#include <string>
int main(int argc, char **argv) {
if (argc < 2) {
std::fprintf(stderr, "usage: r8forge_tape_opt <in.rot8> [out.rot8]\n");
return 2;
}
std::ifstream in(argv[1], std::ios::binary);
if (!in) {
std::fprintf(stderr, "could not open %s\n", argv[1]);
return 1;
}
const std::string tape((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
const std::string out = rot8_optimize(tape, kDefaultCellSize);
if (out.empty()) {
std::fprintf(stderr, "no instructions in %s\n", argv[1]);
return 1;
}
if (argc > 2) {
std::ofstream f(argv[2], std::ios::binary);
if (!f) {
std::fprintf(stderr, "could not write %s\n", argv[2]);
return 1;
}
f << out;
} else {
std::fwrite(out.data(), 1, out.size(), stdout);
}
std::fprintf(stderr, "r8forge_tape_opt: %zu -> %zu characters\n",
tape.size(), out.size());
return 0;
}