Fix the ROT-8 interpreters: biz / rnz test the low bit

Four interpreters here (tests/synth_test.cc, src/derive.cc and the two I added
earlier: tests/tape_run.cc, tests/byte_add_test.cc) implemented '[' and ']' as
a Brainfuck style "is this whole cell zero" test.  The reference implementation
does not:

    ROT-8-viz src/rot8.c
    rot8_biz: if ((*mem & 1) == 0) skip to just past the matching ']'
    rot8_rnz: if ((*mem & 1) == 1) jump back to the matching '['

That one difference is why every byte level program in the library looked like
an endless loop.  It is invisible in the bit level world -- for a cell holding 0
or 1 the low bit test and the zero test agree -- which is why the synth tables,
asm/test.r8asm and full_add never noticed anything.

Cross checked against the reference before touching anything: the tape our
assembler produces for "A = 128, set_0, B = 3, raw_add" prints 128 3 0 131 0 on
ROT-8-viz/build/rot8_test.exe and hung in our derive.

With the fix, measured:

    raw_add   65536/65536 pairs ok  1647 chars
    raw_and   65536/65536            639
    raw_or    65536/65536            575
    raw_xor   65536/65536            463
    raw_inc   512/512               1214
    asm/fibonacci.r8asm prints 1 1 2 3 5 8 13 21 34 55, exactly what its
    comment claims

So the byte level layer was never broken.  Two commits ago it was declared dead
-- set_0 "only converges on 0 and 1", the bits of a packed byte "unreadable",
raw_add "only survives 0+0" -- entirely on the strength of the broken
interpreters.  AGENTS.md and README.md now say the opposite and keep the wrong
diagnosis as a worked example: when byte level code looks hung, check the
interpreter first.

New:
  tests/byte_op_test.cc + drv/raw_{add,and,or,xor,inc}_byte.r8asm
      exhaustive runtime proof for the byte level library, 0.5 s
  tests/tape_run.cc + r8forge_tape_run
      a second interpreter that runs a .rot8 file directly -- cross checking
      derive is now one command

verify_set_0.r8asm now demonstrates what set_0 really does instead of claiming
it hangs: 255 -> 254, 5 -> 4, 128 -> 128 (it clears the low bit, not the cell).

The one bit per cell layer (byte_add / pack_byte) stays as a documented
alternative: it is correct under the real semantics too, just redundant.
This commit is contained in:
starcells committed 2026-11-07 00:01:25 +08:00
1 parent 3c71bddab5
commit 86a54aa23c
14 files changed
+549 -119

No files matched your search

