Splice %synth into the tape, and check it on a ROT-8 machine

The synthesised body is written out as a macro file and imported, so the
generated code goes through the ordinary expansion path instead of being
spliced by hand.  set_1 is spelled out as set_0 plus flb, so the generated file
needs nothing from lib.r8asm.

examples/full_add.r8asm now assembles: 7.7 seconds of search at assembly time,
then a 95 character tape.  tests/synth_test.cc runs that tape on a small ROT-8
machine for all eight input combinations and checks S and Co -- all eight pass.

Two things that cost me time and are worth writing down:

  * the opcode map is "><+-[].,", i.e. '-' is flb and '+' is ror.  Guess it the
    other way round and a perfectly good tape looks like an infinite loop.
  * synth names must not collide with mnemonics: 'out' is lexed as rot8_out
    before it can be a block keyword.
This commit is contained in:
starcells committed 2026-11-06 00:08:29 +08:00
1 parent 6d0b6270fd
commit bc9d873cfc
5 files changed
+221 -56

No files matched your search

+3
View File
@@ -5,3 +5,6 @@ build/
# 汇编产物
*.rot8
*.err
*.log
*.synth.r8asm
+3
View File
@@ -16,3 +16,6 @@ endif()
add_executable(r8forge tests/asm_test.cc)
target_link_libraries(r8forge r8forge_core)
add_executable(r8forge_synth_test tests/synth_test.cc)
target_link_libraries(r8forge_synth_test r8forge_core)
+87 -45
View File
@@ -3,44 +3,89 @@
R8ASM 汇编器 + R8Veritas 搜索器,合成一个仓库。
搜索器不再是独立程序:`%synth` 是**汇编期指令**,描述一张真值表,汇编器现场搜出最短的块
序列,再决定怎么发射。这样代价模型和发射器是同一份代码,不用再维护两套「这个块要花多少
条指令」的估算。
序列直接拼进纸带。代价模型和发射器从此是同一份代码,不用再维护两套「这个块要花多少条
指令」的估算。
## 状态
| 部分 | 状态 |
|---|---|
| 汇编器(原 `r8asm`) | 可用,`asm/test.r8asm` 纸带不变(1714 字符) |
| 搜索器(原 `R8Veritas`) | 可用,位平面 + 反向查表,full_add 5 层最优 |
| `%synth` 解析 + 搜索 | **可用**,汇编期跑,结果打印成可直接粘贴的 r8asm |
| `%synth` 结果拼接进纸带 | **未接线**,现在调用点会明确报 `unknown macro`,不会悄悄生成错纸带 |
真值表描述:
## 用法
```asm
%include "asm/lib.r8asm"
%synth fulladd
params 6
inputs %1 %2 %3 ; 输入位,必须是最前面的参数
inputs %1 %2 %3 ; 输入位,必须排在最前面
outputs %4 %5 ; 要算出来的输出位
map 0 1 1 2 1 2 2 3 ; 每个输入组合对应的输出位取值(bit0 = %4)
%endsynth
.var A 0
.var B 1
.var Ci 2
.var S 3
.var Co 4
.var T 5
fulladd A B Ci S Co T ; 这一行展开成汇编期合成的 5 个块
output S
output Co
```
`inputs`/`outputs` 不能叫 `in`/`out`:`out` 和 ROT-8 的指令助记符撞了,词法会先认成
`rot8_out`。
汇编时的输出:
汇编:
```
r8asm: %synth fulladd: 5 layers (shortest), 20388515 states, 7.16s
r8asm: %synth fulladd body:
.tp %1
biz
.tp %2
flb
...
$ r8forge examples/full_add.r8asm
r8asm: %synth fulladd: 5 layers (shortest), 20388515 states, 7.7s
> [-]-... (95 字符纸带)
```
`tests/synth_test.cc` 把这条纸带丢进一台小 ROT-8 虚拟机,8 种输入组合全对:
```
tape: 95 characters
000 -> 00 expect 00 ok
...
111 -> 11 expect 11 ok
all eight combinations ok
```
注意 `inputs` / `outputs` 不能写成 `in` / `out`:`out` 和 ROT-8 助记符撞了,词法会先认成
`rot8_out`,整个 block 解析错位。
## 实现方式
`%synth` 在 `parse()` 里被读成一张真值表,随即调用搜索器;得到的块序列写成
```asm
%macro fulladd 6
.tp %1
biz
...
%endmacro
```
这样一个临时文件(`<名字>.synth.r8asm`),再 `import_file` 进来、删掉。于是合成出来的代码
走的是**正常宏展开**路径,不是手工拼 AST —— 少一套容易写错的代码。
生成的块体里 `set_1` 展开成 `biz/flb/rnz` + `flb`(即 `set_0` + 翻转),所以生成文件不依赖
`lib.r8asm`。
## 搜索器
- 状态 = 位平面真值表,只留影响答案的输入(加法器类问题通常 3 个,48 bit 一个 `uint64_t`)
- 前向 BFS 到 d−1 层,最后一层不展开:枚举目标的一步前驱反查表
- `proven_optimal` 为真表示长度已被穷尽证明
full_add(`r8veritas<6>`):**5 层,2038 万状态,7.7 秒,穷尽搜索下最短**。
比它更宽松的指令语义也没有 4 层解(都做过穷尽搜索):
| 放宽 | 指令数 | 搜索规模 | 4 层? |
|---|---|---|---|
| 每目的地独立 OR/XOR | 1,458 | 前向 3 层 173 万 + 反向 20,096 前驱 | 无 |
| 再加 `set_0` | 6,144 | 前向 3 层 956 万 + 反向 40,928 | 无 |
| 参数 6 → 7 → 8 个 | 2,040 | 穷尽 540 万 / 4410 万状态 | 无 |
| 条件位 ≠ 牺牲位 | 2,304 | 前向 3 层 317 万 + 反向 1,280 | 无 |
## 为什么合在一起
代价 = 汇编出来多少条指令,而这只有发射器知道:
@@ -50,28 +95,22 @@ cost(layer) = 2 # biz + rnz
+ Σ (|Δ| 移动 + op) # flb=1, set_0=3, set_1=4
```
其中 `|Δ|` 来自**调用点的 cell 布局**,不是汇编器的内部知识 —— 同一份 5 层程序,
cell 紧邻时 87 字符,间隔 2 格时 136 字符。所以这个数只能由「知道布局的那一方」算,
也就是汇编期。
`|Δ|` 来自**调用点的 cell 布局**:同一份 5 层程序,cell 紧邻是 87 字符,隔两格是 136 字符。
这是「程序 × 布局」的属性,只有看得见调用点的那一方算得出来 —— 也就是汇编期。
## 搜索器
## 坑
- 状态 = 位平面真值表,只留影响答案的输入(加法器类问题通常 3 个,48 bit 一个 `uint64_t`)
- 前向 BFS 到 d−1 层,最后一层不展开:枚举目标的一步前驱反查表
- `proven_optimal` 为真表示长度已被穷尽证明
full_add 结果(`r8veritas<6>`):5 层,2038 万状态,7.2 s,5 层是穷尽搜索下的最短。
`>=4` 层被排除,而且换更宽松的指令语义(每目的地独立 OR/XOR、`set_0`、条件位≠牺牲位、
8 个参数 cell)也没有 4 层解。
- ROT-8 的字符映射是 `"><+-[].,"`,也就是 **`-` 是 flb,`+` 是 ror**。写仿真器时按常识
猜会反(我第一次就反了,纸带看起来「死循环」)。
- `%synth` 的名字不能和 ROT-8 助记符重名(`out`、`flb`、`biz`…),否则词法先认成指令。
## 下一次要做的事
1. **把 `%synth` 的结果接进纸带**。两条路:
- 生成宏体 → `import_macro`(内存版,我在 `parse()` 递归里踩了 bug,还没追完)
- 生成一个临时 `.r8asm` 再 `%include`(绕开内存 token 流,最稳)
2. 搜索的代价从「1/层」换成真实指令数(Dijkstra + 每层目的地访问顺序的 TSP),
这样嵌套条件块(`A AND B` 门控)也能公平地参与竞争。
3. 缓存:同一个 `%synth` 已经在汇编期只跑一次(按名字),但要跨进程缓存还得落盘。
1. 搜索的代价从「1/层」换成真实指令数(Dijkstra + 每层目的地访问顺序的 TSP),这样嵌套条件
块(`A AND B` 门控)也能公平参与竞争。注意嵌套会降低层数但拉长纸带 —— 层数不是长度
的好代理。
2. 缓存:现在每次汇编都要重跑搜索(full_add 是 7.7 秒)。按真值表 + 布局落盘缓存。
3. `%synth` 只支持 8 位以内的参数(状态要塞进 64 位字里)。
## 构建
@@ -79,6 +118,7 @@ full_add 结果(`r8veritas<6>`):5 层,2038 万状态,7.2 s,5 层是
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 # 合成 + 跑虚拟机自检
```
`CMakeLists.txt` 里没有 `set(CMAKE_CXX_FLAGS ...)`:那会把默认 flag 整个换掉,MSVC 下丢
@@ -87,10 +127,12 @@ build\Release\r8forge.exe asm\test.r8asm > test.rot8
## 布局
```
include/r8forge/r8asm.hh 汇编器
include/r8forge/r8asm.hh 汇编器 + %synth 指令
include/r8forge/r8veritas.hh 搜索器
src/r8asm.cc 汇编器 + %synth 指令
src/synth.cc %synth 的真值表 -> 搜索
example(s)/ 用法示例
src/r8asm.cc 汇编器实现
src/synth.cc 真值表 -> 搜索
tests/asm_test.cc 汇编器自检(纸带不变)
tests/synth_test.cc 合成 + ROT-8 虚拟机自检
asm/ 标准库与既有实现
examples/full_add.r8asm 汇编期合成全加器
```
+26 -11
View File
@@ -1,4 +1,7 @@
#include "r8forge/r8asm.hh"
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <algorithm>
#include <cstddef>
#include <iostream>
@@ -470,21 +473,33 @@ r8asm::ast_node r8asm::parse(const token_stream &stream) {
}
auto prog = r8asm_synth_program(spec.params, spec.in, spec.out,
spec.map, name);
if (prog.empty())
if (prog.empty()) {
main_tree.fail("%synth '" + name + "': nothing emitted");
else {
// TODO: splice this into the tape. For now the synthesised body is
// printed (ready to paste) and the call site is left undefined, so
// nothing silently assembles to the wrong thing.
std::cerr << "r8asm: %synth " << name << " body:\n";
} else {
// Write the synthesised body out as a macro and import it: the code
// then goes through the normal, well tested expansion path instead
// of being spliced by hand. set_1 is spelled out (set_0 + flb) so
// the generated file needs nothing from lib.r8asm.
const std::string path = (std::filesystem::temp_directory_path() /
(name + ".synth.r8asm"))
.string();
std::ofstream file(path);
file << "%macro " << name << " " << spec.params << "\n";
for (const auto &i : prog) {
std::cerr << "\t.tp %" << i[0] + 1 << "\n\tbiz\n";
file << ".tp %" << i[0] + 1 << "\nbiz\n";
for (int b = 0; b < 8; b++)
if (i[1] & (1 << b))
std::cerr << "\t\t.tp %" << b + 1 << "\n\t\t"
<< (i[2] ? "set_1" : "flb") << "\n";
std::cerr << "\t.tp %" << i[0] + 1 << "\n\tflb\n\trnz\n";
if (i[1] & (1 << b)) {
file << ".tp %" << b + 1 << "\n";
if (i[2])
file << "biz\nflb\nrnz\n"; // set_0
file << "flb\n";
}
file << ".tp %" << i[0] + 1 << "\nflb\nrnz\n";
}
file << "%endmacro\n";
file.close();
import_file(path, main_tree.CELL_SIZE);
std::remove(path.c_str());
}
} break;
default:
+102
View File
@@ -0,0 +1,102 @@
// Assembles examples/full_add.r8asm (whose body is synthesised at assembly
// time) and runs the resulting tape on a tiny ROT-8 machine for all eight
// input combinations.
#include "r8forge/r8asm.hh"
#include <cstdlib>
#include <iostream>
#include <vector>
namespace {
// the eight ROT-8 instructions
const char *const INSTRUCTIONS = "><-+[].r"; // r = our ror alias
// real ROT-8: '>' '<' '-' '+' '[' ']' '.' ','
// note "-" is ror, and there is no separate 'r'
struct machine {
std::vector<uint8_t> cells = std::vector<uint8_t>(256, 0);
std::vector<uint8_t> out;
size_t dp = 0;
static uint8_t ror(uint8_t v) { return uint8_t((v >> 1) | (v << 7)); }
void run(const std::string &tape) {
for (size_t pc = 0; pc < tape.size(); pc++) {
switch (tape[pc]) {
case '>':
dp++;
break;
case '<':
dp--;
break;
case '-': // flb: flip last bit
cells[dp] ^= 1;
break;
case '+': // ror: rotate right
cells[dp] = ror(cells[dp]);
break;
case '[':
if (cells[dp] == 0) {
int depth = 1;
while (depth) {
pc++;
if (tape[pc] == '[')
depth++;
else if (tape[pc] == ']')
depth--;
}
}
break;
case ']':
if (cells[dp] != 0) {
int depth = 1;
while (depth) {
pc--;
if (tape[pc] == ']')
depth++;
else if (tape[pc] == '[')
depth--;
}
}
break;
case '.':
out.push_back(cells[dp]);
break;
default:
break;
}
}
}
};
} // namespace
int main() {
r8asm assembler;
if (!assembler.import_file("examples/full_add.r8asm", 8)) {
std::cerr << "could not assemble examples/full_add.r8asm\n";
return 1;
}
const std::string tape = assembler.export_rot8();
std::cout << "tape: " << tape.size() << " characters\n";
int failures = 0;
for (int combo = 0; combo < 8; combo++) {
const int a = combo & 1, b = (combo >> 1) & 1, c = (combo >> 2) & 1;
machine m;
m.cells[0] = uint8_t(a); // A
m.cells[1] = uint8_t(b); // B
m.cells[2] = uint8_t(c); // Ci
m.run(tape);
const int sum = a ^ b ^ c;
const int carry = (a & b) | (a & c) | (b & c);
const bool ok = m.out.size() == 2 && m.out[0] == sum && m.out[1] == carry;
std::cout << " " << a << b << c << " -> " << (m.out.size() > 0 ? int(m.out[0]) : -1)
<< (m.out.size() > 1 ? int(m.out[1]) : -1) << " expect " << sum
<< carry << (ok ? " ok" : " WRONG") << "\n";
if (!ok)
failures++;
}
std::cout << (failures ? "FAILED\n" : "all eight combinations ok\n");
return failures ? 1 : 0;
}