Files
R8Forge/tests/examples_test.cc
T
dsh ae268b9442 Interactive I/O: teach the VMs INP, and let examples declare their input
The library can read characters now that the viz defaults to serial ASCII, but
R8Forge's own machines could not: r8forge_derive, r8forge_tape_run and the
examples harness all skipped ',' ("input is not modelled"), so an interactive
program could only be run through ROT-8-viz -- the wrong end of the dev loop,
and nothing in CI could cover it.

Three small pieces:

  * INP (',') reads the next scripted character (low 7 bits) and 0 once the
    text runs out, in tests/tape_run.cc, src/derive.cc and the examples VM.
    r8forge_tape_run and r8forge_derive take -i/--input "<text>", so an
    interactive program is run and checked exactly like any other:
        r8forge_tape_run t.rot8 -i "12+34="
        r8forge_derive calc.r8asm 0 -i "12+34="
  * examples_test learns an optional `;   in ...` header next to `;   out`:
    the characters after the marker are fed to INP before the run.  The marker
    must be the first word after ';' so "include" in a comment is not eaten.
  * examples/echo_chars.r8asm: the smallest interactive program -- read four
    characters, print them back.  in R8F! -> out 82 56 70 33, 8 characters,
    8 steps.

Verified the same tape three ways: tape_run -i "R8F!" -> 82 56 70 33,
derive 0 -i "R8F!" -> same, rot8_test --input R8F! -> prints R8F.  With no
input at all INP reads 0, which is how every non-interactive example keeps
running unchanged.

Baseline: examples_test is now 15 examples + asm/test.r8asm.
2026-11-09 17:14:12 +08:00

249 lines
8.0 KiB
C++

