Files
R8Forge/tests/tape_pack_test.cc
T
dsh 1e7acc018e hardware: the 74LS machine gets a period bill of materials, and a mechanics plan
Two things: the TTL build is now the main target (Tang Nano looks too modern), and
the packer learned the format that makes the TTL build simple.

Format: r8forge_tape_pack --eprom writes one byte per instruction with the opcode
in the low three bits.  Then ip is the EPROM address and D2..D0 are the opcode --
no shift register, no 16 bit window, no decoder.  It wastes five bits per
instruction, and a 27C512 is exactly 64K, which is the historical instruction
budget: the 8 bit calculator (51378) and the flagship (43676) both fit.  Both
formats live in the same .r8t trailer now (format byte 1 = packed, 2 = one byte
per instruction), decode dispatches on it, and the test runs both and requires
the same output and step count.

Carrier: 74LS DIPs on a green board, 27C512 in a socket with its quartz window,
6116 SRAM, 74LS299 for the rotate, 6850 ACIA for serial, 74LS47 and four seven
segment displays on the panel, 1 MHz can oscillator.  About 31 to 40 chips, 400
to 700 CNY, a few weeks.  The FPGA stays as a bench-only stepping stone.

hardware/mechanics.md: where mechanics actually pays.  The program must stay
electronic (130 metres of paper tape for the calculator), and 512 relays for the
data ring are out, but the pointer is worth it -- > and < are 71 to 73 percent of
all steps, so a 64 position ratchet or uniselector makes the machine physically
walk the ring.  Also listed: an electromagnetic step counter (10 to 20 Hz, so
only in single step mode, with a clutch for free running), a paper tape punch or
plotter for output, a tape/card reader or plain keypad for input, and a hand crank
as the clock.  The rule that keeps this safe: mechanics only ever sit on sensor
and actuator pins and never in the logic path, and the handshake just stops the
sequencer while something moves -- since nothing in the ISA can observe time,
slower is not different.  A relay-only machine is priced honestly too: 60 to 120
relays, 10 to 50 Hz, hello in 10 to 40 seconds, the calculator in four hours, so
that one is an exhibit.

Also fixed: the synthesised macro fallback file name now carries a per-run token.
When the system temp directory is not writable every r8asm falls back to the same
working directory, so parallel ctest runs could write and import the same file --
which showed up as a random one-test failure in 0.39 seconds and nothing else.
2026-11-20 16:35:02 +08:00

286 lines
12 KiB
C++

