Files
dsh 9b31a51fec hardware: M0 -- the packer, the RTL, and a simulator that agrees byte for byte
The two things software cannot check by reading its own source are the 3 bit
packing and the bracket strategy, so both got a tool and a test.

New in the library (r8forge/tape.hh, src/tape.cc): the opcode numbering (taken
from ROT-8-viz enum, so the packed image and the hardware decoder cannot drift),
text <-> opcodes, opcodes <-> 3 bit bytes, the .r8t image with its trailer and
crc32, and a machine model that runs a packed tape the way a board would.  The
model takes the bracket strategy as an option: backward scan with loop stack or
not, and jump-back-onto-the-[ (the contract) or past it (what the interpreters
do).  All four combinations print the same thing, and the step count differs by
exactly the number of taken ] instructions -- which is what the test asserts.

Found and fixed while writing it: the loop stack discipline depends on the jump
convention.  Jumping onto the [ means the [ re-pushes, so ] must pop on the jump;
jumping past it means the entry must stay until the loop exits.  Mixing them up
emptied the stack on the second iteration of the calculator main loop -- caught
by the equivalence test on examples/calc.r8asm, not by reading the code.

Tools: r8forge_tape_pack (text tape -> image + --hex for $readmemh + --verify,
727 instructions become 273 bytes for hello, 62%, and the trailer sits past the
halt so address 0 of a ROM is instruction 0), and r8forge_tape_run now reads an
image directly and takes --loop-stack / --retest.

hardware/rot8.v: the 8 bit / 64 cell machine -- 3 bit opcodes from a byte
addressed memory read as a 16 bit window, a 6 bit dp with free wrap, the loop
stack bracket jump, blocking input, halt on ip == length, and a step counter that
counts instructions rather than cycles.  hardware/tb_rot8.v loads a --hex image
and prints the OUT stream in tape_run format.

Verified with Icarus Verilog 14 (the RTL against tape_run --loop-stack --retest):
  hello        577 instructions  417 steps  10 outs
  term         16414            17643      11 (fed "lhi")
  calc         51378           166741      19 (fed "12 34 + .": prints the prompt,
                                                046 and the next prompt)
  flagship     43676           100142      93
Every OUT stream identical.  ctest -R rtl_sim runs that comparison from an 8 bit
build (11 tests in the default build now, where the RTL test self-skips because
the RTL is the 8 bit machine).

Two traps worth remembering: Icarus passes plusargs through as raw bytes, so an
absolute +HEX path containing non-ASCII (this checkout is under a Chinese
directory name) arrives mangled, $readmemh silently leaves the memory empty and
the machine obediently runs LEN steps of opcode 0 printing nothing -- run vvp
from the directory holding the hex with a relative name.  And in_ready must not
be qualified with !in_valid or the input handshake deadlocks.
2026-11-20 16:25:54 +08:00

186 lines
6.0 KiB
C++

#include "r8forge/geometry.hh"
#include "r8forge/tape.hh"
// Independent ROT-8 interpreter. Reads a tape straight from a file -- no macro,
// no assembler, no r8asm -- and prints what `out` ('.') produced.
//
// r8forge_tape_run <file> [-i text] [--trace] [--profile]
// [--loop-stack] [--retest] [cells...]
//
// <file> is either the text form (one character per instruction) or the packed
// image `r8forge_tape_pack` writes (recognised by its "R8T1" trailer). The
// packed path is the one the hardware takes, so running both and comparing is
// how the packer and the bit order get checked.
//
// cells are addr=value (decimal), e.g. 0=128
// -i/--input gives INP (",") its characters, low 7 bits each; when the text
// runs out INP reads 0. That is enough to drive an interactive program from
// a script -- the ROT-8-viz CLI is the one that prompts a live terminal.
//
// --loop-stack implements ']' with the board's LIFO of loop entry positions
// instead of a backward scan. --retest makes ']' jump back onto the '[' (the
// reference interpreter's reading) instead of past it; that changes the step
// count by exactly one per taken ']', never the output.
//
// This exists as a second opinion for r8forge_derive: if the two disagree, the
// difference is in derive; if they agree, the disagreement is in the program.
//
// Note the character map: "><+-[].," -- '-' is flb, '+' is ror, and ror does
// not change whether a cell is zero (that is what makes [-] a two value loop).
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
namespace {
struct image {
std::vector<uint8_t> code;
size_t width = kDefaultCellSize;
size_t ring = kDefaultMemoryCells;
std::string error;
};
// Text or packed? The image format is defined in r8forge/tape.hh; the loader
// asks the library whether the trailing trailer is there, so a file name is
// never trusted and the two tools cannot drift apart.
bool load(const std::string &path, image &img) {
std::ifstream in(path, std::ios::binary);
if (!in) {
img.error = "could not open " + path;
return false;
}
const std::string raw((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
const std::vector<uint8_t> bytes(raw.begin(), raw.end());
if (!tape_is_image(bytes))
return tape_decode(raw, img.code, img.error);
tape_image decoded;
if (!tape_image_decode(bytes, decoded, img.error))
return false;
img.code = decoded.code;
img.width = decoded.width;
img.ring = decoded.ring;
return true;
}
void print_trace(void *, size_t ip, size_t dp, const uint32_t *cells, size_t,
uint8_t op) {
static const char *k = "><+-[].,";
std::cout << "pc " << ip << " " << k[op & 7] << " dp " << dp << " [";
for (size_t i = 0; i < 4; i++)
std::cout << (i ? " " : "") << cells[i];
std::cout << "]\n";
}
} // namespace
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "usage: r8forge_tape_run <file> [addr=value ...]\n";
return 2;
}
image img;
if (!load(argv[1], img)) {
std::cerr << img.error << "\n";
return 1;
}
std::vector<uint32_t> input;
std::vector<uint32_t> seed(img.ring, 0);
bool have_seed = false;
machine_options opt;
opt.width = img.width;
opt.ring = img.ring;
bool trace = false;
bool profile = false;
for (int i = 2; i < argc; i++) {
const std::string a = argv[i];
if (a == "--trace" || a == "-t") {
trace = true;
continue;
}
if (a == "--profile" || a == "-p") {
profile = true;
continue;
}
if (a == "--loop-stack") {
opt.loop_stack = true;
continue;
}
if (a == "--retest") {
opt.retest = true;
continue;
}
if (a == "-i" || a == "--input") {
if (i + 1 >= argc) {
std::cerr << "-i needs a string of input characters\n";
return 2;
}
for (const char *p = argv[++i]; *p; p++)
input.push_back(uint32_t((unsigned char)*p & 0x7f));
continue;
}
const size_t eq = a.find('=');
if (eq == std::string::npos)
continue;
const size_t at = size_t(std::stoul(a.substr(0, eq)));
if (at >= img.ring) {
std::cerr << "cell " << at << " is outside the " << img.ring
<< " cell ring\n";
return 2;
}
seed[at] = uint32_t(std::stoul(a.substr(eq + 1)));
have_seed = true;
}
const uint32_t mask = img.width >= 32
? 0xFFFFFFFFu
: uint32_t((uint64_t(1) << img.width) - 1);
for (uint32_t &v : seed)
v &= mask;
if (have_seed)
opt.initial = &seed;
opt.profile = profile;
if (trace)
opt.trace = &print_trace;
const machine_result r = tape_run(img.code, input, opt);
if (!r.error.empty()) {
std::cout << r.error << "\n";
return r.overrun ? 3 : 4;
}
if (profile) {
// The opcode numbering is the packing order, so the profile line can simply
// walk it instead of switching on characters.
static const char *kinds = "><+-[].,";
std::fprintf(stderr, "profile: %zu steps\n", r.steps);
for (size_t op = 0; op < 8; op++)
std::fprintf(stderr, " %c %8zu %5.1f%%\n", kinds[op], r.op_counts[op],
100.0 * double(r.op_counts[op]) / double(r.steps));
std::vector<size_t> order(r.cell_hits.size());
for (size_t i = 0; i < order.size(); i++)
order[i] = i;
std::sort(order.begin(), order.end(), [&](size_t a, size_t b) {
return r.cell_hits[a] > r.cell_hits[b];
});
std::fprintf(stderr, " hottest cells (steps spent there):");
for (size_t i = 0; i < order.size() && i < 10; i++) {
if (r.cell_hits[order[i]] == 0)
break;
std::fprintf(stderr, " %zu:%zu", order[i], r.cell_hits[order[i]]);
}
std::fprintf(stderr, "\n");
}
std::cout << "out";
for (uint32_t v : r.out)
std::cout << " " << int(v);
std::cout << " (" << r.steps << " steps, cell0 ended 0x" << std::hex
<< int(r.cells[0]) << std::dec << ")\n";
return 0;
}