// Runs every program in examples/ and compares its OUT stream with the one
// written in the file header:
//
// ; out 254 0 1024 ...
//
// The marker is part of the example's documentation -- a reader sees at a
// glance what the program prints -- and this test is what keeps the doc true:
// an example that stops printing what its header says is a broken example, and
// one that does not assemble at all would otherwise rot silently.
//
// It is also the only place that runs examples/*.r8asm: the %synth ones are
// covered combination by combination by r8forge_synth_test, but every file in
// examples/ is still a stand alone program, so it has to keep running.
//
// r8forge_examples_test [examples dir] default: examples
#include "r8forge/r8asm.hh"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace {
struct machine {
std::vector<uint16_t> cells = std::vector<uint16_t>(kDefaultMemoryCells, 0);
std::vector<uint16_t> out;
std::deque<uint16_t> in; // characters for INP, from the header's `; in`
size_t dp = 0;
size_t steps = 0;
bool finished = true; // false: the step limit ran out
static uint16_t ror(uint16_t v) {
return uint16_t((v >> 1) | ((v & 1u) << (kDefaultCellSize - 1)));
}
void run(const std::string &tape, size_t limit = 5'000'000) {
for (size_t pc = 0; pc < tape.size(); pc++) {
if (++steps > limit) {
finished = false;
return;
}
switch (tape[pc]) {
case '>':
dp = (dp + 1) % cells.size();
break;
case '<':
dp = (dp + cells.size() - 1) % cells.size();
break;
case '-': // flb
cells[dp] ^= 1;
break;
case '+': // ror
cells[dp] = ror(cells[dp]);
break;
// biz / rnz test the LOW BIT, not "is the cell zero" (ROT-8-viz
// src/rot8.c). Reading them as a Brainfuck style zero test makes every
// byte level program look like an endless loop.
case '[':
if ((cells[dp] & 1) == 0) {
int depth = 1;
while (depth) {
pc++;
if (tape[pc] == '[')
depth++;
else if (tape[pc] == ']')
depth--;
}
}
break;
case ']':
if ((cells[dp] & 1) == 1) {
int depth = 1;
while (depth) {
pc--;
if (tape[pc] == ']')
depth++;
else if (tape[pc] == '[')
depth--;
}
}
break;
case '.':
out.push_back(cells[dp]);
break;
case ',': // INP: low 7 bits of the next header character, 0 when empty
cells[dp] = in.empty() ? 0 : in.front();
if (!in.empty())
in.pop_front();
break;
default: // ',' (input) is not modelled
break;
}
}
}
};
// import_file() only reports what the parser found; an unknown macro is found
// while the tree is expanded, and a truncated tape still runs and prints
// something plausible. Same order as r8forge's own main.
bool assemble(const std::filesystem::path &file, std::string &tape) {
r8asm assembler;
if (!assembler.import_file(file.string(), kDefaultCellSize)) {
std::cerr << " could not assemble " << file.string() << "\n";
return false;
}
tape = assembler.export_rot8();
if (assembler.failed()) {
std::cerr << " could not assemble " << file.string() << "\n";
return false;
}
return true;
}
// The `; out 1 2 3` line in the header. Returns false when it is missing or
// carries no numbers -- the marker is required, not optional.
bool expected_out(const std::filesystem::path &file, std::vector<int> &want) {
std::ifstream in(file);
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
const size_t at = line.find_first_not_of(" \t");
if (at == std::string::npos || line[at] != ';')
continue;
std::istringstream rest(line.substr(at + 1));
std::string word;
if (!(rest >> word) || word != "out")
continue;
std::vector<int> values;
int v;
while (rest >> v)
values.push_back(v);
if (values.empty())
continue;
want = values;
return true;
}
return false;
}
// The optional `; in R8F!` line: characters handed to INP. Everything after
// the marker is taken literally (leading spaces are dropped), so an interactive
// example can spell out a whole session in its header. No marker means "no
// input": INP then reads 0, which is how the non-interactive examples run.
void expected_in(const std::filesystem::path &file, std::string &text) {
std::ifstream in(file);
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
const size_t at = line.find_first_not_of(" \t");
if (at == std::string::npos || line[at] != ';')
continue;
// Require the marker to be the first word after ';' -- "include" in a
// comment must not be mistaken for an input declaration.
size_t w = at + 1;
while (w < line.size() && (line[w] == ' ' || line[w] == '\t'))
w++;
if (line.compare(w, 2, "in") != 0)
continue;
w += 2;
if (w < line.size() && line[w] != ' ' && line[w] != '\t')
continue;
const size_t b = line.find_first_not_of(" \t", w);
text = b == std::string::npos ? std::string() : line.substr(b);
return;
}
}
std::string join(const std::vector<int> &v) {
std::ostringstream os;
for (size_t i = 0; i < v.size(); i++)
os << (i ? " " : "") << v[i];
return os.str();
}
} // namespace
int main(int argc, char **argv) {
const std::filesystem::path dir = argc > 1 ? argv[1] : "examples";
std::error_code ec;
std::vector<std::filesystem::path> files;
for (const auto &entry : std::filesystem::directory_iterator(dir, ec)) {
if (entry.path().extension() == ".r8asm")
files.push_back(entry.path());
}
if (ec || files.empty()) {
std::cerr << "cannot read " << dir.string() << " (" << ec.message() << ")\n";
return 2;
}
std::sort(files.begin(), files.end());
int failures = 0;
auto check = [&](const std::filesystem::path &file, const std::string &name) {
std::vector<int> want;
if (!expected_out(file, want)) {
std::cout << name << ": no '; out ...' line in the header\n";
failures++;
return;
}
std::string tape;
if (!assemble(file, tape)) {
failures++;
return;
}
std::string in_text;
expected_in(file, in_text);
machine m;
for (char ch : in_text)
m.in.push_back(uint16_t((unsigned char)ch & 0x7f));
m.run(tape);
std::vector<int> got;
for (uint16_t v : m.out)
got.push_back(int(v));
const bool ok = m.finished && got == want;
std::cout << name << ": " << tape.size() << " characters, " << m.steps
<< " steps, out " << join(got) << (ok ? " ok" : " FAILED");
if (!ok) {
std::cout << " (want " << join(want) << (m.finished ? "" : ", HANG") << ")";
failures++;
}
std::cout << "\n";
};
for (const std::filesystem::path &file : files)
check(file, file.filename().string());
// asm/test.r8asm is the flagship: it calls every macro in the library, so it
// gets exactly the same header check. It does not live in examples/ because
// it is a test, not a demo. The path is relative to the examples directory
// so this works whatever the working directory is.
const std::filesystem::path flagship = dir / ".." / "asm" / "test.r8asm";
const bool have_flagship = std::filesystem::exists(flagship);
if (have_flagship)
check(flagship, "asm/test.r8asm");
std::cout << (failures ? "FAILED: " + std::to_string(failures) + " file(s)\n"
: "all " + std::to_string(files.size()) + " examples" +
(have_flagship ? " and asm/test.r8asm" : "") +
" print what their headers say\n");
return failures ? 1 : 0;
}