+65 -73
View File
@@ -20,6 +20,9 @@
--build build --config Release
```
* 会话很长时传输容易失败,重要结论要落到 **commit message 和文件注释**里,别只留在对话里。
* **写结论之前先对虚拟机**:这个仓库最贵的一次事故就是虚拟机语义写错,然后在错的东西上
写了一整套"实测结论"(见「字节级运算」)。字节级结论必须能被 ROT-8-viz
(`C:\Users\peng0\git\ROT-8-viz`,权威实现)复现。
## 构建与自检
@@ -32,23 +35,18 @@ cmake --build build --config Release
clang-cl /nologo /std:c++20 /EHsc /O2 /I include src/r8asm.cc src/synth.cc tests/asm_test.cc /Fe:r8forge.exe
```
自检三件套:
自检:
```sh
r8forge asm/test.r8asm # 应 exit 0,1666 字符,7/7 命中缓存
r8forge asm/test.r8asm # 应 exit 0,1666 字符,7/7 命中缓存
r8forge_synth_test examples/full_add.r8asm # all eight combinations ok
r8forge verify_raw_add_nc.r8asm # 4 cell 加法切片驱动
r8forge verify_raw_add_nc.r8asm # 4 cell 加法切片驱动
r8forge_byte_op_test # 字节级库:65536×4 + 512 全过,0.5 秒
r8forge_byte_add_test # 一位一 cell 的备选层:65536 + 256 全过
```
跑纸带的第四件(**唯一一个真的执行纸带、按返回值判断对错的**):
```sh
r8forge_byte_add_test # add8: 65536/65536,add8_inc: 256/256
```
它汇编 `examples/add8*.r8asm` 并在内置的 ROT-8 虚拟机里穷举输入。约 0.3 秒。
`asm/test.r8asm` 那三件只证明"汇编得出来",不证明"跑得对" —— 这个区别踩过坑,见下面
「字节级运算」。
`r8forge_byte_op_test` 是**唯一按返回值判断字节级对错的**;前三个只证明"汇编得出来"或
"位级正确"。
`r8forge_derive` 是验证工具:
@@ -59,82 +57,76 @@ r8forge_derive <file.r8asm> -2 0=100 # 同上,另外倒出所有非零 ce
```
注意 `-1/-2` 是拿**汇编源码**跑的(内部会先 `import_file`),不能直接喂 `.rot8` 纸带。
`r8forge_tape_run <file.rot8> [addr=value...]` 是第二个实现,直接喂纸带,用来交叉验证
`derive`(两个实现同时写错的可能性比一个低)。
## 指令集语义(这些搞错会浪费一整轮)
```
'-' flb 翻转最低位 cells[dp] ^= 1
'+' ror 右旋整个 cell
'[' biz 当前 cell 为零 -> 跳到匹配的 ']' 之后
']' rnz 当前 cell 非零 -> 跳回匹配的 '['
'[' biz 最低位为 0 -> 跳到匹配的 ']' 之后
']' rnz 最低位为 1 -> 跳回匹配的 '['
```
由此推出三条**关键约束**:
**最后两条的关键在"最低位"三个字**:`biz`/`rnz` 判的是 `cell & 1`,不是"整格是否为零"。
权威实现是 `ROT-8-viz/src/rot8.c`:
1. **`set_0`(= `[-]`)只对 0 和 1 收敛。**
`5` 会 `5->4->5->4` 死循环,`0x80` 永远不变,而且 tape 走不到下一条指令、不报错。
`erase`(`%rep _CELL_SIZE { set_0; ror }`)卡在同一个 `set_0` 上,也清不掉任意 cell。
→ **清必须发生在 cell 还只放一位的时候。**
```c
void rot8_biz(rot8_iter *iter) { if ((*(iter->mem_now) & 1) == 0) { ... } }
void rot8_rnz(rot8_iter *iter) { if ((*(iter->mem_now) & 1) == 1) { ... } }
```
由此推出两条**关键约束**:
1. **`set_0` = `[-]` 清的是最低位,不是整个 cell。**
`set_0` 把 255 变成 254、把 128 原样留着、把 5 变成 4。要清整个字节就
`%rep _CELL_SIZE { set_0; ror }`(`erase` 就是这么写的)。一个字节的位能读:
`ror` 若干次把目标位转到最低位,再 `biz`。
2. **合成的程序只碰每个 cell 的低 K 位**(K = 参与运算的输入位数),高位不追踪。
所以 `%synth` 出来的块只适用于"每格一位"的世界。
3. **一个 cell 里放了多个位,它的位在程序里根本读不出来。**
没有移位指令,只有 `ror`,而 `ror` 不改变"这个 cell 是不是 0",所以 `biz` 对整字节
永远只能回答"是不是 0";`flb` 只动最低位(写,不是读)。
→ **字节级运算只能一位一 cell**;"把一个字节放进一个 cell 再逐位处理"这条路在
这个 ISA 里不存在。详见下面「字节级运算」。
## 字节级运算(一位一 cell)
曾经这里还写过第三条("多字节 cell 的位读不出来")—— 那是把 `biz` 当成 Brainfuck 的
整格零判断推出来的,**错的**,已删。
先记结论:**库里原来那层"整字节放一个 cell + ror 轮转"的宏,在运行时全是坏的。**
全是实测,不是推的:
## 字节级运算(一个 cell 一个字节)
| 调用 | 结果 |
|---|---|
| `raw_add` 0+0(`drv/raw_add_byte.r8asm`) | 唯一能跑完的输入,`out 0 0 0 0 0`,而且是对的 |
| `raw_add` 1+0、0+1、1+1、2+2、5+3、10+20、128+0、128+128、255+1、255+255 | 全部跑不完(`out` 空) |
| `raw_and` 0xF0 & 0xCC、1 & 1、0 & 5 | 都跑不完 |
| `copy`(`lib.r8asm`)A=5 | 跑不完;只有 A=0 才正常返回 |
结论:**库里的字节级宏是对的,穷举全过**。`r8forge_byte_op_test` 实测(0.5 秒):
原因就是约束 1 + 3:轮转驱动每轮都用 `set_0` 清一个已经装了 7 位的累加器,而切片里的
`biz` 判的是整字节。**别去修它们**,那层的前提在 ROT-8 里不成立。
| 宏 | 驱动 | 纸带 | 结果 |
|---|---|---|---|
| `raw_add`(a+b,含进位) | `drv/raw_add_byte.r8asm` | 1647 字符 | **65536/65536** |
| `raw_and` | `drv/raw_and_byte.r8asm` | 639 字符 | **65536/65536** |
| `raw_or` | `drv/raw_or_byte.r8asm` | 575 字符 | **65536/65536** |
| `raw_xor` | `drv/raw_xor_byte.r8asm` | 463 字符 | **65536/65536** |
| `raw_inc`(a+进位) | `drv/raw_inc_byte.r8asm` | 1214 字符 | **512/512** |
| `asm/fibonacci.r8asm` | — | 8761 字符 | 跑出 `1 1 2 3 5 8 13 21 34 55`,和文件注释一致 |
自己复现,一条命令一个(`out` 为空就是卡死:`derive` 有 5M 步上限,超了就停):
顺带纠正一个流传下来的说法:`raw_add` **不**吃掉操作数。实测 `5+3 → A=5 B=3 S=8`,
`255+255 → A=255 B=255 S=254 Co=1`。`asm/fibonacci.r8asm` 里"每圈都要重新复印"的注释
是过度保守(它确实复印了,但不复印也对)。
```sh
r8forge_derive verify_set_0.r8asm -1 0=128 # [- ] 卡在 0x80 上
r8forge_derive drv/raw_add_byte.r8asm -2 0=5 2=3 # raw_add 卡死
```
### 这次差点被写进文档的错误诊断(别再犯)
别拿 `asm/test.r8asm` 当尺子:它自带 `.xor 127` / `.xor 130`,会把你给的初值再异或一次
(上一轮回合我就在这儿看错过一次)。`drv/raw_add_byte.r8asm` 是不预置常量的干净驱动,
`out` 依次是 A、B、Ci、S、Co。
有一轮里,`raw_add` / `raw_and` / `copy` / `fibonacci` 全被判定"运行时是坏的",
理由是 `set_0` 对多字节 cell 不收敛、纸带跑到步数上限。**那是虚拟机写错了**:
仓库里有三份解释器(`tests/synth_test.cc`、`src/derive.cc`、`tests/tape_run.cc`)
把 `biz`/`rnz` 实现成了"整格是否为零"(Brainfuck 直觉),于是每个字节级程序
都变成死循环。改回 `& 1` 之后全部通过。
踩在这层上的还有两个现成文件,都别信:
为什么之前没被发现:位级程序在两种语义下行为完全一样(0/1 的最低位就是它自己),
`%synth` 的表、`asm/test.r8asm`、`full_add` 全都不受影响;只有字节级驱动能区分。
**所以以后凡是"字节级看起来跑不动",第一个怀疑对象是虚拟机,不是库。**
* `asm/test.r8asm`(自检里那 1666 字符)只证明**汇编**得出来;它跑的 `raw_add` 会卡住。
* `asm/fibonacci.r8asm` 汇编出 8761 字符,跑起来只输出 `1 1` 就卡住。文件顶上那串
`1 1 2 3 5 8 13 21 34 55` 是旧实现时代的记录,现在对不上。
验证方法:拿 `ROT-8-viz/build/rot8_test.exe` 跑同一条纸带对答案。
`tests/tape_run.cc` 现在是正确语义(`& 1`),可以直接对。
能用的是一层新写的、一位一 cell 的东西:
### 另一位一 cell 的实现(备选,不是主线)
| 文件 | 内容 |
|---|---|
| `asm/byte_add.r8asm` | `byte_add %1`:8 位加法/累加。第 i 位占 `%1+4i`(A) `+4i+1`(B) `+4i+2`(进位) `+4i+3`(草稿);b7 的进位留在 `%1+30` |
| `asm/pack_byte.r8asm` | `pack_byte %1 %2 %3`:八个 flag(base、步长、目标)压成一个字节;`bit_raw_flip_if` 是它的积木 |
| `examples/add8.r8asm` | a+b,**1308 字符** |
| `examples/add8_inc.r8asm` | 连加三次 1,3142 字符,演示"可拼" |
| `tests/byte_add_test.cc` | `r8forge_byte_add_test`:65536 + 256 组合,0.3 秒 |
四条实测属性:
* **A 是累加器**:`byte_add` 之后 B 的八个 cell 全是 0,把下一个操作数摆进去再叫一次就接着加。
每次都清进位输入,所以是 mod 256(`add8_inc` 的进位只反映最后一次加的进位)。
* **压字节是单向的**:`pack_byte` 之后 flag 全被吃掉;压出来的字节能 `out`,但**不能再参与运算**
(约束 3)。所以"字节级加法"的输入只能是 flag,输出才能是字节。
* **cell 数 32**(8 组 quartet)。最早的共用进位版本只要 25 个 cell,但 8 个 bit 共用一个远端
进位 cell 让每片都付几十次 `.tp` 跳跃,实测 **2517 字符** —— 每 bit 自带进位 cell 换来
1308 字符,是划算的。
* **拼接靠 A**:想算 a+b+c,就 `byte_add` 两次(第二次前把 c 摆进 B)。
`asm/byte_add.r8asm` + `asm/pack_byte.r8asm`:每 bit 一个 cell(32 cell),
`byte_add` 把 A 当累加器(`A += B`,可以连着加),`pack_byte` 把八个 flag 压回一个字节。
在正确语义下也是对的(`r8forge_byte_add_test`:65536 + 256 全过,1308 / 3142 字符),
但和 `raw_add` 功能重复、cell 多得多。留着当备选。
## %synth 相关
@@ -155,17 +147,17 @@ r8forge_derive drv/raw_add_byte.r8asm -2 0=5 2=3 # raw_add 卡死
|---|---|
| 库里的 7 个位运算块(and/or/xor/inc/add) | 合成版比手写短:`asm/test.r8asm` 1714 → 1666 字符 |
| `bit_raw_add_nc`(4 cell 忽略进位切片) | flat 代价 **27**,完整全加器切片是 38;8/8 组合正确 |
| `bit_raw_add`(6 cell 全加器切片) | 保留 A、B,配合轮转使用(原版库的做法) |
| `byte_add`(8 位加法器,一位一 cell) | 32 cell / 1308 字符;**65536 组合穷举全对** |
| `pack_byte`(八个 flag -> 一个字节) | 单向可写;`bit_raw_flip_if` 是唯一"条件翻转、不清目标"的积木 |
| `bit_raw_add`(6 cell 全加器切片) | 保留 A、B;字节级 `raw_add` 1647 字符,65536 组合全对 |
| `raw_and` / `raw_or` / `raw_xor` / `raw_inc` | 639 / 575 / 463 / 1214 字符,各 65536(inc 512)全对 |
| `asm/fibonacci.r8asm` | 8761 字符,跑出 10 项斐波那契,和注释一致 |
| `byte_add` + `pack_byte`(一位一 cell) | 备选层:32 cell,1308 字符,65536 组合全对 |
## 已经确认走不通的(别重试)
* **3 个 cell 做加法切片**:层数上限 5 和 8 都报 `no program up to N layers`。
* **轮转 + 合成切片做字节级运算**:`raw_add`/`raw_and`/`raw_or`/`raw_xor`/`raw_inc`/`copy`/
`erase` 这一整层运行时是坏的(实测见上面「字节级运算」)。不是"只差操作数保留":
`set_0` 清不动带多个位的 cell,切片里的 `biz` 又只判整字节。
* **把一个字节放进一个 cell 再逐位处理**:约束 3 —— 那些位读不出来,做不到。
* **让 `%synth` 合成的块自己保留操作数(没有草稿 cell)**:轮转要求 A、B 保留,
而合成的程序只会吃掉操作数;把表改成"保留 A、B"后同样报 `no program up to 8 layers`。
只有 6 cell 的 `bit_raw_add`(有草稿 cell)能做到。
* 字节级(2^16 项真值表)交给 `%synth`:搜索空间不可行。
## 命名与注释格式(`asm/lib.r8asm` 的约定)
+9
View File
@@ -26,10 +26,19 @@ target_link_libraries(r8forge_synth_test r8forge_core)
add_executable(r8forge_derive src/derive.cc)
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)
# Runs the byte level adders over every input combination.
add_executable(r8forge_byte_add_test tests/byte_add_test.cc)
target_link_libraries(r8forge_byte_add_test r8forge_core)
# Runs the byte level library macros (raw_add / raw_and / raw_or / raw_xor /
# raw_inc) over every input combination.
add_executable(r8forge_byte_op_test tests/byte_op_test.cc)
target_link_libraries(r8forge_byte_op_test r8forge_core)
add_executable(r8forge_cost_par tests/cost_par.cc)
target_link_libraries(r8forge_cost_par r8forge_core)
+62 -32
View File
@@ -187,46 +187,73 @@ build/Release/r8forge_derive drv/bit_raw_add.r8asm 6
2. `map` 一项里的 bit0 落在 `%(K+1)`、bit1 落在 `%(K+2)`……超出 `params` 会直接报错。
3. `stat` 必须给 `2^params` 项,每项是那个输入组合下所有参数的取值。
## 字节级运算:只能一位一 cell
## 字节级运算:一个 cell 一个字节
```asm
%include "asm/byte_add.r8asm"
%include "asm/pack_byte.r8asm"
%include "asm/raw_add.r8asm"
.var BITS 0
.var P 15
.var A 0
.var B 2
.var Ci 4
.var S 6
.var Co 8
.var tmp 1
byte_add BITS ; A 的八位在 0,4,...,28;B 的八位在 1,5,...,29
pack_byte BITS 4 P ; 八位 -> 一个字节
output P
output 30 ; b7 的进位
raw_add A B Ci S Co tmp ; S = A + B,Co = 进位,A、B 保留
output A
output B
output Ci
output S
output Co
```
`byte_add` 是 8 位加法器:第 i 位占 `BITS + 4i`(A)、`+4i+1`(B)、`+4i+2`(进位)、`+4i+3`(草稿)。
四个 cell 紧邻,所以切片内部来回跳跃只有 1~2 步;进位到下一块用 `clb_bit_mov` 搬一格。
A 同时是累加器 —— 算完 B 的八个 cell 归零,把下一个操作数摆进去再叫一次就接着加,
`examples/add8_inc.r8asm` 连加三次 1 就是这么写的。
`raw_add` 把 A、B、S 各当一个**字节**:每轮把当前最低位送进 4~6 cell 的位级切片,
然后把整个字节 `ror` 一格,8 轮走完。`raw_and` / `raw_or` / `raw_xor` / `raw_inc` 同理。
**为什么不能"一个 cell 放一个字节再轮转"**:ROT-8 没有移位,只有 `ror`,而 `ror` 不改变
"这个 cell 是不是 0",所以 `biz` 对整字节永远只能回答"是不是 0";`flb` 只写最低位,不读。
一个带多个位的 cell,它的位在程序里根本读不出来 —— 再加上 `set_0` 对多字节 cell 不收敛。
库里原来那层 `raw_add`/`raw_and`/`raw_or`/`raw_xor`/`raw_inc`/`copy` 全踩在这上面,
实测跑不完(连 `raw_add` 的 `0+0` 都卡死,`127+130` 能跑完但输出全 0)。所以字节级
运算只能一位一 cell。
`r8forge_byte_add_test` 汇编 `examples/add8*.r8asm`,在 rot8 虚拟机里把每种输入都跑一遍,
0.3 秒:
`r8forge_byte_op_test` 在 ROT-8 虚拟机上把每种输入都跑一遍(0.5 秒):
```
add8: 1308 characters
all 65536 combinations ok
add8_inc: 3142 characters
all 256 combinations ok
byte level adders ok
raw_xor: 463 characters all 65536 combinations ok
raw_or: 575 characters all 65536 combinations ok
raw_and: 639 characters all 65536 combinations ok
raw_inc: 1214 characters all 512 combinations ok
raw_add: 1647 characters all 65536 combinations ok
byte level library ok
```
`pack_byte` 是**单向**的:八个 flag 压成字节,压完 flag 全被吃掉;压出来的字节能 `out`,
但不能再参与运算。反过来把字节拆成八位 —— 做不到(同上)。
`asm/fibonacci.r8asm` 也是这条路上的:8761 字符,跑出 `1 1 2 3 5 8 13 21 34 55`。
### 一个坑:`biz`/`rnz` 看的是最低位
```
biz: 最低位 == 0 -> 跳到匹配的 ']' 之后
rnz: 最低位 == 1 -> 跳回匹配的 '['
```
不是 Brainfuck 那种"整格是否为零"。所以 `set_0` = `[-]` 是**清最低位**:255 → 254、
128 → 128、5 → 4;要清整个字节得 `%rep _CELL_SIZE { set_0; ror }`(就是 `erase`)。
仓库里曾经有三份解释器把它写成整格零判断,于是所有字节级程序看起来都在死循环 ——
顺着那个错误还得出过"字节级运算只能一位一 cell"的结论,是错的。权威语义见
`ROT-8-viz/src/rot8.c`:
```c
void rot8_biz(rot8_iter *iter) { if ((*(iter->mem_now) & 1) == 0) { ... } }
void rot8_rnz(rot8_iter *iter) { if ((*(iter->mem_now) & 1) == 1) { ... } }
```
### 另一条路:一位一 cell(备选)
`asm/byte_add.r8asm` + `asm/pack_byte.r8asm`:每 bit 一个 cell(32 cell),
`byte_add` 以 A 为累加器(`A += B`,可连续调用),`pack_byte` 把八个 flag 压成一个字节。
在正确语义下也是对的(`r8forge_byte_add_test`:65536 + 256 全过,1308 / 3142 字符),
但和 `raw_add` 重复、cell 多得多,所以只是备选。
```
add8: 1308 characters all 65536 combinations ok
add8_inc: 3142 characters all 256 combinations ok
```
## 实现方式
@@ -359,7 +386,8 @@ cmake -S . -B build -G "Visual Studio 18 2026" -A x64
cmake --build build --config Release
build\Release\r8forge.exe asm\test.r8asm > test.rot8
build\Release\r8forge_synth_test.exe # 合成 + 跑虚拟机自检
build\Release\r8forge_byte_add_test.exe # 8 位加法器:65536 组合全对
build\Release\r8forge_byte_op_test.exe # 字节级库穷举:65536×4 + 512 全对
build\Release\r8forge_byte_add_test.exe # 一位一 cell 的备选层:65536 + 256 全对
```
`build/` 已经有生成器了,重编译时**别用 PATH 上的另一个 cmake**(版本不一致会重新配置,
@@ -381,9 +409,11 @@ src/r8asm.cc 汇编器实现
src/synth.cc 真值表 -> 搜索
tests/asm_test.cc 汇编器自检(纸带不变)
tests/synth_test.cc 合成 + ROT-8 虚拟机自检
tests/byte_add_test.cc 8 位加法器穷举自检(65536 组合)
tests/byte_op_test.cc 字节级库穷举自检(65536×4 + 512)
tests/byte_add_test.cc 一位一 cell 备选层的穷举自检
tests/tape_run.cc 第二个 ROT-8 解释器,直接跑 .rot8 交叉验证
asm/ 标准库与既有实现
asm/byte_add.r8asm 8 位加法器(一位一 cell)
asm/byte_add.r8asm 8 位加法器(一位一 cell,备选)
asm/pack_byte.r8asm 八个 flag -> 一个字节
examples/full_add.r8asm 汇编期合成全加器
examples/add8.r8asm a+b,结果压成一个字节省出来
+3 -3
View File
@@ -1,12 +1,12 @@
%include "asm/raw_add.r8asm"
; raw_add 的字节级驱动:两个操作数直接放在 A、B 里,不预置任何常量。
; (asm/test.r8asm 那种写法里带 .xor 127 /.xor 130,会把你给的初值再异或一次,别拿它当尺子。)
; (asm/test.r8asm 里有 .xor 127 /.xor 130,会把你给的初值再异或一次,别拿它当尺子。)
;
; r8forge_derive drv/raw_add_byte.r8asm -2 0=5 2=3
;
; out 依次是 A、B、Ci、S、Co。实测:只有 0+0 能跑完,其余全在 set_0 上卡死
; (out 为空 = 没走到第一条 output)。见 verify_set_0.r8asm。
; out 依次是 A、B、Ci、S、Co。A、B 是保留的,S = A + B 的低字节,Co 是进位。
; 全输入穷举见 r8forge_byte_op_test。
.var A 0
.var B 2
.var Ci 4
+17
View File
@@ -0,0 +1,17 @@
%include "asm/raw_and.r8asm"
; raw_and 的字节级驱动:操作数直接放在 A、B 里,不预置任何常量。
;
; r8forge_derive drv/raw_and_byte.r8asm -2 0=240 2=204
;
; out 依次是 A、B、S。A、B 应当保留(bit_raw_and 的表是"保留操作数"的)。
.var A 0
.var B 2
.var S 4
.var tmp 1
raw_and A B S tmp
output A
output B
output S
+19
View File
@@ -0,0 +1,19 @@
%include "asm/raw_inc.r8asm"
; raw_inc 的字节级驱动:一个操作数 + 进位输入。
;
; r8forge_derive drv/raw_inc_byte.r8asm -2 0=5 2=0 # 5+1
;
; out 依次是 A、Ci、S、Co。
.var A 0
.var Ci 2
.var S 4
.var Co 6
.var tmp 1
raw_inc A Ci S Co tmp
output A
output Ci
output S
output Co
+17
View File
@@ -0,0 +1,17 @@
%include "asm/raw_or.r8asm"
; raw_or 的字节级驱动:操作数直接放在 A、B 里,不预置任何常量。
;
; r8forge_derive drv/raw_or_byte.r8asm -2 0=240 2=204
;
; out 依次是 A、B、S。
.var A 0
.var B 2
.var S 4
.var tmp 1
raw_or A B S tmp
output A
output B
output S
+17
View File
@@ -0,0 +1,17 @@
%include "asm/raw_xor.r8asm"
; raw_xor 的字节级驱动:操作数直接放在 A、B 里,不预置任何常量。
;
; r8forge_derive drv/raw_xor_byte.r8asm -2 0=240 2=204
;
; out 依次是 A、B、S。
.var A 0
.var B 2
.var S 4
.var tmp 1
raw_xor A B S tmp
output A
output B
output S
+8 -2
View File
@@ -37,8 +37,14 @@ struct machine {
case '+': // ror
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). The bit level tables derived here
// are unaffected either way -- every parameter is fed a single 0/1 --
// but byte level programs only run under this reading.
case '[':
if (cells[dp] == 0) {
if ((cells[dp] & 1) == 0) {
int depth = 1;
while (depth) {
pc++;
@@ -50,7 +56,7 @@ struct machine {
}
break;
case ']':
if (cells[dp] != 0) {
if ((cells[dp] & 1) == 1) {
int depth = 1;
while (depth) {
pc--;
+4 -2
View File
@@ -42,8 +42,10 @@ struct machine {
case '+': // ror
cells[dp] = ror(cells[dp]);
break;
// biz / rnz test the LOW BIT of the cell (ROT-8-viz src/rot8.c), not
// "is the cell zero".
case '[':
if (cells[dp] == 0) {
if ((cells[dp] & 1) == 0) {
int depth = 1;
while (depth) {
pc++;
@@ -55,7 +57,7 @@ struct machine {
}
break;
case ']':
if (cells[dp] != 0) {
if ((cells[dp] & 1) == 1) {
int depth = 1;
while (depth) {
pc--;
+201
View File
@@ -0,0 +1,201 @@
// Runs the byte level library macros over every input pair on a ROT-8 machine.
//
// r8forge_byte_op_test [repo root]
//
// The machine below follows the reference implementation in ROT-8-viz
// (src/rot8.c): `biz` jumps when the LOW BIT of the cell is 0 and `rnz` jumps
// back when it is 1, so `set_0` (= [-]) clears the low bit of whatever is in
// the cell. Reading `[`/`]` as a Brainfuck style "is the cell zero" test makes
// every one of these programs look like an endless loop -- which is exactly the
// mistake three interpreters in this repo used to make.
#include "r8forge/r8asm.hh"
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
namespace {
struct machine {
std::vector<uint8_t> cells = std::vector<uint8_t>(256, 0);
std::vector<uint8_t> out;
size_t dp = 0;
size_t steps = 0;
bool finished = true; // false: the step limit ran out
static uint8_t ror(uint8_t v) { return uint8_t((v >> 1) | (v << 7)); }
void run(const std::string &tape, size_t limit) {
for (size_t pc = 0; pc < tape.size(); pc++) {
if (++steps > limit) {
finished = false;
return;
}
switch (tape[pc]) {
case '>':
dp = (dp + 1) % cells.size();
break;
case '<':
dp = (dp + cells.size() - 1) % cells.size();
break;
case '-': // flb
cells[dp] ^= 1;
break;
case '+': // ror
cells[dp] = ror(cells[dp]);
break;
case '[': // biz: branch when the low bit is zero
if ((cells[dp] & 1) == 0) {
int depth = 1;
while (depth) {
pc++;
if (tape[pc] == '[')
depth++;
else if (tape[pc] == ']')
depth--;
}
}
break;
case ']': // rnz: return when the low bit is one
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: // ',' (input) is not modelled
break;
}
}
}
};
std::string assemble(const std::string &file) {
r8asm assembler;
if (!assembler.import_file(file, 8) || assembler.failed()) {
std::cerr << "could not assemble " << file << "\n";
std::exit(1);
}
return assembler.export_rot8();
}
int failures = 0;
void report(const std::string &name, int a, int b, const machine &m,
const std::string &want) {
if (failures++ < 5) {
std::cerr << " WRONG " << name << " a=" << a << " b=" << b << " out";
for (uint8_t v : m.out)
std::cerr << " " << int(v);
std::cerr << " want " << want << " finished=" << m.finished
<< " steps=" << m.steps << "\n";
}
}
// raw_and / raw_or / raw_xor: both operands are preserved, the result is third.
int test_bitop(const std::string &file, const char *name, int op) {
const std::string tape = assemble(file);
std::cout << name << ": " << tape.size() << " characters\n";
int bad = 0;
for (int a = 0; a < 256; a++)
for (int b = 0; b < 256; b++) {
machine m;
m.cells[0] = uint8_t(a); // A
m.cells[2] = uint8_t(b); // B
m.run(tape, 100'000);
const int want = op == 0 ? (a & b) : op == 1 ? (a | b) : (a ^ b);
const bool ok = m.finished && m.out.size() == 3 && m.out[0] == a &&
m.out[1] == b && m.out[2] == want;
if (!ok) {
bad++;
if (bad <= 3)
report(name, a, b, m,
std::to_string(a) + " " + std::to_string(b) + " " +
std::to_string(want));
}
}
std::cout << " " << (bad ? "FAILED" : "all 65536 combinations ok")
<< (bad ? " (" + std::to_string(bad) + " wrong)" : "") << "\n";
return bad;
}
// raw_add: out is A, B, Ci, S, Co.
int test_add(const std::string &file) {
const std::string tape = assemble(file);
std::cout << "raw_add: " << tape.size() << " characters\n";
int bad = 0;
for (int a = 0; a < 256; a++)
for (int b = 0; b < 256; b++) {
machine m;
m.cells[0] = uint8_t(a);
m.cells[2] = uint8_t(b);
m.run(tape, 100'000);
const int sum = a + b;
const bool ok = m.finished && m.out.size() == 5 && m.out[0] == a &&
m.out[1] == b && m.out[2] == 0 &&
m.out[3] == (sum & 0xff) && m.out[4] == (sum >> 8);
if (!ok) {
bad++;
if (bad <= 3)
report("raw_add", a, b, m,
std::to_string(a) + " " + std::to_string(b) + " 0 " +
std::to_string(sum & 0xff) + " " +
std::to_string(sum >> 8));
}
}
std::cout << " " << (bad ? "FAILED" : "all 65536 combinations ok")
<< (bad ? " (" + std::to_string(bad) + " wrong)" : "") << "\n";
return bad;
}
// raw_inc: out is A, Ci, S, Co; S = A + Ci.
int test_inc(const std::string &file) {
const std::string tape = assemble(file);
std::cout << "raw_inc: " << tape.size() << " characters\n";
int bad = 0;
for (int a = 0; a < 256; a++)
for (int ci = 0; ci < 2; ci++) {
machine m;
m.cells[0] = uint8_t(a);
m.cells[2] = uint8_t(ci);
m.run(tape, 100'000);
const int sum = a + ci;
const bool ok = m.finished && m.out.size() == 4 && m.out[0] == a &&
m.out[1] == ci && m.out[2] == (sum & 0xff) &&
m.out[3] == (sum >> 8);
if (!ok) {
bad++;
if (bad <= 3)
report("raw_inc", a, ci, m,
std::to_string(a) + " " + std::to_string(ci) + " " +
std::to_string(sum & 0xff) + " " +
std::to_string(sum >> 8));
}
}
std::cout << " " << (bad ? "FAILED" : "all 512 combinations ok")
<< (bad ? " (" + std::to_string(bad) + " wrong)" : "") << "\n";
return bad;
}
} // namespace
int main(int argc, char **argv) {
const std::string root = argc > 1 ? argv[1] : ".";
const std::string drv = root + "/drv/";
const int bad = test_add(drv + "raw_add_byte.r8asm") +
test_bitop(drv + "raw_and_byte.r8asm", "raw_and", 0) +
test_bitop(drv + "raw_or_byte.r8asm", "raw_or", 1) +
test_bitop(drv + "raw_xor_byte.r8asm", "raw_xor", 2) +
test_inc(drv + "raw_inc_byte.r8asm");
std::cout << (bad ? "FAILED\n" : "byte level library ok\n");
return bad ? 1 : 0;
}
+7 -2
View File
@@ -35,8 +35,13 @@ struct machine {
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] == 0) {
if ((cells[dp] & 1) == 0) {
int depth = 1;
while (depth) {
pc++;
@@ -48,7 +53,7 @@ struct machine {
}
break;
case ']':
if (cells[dp] != 0) {
if ((cells[dp] & 1) == 1) {
int depth = 1;
while (depth) {
pc--;
+114
View File
@@ -0,0 +1,114 @@
// Independent ROT-8 interpreter. Reads a .rot8 tape straight from a file --
// no macro, no assembler, no r8asm -- and prints what `out` ('.') produced.
//
// r8forge_tape_run <file.rot8> [cells...]
//
// cells are addr=value (decimal), e.g. 0=128
//
// 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 <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "usage: r8forge_tape_run <file.rot8> [addr=value ...]\n";
return 2;
}
std::ifstream in(argv[1], std::ios::binary);
if (!in) {
std::cerr << "could not open " << argv[1] << "\n";
return 1;
}
const std::string tape((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
std::vector<uint8_t> cells(1024, 0);
for (int i = 2; i < argc; i++) {
const std::string a = argv[i];
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) = uint8_t(std::stoul(a.substr(eq + 1)) & 0xff);
}
std::vector<uint8_t> out;
size_t dp = 0;
const size_t limit = 5'000'000; // same as r8forge_derive
size_t pc = 0;
size_t steps = 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;
}
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] = uint8_t((cells[dp] >> 1) | (cells[dp] << 7));
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;
default: // ',' and anything else: not modelled
break;
}
}
std::cout << "out";
for (uint8_t v : out)
std::cout << " " << int(v);
std::cout << " (" << steps << " steps, cell0 ended 0x" << std::hex
<< int(cells[0]) << std::dec << ")\n";
return 0;
}
+6 -5
View File
@@ -1,12 +1,13 @@
%include "asm/lib.r8asm"
; set_0 就是 [-]。它只对 0 和 1 收敛,别的值会在里面无限翻最低位。
; set_0 = [-],清的是当前 cell 的**最低位**(biz / rnz 判的是 cell & 1)。
;
; r8forge_derive verify_set_0.r8asm -1 0=1 -> out 0
; r8forge_derive verify_set_0.r8asm -1 0=128 -> out 为空(撞 5M 步上限)
; r8forge_derive verify_set_0.r8asm -1 0=255 -> out 254
; r8forge_derive verify_set_0.r8asm -1 0=5 -> out 4
; r8forge_derive verify_set_0.r8asm -1 0=128 -> out 128
;
; 这就是 raw_add 卡死的根:第一轮之后和落在 S 的高位上(比如 sum0 = 1 时 S = 0x80),
; 下一轮开头的 set_0 再也出不来。所以只有 0+0 这种"中间和不产生任何 1"的情况能跑完。
; 128 原样留着,正说明它不是"整格清零"。曾经有人把 biz 当成 Brainfuck 的整格零判断,
; 于是 0x80 看起来是死循环,顺手把整个字节级库判成了坏的 —— 见 AGENTS.md。
.var A 0
set_0