// The two things in the hardware that software cannot check by inspecting the
// source: the 3 bit packing, and the bracket strategy.
//
// r8forge_tape_pack_test [paths...] default: a built in list
//
// For every tape:
// * text -> opcodes -> text round trips exactly;
// * opcodes -> 3 bit bytes -> opcodes round trips exactly (padding bits in the
// last byte are checked to be the only thing that is ignored);
// * running the *packed* image gives the same output, the same final cells and
// the same step count as running the text -- that pins the bit order;
// * the board's loop stack gives the same result as the reference backward
// scan, which is the equivalence the hardware relies on;
// * the contract reading ('jump back onto the [') gives the same output and
// exactly `back_jumps` more steps than the interpreter reading -- the two
// interpretations differ by one step per loop, never by behaviour.
//
// Also checks that a broken tape is *reported*: an unbalanced bracket, a junk
// character, a truncated image.
#include "r8forge/r8asm.hh"
#include "r8forge/geometry.hh"
#include "r8forge/tape.hh"
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace {
bool assemble(const std::filesystem::path &file, std::vector<uint8_t> &code,
std::string &error) {
r8asm assembler;
if (!assembler.import_file(file.string(), kDefaultCellSize)) {
error = "could not assemble";
return false;
}
return tape_decode(assembler.export_rot8(), code, error);
}
bool same(const std::vector<uint32_t> &a, const std::vector<uint32_t> &b) {
return a == b;
}
int failures = 0;
void fail(const std::string &what) {
std::cout << " FAILED: " << what << "\n";
failures++;
}
void check(const std::string &path) {
std::cout << path << "\n";
std::vector<uint8_t> code;
std::string error;
if (!assemble(path, code, error)) {
fail(path + ": " + error);
return;
}
const std::string text = tape_encode(code);
// 1. text round trip
std::vector<uint8_t> back;
if (!tape_decode(text, back, error) || back != code)
fail("text round trip");
if (tape_encode(code) != text)
fail("encode round trip");
// 2. packed round trip
const std::vector<uint8_t> body = tape_pack(code);
if (body.size() != (code.size() * 3 + 7) / 8)
fail("packed size is not ceil(3n/8)");
std::vector<uint8_t> unpacked;
if (!tape_unpack(body, code.size(), unpacked, error))
fail("unpack: " + error);
else if (unpacked != code)
fail("pack round trip");
// The padding bits of the last byte must not carry instructions. Only the
// bits *above* the last instruction are padding: 3n % 8 of the byte's low bits
// are real, so filling those would just corrupt the tape (the first version of
// this check did exactly that and blamed the codec).
if (code.size() * 3 % 8) {
const unsigned used = unsigned(code.size() * 3 % 8);
std::vector<uint8_t> padded = body;
padded.back() |= uint8_t(0xFFu << used); // fill only the padding with ones
std::vector<uint8_t> junk;
if (!tape_unpack(padded, code.size(), junk, error))
fail("unpack with padding set: " + error);
else if (junk != code)
fail("padding bits leak into the instructions");
}
// 3. the machine: text vs packed, scan vs loop stack, interpreter vs contract
machine_options scan;
scan.width = kDefaultCellSize;
scan.ring = kDefaultMemoryCells;
machine_options stack = scan;
stack.loop_stack = true;
machine_options contract = scan;
contract.retest = true;
const machine_result a = tape_run(code, {}, scan);
if (!a.error.empty()) {
fail("text run: " + a.error);
return;
}
const machine_result b = tape_run(unpacked, {}, scan);
if (!b.error.empty() || b.out != a.out || b.steps != a.steps ||
b.cells != a.cells)
fail("packed image does not run like the text tape");
const machine_result c = tape_run(unpacked, {}, stack);
if (!c.error.empty() || c.out != a.out || c.steps != a.steps ||
c.cells != a.cells)
fail("loop stack does not match the backward scan");
// The board jumps onto the '[' (the contract), so the fourth combination is
// the one the hardware actually uses: loop stack *and* retest. Its output has
// to match, and its step count has to be the retest count.
machine_options board = scan;
board.loop_stack = true;
board.retest = true;
const machine_result e = tape_run(unpacked, {}, board);
if (!e.error.empty() || e.out != a.out || e.cells != a.cells)
fail("the board's strategy (loop stack + retest) prints something else");
else if (e.steps != a.steps + a.back_jumps)
fail("the board's strategy has the wrong step count");
const machine_result d = tape_run(code, {}, contract);
if (!d.error.empty() || d.out != a.out)
fail("the contract reading prints something else");
else if (d.steps != a.steps + a.back_jumps)
fail("contract steps " + std::to_string(d.steps) + " != interp steps " +
std::to_string(a.steps) + " + back jumps " +
std::to_string(a.back_jumps));
std::cout << " " << code.size() << " instructions, " << body.size()
<< " bytes, " << a.steps << " steps, " << a.out.size() << " outs, "
<< a.back_jumps << " back jumps";
if (a.steps == a.back_jumps)
std::cout << " (no loops taken?)";
std::cout << "\n";
}
void check_broken_tapes() {
std::cout << "broken tapes are reported\n";
std::vector<uint8_t> code;
std::string error;
// 'x' is not one of the eight instructions; whitespace is allowed.
if (tape_decode(">x<", code, error) || error.empty())
fail("'x' should be an error");
if (!tape_decode(">+-[].,<", code, error) || !error.empty())
fail("the eight instructions should decode");
if (!tape_decode("> + <\n", code, error) || !error.empty() || code.size() != 3)
fail("whitespace should be ignored, not decoded");
if (code.size() != 3 || code[0] != uint8_t(opcode::stp) ||
code[1] != uint8_t(opcode::ror) || code[2] != uint8_t(opcode::btp))
fail("whitespace changed the instruction order");
machine_options opt;
opt.ring = 64;
// '[' with a zero cell skips forward and runs off the end: unbalanced.
const machine_result unopened =
tape_run({uint8_t(opcode::biz), uint8_t(opcode::stp)}, {}, opt);
if (unopened.error.empty())
fail("an unclosed '[' should be reported");
// '-' makes the low bit 1, so this ']' fires with no '[' behind it.
const machine_result unclosed =
tape_run({uint8_t(opcode::flb), uint8_t(opcode::rnz)}, {}, opt);
if (unclosed.error.empty())
fail("a ']' that fires without a '[' should be reported");
machine_options stack = opt;
stack.loop_stack = true;
// '[' with a zero cell skips forward, so the ']' is never executed and the
// loop stack stays empty -- that has to be fine, not an "empty stack" error.
const std::vector<uint8_t> skip_tape = {uint8_t(opcode::stp),
uint8_t(opcode::biz),
uint8_t(opcode::rnz),
uint8_t(opcode::stp)};
const machine_result skip = tape_run(skip_tape, {}, stack);
if (!skip.error.empty())
fail("skipping a loop in loop stack mode: " + skip.error);
// A loop that runs: the entry has to survive every iteration and only be
// dropped when the loop exits, otherwise the second iteration sees an empty
// stack. This is the one bug the equivalence test caught.
const std::vector<uint8_t> counted = {uint8_t(opcode::biz),
uint8_t(opcode::flb),
uint8_t(opcode::rnz),
uint8_t(opcode::btp)};
// '[' skips (cell is 0) ... so drive it through the loop with a seed instead.
machine_options seeded = stack;
std::vector<uint32_t> one(64, 0);
one[0] = 1;
seeded.initial = &one;
const machine_result looped = tape_run(counted, {}, seeded);
if (!looped.error.empty())
fail("loop stack, one iteration: " + looped.error);
machine_options seeded_scan = seeded;
seeded_scan.loop_stack = false;
const machine_result looped_scan = tape_run(counted, {}, seeded_scan);
if (!looped_scan.error.empty())
fail("backward scan, one iteration: " + looped_scan.error);
if (looped.steps != looped_scan.steps || looped.out != looped_scan.out)
fail("a single loop disagrees between loop stack and scan");
std::vector<uint8_t> body = tape_pack({uint8_t(opcode::out)});
std::vector<uint8_t> truncated;
if (tape_unpack(body, 100, truncated, error) || error.empty())
fail("an image too short for its length should be reported");
// All eight opcodes are legal, so a full byte of ones is legal too -- this
// pins that down instead of pretending there is a spare opcode slot.
std::vector<uint8_t> ones = {0xFF, 0xFF, 0xFF};
if (!tape_unpack(ones, 8, truncated, error) || truncated.size() != 8)
fail("eight opcode-7 instructions should decode");
else if (truncated[0] != 7)
fail("0xFF should decode to opcode 7 first");
// The .r8t image: encode/decode round trip, and every kind of damage refused.
const std::vector<uint8_t> tape = {uint8_t(opcode::out), uint8_t(opcode::stp),
uint8_t(opcode::flb), uint8_t(opcode::rnz)};
const std::vector<uint8_t> image = tape_image_encode(tape, 8, 64);
if (image.size() != (tape.size() * 3 + 7) / 8 + 16)
fail("image size is not body + trailer");
if (!tape_is_image(image))
fail("a freshly encoded image is not recognised");
tape_image decoded;
if (!tape_image_decode(image, decoded, error))
fail("decode own image: " + error);
else if (decoded.code != tape || decoded.width != 8 || decoded.ring != 64)
fail("image round trip lost something");
// The EPROM format: one byte per instruction, low three bits. It runs the
// same, it is bigger, and a byte with the high bits set must be refused.
const std::vector<uint8_t> eprom = tape_image_encode(tape, 8, 64, 2);
if (eprom.size() != tape.size() + 16)
fail("eprom image is not one byte per instruction plus the trailer");
tape_image nvram;
if (!tape_image_decode(eprom, nvram, error))
fail("decode eprom image: " + error);
else if (nvram.code != tape || nvram.format != 2)
fail("eprom image round trip lost something");
const machine_result from_packed = tape_run(tape, {}, opt);
const machine_result from_eprom = tape_run(nvram.code, {}, opt);
if (from_packed.out != from_eprom.out || from_packed.steps != from_eprom.steps)
fail("the two image formats do not run the same");
std::vector<uint8_t> bad_eprom = eprom;
bad_eprom[0] = 0x55; // high bits set: not an opcode
if (tape_image_decode(bad_eprom, nvram, error) || error.empty())
fail("an eprom byte that is not an opcode should be refused");
std::vector<uint8_t> flipped = image;
flipped[0] ^= 0x01;
if (tape_image_decode(flipped, decoded, error) || error.empty())
fail("a flipped body bit should fail the crc");
std::vector<uint8_t> chopped(image.begin(), image.end() - 16);
if (tape_image_decode(chopped, decoded, error) || error.empty())
fail("a body without its trailer should be refused");
std::vector<uint8_t> bad_width = image;
bad_width[bad_width.size() - 16 + 4] = 99;
if (tape_image_decode(bad_width, decoded, error) || error.empty())
fail("a nonsense cell width should be refused");
}
} // namespace
int main(int argc, char **argv) {
std::vector<std::string> paths;
for (int i = 1; i < argc; i++)
paths.push_back(argv[i]);
if (paths.empty())
paths = {"asm/test.r8asm", "examples/hello.r8asm", "examples/term.r8asm",
"examples/calc.r8asm", "examples/signed_demo.r8asm"};
for (const std::string &p : paths) {
if (!std::filesystem::exists(p)) {
std::cout << p << ": missing\n";
failures++;
continue;
}
check(p);
}
check_broken_tapes();
std::cout << (failures ? "FAILED (" + std::to_string(failures) + ")\n"
: "tape packing and bracket strategies ok\n");
return failures ? 1 : 0;
}