Files

204 lines
6.5 KiB
C++

// 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
// trailer describes the instruction encoding and machine geometry.
//
// 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.
//
#include "r8forge/geometry.hh"
#include "r8forge/tape.hh"
#include <algorithm>
#include <charconv>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <string_view>
#include <utility>
#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 = std::move(decoded.code);
img.width = decoded.width;
img.ring = decoded.ring;
return true;
}
template <typename T>
bool parse_decimal(std::string_view text, T &out) {
if (text.empty())
return false;
const auto result = std::from_chars(text.data(), text.data() + text.size(), out);
return result.ec == std::errc{} && result.ptr == text.data() + text.size();
}
void print_trace(void *, size_t ip, size_t dp, const uint32_t *cells, size_t ring,
uint8_t op) {
static const char *k = "><+-[].,";
std::cout << "pc " << ip << " " << k[op & 7] << " dp " << dp << " [";
for (size_t i = 0; i < std::min<size_t>(4, ring); 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> [-i text] [--trace] [--profile] "
"[--loop-stack] [--retest] [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) {
std::cerr << "unknown argument '" << a << "'\n";
return 2;
}
const std::string_view seed_arg(a);
size_t at = 0;
int64_t value = 0;
if (!parse_decimal(seed_arg.substr(0, eq), at) ||
!parse_decimal(seed_arg.substr(eq + 1), value) ||
value < -int64_t(UINT32_MAX) || value > UINT32_MAX) {
std::cerr << "invalid cell assignment '" << a << "' (expected addr=value)\n";
return 2;
}
if (at >= img.ring) {
std::cerr << "cell " << at << " is outside the " << img.ring
<< " cell ring\n";
return 2;
}
seed[at] = uint32_t(value);
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],
r.steps ? 100.0 * double(r.op_counts[op]) / double(r.steps)
: 0.0);
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;
}