// Assembles examples/full_add.r8asm (whose body is synthesised at assembly // time) and runs the resulting tape on a tiny ROT-8 machine for all eight // input combinations. #include "r8forge/geometry.hh" #include "r8forge/r8asm.hh" #include #include #include namespace { // the eight ROT-8 instructions const char *const INSTRUCTIONS = "><-+[].r"; // r = our ror alias // real ROT-8: '>' '<' '-' '+' '[' ']' '.' ',' // note "-" is ror, and there is no separate 'r' struct machine { std::vector cells = std::vector(kDefaultMemoryCells, 0); std::vector out; size_t dp = 0; static uint32_t ror(uint32_t v) { return uint32_t((v >> 1) | ((v & 1u) << (kDefaultCellSize - 1))); } void run(const std::string &tape) { for (size_t pc = 0; pc < tape.size(); pc++) { switch (tape[pc]) { case '>': dp++; break; case '<': dp--; break; case '-': // flb: flip last bit cells[dp] ^= 1; break; case '+': // ror: rotate right cells[dp] = ror(cells[dp]); break; // biz / rnz test the LOW BIT of the cell, not "is the cell zero": // rot8_biz: if ((*mem & 1) == 0) jump past the matching ']' // rot8_rnz: if ((*mem & 1) == 1) jump back to the matching '[' // (reference: ROT-8-viz src/rot8.c). With "cell == 0" instead, every // byte level program in the library looks 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; default: break; } } } }; } // namespace int main(int argc, char **argv) { const char *file = argc > 1 ? argv[1] : "examples/full_add.r8asm"; r8asm assembler; if (!assembler.import_file(file, kDefaultCellSize)) { std::cerr << "could not assemble " << file << "\n"; return 1; } const std::string tape = assembler.export_rot8(); if (assembler.failed()) { // unknown macro / bad '.tp', found while expanding std::cerr << "could not assemble " << file << "\n"; return 1; } std::cout << "tape: " << tape.size() << " characters\n"; int failures = 0; for (int combo = 0; combo < 8; combo++) { const int a = combo & 1, b = (combo >> 1) & 1, c = (combo >> 2) & 1; machine m; m.cells[0] = uint32_t(a); // A m.cells[1] = uint32_t(b); // B m.cells[2] = uint32_t(c); // Ci m.run(tape); const int sum = a ^ b ^ c; const int carry = (a & b) | (a & c) | (b & c); const bool ok = m.out.size() == 2 && m.out[0] == sum && m.out[1] == carry; std::cout << " " << a << b << c << " -> " << (m.out.size() > 0 ? int(m.out[0]) : -1) << (m.out.size() > 1 ? int(m.out[1]) : -1) << " expect " << sum << carry << (ok ? " ok" : " WRONG") << "\n"; if (!ok) failures++; } std::cout << (failures ? "FAILED\n" : "all eight combinations ok\n"); return failures ? 1 : 0; }