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.
This commit is contained in:
1 parent
0c7d0c8754
commit
9b31a51fec
13 files changed
+1621
-130
No files matched your search
@@ -46,6 +46,11 @@ r8forge asm/test.r8asm # 62351 字符(除两个有符号
|
||||
r8forge_byte_op_test # 23 项(divmod 16384 组、digits 2048、digits_signed 2048、divmod_signed 4202、undigits 4096);8/11/16 位真跑,17 位以上打印 skipped
|
||||
r8forge_examples_test # 19 个 example + asm/test.r8asm,核对头部 `; out`/`; in`
|
||||
r8forge_macro_docs_test # 55 macros in 23 files
|
||||
r8forge_tape_pack hello.rot8 -o hello.r8t --hex hello.hex --verify # 文本纸带 -> 3 bit 打包镜像,--hex 是 $readmemh 用的
|
||||
r8forge_tape_pack_test # 打包/解包往返 + 括号四种实现输出一致(含循环栈 + retest)
|
||||
r8forge_tape_run hello.r8t --loop-stack --retest # 直接跑打包镜像;这两个开关对应板子的实现
|
||||
# 8 位 + 64 格是物理机的几何(-DR8FORGE_CELL_SIZE=8 -DR8FORGE_MEMORY_CELLS=64):
|
||||
# ctest -R rtl_sim 在那里会真编 hardware/rot8.v 跑 iverilog 对拍,其它几何打印 SKIP
|
||||
r8forge --opt asm/test.r8asm # 纸带窥孔优化 62351 -> 56338(>< 净位移、+ mod W、- mod 2)
|
||||
r8forge_tape_opt in.rot8 out.rot8 # 同一优化,但作用在已有纸带上
|
||||
r8forge_tape_run t.rot8 --profile # 剖面:指针移动占 66~73% 步数(实测,见下)
|
||||
@@ -187,11 +192,12 @@ term 27,全家桶自检 155),再跑整轮自检确认。物理机取 **8
|
||||
迷你 `printf`(终端纸带和计算器外壳都做完之后用处要重新评估)、以及栈要不要再深一格
|
||||
(3 → 4 格现在没有预算障碍了)。
|
||||
|
||||
**硬件那条线**单独放在 [`docs/hardware.md`](docs/hardware.md):ISA 已经全部实现,机器语义
|
||||
里没有任何东西能看见时间,所以"状态序列一致"就是同一台机器;文档里钉了硬件需求(含
|
||||
`biz`/`rnz` 扫描的确切边界)、ROM/RAM 预算(`ip` 至少要 17 位 —— 计算器 73624 已经越过
|
||||
历史 `INS_SIZE`)、FPGA / 分立 TTL / 机电三档载体,以及"先写 `r8forge tape pack` + RTL
|
||||
testbench 对拍"的 M0~M4 路线。没开工,等选档。
|
||||
**硬件那条线**单独放在 [`docs/hardware.md`](docs/hardware.md) 和 [`hardware/`](hardware/):ISA
|
||||
已经全部实现,机器语义里没有任何东西能看见时间,所以"状态序列一致"就是同一台机器。已定
|
||||
**8 位 / 64 格**;**M0 做完了** —— `r8forge_tape_pack` 出 3 bit 打包镜像,`hardware/rot8.v`
|
||||
(循环栈括号 + 就地执行)在 iverilog 里跑,`hello` / `term` / `calc` / 全家桶的 OUT 流与
|
||||
步数和 `tape_run --loop-stack --retest` **逐字节一致**,`ctest -R rtl_sim` 固化(8 位构建)。
|
||||
上板(M1)还没开始,缺引脚约束、串口和面板。
|
||||
|
||||
## 索引
|
||||
|
||||
|
||||
+39
-3
@@ -39,7 +39,7 @@ add_compile_definitions(R8FORGE_MEMORY_CELLS=${R8FORGE_MEMORY_CELLS})
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
add_library(r8forge_core src/r8asm.cc src/synth.cc src/tape_opt.cc)
|
||||
add_library(r8forge_core src/r8asm.cc src/synth.cc src/tape_opt.cc src/tape.cc)
|
||||
target_link_libraries(r8forge_core PUBLIC Threads::Threads)
|
||||
|
||||
# 别再 set(CMAKE_CXX_FLAGS ...) 了:那会把默认 flag 整个换掉,MSVC 下丢 /EHsc、
|
||||
@@ -60,6 +60,14 @@ target_link_libraries(r8forge_derive r8forge_core)
|
||||
# A second, independent ROT-8 interpreter: runs a .rot8 file with no assembler
|
||||
# and no macros involved, so its verdict can be checked against r8forge_derive.
|
||||
add_executable(r8forge_tape_run tests/tape_run.cc)
|
||||
target_link_libraries(r8forge_tape_run r8forge_core)
|
||||
add_executable(r8forge_tape_pack tests/tape_pack.cc)
|
||||
target_link_libraries(r8forge_tape_pack r8forge_core)
|
||||
|
||||
# The two things software cannot check by reading the source: the 3 bit packing
|
||||
# the hardware decodes, and the bracket strategy it uses.
|
||||
add_executable(r8forge_tape_pack_test tests/tape_pack_test.cc)
|
||||
target_link_libraries(r8forge_tape_pack_test r8forge_core)
|
||||
|
||||
# Runs the byte level library macros (raw_add / raw_and / raw_or / raw_xor /
|
||||
# raw_inc) over every input combination.
|
||||
@@ -104,10 +112,38 @@ add_test(NAME bit_add_slice COMMAND r8forge verify_clb_bit_add_nc.r8asm)
|
||||
add_test(NAME bit_inc_slice COMMAND r8forge verify_clb_bit_inc_nc.r8asm)
|
||||
add_test(NAME loop_derive COMMAND r8forge_derive verify_loop.r8asm -1 0=5)
|
||||
add_test(NAME macro_docs COMMAND r8forge_macro_docs_test)
|
||||
# The packer's CLI and the runner's loader, end to end: assemble, pack, then run
|
||||
# the text tape and the packed file and require the same output under every
|
||||
# bracket strategy.
|
||||
add_test(NAME pack_roundtrip
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DR8FORGE=$<TARGET_FILE:r8forge>
|
||||
-DPACK=$<TARGET_FILE:r8forge_tape_pack>
|
||||
-DRUN=$<TARGET_FILE:r8forge_tape_run>
|
||||
-DSOURCE=${R8FORGE_TEST_DIR}/examples/hello.r8asm
|
||||
-DWORK=${CMAKE_CURRENT_BINARY_DIR}
|
||||
-P ${R8FORGE_TEST_DIR}/tests/pack_roundtrip.cmake)
|
||||
add_test(NAME tape_pack COMMAND r8forge_tape_pack_test)
|
||||
# The RTL against the interpreter: compiles hardware/rot8.v with iverilog, runs
|
||||
# a tape on it, and requires the same OUT stream and step count as
|
||||
# `tape_run --loop-stack --retest`. The RTL is the 8 bit / 64 cell machine, so
|
||||
# the script reports SKIP (and passes) in any other geometry.
|
||||
find_program(IVERILOG_EXE iverilog)
|
||||
add_test(NAME rtl_sim
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DGEOMETRY=${R8FORGE_CELL_SIZE}/${R8FORGE_MEMORY_CELLS}
|
||||
-DIVERILOG=${IVERILOG_EXE}
|
||||
-DPACK=$<TARGET_FILE:r8forge_tape_pack>
|
||||
-DRUN=$<TARGET_FILE:r8forge_tape_run>
|
||||
-DR8FORGE=$<TARGET_FILE:r8forge>
|
||||
-DSOURCE=${R8FORGE_TEST_DIR}/examples/hello.r8asm
|
||||
-DHARDWARE=${R8FORGE_TEST_DIR}/hardware
|
||||
-DWORK=${CMAKE_CURRENT_BINARY_DIR}
|
||||
-P ${R8FORGE_TEST_DIR}/tests/rtl_sim.cmake)
|
||||
|
||||
set_tests_properties(flagship byte_ops examples PROPERTIES LABELS "default-width")
|
||||
set_tests_properties(synth_full_add bit_add_slice bit_inc_slice loop_derive
|
||||
set_tests_properties(synth_full_add bit_add_slice bit_inc_slice loop_derive pack_roundtrip tape_pack rtl_sim
|
||||
macro_docs PROPERTIES LABELS "widthfree")
|
||||
set_tests_properties(flagship byte_ops examples synth_full_add bit_add_slice
|
||||
bit_inc_slice loop_derive macro_docs
|
||||
bit_inc_slice loop_derive macro_docs tape_pack pack_roundtrip rtl_sim
|
||||
PROPERTIES WORKING_DIRECTORY ${R8FORGE_TEST_DIR})
|
||||
+3
-3
@@ -206,10 +206,10 @@ rnz, 最低位 == 1: ip-- ; 深度=0
|
||||
|
||||
| | 内容 | 验收 |
|
||||
|---|---|---|
|
||||
| M0 | 打包器 + RTL 仿真 | `hello`(577 条)、`term`(16 414)、`asm/test.r8asm`(43 676)三条纸带的终态与 `tape_run` 一致 |
|
||||
| ✅ M0 | 打包器 + RTL 仿真 | **做完**(2026-11,iverilog 14):`hello` 417 步、`term`(喂 `lhi`)17 643 步、`calc`(喂 `12 34 + .`)166 741 步、全家桶 100 142 步 —— RTL 的 OUT 流与步数和 `tape_run --loop-stack --retest` **逐字节一致**;`ctest -R rtl_sim` 固化 |
|
||||
| M1 | 上板,面板 + 单步 | 单步跑 `hello`,OUT 与仿真逐字符一致 |
|
||||
| M2 | UART + 连续运行 | `asm/test.r8asm` 跑完:52 个 OUT、步数 = **99 824** |
|
||||
| M3 | 交互 | 终端里把计算器会话打出来(`12 34 + .` → `046`,**166 348** 步) |
|
||||
| M2 | UART + 连续运行 | `asm/test.r8asm` 跑完:93 个 OUT、步数 = **100 142**(`--retest` 口径;软硬件都已对上,等真板子) |
|
||||
| M3 | 交互 | 终端里把计算器会话打出来(`12 34 + .` → `046`,**166 741** 步 —— 仿真里已经做到) |
|
||||
| M4 | 加宽到 11 位(可选) | 换一份 ROM 跑 `asm/test.r8asm`:步数 = 202 159 —— 证明"宽度是构建参数、不是运行时状态" |
|
||||
|
||||
## 8. 动手前必须先定下来的语义(软件里已经定了,硬件要照抄)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# ROT-8 硬件:这个目录里有什么
|
||||
|
||||
`docs/hardware.md` 的落地部分。三样东西都跑通了(Icarus Verilog 14.0):
|
||||
|
||||
| 文件 | 是什么 | 状态 |
|
||||
|---|---|---|
|
||||
| `rot8.v` | 机器的 RTL:8 条指令、3 bit 操作码、6 位 `dp` 的 64 格环、**循环栈**式括号跳转 | ✅ 与软件逐字节一致 |
|
||||
| `tb_rot8.v` | testbench:`$readmemh` 一张镜像,跑到停机,按 `tape_run` 的格式打印 OUT 流和步数 | ✅ |
|
||||
| (工具)`r8forge_tape_pack` | 文本纸带 → 3 bit 打包镜像 + `--hex`(`$readmemh` 用) | ✅ 在 `tests/` 里 |
|
||||
|
||||
## 实测:RTL 与软件完全一致
|
||||
|
||||
8 位 / 64 格,`tape_run --loop-stack --retest`(板子实际采用的口径)对标 `vvp`:
|
||||
|
||||
| 纸带 | 指令数 | 步数 | OUT 个数 | 结果 |
|
||||
|---|---|---|---|---|
|
||||
| `-+.` 微测试 | 3 | 3 | 1 | ✅ 打出 128 |
|
||||
| `hello` | 577 | 417 | 10 | ✅ |
|
||||
| `term`(输入 `lhi`) | 16 414 | 17 643 | 11 | ✅ |
|
||||
| **`calc`(输入 `12 34 + .`)** | 51 378 | 166 741 | 19 | ✅ 打出 `> 12 34 + .` / `046` / `> ` |
|
||||
| 全家桶 `asm/test.r8asm` | 43 676 | 100 142 | 93 | ✅ |
|
||||
|
||||
自动化:`ctest -R rtl_sim`(在 8 位 / 64 格的构建里真跑,其它几何打印 SKIP)。
|
||||
`tests/rtl_sim.cmake` 就是那一轮:汇编 → 打包 → 软件跑 → `iverilog` 编 → `vvp` 跑 → 比对
|
||||
OUT 流和步数。
|
||||
|
||||
## 自己跑一遍
|
||||
|
||||
```sh
|
||||
# 8 位 / 64 格的构建(RTL 就是这台机器)
|
||||
cmake -S . -B build8 -DR8FORGE_CELL_SIZE=8 -DR8FORGE_MEMORY_CELLS=64
|
||||
cmake --build build8 --config Release
|
||||
|
||||
# 1) 汇编 + 打包 + 出 hex
|
||||
build8/Release/r8forge examples/hello.r8asm > hello.rot8
|
||||
build8/Release/r8forge_tape_pack hello.rot8 -o hello.r8t --hex hello.hex --verify
|
||||
|
||||
# 2) 软件侧金标准(注意两个开关)
|
||||
build8/Release/r8forge_tape_run hello.r8t --loop-stack --retest
|
||||
|
||||
# 3) RTL
|
||||
iverilog -g2012 -o rot8_tb.vvp hardware/rot8.v hardware/tb_rot8.v
|
||||
vvp rot8_tb.vvp +HEX=hello.hex +LEN=577
|
||||
```
|
||||
|
||||
带输入的程序(`calc`、`term`):把输入写成**一个文件**(不要换行),用 `+INFILE=` 喂;
|
||||
文件读完之后机器读到 0(和解释器的 EOF 语义一致):
|
||||
|
||||
```sh
|
||||
printf '12 34 + .' > calc_in.txt
|
||||
vvp rot8_tb.vvp +HEX=calc8.hex +LEN=51378 +INFILE=calc_in.txt
|
||||
build8/Release/r8forge_tape_run calc8.r8t --loop-stack --retest -i '12 34 + .'
|
||||
```
|
||||
|
||||
## 两个坑(都踩过)
|
||||
|
||||
1. **`+HEX=` / `+INFILE=` 的路径必须是纯 ASCII**。Icarus 把 plusarg 原样传下去,路径里有
|
||||
中文(这个仓库就在 `…/文档/…` 下)时 `$readmemh` 收到的是乱码,内存**静默留空**,机器
|
||||
就把一整条"全是 0 号操作码"的纸带跑完、什么都不打。要么 `cd` 进 hex 所在目录用相对
|
||||
路径(`tests/rtl_sim.cmake` 就是这么做的),要么把文件拷到 ASCII 路径。
|
||||
2. **`in_ready` 不能加 `!in_valid`** 的限定。第一版写成 `in_ready = … && !in_valid`,
|
||||
于是生产者永远看不到"接受"的边沿、握手死锁 —— 只有 `hello` 这种不读输入的纸带能跑。
|
||||
|
||||
## RTL 里几个"故意这么写"的地方
|
||||
|
||||
1. **程序存储器读 16 位窗口**(`prog_addr0` / `prog_addr1` 两次字节读):3 bit 指令会跨字节,
|
||||
取指必须看到相邻两个字节。真实板子上这对应"16 位宽 ROM"、"两片 ROM"或一个移位寄存器。
|
||||
2. **循环栈的进出账跟跳法绑定**:跳回 `['` 本身(`retest`)时 `]` 必须**弹栈**(`['` 重跑会
|
||||
再压一次);跳回 `['` 之后一格时要**留栈**到循环退出。RTL 只实现前者(契约口径),
|
||||
软件侧 `--loop-stack --retest` 与它对应;`r8forge_tape_pack_test` 盯着四种组合输出一致。
|
||||
3. **`biz` 的前向跳过是独立状态**(`S_SCAN`):每拍读一条、不算步数,跳到配对的 `]` 之后
|
||||
再多走一格。
|
||||
4. **`,` 阻塞**:`in_ready` 拉高、所有寄存器保持到 `in_valid`;读到 0 必须显式给
|
||||
(`in_valid` + `in_data=0`)。
|
||||
5. **停机**:`ip >= prog_len` → `halted`,并且这一拍不再执行(第一版漏了判断,会从纸带外
|
||||
多取一条、步数多 1)。
|
||||
|
||||
## 还没做的
|
||||
|
||||
* **上板**(M1):RTL 已经能跑,缺的是引脚约束、时钟、串口和面板。
|
||||
* **ROM 烧写格式**:28C256 / 39SF010 吃裸二进制 —— `tape pack -o x.bin` 去掉 16 字节
|
||||
trailer 即可(`--hex` 那份是给仿真用的)。
|
||||
* **UART / 前面板 / 单步**:RTL 已经留了 `run` / `step` / `ip` / `dp` / `steps` / `halted`。
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
// ROT-8, the machine.
|
||||
//
|
||||
// Eight instructions, three bit opcodes packed into a byte addressed program
|
||||
// memory, a 64 cell by 8 bit data ring, and -- this is the part the software
|
||||
// cannot check -- the hardware bracket strategy: a LIFO of loop entry positions
|
||||
// instead of a backward scan, jumping back *onto* the '[' so it re-tests.
|
||||
//
|
||||
// * program memory is read as a 16 bit window (two byte reads), because a three
|
||||
// bit instruction can straddle a byte boundary. A real board does this with
|
||||
// a 16 bit wide ROM, two ROMs, or a shift register; the interface is written
|
||||
// as two reads so all three are countable.
|
||||
// * the data ring is 64 cells, so `dp` is a 6 bit counter whose wrap is free.
|
||||
// * `,` blocks: `in_ready` goes high and the machine does not advance until
|
||||
// `in_valid` is seen. Reading zero has to be an explicit event (`in_valid`
|
||||
// with `in_data` zero), otherwise an idle keyboard would feed the program a
|
||||
// stream of EOFs.
|
||||
// * the step counter counts instructions, not cycles, and a bracket jump costs
|
||||
// exactly one step -- the scan and the LIFO bookkeeping are free, which is
|
||||
// what keeps the hardware's step counts comparable with the interpreters
|
||||
// (see `--loop-stack --retest` in r8forge_tape_run).
|
||||
//
|
||||
// Opcodes, in the order the assembler packs them (ROT-8-viz's enum):
|
||||
// 0 '>' STP 1 '<' BTP 2 '+' ROR 3 '-' FLB
|
||||
// 4 '[' BIZ 5 ']' RNZ 6 '.' OUT 7 ',' INP
|
||||
//
|
||||
// This file is the executable spec of the board. It has not been run yet: there
|
||||
// is no Verilog simulator on the development machine, so hardware/README.md says
|
||||
// how to run it and what to compare it against once one is available.
|
||||
`default_nettype none
|
||||
|
||||
module rot8 #(
|
||||
parameter integer WIDTH = 8, // bits per data cell
|
||||
parameter integer RING = 64, // data cells (power of two: free wrap)
|
||||
parameter integer IPW = 16, // instruction pointer width
|
||||
parameter integer STACKW = 4 // loop stack depth: 2^STACKW entries
|
||||
) (
|
||||
input wire clk,
|
||||
input wire rst_n,
|
||||
input wire run, // 1: free run, 0: halted between steps
|
||||
input wire step, // one instruction while run is 0
|
||||
|
||||
// program memory: two byte reads at prog_addr0 / prog_addr1
|
||||
output wire [IPW-1:0] prog_addr0,
|
||||
output wire [IPW-1:0] prog_addr1,
|
||||
input wire [7:0] prog_data0,
|
||||
input wire [7:0] prog_data1,
|
||||
input wire [IPW-1:0] prog_len, // instruction count: ip == prog_len halts
|
||||
|
||||
// input: blocks until in_valid, one byte per ','
|
||||
input wire in_valid,
|
||||
input wire [7:0] in_data,
|
||||
output wire in_ready,
|
||||
|
||||
// output: one cycle pulse per '.'
|
||||
output reg out_valid,
|
||||
output reg [7:0] out_data,
|
||||
|
||||
// debug / panel
|
||||
output reg [IPW-1:0] ip,
|
||||
// $clog2 rather than DPW here: a localparam declared in the body is not in
|
||||
// scope in the port list, and the width has to be a constant expression
|
||||
output reg [$clog2(RING)-1:0] dp,
|
||||
output reg [31:0] steps,
|
||||
output reg halted
|
||||
);
|
||||
|
||||
localparam integer DPW = $clog2(RING);
|
||||
|
||||
localparam [2:0] OP_STP = 3'd0, OP_BTP = 3'd1, OP_ROR = 3'd2, OP_FLB = 3'd3;
|
||||
localparam [2:0] OP_BIZ = 3'd4, OP_RNZ = 3'd5, OP_OUT = 3'd6, OP_INP = 3'd7;
|
||||
|
||||
localparam [1:0] S_FETCH = 2'd0, S_SCAN = 2'd1, S_HALT = 2'd2;
|
||||
|
||||
reg [1:0] state;
|
||||
reg [WIDTH-1:0] cells [0:RING-1];
|
||||
reg [IPW-1:0] stack [0:(1<<STACKW)-1];
|
||||
reg [STACKW-1:0] sp;
|
||||
|
||||
// ---- fetch ----------------------------------------------------------------
|
||||
// instruction ip starts at bit 3*ip of the byte stream
|
||||
wire [IPW+1:0] bit_index = ip * 3;
|
||||
wire [IPW-1:0] byte_index = bit_index >> 3;
|
||||
wire [2:0] bit_offset = bit_index[2:0];
|
||||
wire [15:0] window = {prog_data1, prog_data0};
|
||||
wire [2:0] op_now = (window >> bit_offset) & 16'h0007;
|
||||
|
||||
assign prog_addr0 = byte_index;
|
||||
assign prog_addr1 = byte_index + 1'b1;
|
||||
// in_ready means "the byte I am waiting for would be taken this cycle". It
|
||||
// must NOT be qualified with !in_valid: a producer then never sees the
|
||||
// acceptance edge and the handshake deadlocks (the first testbench did exactly
|
||||
// that and hello, which reads nothing, was the only tape that could run).
|
||||
assign in_ready = (state == S_FETCH) && (op_now == OP_INP);
|
||||
|
||||
// forward depth counter for the '[' skip
|
||||
reg [STACKW:0] scan_depth;
|
||||
|
||||
integer i;
|
||||
always @(posedge clk or negedge rst_n) begin
|
||||
if (!rst_n) begin
|
||||
state <= S_FETCH;
|
||||
ip <= {IPW{1'b0}};
|
||||
dp <= {DPW{1'b0}};
|
||||
sp <= {STACKW{1'b0}};
|
||||
steps <= 32'd0;
|
||||
halted <= 1'b0;
|
||||
out_valid <= 1'b0;
|
||||
out_data <= 8'd0;
|
||||
scan_depth <= {(STACKW+1){1'b0}};
|
||||
for (i = 0; i < RING; i = i + 1)
|
||||
cells[i] <= {WIDTH{1'b0}};
|
||||
end else begin
|
||||
out_valid <= 1'b0;
|
||||
|
||||
// ip == prog_len is the halt: the tape ran off its end
|
||||
if (ip >= prog_len) begin
|
||||
halted <= 1'b1;
|
||||
state <= S_HALT;
|
||||
end
|
||||
|
||||
case (state)
|
||||
S_FETCH: begin
|
||||
if (!halted && (ip < prog_len) && (run || step)) begin
|
||||
case (op_now)
|
||||
OP_STP: begin
|
||||
dp <= (dp == RING - 1) ? {DPW{1'b0}} : dp + 1'b1;
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
OP_BTP: begin
|
||||
dp <= (dp == 0) ? (RING - 1) : dp - 1'b1;
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
OP_ROR: begin
|
||||
cells[dp] <= {cells[dp][0], cells[dp][WIDTH-1:1]};
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
OP_FLB: begin
|
||||
cells[dp][0] <= ~cells[dp][0];
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
OP_BIZ: begin
|
||||
if (!cells[dp][0]) begin
|
||||
// skip forward to the matching ']', then past it
|
||||
scan_depth <= {{STACKW{1'b0}}, 1'b1};
|
||||
state <= S_SCAN;
|
||||
ip <= ip + 1'b1;
|
||||
end else begin
|
||||
// entering the loop: remember where it starts
|
||||
stack[sp] <= ip;
|
||||
sp <= sp + 1'b1;
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
end
|
||||
OP_RNZ: begin
|
||||
if (cells[dp][0]) begin
|
||||
// jump back ONTO the '[' (it re-tests, and re-pushes), so the
|
||||
// entry is popped here
|
||||
if (sp != 0) begin
|
||||
ip <= stack[sp - 1'b1];
|
||||
sp <= sp - 1'b1;
|
||||
end else begin
|
||||
// ']' with nothing entered: a malformed tape. Halt rather
|
||||
// than index below the stack.
|
||||
halted <= 1'b1;
|
||||
state <= S_HALT;
|
||||
end
|
||||
end else begin
|
||||
if (sp != 0)
|
||||
sp <= sp - 1'b1; // the loop finished
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
end
|
||||
OP_OUT: begin
|
||||
out_valid <= 1'b1;
|
||||
out_data <= cells[dp];
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
OP_INP: begin
|
||||
if (in_valid) begin
|
||||
cells[dp] <= in_data[WIDTH-1:0];
|
||||
ip <= ip + 1'b1;
|
||||
end
|
||||
// else: hold every register; in_ready is already high
|
||||
end
|
||||
default: ip <= ip + 1'b1;
|
||||
endcase
|
||||
// a held ',', a scan or a halt does not count as an instruction
|
||||
if (op_now != OP_INP || in_valid)
|
||||
steps <= steps + 32'd1;
|
||||
end
|
||||
end
|
||||
|
||||
S_SCAN: begin
|
||||
// one opcode per cycle: forward only, and free (it is not a step)
|
||||
if (run || step) begin
|
||||
if (op_now == OP_BIZ)
|
||||
scan_depth <= scan_depth + 1'b1;
|
||||
else if (op_now == OP_RNZ)
|
||||
scan_depth <= scan_depth - 1'b1;
|
||||
ip <= ip + 1'b1;
|
||||
if (op_now == OP_RNZ && scan_depth == 1) begin
|
||||
state <= S_FETCH; // ip now points past the matching ']'
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
S_HALT: begin
|
||||
halted <= 1'b1;
|
||||
end
|
||||
|
||||
default: state <= S_FETCH;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
|
||||
endmodule
|
||||
|
||||
`default_nettype wire
|
||||
@@ -0,0 +1,141 @@
|
||||
// Testbench for rot8.v: run one packed image and print what the machine printed,
|
||||
// in the same shape as `r8forge_tape_run` so the two can be diffed.
|
||||
//
|
||||
// iverilog -o rot8_tb hardware/rot8.v hardware/tb_rot8.v
|
||||
// vvp rot8_tb +HEX=hello.hex +LEN=727
|
||||
//
|
||||
// The hex file comes from `r8forge_tape_pack hello.rot8 -o hello.r8t --hex
|
||||
// hello.hex` (the body alone, one byte per line) and LEN from the comment on its
|
||||
// first line.
|
||||
//
|
||||
// What it is for: the OUT stream and the step count have to match
|
||||
// r8forge_tape_run hello.r8t --loop-stack --retest
|
||||
// which is the combination the board implements. That one comparison validates
|
||||
// the RTL, the packer and the bracket strategy at the same time.
|
||||
//
|
||||
// Not run yet: the development machine has no Verilog simulator (no iverilog, no
|
||||
// verilator). See hardware/README.md.
|
||||
`timescale 1ns/1ps
|
||||
`default_nettype none
|
||||
|
||||
module tb_rot8;
|
||||
|
||||
parameter integer MEMW = 16; // program memory address bits
|
||||
parameter integer MAX_OUT = 4096;
|
||||
|
||||
reg clk = 0;
|
||||
reg rst_n = 0;
|
||||
reg run = 1;
|
||||
reg step = 0;
|
||||
reg in_valid = 0;
|
||||
reg [7:0] in_data = 0;
|
||||
|
||||
wire [MEMW-1:0] prog_addr0, prog_addr1;
|
||||
wire [7:0] prog_data0, prog_data1;
|
||||
wire [MEMW-1:0] prog_len;
|
||||
wire out_valid;
|
||||
wire [7:0] out_data;
|
||||
wire in_ready;
|
||||
wire [MEMW-1:0] ip;
|
||||
wire [5:0] dp;
|
||||
wire [31:0] steps;
|
||||
wire halted;
|
||||
|
||||
reg [7:0] mem [0:(1<<MEMW)-1];
|
||||
reg [MEMW-1:0] length;
|
||||
integer outs [0:MAX_OUT-1];
|
||||
integer n_out = 0;
|
||||
integer cycles = 0;
|
||||
integer stalls = 0;
|
||||
integer i;
|
||||
|
||||
reg [1023:0] hex_path;
|
||||
reg [1023:0] in_path;
|
||||
integer in_fd = 0;
|
||||
reg in_eof = 0;
|
||||
integer next_char;
|
||||
|
||||
assign prog_data0 = mem[prog_addr0];
|
||||
assign prog_data1 = mem[prog_addr1];
|
||||
assign prog_len = length;
|
||||
|
||||
// Input: characters from +INFILE, one per accepted ','. When the file runs out
|
||||
// the machine is fed zeros, which is exactly what the interpreters do when
|
||||
// their scripted input is exhausted (EOF reads as 0). Without +INFILE,
|
||||
// in_valid stays low, so a tape that reads stops on the cycle cap and says so
|
||||
// instead of hanging the simulator.
|
||||
task take_char;
|
||||
begin
|
||||
next_char = $fgetc(in_fd);
|
||||
if (next_char < 0) begin
|
||||
in_eof <= 1'b1;
|
||||
in_data <= 8'd0;
|
||||
end else begin
|
||||
in_data <= next_char[7:0];
|
||||
end
|
||||
end
|
||||
endtask
|
||||
|
||||
rot8 #(.WIDTH(8), .RING(64), .IPW(MEMW), .STACKW(4)) dut (
|
||||
.clk(clk), .rst_n(rst_n), .run(run), .step(step),
|
||||
.prog_addr0(prog_addr0), .prog_addr1(prog_addr1),
|
||||
.prog_data0(prog_data0), .prog_data1(prog_data1),
|
||||
.prog_len(prog_len),
|
||||
.in_valid(in_valid), .in_data(in_data), .in_ready(in_ready),
|
||||
.out_valid(out_valid), .out_data(out_data),
|
||||
.ip(ip), .dp(dp), .steps(steps), .halted(halted));
|
||||
|
||||
// 100 MHz: two cycles per instruction, so the cycle count is about twice the
|
||||
// step count. A real board's clock is unrelated to the semantics.
|
||||
always #5 clk = ~clk;
|
||||
|
||||
initial begin
|
||||
if (!$value$plusargs("HEX=%s", hex_path)) begin
|
||||
$display("tb_rot8: pass +HEX=<file>");
|
||||
$finish;
|
||||
end
|
||||
if (!$value$plusargs("LEN=%d", length)) begin
|
||||
$display("tb_rot8: pass +LEN=<instruction count>");
|
||||
$finish;
|
||||
end
|
||||
for (i = 0; i < (1<<MEMW); i = i + 1)
|
||||
mem[i] = 8'h00;
|
||||
$readmemh(hex_path, mem);
|
||||
if ($value$plusargs("INFILE=%s", in_path))
|
||||
in_fd = $fopen(in_path, "r");
|
||||
#20 rst_n = 1;
|
||||
if (in_fd != 0) begin
|
||||
in_valid = 1'b1;
|
||||
take_char;
|
||||
end
|
||||
|
||||
// A tape that reads ',' with no input at all stays in in_ready; the cycle cap
|
||||
// turns that into a report instead of a hang.
|
||||
while (!halted && cycles < 100000000) begin
|
||||
@(posedge clk);
|
||||
cycles = cycles + 1;
|
||||
if (in_ready && !in_valid)
|
||||
stalls = stalls + 1;
|
||||
if (in_ready && in_valid && in_fd != 0 && !in_eof)
|
||||
take_char; // the machine took this byte: fetch the next one
|
||||
if (out_valid && n_out < MAX_OUT) begin
|
||||
outs[n_out] = out_data;
|
||||
n_out = n_out + 1;
|
||||
end
|
||||
end
|
||||
|
||||
$write("out");
|
||||
for (i = 0; i < n_out; i = i + 1)
|
||||
$write(" %0d", outs[i]);
|
||||
if (halted)
|
||||
$display(" (%0d steps, %0d cycles, %0d stalled on input)", steps, cycles,
|
||||
stalls);
|
||||
else
|
||||
$display(" (no halt after %0d cycles: ip %0d dp %0d, %0d input stalls)",
|
||||
cycles, ip, dp, stalls);
|
||||
$finish;
|
||||
end
|
||||
|
||||
endmodule
|
||||
|
||||
`default_nettype wire
|
||||
@@ -0,0 +1,133 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// The ROT-8 tape as *bits*, not as text.
|
||||
//
|
||||
// The assembler emits `.rot8`: one character per instruction, which is what the
|
||||
// tools and the visualizer read. The hardware cannot afford that (an eight
|
||||
// opcode instruction set needs three bits, so text wastes 62% of a ROM and needs
|
||||
// an ASCII decoder in the datapath), so the image that goes into a ROM or a
|
||||
// block RAM is packed.
|
||||
//
|
||||
// Opcode numbering follows the enum in the reference interpreter
|
||||
// (ROT-8-viz/include/rot8/rot8.h: STP, BTP, ROR, FLB, BIZ, RNZ, OUT, INP).
|
||||
// That table *is* the hardware's decoder, so the numbering is part of the
|
||||
// interface: do not renumber it and do not change the packing.
|
||||
//
|
||||
// Packing: three bits per instruction, little end first, instructions laid out
|
||||
// consecutively, so eight instructions fill exactly three bytes. Instruction i
|
||||
// occupies bits 3*i .. 3*i+2 of the byte stream.
|
||||
enum class opcode : uint8_t {
|
||||
stp = 0, // '>'
|
||||
btp = 1, // '<'
|
||||
ror = 2, // '+'
|
||||
flb = 3, // '-'
|
||||
biz = 4, // '['
|
||||
rnz = 5, // ']'
|
||||
out = 6, // '.'
|
||||
inp = 7, // ','
|
||||
};
|
||||
|
||||
// Text (".rot8") -> opcodes. A character outside "><+-[].," is an error: the
|
||||
// assembler never emits one, so seeing one means the tape is broken, and
|
||||
// silently skipping it would hide that.
|
||||
bool tape_decode(const std::string &text, std::vector<uint8_t> &code,
|
||||
std::string &error);
|
||||
// Opcodes -> text. `tape_decode` inverts this; a round trip has to be exact.
|
||||
std::string tape_encode(const std::vector<uint8_t> &code);
|
||||
|
||||
// 3 bits per instruction, little end first.
|
||||
std::vector<uint8_t> tape_pack(const std::vector<uint8_t> &code);
|
||||
// The inverse. `length` comes from outside: the byte stream has padding bits at
|
||||
// the top, so it cannot be recovered from the bytes alone.
|
||||
bool tape_unpack(const std::vector<uint8_t> &bytes, size_t length,
|
||||
std::vector<uint8_t> &code, std::string &error);
|
||||
|
||||
// ---- the .r8t image ----------------------------------------------------------
|
||||
//
|
||||
// The file a programmer burns or a block RAM initialises from: the packed body
|
||||
// followed by a 16 byte trailer, so that address 0 of the medium is instruction
|
||||
// 0 and the program can be executed in place (the trailer sits past the halt
|
||||
// point and is never fetched).
|
||||
//
|
||||
// trailer +0 u32 instruction count, little endian
|
||||
// +4 u8 cell width the tape was assembled for
|
||||
// +5 u8 ring size in cells (0 = more than 255, use the default)
|
||||
// +6 u8 format version (1)
|
||||
// +7 u8 reserved (0)
|
||||
// +8 "R8T1"
|
||||
// +12 u32 crc32 of the body, little endian
|
||||
struct tape_image {
|
||||
std::vector<uint8_t> code;
|
||||
size_t width = 0;
|
||||
size_t ring = 0;
|
||||
};
|
||||
|
||||
std::vector<uint8_t> tape_image_encode(const std::vector<uint8_t> &code,
|
||||
size_t width, size_t ring);
|
||||
// True when the bytes end with the trailer (the loader uses this to tell an
|
||||
// image from a text tape without trusting the file name).
|
||||
bool tape_is_image(const std::vector<uint8_t> &bytes);
|
||||
bool tape_image_decode(const std::vector<uint8_t> &bytes, tape_image &img,
|
||||
std::string &error);
|
||||
|
||||
// ---- the machine -------------------------------------------------------------
|
||||
//
|
||||
// A model of the *hardware*, not of the assembler: it executes a packed image
|
||||
// (or the opcode vector, which is the same thing unpacked) and reports what a
|
||||
// board would report -- the output stream, the final cells, and the step count.
|
||||
//
|
||||
// Why it exists: `r8forge_tape_run` reads text and `r8forge_derive` reads source;
|
||||
// both are software interpreters. The board reads three bit opcodes out of a
|
||||
// ROM and has to implement the bracket jump one way or another, so the two
|
||||
// things that can go wrong in the hardware -- the packing and the bracket
|
||||
// strategy -- need a model that is compared against the text level tools.
|
||||
struct machine_options {
|
||||
size_t ring = 0; // data cells, 0 = the build's default
|
||||
size_t width = 0; // bits per cell, 0 = the build's default
|
||||
size_t limit = 20'000'000; // step limit, the same as the other VMs
|
||||
// The board has two ways to implement ']': scan backwards through the tape
|
||||
// (what the interpreters do) or keep a stack of loop entry positions (what the
|
||||
// hardware does, because scanning is O(body) *per iteration*). Both are
|
||||
// compared here so the equivalence is a test and not a claim.
|
||||
bool loop_stack = false;
|
||||
// The contract (SPEC section 1, and ROT-8-viz) says ']' jumps back *onto* the
|
||||
// '[' so it re-executes. The interpreters jump to the instruction after it,
|
||||
// which prints the same thing but is one step shorter per loop. Default to
|
||||
// the interpreters' reading so documented step counts stay comparable;
|
||||
// `retest` is the contract reading, and the difference is exactly the number
|
||||
// of taken ']' instructions, which the test asserts.
|
||||
bool retest = false;
|
||||
// Bookkeeping for the profiler. Off by default: counting every step is not
|
||||
// free on a 20M step run.
|
||||
bool profile = false;
|
||||
// Optional starting cells (the debugger's `addr=value`). Copies over the
|
||||
// zeroed ring, so a shorter vector only overwrites its own prefix.
|
||||
const std::vector<uint32_t> *initial = nullptr;
|
||||
// Called before each instruction when set (the debugger view).
|
||||
void (*trace)(void *ctx, size_t ip, size_t dp, const uint32_t *cells,
|
||||
size_t ring, uint8_t op) = nullptr;
|
||||
void *trace_ctx = nullptr;
|
||||
};
|
||||
|
||||
struct machine_result {
|
||||
bool halted = false; // ran off the end of the tape
|
||||
bool overrun = false; // hit the step limit
|
||||
size_t steps = 0;
|
||||
size_t back_jumps = 0; // taken ']' instructions (the step-count difference)
|
||||
std::string error; // unbalanced bracket or bad opcode, empty when fine
|
||||
std::vector<uint32_t> out;
|
||||
std::vector<uint32_t> cells;
|
||||
// Filled in only when machine_options::profile is set.
|
||||
std::array<size_t, 8> op_counts{};
|
||||
std::vector<size_t> cell_hits;
|
||||
};
|
||||
|
||||
machine_result tape_run(const std::vector<uint8_t> &code,
|
||||
const std::vector<uint32_t> &input,
|
||||
const machine_options &opt = {});
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#include "r8forge/tape.hh"
|
||||
|
||||
#include "r8forge/geometry.hh"
|
||||
|
||||
#include <algorithm>`n#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
char to_char(opcode op) {
|
||||
switch (op) {
|
||||
case opcode::stp: return '>';
|
||||
case opcode::btp: return '<';
|
||||
case opcode::ror: return '+';
|
||||
case opcode::flb: return '-';
|
||||
case opcode::biz: return '[';
|
||||
case opcode::rnz: return ']';
|
||||
case opcode::out: return '.';
|
||||
case opcode::inp: return ',';
|
||||
}
|
||||
return '?';
|
||||
}
|
||||
|
||||
bool from_char(char c, uint8_t &op) {
|
||||
switch (c) {
|
||||
case '>': op = uint8_t(opcode::stp); return true;
|
||||
case '<': op = uint8_t(opcode::btp); return true;
|
||||
case '+': op = uint8_t(opcode::ror); return true;
|
||||
case '-': op = uint8_t(opcode::flb); return true;
|
||||
case '[': op = uint8_t(opcode::biz); return true;
|
||||
case ']': op = uint8_t(opcode::rnz); return true;
|
||||
case '.': op = uint8_t(opcode::out); return true;
|
||||
case ',': op = uint8_t(opcode::inp); return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool tape_decode(const std::string &text, std::vector<uint8_t> &code,
|
||||
std::string &error) {
|
||||
code.clear();
|
||||
error.clear();
|
||||
code.reserve(text.size());
|
||||
for (size_t i = 0; i < text.size(); i++) {
|
||||
const char c = text[i];
|
||||
// Whitespace is formatting, not instructions: a .rot8 file that came from a
|
||||
// shell redirect or an editor usually ends with a newline, and a wrapped
|
||||
// tape is still the same tape. Anything else that is not an instruction is
|
||||
// an error -- the old interpreter silently ignored junk, which hid exactly
|
||||
// the corruption this tool exists to catch.
|
||||
if (c == '\n' || c == '\r' || c == ' ' || c == '\t')
|
||||
continue;
|
||||
uint8_t op = 0;
|
||||
if (!from_char(c, op)) {
|
||||
error = "character " + std::to_string(i) + " is not an instruction (0x" +
|
||||
std::to_string(int((unsigned char)c)) + ")";
|
||||
return false;
|
||||
}
|
||||
code.push_back(op);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string tape_encode(const std::vector<uint8_t> &code) {
|
||||
std::string text;
|
||||
text.reserve(code.size());
|
||||
for (uint8_t op : code)
|
||||
text.push_back(to_char(opcode(op)));
|
||||
return text;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> tape_pack(const std::vector<uint8_t> &code) {
|
||||
std::vector<uint8_t> bytes((code.size() * 3 + 7) / 8, 0);
|
||||
for (size_t i = 0; i < code.size(); i++)
|
||||
for (int b = 0; b < 3; b++)
|
||||
if ((code[i] >> b) & 1u) {
|
||||
const size_t bit = i * 3 + size_t(b);
|
||||
bytes[bit / 8] |= uint8_t(1u << (bit % 8));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
bool tape_unpack(const std::vector<uint8_t> &bytes, size_t length,
|
||||
std::vector<uint8_t> &code, std::string &error) {
|
||||
code.clear();
|
||||
code.reserve(length);
|
||||
if ((length * 3 + 7) / 8 > bytes.size()) {
|
||||
error = "image holds " + std::to_string(bytes.size()) +
|
||||
" bytes, too few for " + std::to_string(length) + " instructions";
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
uint8_t op = 0;
|
||||
for (int b = 0; b < 3; b++) {
|
||||
const size_t bit = i * 3 + size_t(b);
|
||||
if ((bytes[bit / 8] >> (bit % 8)) & 1u)
|
||||
op = uint8_t(op | (1u << b));
|
||||
}
|
||||
if (op > uint8_t(opcode::inp)) {
|
||||
error = "instruction " + std::to_string(i) + " decodes to opcode " +
|
||||
std::to_string(int(op)) + ", which does not exist";
|
||||
return false;
|
||||
}
|
||||
code.push_back(op);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- the .r8t image ----------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
uint32_t crc32(const std::vector<uint8_t> &data) {
|
||||
uint32_t crc = 0xFFFFFFFFu;
|
||||
for (uint8_t b : data) {
|
||||
crc ^= b;
|
||||
for (int i = 0; i < 8; i++)
|
||||
crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
|
||||
}
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
void put_u32(std::vector<uint8_t> &v, size_t at, uint32_t value) {
|
||||
for (int i = 0; i < 4; i++)
|
||||
v[at + size_t(i)] = uint8_t((value >> (8 * i)) & 0xFF);
|
||||
}
|
||||
|
||||
uint32_t get_u32(const std::vector<uint8_t> &v, size_t at) {
|
||||
uint32_t value = 0;
|
||||
for (int i = 0; i < 4; i++)
|
||||
value |= uint32_t(v[at + size_t(i)]) << (8 * i);
|
||||
return value;
|
||||
}
|
||||
|
||||
constexpr size_t kTrailer = 16;
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> tape_image_encode(const std::vector<uint8_t> &code,
|
||||
size_t width, size_t ring) {
|
||||
std::vector<uint8_t> image = tape_pack(code);
|
||||
const size_t at = image.size();
|
||||
image.resize(at + kTrailer, 0);
|
||||
put_u32(image, at + 0, uint32_t(code.size()));
|
||||
image[at + 4] = uint8_t(width);
|
||||
image[at + 5] = uint8_t(ring > 255 ? 0 : ring);
|
||||
image[at + 6] = 1; // format version
|
||||
std::memcpy(&image[at + 8], "R8T1", 4);
|
||||
const std::vector<uint8_t> body(image.begin(), image.begin() + std::ptrdiff_t(at));
|
||||
put_u32(image, at + 12, crc32(body));
|
||||
return image;
|
||||
}
|
||||
|
||||
bool tape_is_image(const std::vector<uint8_t> &bytes) {
|
||||
return bytes.size() >= kTrailer && bytes[bytes.size() - 8] == 'R' &&
|
||||
bytes[bytes.size() - 7] == '8' && bytes[bytes.size() - 6] == 'T' &&
|
||||
bytes[bytes.size() - 5] == '1';
|
||||
}
|
||||
|
||||
bool tape_image_decode(const std::vector<uint8_t> &bytes, tape_image &img,
|
||||
std::string &error) {
|
||||
img = tape_image{};
|
||||
error.clear();
|
||||
if (!tape_is_image(bytes)) {
|
||||
error = "no R8T1 trailer: not a packed image";
|
||||
return false;
|
||||
}
|
||||
const size_t body = bytes.size() - kTrailer;
|
||||
const size_t length = get_u32(bytes, body);
|
||||
const unsigned width = bytes[body + 4];
|
||||
const unsigned ring = bytes[body + 5];
|
||||
if (width < 1 || width > 32) {
|
||||
error = "image says " + std::to_string(width) + " bits per cell";
|
||||
return false;
|
||||
}
|
||||
const std::vector<uint8_t> payload(bytes.begin(),
|
||||
bytes.begin() + std::ptrdiff_t(body));
|
||||
if (get_u32(bytes, body + 12) != crc32(payload)) {
|
||||
error = "image crc mismatch (truncated or edited)";
|
||||
return false;
|
||||
}
|
||||
img.width = width;
|
||||
img.ring = ring ? size_t(ring) : kDefaultMemoryCells;
|
||||
return tape_unpack(payload, length, img.code, error);
|
||||
}
|
||||
|
||||
machine_result tape_run(const std::vector<uint8_t> &code,
|
||||
const std::vector<uint32_t> &input,
|
||||
const machine_options &opt) {
|
||||
machine_result r;
|
||||
const size_t ring = opt.ring ? opt.ring : kDefaultMemoryCells;
|
||||
const size_t width = opt.width ? opt.width : kDefaultCellSize;
|
||||
const uint32_t mask =
|
||||
width >= 32 ? 0xFFFFFFFFu : uint32_t((uint64_t(1) << width) - 1);
|
||||
r.cells.assign(ring, 0);
|
||||
if (opt.initial) {
|
||||
const size_t n = std::min(ring, opt.initial->size());
|
||||
for (size_t i = 0; i < n; i++)
|
||||
r.cells[i] = (*opt.initial)[i] & mask;
|
||||
}
|
||||
if (opt.profile)
|
||||
r.cell_hits.assign(ring, 0);
|
||||
|
||||
size_t dp = 0;
|
||||
size_t ip = 0;
|
||||
size_t in_pos = 0;
|
||||
std::vector<size_t> loop; // loop_stack mode: the '[' positions that were entered
|
||||
|
||||
// Forward skip for '[': stop on the matching ']' (the caller then advances
|
||||
// past it, which is what "jump to the instruction after the loop" means).
|
||||
auto skip_forward = [&](size_t at) -> size_t {
|
||||
int depth = 1;
|
||||
for (size_t p = at + 1; p < code.size(); p++) {
|
||||
if (code[p] == uint8_t(opcode::biz)) depth++;
|
||||
else if (code[p] == uint8_t(opcode::rnz)) depth--;
|
||||
if (depth == 0) return p;
|
||||
}
|
||||
return code.size();
|
||||
};
|
||||
// Backward scan for ']': stop on the matching '['.
|
||||
auto scan_backward = [&](size_t at) -> size_t {
|
||||
int depth = 1;
|
||||
for (size_t p = at; p-- > 0;) {
|
||||
if (code[p] == uint8_t(opcode::rnz)) depth++;
|
||||
else if (code[p] == uint8_t(opcode::biz)) depth--;
|
||||
if (depth == 0) return p;
|
||||
}
|
||||
return code.size();
|
||||
};
|
||||
|
||||
while (ip < code.size()) {
|
||||
if (++r.steps > opt.limit) {
|
||||
r.overrun = true;
|
||||
r.error = "step limit";
|
||||
return r;
|
||||
}
|
||||
if (opt.profile) {
|
||||
r.op_counts[size_t(code[ip]) & 7]++;
|
||||
r.cell_hits[dp]++;
|
||||
}
|
||||
if (opt.trace)
|
||||
opt.trace(opt.trace_ctx, ip, dp, r.cells.data(), ring, code[ip]);
|
||||
bool advance = true;
|
||||
switch (opcode(code[ip])) {
|
||||
case opcode::stp:
|
||||
dp = (dp + 1) % ring;
|
||||
break;
|
||||
case opcode::btp:
|
||||
dp = (dp + ring - 1) % ring;
|
||||
break;
|
||||
case opcode::ror: {
|
||||
const uint32_t v = r.cells[dp];
|
||||
r.cells[dp] = uint32_t(((v >> 1) | ((v & 1u) << (width - 1))) & mask);
|
||||
break;
|
||||
}
|
||||
case opcode::flb:
|
||||
r.cells[dp] ^= 1;
|
||||
break;
|
||||
case opcode::biz:
|
||||
if ((r.cells[dp] & 1) == 0) {
|
||||
const size_t partner = skip_forward(ip);
|
||||
if (partner >= code.size()) {
|
||||
r.error = "unbalanced '[' at instruction " + std::to_string(ip);
|
||||
return r;
|
||||
}
|
||||
ip = partner; // the ']' itself; the advance below steps past it
|
||||
} else if (opt.loop_stack) {
|
||||
loop.push_back(ip); // the loop is entered: remember where it starts
|
||||
}
|
||||
break;
|
||||
case opcode::rnz:
|
||||
if ((r.cells[dp] & 1) == 1) {
|
||||
r.back_jumps++;
|
||||
size_t target = code.size();
|
||||
if (opt.loop_stack) {
|
||||
if (loop.empty()) {
|
||||
r.error = "empty loop stack: ']' at instruction " + std::to_string(ip);
|
||||
return r;
|
||||
}
|
||||
target = loop.back();
|
||||
// Which entry discipline goes with which jump:
|
||||
// retest -> the jump lands ON the '[', which pushes again, so this
|
||||
// entry has done its job and is popped now;
|
||||
// !retest -> the jump lands PAST the '[', which therefore never
|
||||
// re-pushes, so the entry has to stay until the loop
|
||||
// exits. Popping it here emptied the stack for the next
|
||||
// iteration -- a real bug, caught by the equivalence test
|
||||
// on examples/calc.r8asm.
|
||||
if (opt.retest)
|
||||
loop.pop_back();
|
||||
} else {
|
||||
target = scan_backward(ip);
|
||||
if (target >= code.size()) {
|
||||
r.error = "unbalanced ']' at instruction " + std::to_string(ip);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
ip = opt.retest ? target : target + 1;
|
||||
advance = false;
|
||||
} else if (opt.loop_stack && !loop.empty()) {
|
||||
loop.pop_back(); // the loop finished: drop its entry
|
||||
}
|
||||
break;
|
||||
case opcode::out:
|
||||
r.out.push_back(r.cells[dp]);
|
||||
break;
|
||||
case opcode::inp:
|
||||
r.cells[dp] = in_pos < input.size() ? (input[in_pos++] & mask) : 0;
|
||||
break;
|
||||
}
|
||||
if (advance)
|
||||
ip++;
|
||||
}
|
||||
r.halted = true;
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
# End-to-end check of the packer, at the CLI level: assemble a tape, pack it,
|
||||
# then run the *file* both ways and require identical output. The in-process
|
||||
# test (r8forge_tape_pack_test) covers the codec and the bracket strategies; this
|
||||
# one covers the two programs a person actually runs, including the image format
|
||||
# and its trailer.
|
||||
#
|
||||
# cmake -DR8FORGE=... -DPACK=... -DRUN=... -DSOURCE=... -DWORK=... -P pack_roundtrip.cmake
|
||||
foreach(var R8FORGE PACK RUN SOURCE WORK)
|
||||
if(NOT DEFINED ${var})
|
||||
message(FATAL_ERROR "pack_roundtrip.cmake needs -D${var}=...")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
execute_process(COMMAND ${R8FORGE} ${SOURCE} OUTPUT_VARIABLE text
|
||||
RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "assembling ${SOURCE} failed: ${rc}")
|
||||
endif()
|
||||
string(LENGTH "${text}" length)
|
||||
file(WRITE ${WORK}/pack_roundtrip.rot8 "${text}")
|
||||
|
||||
execute_process(COMMAND ${PACK} ${WORK}/pack_roundtrip.rot8
|
||||
-o ${WORK}/pack_roundtrip.r8t --verify
|
||||
OUTPUT_VARIABLE packed RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "packing failed: ${rc} ${packed}")
|
||||
endif()
|
||||
message(STATUS "${packed}")
|
||||
|
||||
foreach(flags "" "--loop-stack" "--retest" "--loop-stack --retest")
|
||||
separate_arguments(flag_list UNIX_COMMAND "${flags}")
|
||||
execute_process(COMMAND ${RUN} ${WORK}/pack_roundtrip.rot8 ${flag_list}
|
||||
OUTPUT_VARIABLE from_text RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "text run failed (${flags}): ${rc}")
|
||||
endif()
|
||||
execute_process(COMMAND ${RUN} ${WORK}/pack_roundtrip.r8t ${flag_list}
|
||||
OUTPUT_VARIABLE from_image RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "packed run failed (${flags}): ${rc}")
|
||||
endif()
|
||||
if(NOT from_image STREQUAL from_text)
|
||||
message(FATAL_ERROR
|
||||
"packed image prints something else (${flags})\n"
|
||||
" text: ${from_text}\n image: ${from_image}")
|
||||
endif()
|
||||
string(REGEX MATCH "\\(([0-9]+) steps" _ "${from_text}")
|
||||
message(STATUS "${length} instructions, ${from_image}")
|
||||
endforeach()
|
||||
|
||||
# Image damage (flipped bit, missing trailer, nonsense geometry) is covered by
|
||||
# r8forge_tape_pack_test, which can corrupt a vector without touching files.
|
||||
@@ -0,0 +1,87 @@
|
||||
# Compare the RTL against the software interpreter, on a real tape.
|
||||
#
|
||||
# The RTL in hardware/rot8.v is the *8 bit, 64 cell* machine (that is the physical
|
||||
# one), so this script only does anything when the build has that geometry; other
|
||||
# builds report SKIP and succeed, which is what lets the test live in the
|
||||
# widthfree label.
|
||||
#
|
||||
# cmake -DGEOMETRY=8/64 -DIVERILOG=... -DPACK=... -DRUN=... -DR8FORGE=...
|
||||
# -DSOURCE=... -DHARDWARE=... -DWORK=... -P rtl_sim.cmake
|
||||
#
|
||||
# It assembles SOURCE, packs it, runs `tape_run --loop-stack --retest` (the
|
||||
# combination the board implements), compiles the RTL with iverilog, runs it, and
|
||||
# requires the same OUT stream and the same step count.
|
||||
foreach(var GEOMETRY IVERILOG PACK RUN R8FORGE SOURCE HARDWARE WORK)
|
||||
if(NOT DEFINED ${var})
|
||||
message(FATAL_ERROR "rtl_sim.cmake needs -D${var}=...")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
if(NOT GEOMETRY STREQUAL "8/64")
|
||||
message(STATUS "RTL sim skipped: the RTL is the 8 bit / 64 cell machine, this build is ${GEOMETRY}")
|
||||
return()
|
||||
endif()
|
||||
|
||||
execute_process(COMMAND ${R8FORGE} ${SOURCE} OUTPUT_VARIABLE text RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "assembling ${SOURCE} failed: ${rc}")
|
||||
endif()
|
||||
string(LENGTH "${text}" length)
|
||||
file(WRITE ${WORK}/rtl_sim.rot8 "${text}")
|
||||
execute_process(COMMAND ${PACK} ${WORK}/rtl_sim.rot8 -o ${WORK}/rtl_sim.r8t
|
||||
--hex ${WORK}/rtl_sim.hex
|
||||
OUTPUT_VARIABLE packed RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "packing failed: ${rc} ${packed}")
|
||||
endif()
|
||||
message(STATUS "${packed}")
|
||||
file(WRITE ${WORK}/rtl_sim_in.txt "")
|
||||
|
||||
execute_process(COMMAND ${RUN} ${WORK}/rtl_sim.r8t --loop-stack --retest
|
||||
-i ""
|
||||
OUTPUT_VARIABLE sw RESULT_VARIABLE rc)
|
||||
if(rc EQUAL 2)
|
||||
# -i "" is rejected; that is fine, this tape reads nothing
|
||||
execute_process(COMMAND ${RUN} ${WORK}/rtl_sim.r8t --loop-stack --retest
|
||||
OUTPUT_VARIABLE sw RESULT_VARIABLE rc)
|
||||
endif()
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "software run failed: ${rc} ${sw}")
|
||||
endif()
|
||||
|
||||
execute_process(COMMAND ${IVERILOG} -g2012 -o rot8_tb.vvp
|
||||
${HARDWARE}/rot8.v ${HARDWARE}/tb_rot8.v
|
||||
WORKING_DIRECTORY ${WORK}
|
||||
OUTPUT_VARIABLE build_log RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "iverilog failed: ${build_log}")
|
||||
endif()
|
||||
# Run vvp *from the work directory* with relative file names. Icarus passes
|
||||
# plusargs through as raw bytes, so an absolute path containing non-ASCII (this
|
||||
# checkout lives under a Chinese directory name) arrives at $readmemh mangled and
|
||||
# the memory silently stays empty -- the machine then runs a tape of opcode 0 for
|
||||
# LEN steps and prints nothing.
|
||||
execute_process(COMMAND vvp rot8_tb.vvp +HEX=rtl_sim.hex
|
||||
+LEN=${length} +INFILE=rtl_sim_in.txt
|
||||
WORKING_DIRECTORY ${WORK}
|
||||
OUTPUT_VARIABLE rtl RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "vvp failed: ${rc} ${rtl}")
|
||||
endif()
|
||||
# the simulator prints its own $finish line; keep the first "out ..." one
|
||||
string(REGEX MATCH "out[^\n]*" rtl_out "${rtl}")
|
||||
|
||||
string(REGEX MATCH "^out([^()]*) *\\(([0-9]+) steps" _ "${sw}")
|
||||
set(sw_values "${CMAKE_MATCH_1}")
|
||||
set(sw_steps "${CMAKE_MATCH_2}")
|
||||
string(REGEX MATCH "^out([^()]*) *\\(([0-9]+) steps" _ "${rtl_out}")
|
||||
set(rtl_values "${CMAKE_MATCH_1}")
|
||||
set(rtl_steps "${CMAKE_MATCH_2}")
|
||||
|
||||
if(NOT sw_values STREQUAL rtl_values)
|
||||
message(FATAL_ERROR "OUT streams differ\n sw : ${sw_values}\n rtl: ${rtl_values}")
|
||||
endif()
|
||||
if(NOT sw_steps STREQUAL rtl_steps)
|
||||
message(FATAL_ERROR "step counts differ: sw ${sw_steps}, rtl ${rtl_steps}")
|
||||
endif()
|
||||
message(STATUS "${length} instructions, ${sw_steps} steps: RTL and software agree")
|
||||
@@ -0,0 +1,153 @@
|
||||
// r8forge_tape_pack -- turn a .rot8 text tape into the image a machine reads.
|
||||
//
|
||||
// r8forge_tape_pack <in.rot8> -o out.r8t [--hex out.hex] [--verify]
|
||||
//
|
||||
// The text tape is one character per instruction. The hardware stores three bits
|
||||
// per instruction (eight opcodes), so this packs them and appends a small
|
||||
// trailer; the format is defined once, in `r8forge/tape.hh`, so the runner and
|
||||
// the tests read the file exactly the way this writes it.
|
||||
//
|
||||
// The trailer goes at the *end* on purpose: if the file is burnt into a ROM,
|
||||
// address 0 is instruction 0, so the program is executed in place and the
|
||||
// trailer sits past the halt point, never fetched.
|
||||
//
|
||||
// `--hex` writes the body alone, one byte per line, for Verilog's $readmemh; the
|
||||
// comment on the first line carries the length and the geometry.
|
||||
//
|
||||
// `--verify` reads the file back and compares it, so a wrong bit order or a bad
|
||||
// crc cannot slip through.
|
||||
#include "r8forge/geometry.hh"
|
||||
#include "r8forge/tape.hh"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
bool read_file(const std::string &path, std::vector<uint8_t> &bytes) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in)
|
||||
return false;
|
||||
bytes.assign(std::istreambuf_iterator<char>(in),
|
||||
std::istreambuf_iterator<char>());
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) {
|
||||
std::cerr << "usage: r8forge_tape_pack <in.rot8> -o out.r8t [--hex out.hex] "
|
||||
"[--verify]\n";
|
||||
return 2;
|
||||
}
|
||||
const std::string in_path = argv[1];
|
||||
std::string out_path;
|
||||
std::string hex_path;
|
||||
bool verify = false;
|
||||
for (int i = 2; i < argc; i++) {
|
||||
const std::string a = argv[i];
|
||||
if ((a == "-o" || a == "--output") && i + 1 < argc) {
|
||||
out_path = argv[++i];
|
||||
} else if (a == "--hex" && i + 1 < argc) {
|
||||
hex_path = argv[++i];
|
||||
} else if (a == "--verify") {
|
||||
verify = true;
|
||||
} else {
|
||||
std::cerr << "unknown argument '" << a << "'\n";
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (out_path.empty())
|
||||
out_path = in_path + ".r8t";
|
||||
|
||||
std::vector<uint8_t> raw;
|
||||
if (!read_file(in_path, raw)) {
|
||||
std::cerr << "could not read " << in_path << "\n";
|
||||
return 1;
|
||||
}
|
||||
const std::string text(raw.begin(), raw.end());
|
||||
std::vector<uint8_t> code;
|
||||
std::string error;
|
||||
if (!tape_decode(text, code, error)) {
|
||||
std::cerr << in_path << ": " << error << "\n";
|
||||
return 1;
|
||||
}
|
||||
if (code.empty()) {
|
||||
std::cerr << in_path << ": the tape is empty\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
const std::vector<uint8_t> image =
|
||||
tape_image_encode(code, kDefaultCellSize, kDefaultMemoryCells);
|
||||
const size_t body_bytes = image.size() - 16;
|
||||
{
|
||||
std::ofstream out(out_path, std::ios::binary);
|
||||
if (!out) {
|
||||
std::cerr << "could not write " << out_path << "\n";
|
||||
return 1;
|
||||
}
|
||||
out.write(reinterpret_cast<const char *>(image.data()),
|
||||
std::streamsize(image.size()));
|
||||
if (!out) {
|
||||
std::cerr << "could not write " << out_path << "\n";
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hex_path.empty()) {
|
||||
std::ofstream hex(hex_path);
|
||||
if (!hex) {
|
||||
std::cerr << "could not write " << hex_path << "\n";
|
||||
return 1;
|
||||
}
|
||||
hex << "// R8T1 instructions=" << code.size() << " width=" << kDefaultCellSize
|
||||
<< " ring=" << kDefaultMemoryCells << " bytes=" << body_bytes << "\n";
|
||||
hex << std::hex;
|
||||
for (size_t i = 0; i < body_bytes; i++) {
|
||||
hex.width(2);
|
||||
hex.fill('0');
|
||||
hex << unsigned(image[i]) << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
if (verify) {
|
||||
std::vector<uint8_t> back;
|
||||
if (!read_file(out_path, back)) {
|
||||
std::cerr << "verify: could not read back " << out_path << "\n";
|
||||
return 1;
|
||||
}
|
||||
if (back != image) {
|
||||
std::cerr << "verify: " << out_path << " does not read back byte for byte\n";
|
||||
return 1;
|
||||
}
|
||||
tape_image decoded;
|
||||
if (!tape_image_decode(back, decoded, error)) {
|
||||
std::cerr << "verify: " << error << "\n";
|
||||
return 1;
|
||||
}
|
||||
if (decoded.code != code) {
|
||||
std::cerr << "verify: the image decodes to a different tape\n";
|
||||
return 1;
|
||||
}
|
||||
if (decoded.width != kDefaultCellSize ||
|
||||
decoded.ring != kDefaultMemoryCells) {
|
||||
std::cerr << "verify: the trailer records the wrong geometry\n";
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << in_path << ": " << code.size() << " instructions -> "
|
||||
<< body_bytes << " bytes ("
|
||||
<< (100.0 * double(body_bytes) / double(code.size()))
|
||||
<< "% of the text form)";
|
||||
if (!hex_path.empty())
|
||||
std::cout << ", hex in " << hex_path;
|
||||
std::cout << (verify ? ", verified" : "") << "\n";
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// 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");
|
||||
|
||||
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;
|
||||
}
|
||||
+119
-119
@@ -1,43 +1,101 @@
|
||||
#include "r8forge/geometry.hh"
|
||||
// Independent ROT-8 interpreter. Reads a .rot8 tape straight from a file --
|
||||
// no macro, no assembler, no r8asm -- and prints what `out` ('.') produced.
|
||||
#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.rot8> [-i text] [cells...]
|
||||
// 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 <deque>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#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.rot8> [addr=value ...]\n";
|
||||
std::cerr << "usage: r8forge_tape_run <file> [addr=value ...]\n";
|
||||
return 2;
|
||||
}
|
||||
std::ifstream in(argv[1], std::ios::binary);
|
||||
if (!in) {
|
||||
std::cerr << "could not open " << argv[1] << "\n";
|
||||
image img;
|
||||
if (!load(argv[1], img)) {
|
||||
std::cerr << img.error << "\n";
|
||||
return 1;
|
||||
}
|
||||
const std::string tape((std::istreambuf_iterator<char>(in)),
|
||||
std::istreambuf_iterator<char>());
|
||||
|
||||
std::vector<uint32_t> cells(kDefaultMemoryCells, 0);
|
||||
std::deque<uint32_t> input;
|
||||
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++) {
|
||||
@@ -50,136 +108,78 @@ int main(int argc, char **argv) {
|
||||
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;
|
||||
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));
|
||||
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)));
|
||||
cells.at(at) = uint32_t(std::stoul(a.substr(eq + 1)) & kDefaultCellMask);
|
||||
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;
|
||||
|
||||
std::vector<uint32_t> out;
|
||||
size_t dp = 0;
|
||||
const size_t limit = 20'000'000; // same as r8forge_derive
|
||||
size_t pc = 0;
|
||||
size_t steps = 0;
|
||||
size_t ins_count[256] = {};
|
||||
std::vector<size_t> cell_hits(cells.size(), 0);
|
||||
size_t walking = 0;
|
||||
for (; pc < tape.size(); pc++) {
|
||||
if (++steps > limit) {
|
||||
std::cout << "HANG after " << limit << " steps (pc " << pc << ", dp " << dp
|
||||
<< ", cell=0x" << std::hex << int(cells[dp]) << std::dec
|
||||
<< ")\n";
|
||||
return 3;
|
||||
}
|
||||
if (profile) {
|
||||
ins_count[(unsigned char)tape[pc]]++;
|
||||
cell_hits[dp]++;
|
||||
if (tape[pc] == 0x3e || tape[pc] == 0x3c)
|
||||
walking++;
|
||||
}
|
||||
if (trace) {
|
||||
// cells 0..3 are the interesting ones when debugging a library macro
|
||||
std::cout << "pc " << pc << " " << tape[pc] << " dp " << dp << " [";
|
||||
for (size_t i = 0; i < 4; i++)
|
||||
std::cout << (i ? " " : "") << int(cells[i]);
|
||||
std::cout << "]\n";
|
||||
}
|
||||
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] = uint32_t((cells[dp] >> 1) | ((cells[dp] & 1u) << (kDefaultCellSize - 1)));
|
||||
break;
|
||||
// biz / rnz test the LOW BIT, not "is the cell zero" -- see ROT-8-viz // src/rot8.c. Reading them as a Brainfuck style zero test makes every
|
||||
// byte level program in the library look like an endless loop.
|
||||
case '[':
|
||||
if ((cells[dp] & 1) == 0) {
|
||||
for (int depth = 1; depth;) {
|
||||
pc++;
|
||||
if (pc >= tape.size()) {
|
||||
std::cout << "unbalanced '['\n";
|
||||
return 4;
|
||||
}
|
||||
if (tape[pc] == '[')
|
||||
depth++;
|
||||
else if (tape[pc] == ']')
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ']':
|
||||
if ((cells[dp] & 1) == 1) {
|
||||
for (int depth = 1; depth;) {
|
||||
if (pc == 0) {
|
||||
std::cout << "unbalanced ']'\n";
|
||||
return 4;
|
||||
}
|
||||
pc--;
|
||||
if (tape[pc] == ']')
|
||||
depth++;
|
||||
else if (tape[pc] == '[')
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case '.':
|
||||
out.push_back(cells[dp]);
|
||||
break;
|
||||
case ',': // INP: the low 7 bits of the next scripted character
|
||||
cells[dp] = input.empty() ? 0 : input.front();
|
||||
if (!input.empty())
|
||||
input.pop_front();
|
||||
break;
|
||||
default: // anything else: not modelled
|
||||
break;
|
||||
}
|
||||
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) {
|
||||
const char *kinds = "><+-[].,";
|
||||
std::fprintf(stderr, "profile: %zu steps, %zu of them pointer moves (%.1f%%)\n",
|
||||
steps, walking, 100.0 * double(walking) / double(steps));
|
||||
for (const char *k = kinds; *k; k++) {
|
||||
const size_t n = ins_count[(unsigned char)*k];
|
||||
std::fprintf(stderr, " %c %8zu %5.1f%%\n", *k, n,
|
||||
100.0 * double(n) / double(steps));
|
||||
}
|
||||
std::vector<size_t> order(cell_hits.size());
|
||||
// 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 cell_hits[a] > cell_hits[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 (cell_hits[order[i]] == 0)
|
||||
break;
|
||||
std::fprintf(stderr, " %zu:%zu", order[i], cell_hits[order[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 : out)
|
||||
for (uint32_t v : r.out)
|
||||
std::cout << " " << int(v);
|
||||
std::cout << " (" << steps << " steps, cell0 ended 0x" << std::hex
|
||||
<< int(cells[0]) << std::dec << ")\n";
|
||||
std::cout << " (" << r.steps << " steps, cell0 ended 0x" << std::hex
|
||||
<< int(r.cells[0]) << std::dec << ")\n";
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user