R8Forge: assembler and searcher in one repo, %synth directive

The searcher stops being a separate program: %synth is an assembly-time
directive.  It describes a truth table, the assembler runs the search while
parsing, and the block list comes back as ready-to-paste r8asm.

Merging is what makes the cost model honest.  The price of a layer is
  cost = 2 (biz + rnz) + sum(move distance + op cost)
and the move distance depends on the call site's cell layout, not on anything
the assembler knows in advance: the same five-layer adder is 87 characters
with the cells adjacent and 136 with them two apart.  Only the side that sees
the layout can price it, which is now the assembler itself.

Working: the assembler (asm/test.r8asm still assembles to the same 1714
characters), the searcher (bit planes + backward one-step lookup, full_add in
5 layers, proven shortest in 7.2s), and %synth parsing plus the search itself.
Not working yet: splicing the synthesised body into the tape -- a synth call
fails loudly with 'unknown macro' instead of emitting anything, so nothing can
silently assemble wrong.  The two ways to finish it are in the README.

Also carries over the CMake fix: no set(CMAKE_CXX_FLAGS ...), which used to
drop /EHsc, push -O3 into Debug and fight /RTC1.
This commit is contained in:
starcells committed 2026-11-05 23:59:15 +08:00
commit 6d0b6270fd
17 files changed
+2709

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
build/
.cache/
.continue/
.vscode/
# 汇编产物
*.rot8
+18
View File
@@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.10)
project(R8Forge)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(include)
add_library(r8forge_core src/r8asm.cc src/synth.cc)
# 别再 set(CMAKE_CXX_FLAGS ...) 了:那会把默认 flag 整个换掉,MSVC 下丢 /EHsc、
# 还会把 -O3 塞进 Debug 和 /RTC1 打架。Release 配置本来就带 -O3 / /O2 和 NDEBUG。
if(NOT MSVC)
add_compile_options($<$<CONFIG:Release>:-march=native>)
endif()
add_executable(r8forge tests/asm_test.cc)
target_link_libraries(r8forge r8forge_core)
+96
View File
@@ -0,0 +1,96 @@
# R8Forge
R8ASM 汇编器 + R8Veritas 搜索器,合成一个仓库。
搜索器不再是独立程序:`%synth` 是**汇编期指令**,描述一张真值表,汇编器现场搜出最短的块
序列,再决定怎么发射。这样代价模型和发射器是同一份代码,不用再维护两套「这个块要花多少
条指令」的估算。
## 状态
| 部分 | 状态 |
|---|---|
| 汇编器(原 `r8asm`) | 可用,`asm/test.r8asm` 纸带不变(1714 字符) |
| 搜索器(原 `R8Veritas`) | 可用,位平面 + 反向查表,full_add 5 层最优 |
| `%synth` 解析 + 搜索 | **可用**,汇编期跑,结果打印成可直接粘贴的 r8asm |
| `%synth` 结果拼接进纸带 | **未接线**,现在调用点会明确报 `unknown macro`,不会悄悄生成错纸带 |
真值表描述:
```asm
%synth fulladd
params 6
inputs %1 %2 %3 ; 输入位,必须是最前面的参数
outputs %4 %5 ; 要算出来的输出位
map 0 1 1 2 1 2 2 3 ; 每个输入组合对应的输出位取值(bit0 = %4)
%endsynth
```
`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
...
```
## 为什么合在一起
代价 = 汇编出来多少条指令,而这只有发射器知道:
```
cost(layer) = 2 # biz + rnz
+ Σ (|Δ| 移动 + op) # flb=1, set_0=3, set_1=4
```
其中 `|Δ|` 来自**调用点的 cell 布局**,不是汇编器的内部知识 —— 同一份 5 层程序,
cell 紧邻时 87 字符,间隔 2 格时 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 层解。
## 下一次要做的事
1. **把 `%synth` 的结果接进纸带**。两条路:
- 生成宏体 → `import_macro`(内存版,我在 `parse()` 递归里踩了 bug,还没追完)
- 生成一个临时 `.r8asm` 再 `%include`(绕开内存 token 流,最稳)
2. 搜索的代价从「1/层」换成真实指令数(Dijkstra + 每层目的地访问顺序的 TSP),
这样嵌套条件块(`A AND B` 门控)也能公平地参与竞争。
3. 缓存:同一个 `%synth` 已经在汇编期只跑一次(按名字),但要跨进程缓存还得落盘。
## 构建
```powershell
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
```
`CMakeLists.txt` 里没有 `set(CMAKE_CXX_FLAGS ...)`:那会把默认 flag 整个换掉,MSVC 下丢
`/EHsc`、还把 `-O3` 塞进 Debug 和 `/RTC1` 打架。
## 布局
```
include/r8forge/r8asm.hh 汇编器
include/r8forge/r8veritas.hh 搜索器
src/r8asm.cc 汇编器 + %synth 指令
src/synth.cc %synth 的真值表 -> 搜索
example(s)/ 用法示例
asm/ 标准库与既有实现
```
+88
View File
@@ -0,0 +1,88 @@
; fibonacci.r8asm
;
; 斐波那契发生器,顺便当 r8asm 的一份冒烟测试:
; 宏、%include、表达式、.var/.anchor/.tp、.xor、biz/rnz、raw_add 都用上了。
;
; 这里不写死 8 位:计数器用 _CELL_MAX,循环长度自然等于 _CELL_SIZE。
; 8 位时的预期输出(用 rot8_test 跑出来的十进制数):
; 1 1 2 3 5 8 13 21 34 55
;
; 数据布局:每个变量占一个 Unit(数据 Cell + 辅助 Cell),
; 辅助 Cell 留给 copy 当位缓冲,raw_add 也会用到相邻的草稿 Cell。
;
; A a
; B b
; S a + b
; X a 的副本 —— raw_add 会把两个操作数都吃掉,所以每圈都得重新复印
; Y b 的副本
; Z 常数 0,当进位输入用
; CO 进位
; T 进位用的一位草稿
; CNT 循环计数器
; BUF copy 用的位缓冲
%include "asm/raw_add.r8asm"
; 一个 Unit 两个 Cell:数据 Cell + 辅助 Cell
.var UNIT 2
.var A 0
.var B (A + UNIT)
.var S (B + UNIT)
.var X (S + UNIT)
.var Y (X + UNIT)
.var Z (Y + UNIT)
.var CO (Z + UNIT)
.var T (CO + UNIT)
.var CNT (T + UNIT)
.var BUF (CNT + UNIT)
; ---------------------------------------------------------------- 前两项
; a = 1,b = 1,先打出来
.tp A
.xor 1
.tp B
.xor 1
output A
output B
; ---------------------------------------------------------------- 循环入口
; CNT 里塞满 _CELL_SIZE 个 1:一个 1 就是一圈。
; biz/rnz 在 rot-8 里就是一对 [ ],运行时按括号配对,
; 所以这里不用写标签,位置本身就是标签。
.tp CNT
.xor _CELL_MAX
biz
; ---------------------------------------------------------------- 循环体
; s = a + b
; raw_add 是破坏性的,先把它要吃的 a、b 各复印一份
.tp A
copy X BUF
.tp B
copy Y BUF
; 进位输入和进位输出都先清零
erase Z
erase CO
; S = X + Y + Z,进位从 CO 出来
raw_add X Y Z S CO T
; 打印新的一项
.tp S
output S
; 滚动:a <- b,b <- s
.tp Y
copy A BUF
.tp S
copy B BUF
; ------------------------------------------------------------ 计数
; 吃掉最低位的 1,再把下一位转下来,
; 等 _CELL_SIZE 个 1 都吃干净,最低位变成 0,循环结束
.tp CNT
flb
ror
rnz
+153
View File
@@ -0,0 +1,153 @@
; Macro step
; %1: step_count
%macro step 1
%rep %1
stp
stp
%endrep
%endmacro
; Macro back
; %1: back_count
%macro back 1
%rep %1
btp
btp
%endrep
%endmacro
; Macro set_0
; %this: CellBit operand
%macro set_0 0
biz
flb
rnz
%endmacro
; Macro set_1
; %this: CellBit operand
%macro set_1 0
set_0
flb
%endmacro
; Macro erase
; %1: Cell operand
%macro erase 1
.anchor before_erase
.tp %1
%rep _CELL_SIZE
set_0
ror
%endrep
.tp before_erase
%endmacro
; Macro rol
; %this: Cell operand
%macro rol 0
%rep _CELL_SIZE - 1
ror
%endrep
%endmacro
; Macro clb_bit_mov
; %this: CellBit data
; %1: CellBit destination
%macro clb_bit_mov 1
.anchor before_clb_bit_mov
.tp %1
set_0
.tp before_clb_bit_mov
biz
.tp %1
flb
.tp before_clb_bit_mov
flb
rnz
.tp before_clb_bit_mov
%endmacro
; Macro bit_copy
; %this: CellBit data
; %1: CellBit destination
; %2: CellBit buffer
%macro bit_copy 2
.anchor before_bit_copy
.tp %1
set_0
.tp %2
set_0
.tp before_bit_copy
biz
.tp %1
flb
.tp %2
flb
.tp before_bit_copy
flb
rnz
.tp %2
clb_bit_mov before_bit_copy
.tp before_bit_copy
%endmacro
; Macro copy
; %this: CellBit data
; %1: CellBit destination
; %2: CellBit buffer
%macro copy 2
.anchor before_copy
%rep _CELL_SIZE
bit_copy %1 %2
ror
.tp %1
ror
.tp %2
ror
.tp before_copy
%endrep
%endmacro
; Macro bit_copy_to_buffer
; %this: UnitBit operand
; %1: CellBit tmp
%macro bit_copy_to_buffer 1
stp
.anchor bit_copy_to_buffer_buf_1
btp
bit_copy bit_copy_to_buffer_buf_1 %1
%endmacro
; Macro copy_to_buffer
; %this: Unit operand
; %1: Cell tmp
%macro copy_to_buffer 1
stp
.anchor copy_to_buffer_buf_1
btp
copy copy_to_buffer_buf_1 %1
%endmacro
; Macro output
; %1: operand
%macro output 1
.anchor before_output
.tp %1
out
.tp before_output
%endmacro
+130
View File
@@ -0,0 +1,130 @@
%include "asm/lib.r8asm"
; Macro bit_raw_add
; %1: CellBit A
; %2: CellBit B
; %3: CellBit Ci
; %4: CellBit S
; %5: CellBit Co
; %6: CellBit buf
%macro bit_raw_add 6
.anchor before_bit_raw_add
.tp %4
biz
flb
rnz
.tp %5
biz
flb
rnz
.tp %6
biz
flb
rnz
.tp %3
biz
.tp %1
flb
.tp %2
flb
.tp %6
flb
.tp %3
flb
rnz
.tp %1
biz
.tp %3
flb
.tp %4
flb
.tp %6
flb
.tp %1
flb
rnz
.tp %2
biz
.tp %1
flb
.tp %3
flb
.tp %5
flb
.tp %6
flb
.tp %2
flb
rnz
.tp %4
biz
.tp %2
set_1
.tp %5
set_1
.tp %4
flb
rnz
.tp %6
biz
.tp %1
flb
.tp %2
flb
.tp %3
flb
.tp %4
flb
.tp %5
flb
.tp %6
flb
rnz
.tp before_bit_raw_add
%endmacro
; Macro raw_add
; %1: Cell A
; %2: Cell B
; %3: CellBit Ci
; %4: Cell S
; %5: CellBit Co
; %6: Cell tmp
%macro raw_add 6
.anchor before_raw_add
.tp %3
bit_copy %6 %5
.tp %6
ror
%rep _CELL_SIZE
bit_raw_add %1 %2 %3 %4 %5 %6
.tp %5
clb_bit_mov %3
.tp %1
ror
.tp %2
ror
.tp %4
ror
%endrep
.tp %3
clb_bit_mov %5
.tp %6
rol
clb_bit_mov %3
.tp before_raw_add
%endmacro
+129
View File
@@ -0,0 +1,129 @@
%include "asm/lib.r8asm"
; Macro clb_bit_and
; %1: CellBit arg1
; %2: CellBit arg2
; %3: CellBit ans
%macro clb_bit_and 3
.anchor before_clb_bit_and
.tp %3
set_0
.tp %1
biz
.tp %2
biz
.tp %3
set_1
.tp %2
set_0
rnz
.tp %1
set_0
rnz
.tp before_clb_bit_and
%endmacro
; Macro clb_and
; %1: Cell arg1
; %2: Cell arg2
; %3: Cell ans
%macro clb_and 3
.anchor before_clb_and
%rep _CELL_SIZE
clb_bit_and %1 %2 %3
.tp %1
ror
.tp %2
ror
.tp %3
ror
%endrep
.tp before_clb_and
%endmacro
; Macro bit_and
; %1: CellBit arg1
; %2: CellBit arg2
; %3: CellBit ans
; %4: CellBit tmp
%macro bit_raw_and 4
.anchor before_bit_raw_and
.tp %3
biz
flb
rnz
.tp %4
biz
flb
rnz
.tp %1
biz
.tp %3
set_1
.tp %4
set_1
.tp %1
flb
rnz
.tp %2
biz
.tp %1
set_1
.tp %3
set_1
.tp %2
flb
rnz
.tp %1
biz
.tp %2
flb
.tp %3
flb
.tp %1
flb
rnz
.tp %4
biz
.tp %1
flb
.tp %3
flb
.tp %4
flb
rnz
.tp before_bit_raw_and
%endmacro
; Macro and
; %1: Cell arg1
; %2: Cell arg2
; %3: Cell ans
; %4: CellBit tmp
%macro raw_and 4
.anchor before_raw_and
%rep _CELL_SIZE
bit_raw_and %1 %2 %3 %4
.tp %1
ror
.tp %2
ror
.tp %3
ror
%endrep
.tp before_raw_and
%endmacro
+107
View File
@@ -0,0 +1,107 @@
%include "asm/lib.r8asm"
; Macro bit_raw_inc
; %1: CellBit A
; %2: CellBit Ci
; %3: CellBit S
; %4: CellBit Co
; %5: CellBit tmp
%macro bit_raw_inc 5
.anchor before_bit_raw_inc
.tp %3
biz
flb
rnz
.tp %4
biz
flb
rnz
.tp %5
biz
flb
rnz
.tp %2
biz
.tp %1
flb
.tp %3
flb
.tp %2
flb
rnz
.tp %1
biz
.tp %4
set_1
.tp %5
set_1
.tp %1
flb
rnz
.tp %3
biz
.tp %1
set_1
.tp %2
set_1
.tp %4
set_1
.tp %3
flb
rnz
.tp %5
biz
.tp %1
flb
.tp %3
flb
.tp %4
flb
.tp %5
flb
rnz
.tp before_bit_raw_inc
%endmacro
; Macro raw_inc
; %1: Cell A
; %2: CellBit Ci
; %3: Cell S
; %4: CellBit Co
; %5: Cell tmp
%macro raw_inc 5
.anchor before_raw_inc
.tp %2
bit_copy %5 %4
.tp %5
ror
%rep _CELL_SIZE
bit_raw_inc %1 %2 %3 %4 %5
.tp %4
clb_bit_mov %2
.tp %1
ror
.tp %3
ror
%endrep
.tp %2
clb_bit_mov %4
.tp %5
rol
clb_bit_mov %2
.tp before_raw_inc
%endmacro
+133
View File
@@ -0,0 +1,133 @@
%include "asm/lib.r8asm"
; Macro clb_bit_or
; %1: CellBit arg1
; %2: CellBit arg2
; %3: CellBit ans
%macro clb_bit_or 3
.anchor before_clb_bit_or
.tp %3
set_0
.tp %1
biz
.tp %3
flb
.tp %1
flb
rnz
.tp %2
biz
.tp %3
set_1
.tp %2
flb
rnz
.tp before_clb_bit_or
%endmacro
; Macro clb_or
; %1: Cell arg1
; %2: Cell arg2
; %3: Cell ans
%macro clb_or 3
.anchor before_clb_or
%rep _CELL_SIZE
clb_bit_or %1 %2 %3
.tp %1
ror
.tp %2
ror
.tp %3
ror
%endrep
.tp before_clb_or
%endmacro
; Macro bit_raw_or
; %1: CellBit arg1
; %2: CellBit arg2
; %3: CellBit ans
; %4: CellBit tmp
%macro bit_raw_or 3
.anchor before_bit_raw_or
.tp %3
biz
flb
rnz
.tp %4
biz
flb
rnz
.tp %1
biz
.tp %3
set_1
.tp %1
flb
rnz
.tp %3
biz
.tp %1
flb
.tp %2
flb
.tp %4
flb
.tp %3
flb
rnz
.tp %2
biz
.tp %3
flb
.tp %4
flb
.tp %2
flb
rnz
.tp %4
biz
.tp %2
set_1
.tp %3
set_1
.tp %4
flb
rnz
.tp before_bit_raw_or
%endmacro
; Macro raw_or
; %1: Cell arg1
; %2: Cell arg2
; %3: Cell ans
; %4: CellBit tmp
%macro raw_or 4
.anchor before_raw_or
%rep _CELL_SIZE
bit_raw_or %1 %2 %3 %4
.tp %1
ror
.tp %2
ror
.tp %3
ror
%endrep
.tp before_raw_or
%endmacro
+123
View File
@@ -0,0 +1,123 @@
%include "asm/lib.r8asm"
; Macro clb_bit_xor
; %1: CellBit arg1
; %2: CellBit arg2
; %3: CellBit ans
%macro clb_bit_xor 3
.anchor before_clb_bit_xor
.tp %3
set_0
.tp %1
biz
.tp %3
flb
.tp %1
set_0
rnz
.tp %2
biz
.tp %3
flb
.tp %2
set_0
rnz
.tp before_clb_bit_xor
%endmacro
; Macro clb_xor
; %1: Cell arg1
; %2: Cell arg2
; %3: Cell ans
%macro clb_xor 3
.anchor before_clb_xor
%rep _CELL_SIZE
clb_bit_xor %1 %2 %3
.tp %1
ror
.tp %2
ror
.tp %3
ror
%endrep
.tp before_clb_xor
%endmacro
; Macro bit_raw_xor
; %1: CellBit arg1
; %2: CellBit arg2
; %3: CellBit ans
; %4: CellBit tmp
%macro bit_raw_xor 4
.anchor before_bit_raw_xor
.tp %3
biz
flb
rnz
.tp %4
biz
flb
rnz
.tp %2
biz
.tp %1
flb
.tp %4
flb
.tp %2
flb
rnz
.tp %1
biz
.tp %2
flb
.tp %3
flb
.tp %4
flb
.tp %1
flb
rnz
.tp %4
biz
.tp %1
flb
.tp %2
flb
.tp %4
flb
rnz
.tp before_xor
%endmacro
; Macro raw_xor
; %1: Unit arg1
; %2: Unit arg2
; %3: Cell ans
%macro raw_xor 4
.anchor before_raw_xor
%rep _CELL_SIZE
bit_raw_xor %1 %2 %3 %4
.tp %1
ror
.tp %2
ror
.tp %3
ror
%endrep
.tp before_raw_xor
%endmacro
+28
View File
@@ -0,0 +1,28 @@
%include "asm/raw_add.r8asm"
%include "asm/raw_and.r8asm"
%include "asm/raw_or.r8asm"
%include "asm/raw_xor.r8asm"
%include "asm/raw_inc.r8asm"
.var A 0
.var B 2
.var Ci 4
.var S 6
.var Co 8
.var tmp 1
.tp A
.xor 127
.tp B
.xor (~126)+1
.tp Ci
.xor 0
raw_add A B Ci S Co tmp
output A
output B
output Ci
output S
output Co
+27
View File
@@ -0,0 +1,27 @@
%include "asm/lib.r8asm"
; 让汇编器在汇编期合成一个全加器 bit-slice。
; %1 %2 %3 = A B Ci 输入(必须是最前面的参数)
; %4 %5 = S Co 要被算出来的输出
; %6 = T 草稿 cell,调用方给一个,结束时它必须是 0
;
; map 的每一项是那个输入组合下 %4%5 的取值(bit0 = %4, bit1 = %5),
; 顺序是输入组合 000,001,...,111。
%synth fulladd
params 6
inputs %1 %2 %3
outputs %4 %5
map 0 1 1 2 1 2 2 3
%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
output S
output Co
+226
View File
@@ -0,0 +1,226 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include "r8forge/r8veritas.hh"
// %synth: run the searcher on a truth table and return the block list as
// {sacrifice, mask, or_mode} triples.
std::vector<std::array<int, 3>>
r8asm_synth_program(int params, const std::vector<int> &in,
const std::vector<int> &out, const std::vector<int> &map,
const std::string &name);
class r8asm {
using data = int16_t;
using parameter_index = uint8_t;
using addr = uint32_t;
using general_data = int32_t;
using line_number = unsigned long long;
using depth_t = unsigned long long;
using precedence_t = uint8_t;
private:
enum class token_t {
STRING,
OPERATOR,
MACROCALL,
ROT8,
DIRECTIVE,
PARAMETER,
BUILTIN,
LPAREN,
RPAREN,
LQUOTE,
RQUOTE,
ENDL,
};
struct token {
token_t type;
std::string value;
};
struct token_line {
line_number number;
std::vector<token> tokens;
};
struct token_stream {
std::string filename;
std::vector<token_line> lines;
const std::set<std::string> raw_rot8_ins = {"stp", "btp", "ror", "flb",
"biz", "rnz", "out", "inp"};
token_stream(const std::string &filename) {
this->filename = filename;
std::ifstream file(filename);
if (!file.is_open()) {
ok = false;
return;
}
std::stringstream buf;
buf << file.rdbuf();
lines = lex(buf.str());
}
std::vector<token_line> lex(const std::string &char_stream);
bool ok = true; // false when the file could not be read
};
enum class ast_node_t {
CONSTANT,
PARAMETER,
VARIABLE,
OPERATOR,
BUILTIN,
MACROCALL,
REPEAT,
ROT8,
CODEBLOCK,
STRING,
};
struct ast_node {
ast_node_t type;
std::string value;
std::vector<ast_node> children;
};
class ast {
public:
ast_node root = {r8asm::ast_node_t::CODEBLOCK, "", {}};
size_t CELL_SIZE;
// I know template class is the most elegant solution of CELL_SIZE
// but I can't be bother to add that.
// The assembler has no exceptions: anything that cannot be assembled
// sets this flag and says why on stderr.
bool error = false;
void fail(const std::string &message) {
std::cerr << "r8asm: " << message << std::endl;
error = true;
}
// ---- %synth ---------------------------------------------------------
// A synth block is a macro whose body the assembler synthesises from a
// truth table. Parameters are %1..%params; the input ones come first
// (they carry the input value), the rest are outputs and scratch cells.
struct synth_spec {
int params = 0;
std::vector<int> in; // param index per input bit, bit 0 first
std::vector<int> out; // param index per output bit, bit 0 first
std::vector<int> map; // 2^|in| entries: output bits of that input
};
private:
addr dataptr = 0;
std::vector<std::map<std::string, general_data>> scopes;
std::map<std::string, ast_node> macros;
std::set<std::string> reported; // keep a typo from being printed n times
enum class builtin_t {
ANCHOR,
TP,
XOR,
LOOP,
ENDLOOP,
VAR,
};
const std::map<std::string, builtin_t> builtin_map = {
{"builtin_anchor", builtin_t::ANCHOR},
{"builtin_tp", builtin_t::TP},
{"builtin_xor", builtin_t::XOR},
{"builtin_loop", builtin_t::LOOP},
{"builtin_endloop", builtin_t::ENDLOOP},
{"builtin_var", builtin_t::VAR},
};
enum class rot8_t {
STP, // Step Tape Pointer,'>'
BTP, // Back Tape Pointer,'<'
ROR, // ROtate Right,'-'
FLB, // Flip Last Bit,'+'
BIZ, // Branch If Zero,'['
RNZ, // Return Not Zero,']'
OUT, // OUTput byte,'.'
INP, // INPut byte,','
};
const std::map<std::string, rot8_t> rot8_map = {
{"rot8_stp", rot8_t::STP}, {"rot8_btp", rot8_t::BTP},
{"rot8_ror", rot8_t::ROR}, {"rot8_flb", rot8_t::FLB},
{"rot8_biz", rot8_t::BIZ}, {"rot8_rnz", rot8_t::RNZ},
{"rot8_out", rot8_t::OUT}, {"rot8_inp", rot8_t::INP},
};
general_data expand_node_to_data(const ast_node &node);
std::string expand_node_to_string(const ast_node &node);
public:
enum class operator_t {
ADD,
SUB,
MUL,
DIV,
XOR,
AND,
OR,
NOT,
};
const std::map<std::string, operator_t> operator_map = {
{"op_add", operator_t::ADD}, {"op_sub", operator_t::SUB},
{"op_mul", operator_t::MUL}, {"op_div", operator_t::DIV},
{"op_xor", operator_t::XOR}, {"op_and", operator_t::AND},
{"op_or", operator_t::OR}, {"op_not", operator_t::NOT},
};
const std::map<operator_t, precedence_t> op_precedence_map = {
{operator_t::NOT, 0}, {operator_t::MUL, 1}, {operator_t::DIV, 1},
{operator_t::ADD, 2}, {operator_t::SUB, 2}, {operator_t::AND, 3},
{operator_t::XOR, 4}, {operator_t::OR, 5},
};
ast_node expand_node_to_ins(const ast_node &node);
std::string expand_root();
bool import_macro(const std::string &macro_name, const ast_node &node);
void set_cell_size(size_t cell_size);
};
ast main_tree;
enum class directive_t {
SYNTH,
ENDSYNTH,
MACRO,
ENDMACRO,
REP,
ENDREP,
INCLUDE,
};
std::map<std::string, directive_t> directive_keywords = {
{"macro", directive_t::MACRO},
{"endmacro", directive_t::ENDMACRO},
{"rep", directive_t::REP},
{"synth", directive_t::SYNTH},
{"endsynth", directive_t::ENDSYNTH},
{"endrep", directive_t::ENDREP},
{"include", directive_t::INCLUDE}};
ast_node parse(const token_stream &stream);
ast_node parse_args(const token_line &line);
ast_node parse_single_arg(const token_line &line);
public:
std::string export_rot8();
bool import_file(const std::string &filename, size_t cell_size);
// True once anything (a missing file, an unknown name, ...) has failed.
bool failed() const { return main_tree.error; }
};
+543
View File
@@ -0,0 +1,543 @@
#ifndef R8VERITAS
#define R8VERITAS
// R8Veritas -- shortest program search over the rot-8 "sacrifice block":
//
// .tp s
// biz
// .tp b ; once per b in the mask
// set_1 / flb ; OR / XOR
// .tp s
// flb
// rnz
//
// A state is the whole truth table of the working cell: for every input
// combination, what the cell holds. Written as bit planes -- plane b is bit
// b of the cell, over all inputs -- one block becomes a handful of 64-bit
// operations:
//
// cond = plane[s]; plane[s] = 0;
// for b in mask: plane[b] |= cond (set_1)
// plane[b] ^= cond (flb)
//
// Search strategy:
// * only the input bits that influence the answer survive (the old
// compress_stat_space), so a plane is a 2^K bit truth table instead of
// 2^CELL_SIZE, and the whole state is CELL_SIZE * 2^K bits
// * forward BFS keeps every reachable state of depth < d plus the block
// that produced it
// * the last block is not searched forward. A block clears its own
// plane, so the goal can only be its target if goal[s] == 0; for each
// such block every preimage of the goal is generated and looked up in
// the BFS table. A hit is the shortest program, and "nothing below d,
// something at d" is a proof.
//
// The backward step enumerates 2^K values of the condition, so it is only
// used while K <= 3; above that the last layer is expanded forward like the
// others (still a lot cheaper than the old implementation).
#include <algorithm>
#include <array>
#include <bit>
#include <bitset>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <optional>
#include <ostream>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
template <int CELL_SIZE> class r8veritas {
public:
using cell = uint8_t;
using stat = std::array<cell, (size_t(1) << CELL_SIZE)>;
using stat_ref = const stat *;
using truthtable = std::pair<stat_ref, stat_ref>;
using op = std::function<cell(cell)>;
// one biz block
struct instruction {
uint8_t sacrifice = 0; // plane whose bit is tested and cleared
uint8_t mask = 0; // bit b set: plane b is a destination
bool or_mode = false; // true: set_1 (|), false: flb (^)
};
struct options {
int max_depth = 5; // longest program to look for
size_t max_states = 80'000'000; // memory guard
bool verbose = false;
};
struct result {
bool found = false;
// true when every program shorter than program.size() was ruled out
bool proven_optimal = false;
std::vector<instruction> program;
size_t states = 0; // states kept by the BFS
int depth_reached = 0; // deepest layer fully expanded
double seconds = 0;
std::string message;
};
std::array<std::string, CELL_SIZE> nicknames;
std::array<std::string, CELL_SIZE> tp_paths;
void initialize_nicknames() {
for (int i = 0; i < CELL_SIZE; i++)
nicknames[i] = "%" + std::to_string(i + 1);
}
void initialize_tp_paths() {
for (int i = 0; i < CELL_SIZE; i++)
tp_paths[i] = ".tp " + nicknames[i];
}
// ---------------------------------------------------------------- states
stat_ref generate_empty_stat() {
stat arr{};
arr.fill(0);
return keep(arr);
}
truthtable generate_truthtable(const op &operation) {
stat in{}, out{};
for (size_t i = 0; i < (size_t(1) << CELL_SIZE); i++) {
in[i] = cell(i);
out[i] = operation(cell(i));
}
return {keep(in), keep(out)};
}
// Build a truthtable straight from two tables (a synth block knows the
// target stat, it does not have a callable function).
truthtable make_truthtable(const stat &in, const stat &out) {
return {keep(in), keep(out)};
}
// Clears the input bits that never influence the answer, so the search
// starts from a canonical state.
truthtable compress_stat_space(const truthtable &raw) {
stat start = *raw.first;
for (int i = 0; i < CELL_SIZE; i++) {
bool influences = false;
for (size_t j = 0; j < (size_t(1) << CELL_SIZE); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)])
influences = true;
if (!influences)
for (size_t j = 0; j < (size_t(1) << CELL_SIZE); j++)
start[j] = cell(start[j] & ~(1u << i));
}
return {keep(start), raw.second};
}
// Applies a program with the reference semantics (one state at a time) and
// tells whether it lands on the target.
bool run_program(const truthtable &raw, const std::vector<instruction> &p,
bool verbose = false) const {
stat cur = *raw.first;
for (const auto &i : p) {
for (size_t j = 0; j < cur.size(); j++)
if (cur[j] & (1u << i.sacrifice)) {
cur[j] = cell(cur[j] & ~(1u << i.sacrifice));
for (int b = 0; b < CELL_SIZE; b++)
if (i.mask & (1 << b))
cur[j] = i.or_mode ? cell(cur[j] | (1u << b))
: cell(cur[j] ^ (1u << b));
}
if (verbose) {
output_stat(cur);
std::cout << "\n";
}
}
return cur == *raw.second;
}
// ---------------------------------------------------------------- output
void output_stat(const stat &s) const {
for (auto v : s)
std::cout << std::bitset<CELL_SIZE>(v).to_string() << " ";
}
void output_ins(const instruction &ins, std::ostream &os,
bool debug_output = true) const {
if (debug_output) {
os << "SACRIFICE: " << int(ins.sacrifice);
if (ins.mask) {
os << (ins.or_mode ? ", SET1: {" : ", FLIP: {");
bool first = true;
for (int b = 0; b < CELL_SIZE; b++)
if (ins.mask & (1 << b)) {
if (!first)
os << ',';
os << b;
first = false;
}
os << '}';
}
os << ';';
return;
}
os << tp_paths[ins.sacrifice] << "\n";
os << "biz\n";
for (int b = 0; b < CELL_SIZE; b++)
if (ins.mask & (1 << b)) {
os << '\t' << tp_paths[b] << "\n";
os << '\t' << (ins.or_mode ? "set_1" : "flb") << "\n";
}
os << '\t' << tp_paths[ins.sacrifice] << "\n";
os << "\tflb\n";
os << "rnz\n";
}
void print_program(const std::vector<instruction> &p, std::ostream &os,
bool debug_output = false) const {
for (const auto &i : p) {
output_ins(i, os, debug_output);
os << "\n";
}
}
// ---------------------------------------------------------------- search
result solve(const truthtable &raw, const options &opt = {}) {
result r;
const auto t0 = std::chrono::steady_clock::now();
auto finish = [&]() {
r.seconds =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
.count();
return r;
};
// which input bits matter, in compression order
std::array<int, CELL_SIZE> bit_of{};
int k = 0;
for (int i = 0; i < CELL_SIZE; i++) {
for (size_t j = 0; j < (size_t(1) << CELL_SIZE); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)]) {
bit_of[k++] = i;
break;
}
}
if (k > 6) {
r.message = "the answer depends on more than 6 inputs; the packed state "
"does not fit and the search would be hopeless anyway";
return finish();
}
// compressed index j -> index in the full truth table
std::vector<size_t> full(size_t(1) << k, 0);
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < k; b++)
if (j & (size_t(1) << b))
full[j] |= size_t(1) << bit_of[b];
switch (k) {
case 0:
return solve_with<0>(raw, full, opt, r, finish);
case 1:
return solve_with<1>(raw, full, opt, r, finish);
case 2:
return solve_with<2>(raw, full, opt, r, finish);
case 3:
return solve_with<3>(raw, full, opt, r, finish);
case 4:
return solve_with<4>(raw, full, opt, r, finish);
case 5:
return solve_with<5>(raw, full, opt, r, finish);
default:
return solve_with<6>(raw, full, opt, r, finish);
}
}
private:
std::set<stat> pool;
stat_ref keep(const stat &s) { return &*pool.insert(s).first; }
// ---------------------------------------------------------------- engine
// K relevant inputs: every plane is a 2^K bit truth table, the whole state
// is CELL_SIZE * 2^K bits packed into KEYW words.
template <int K> struct engine {
static constexpr int M = 1 << K; // bits per plane
static constexpr int KEYW = (CELL_SIZE * M + 63) / 64;
static constexpr uint64_t PMASK =
(M >= 64) ? ~uint64_t(0) : ((uint64_t(1) << (M & 63)) - 1);
using key = std::array<uint64_t, KEYW>;
static uint64_t get(const key &k, int b) {
const int off = b * M;
return (k[off >> 6] >> (off & 63)) & PMASK;
}
static void put(key &k, int b, uint64_t v) {
const int off = b * M;
k[off >> 6] =
(k[off >> 6] & ~(PMASK << (off & 63))) | ((v & PMASK) << (off & 63));
}
static key zero() {
key k{};
return k;
}
static uint64_t cond(const key &k, const instruction &i) {
return get(k, i.sacrifice);
}
static key step(const key &k, const instruction &i) {
key n = k;
const uint64_t c = get(k, i.sacrifice);
put(n, i.sacrifice, 0);
for (int b = 0; b < CELL_SIZE; b++)
if (i.mask & (1 << b))
put(n, b, i.or_mode ? (get(k, b) | c) : (get(k, b) ^ c));
return n;
}
static uint64_t hash(const key &k) {
uint64_t h = 0xcbf29ce484222325ULL;
for (int i = 0; i < KEYW; i++) {
h ^= k[i];
h *= 0x100000001b3ULL;
h ^= h >> 29;
h *= 0xbf58476d1ce4e5b9ULL;
h ^= h >> 32;
}
return h;
}
struct slot {
key k{};
key parent{};
uint16_t ins = 0xFFFF; // 0xFFFF free, 0xFFFE start of a program
};
struct table {
std::vector<slot> v;
uint64_t mask = 0;
size_t used = 0;
static constexpr uint16_t FREE = 0xFFFF, ROOT = 0xFFFE;
static uint64_t capacity_for(size_t n) {
uint64_t c = 1 << 12;
while (c * 3 < n * 4 + 4)
c <<= 1;
return c;
}
void init(uint64_t cap) {
v.assign(cap, slot{});
mask = cap - 1;
used = 0;
}
void grow() {
std::vector<slot> old = std::move(v);
init(old.size() * 2);
for (const auto &s : old)
if (s.ins != FREE)
insert(s.k, s.parent, s.ins);
}
bool insert(const key &k, const key &parent, uint16_t ins) {
uint64_t j = hash(k) & mask;
while (v[j].ins != FREE) {
if (v[j].k == k)
return false;
j = (j + 1) & mask;
}
v[j].k = k;
v[j].parent = parent;
v[j].ins = ins;
if (++used * 4 > (mask + 1) * 3)
grow();
return true;
}
const slot *find(const key &k) const {
uint64_t j = hash(k) & mask;
while (v[j].ins != FREE) {
if (v[j].k == k)
return &v[j];
j = (j + 1) & mask;
}
return nullptr;
}
};
};
template <int K>
result solve_with(const truthtable &raw, const std::vector<size_t> &full,
const options &opt, result &r,
const std::function<result()> &finish) {
using E = engine<K>;
using table_t = typename E::table;
using key = typename E::key;
constexpr uint16_t ROOT = table_t::ROOT;
const std::vector<instruction> insns = build_instructions();
// start = identity over the compressed inputs, goal = the target
key start = E::zero(), goal = E::zero();
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < CELL_SIZE; b++) {
if (j & (size_t(1) << b))
E::put(start, b, E::get(start, b) | (uint64_t(1) << j));
if ((*raw.second)[full[j]] & (1u << b))
E::put(goal, b, E::get(goal, b) | (uint64_t(1) << j));
}
table_t tab;
tab.init(table_t::capacity_for(1 << 16));
tab.insert(start, E::zero(), ROOT);
std::vector<key> frontier{start};
auto path_to = [&](const key &k, int extra) {
std::vector<instruction> p;
if (extra >= 0)
p.push_back(insns[size_t(extra)]);
key cur = k;
while (true) {
const auto *s = tab.find(cur);
if (s == nullptr || s->ins == ROOT)
break;
p.push_back(insns[s->ins]);
cur = s->parent;
}
std::reverse(p.begin(), p.end());
return p;
};
if (start == goal) {
r.found = r.proven_optimal = true;
return finish();
}
for (int d = 1; d <= opt.max_depth; d++) {
// ---- close the last block: enumerate the goal's preimages ----
// Only worth it while 2^K is small enough to walk every condition.
if (K <= 3) {
for (uint16_t ii = 0; ii < insns.size(); ii++) {
const instruction &i = insns[ii];
if (E::get(goal, i.sacrifice) != 0)
continue; // the block clears its own plane
for (uint64_t c = 1; c <= E::PMASK; c++) {
bool hit = false;
for_each_preimage<E>(
goal, i, c, [&](const key &p) {
if (tab.find(p) != nullptr) {
r.program = path_to(p, int(ii));
r.found = true;
r.proven_optimal = true;
hit = true;
return true;
}
return false;
});
if (hit)
return finish();
}
}
// the backward step has covered this length already
if (d == opt.max_depth)
break;
}
// ---- expand the BFS by one layer ----
std::vector<key> next;
next.reserve(frontier.size());
for (const auto &k : frontier) {
for (uint16_t ii = 0; ii < insns.size(); ii++) {
if (E::cond(k, insns[ii]) == 0)
continue; // nothing to sacrifice, the block would do nothing
key n = E::step(k, insns[ii]);
if (n == goal) {
r.program = path_to(k, int(ii));
r.found = true;
r.proven_optimal = true;
r.states = tab.used;
r.depth_reached = d;
return finish();
}
if (tab.insert(n, k, ii))
next.push_back(n);
}
if (tab.used > opt.max_states) {
r.message = "state budget exhausted: the search is not complete";
r.states = tab.used;
r.depth_reached = d;
return finish();
}
}
r.states = tab.used;
r.depth_reached = d;
if (opt.verbose)
std::cout << " depth " << d << ": " << next.size() << " new, "
<< tab.used << " kept\n";
frontier.swap(next);
}
r.proven_optimal = (r.message.empty());
if (r.message.empty())
r.message = "no program of length <= " + std::to_string(opt.max_depth);
return finish();
}
// Calls f on every preimage of `post` under `ins` with condition `c`.
// XOR destinations are forced, OR destinations are free on the bits of c
// they contain, so walk the destinations and branch where needed.
template <class E, class F>
static bool for_each_preimage(const typename E::key &post,
const instruction &ins, uint64_t c, F &&f) {
using key = typename E::key;
key pre = post;
E::put(pre, ins.sacrifice, c);
return preimage_walk<E>(post, ins, c, pre, 0, f);
}
template <class E, class F>
static bool preimage_walk(const typename E::key &post,
const instruction &ins, uint64_t c,
typename E::key pre, int b, F &f) {
using key = typename E::key;
for (; b < CELL_SIZE; b++)
if (ins.mask & (1 << b))
break;
if (b == CELL_SIZE)
return f(pre);
const uint64_t T = E::get(post, b);
if (!ins.or_mode) {
E::put(pre, b, T ^ c);
return preimage_walk<E>(post, ins, c, pre, b + 1, f);
}
if ((T & c) != c)
return false; // a destination bit can only be set, not cleared
const uint64_t fixed = T & ~c, free = T & c;
for (uint64_t sub = free;; sub = (sub - 1) & free) {
E::put(pre, b, fixed | sub);
if (preimage_walk<E>(post, ins, c, pre, b + 1, f))
return true;
if (sub == 0)
break;
}
return false;
}
// ---------------------------------------------------------------- syntax
std::vector<instruction> build_instructions() const {
std::vector<instruction> out;
out.reserve(CELL_SIZE * (2 * (1 << (CELL_SIZE - 1)) + 1));
for (int s = 0; s < CELL_SIZE; s++) {
out.push_back({uint8_t(s), 0, false}); // pure sacrifice: clear plane s
for (int sub = 1; sub < (1 << (CELL_SIZE - 1)); sub++) {
uint8_t m = 0;
int bit = 0;
for (int b = 0; b < CELL_SIZE; b++)
if (b != s)
m |= uint8_t(((sub >> bit++) & 1) << b);
out.push_back({uint8_t(s), m, false});
out.push_back({uint8_t(s), m, true});
}
}
return out;
}
};
#endif
+791
View File
@@ -0,0 +1,791 @@
#include "r8forge/r8asm.hh"
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#define EMPTY_CHARS (" \t\n\r\f\v")
#define OPERATORS ("+-*/^~\"()&|")
namespace r8asm_strtools {
bool is_integer(const std::string &str) {
return !str.empty() &&
std::ranges::all_of(str, [](char c) { return c >= '0' && c <= '9'; });
}
void trim(std::string &str) { // Clean empty chars in the string.
auto start = str.find_first_not_of(EMPTY_CHARS);
if (!(start ==
std::string::npos)) { // The string isn't filled with empty chars.
auto tmp_end = str.find_last_not_of(EMPTY_CHARS);
str = str.substr(start, tmp_end - start + 1);
} else
str = "";
}
std::string peel(std::string &str) { // Peel the first word from string.
for (size_t i = 1; i < str.size();
i++) { // insert space before and after operators appear
if (std::string(OPERATORS).find(str[i]) != std::string::npos) {
if (str[i - 1] != ' ') {
str = str.substr(0, i) + ' ' + str.substr(i, str.size());
i++;
}
if (str[i + 1] != ' ') {
str = str.substr(0, i + 1) + ' ' + str.substr(i + 1, str.size());
}
}
}
trim(str);
auto end = str.find_first_of(EMPTY_CHARS);
if (end != std::string::npos) {
std::string tmp_str = str.substr(0, end);
str = str.substr(end);
trim(str);
return (tmp_str);
} else {
std::string tmp_str = str;
str = "";
return (tmp_str);
}
}
} // namespace r8asm_strtools
#undef EMPTY_CHARS
#undef OPERATORS
void r8asm::ast::set_cell_size(size_t cell_size) {
CELL_SIZE = cell_size;
scopes = {{{"_CELL_SIZE", static_cast<general_data>(cell_size)},
{"_CELL_MAX", static_cast<general_data>((1 << cell_size) - 1)},
{"_ROL_STEP", static_cast<general_data>(cell_size - 1)}}};
}
r8asm::general_data r8asm::ast::expand_node_to_data(const ast_node &node) {
general_data to_return = 0;
switch (node.type) {
case ast_node_t::CONSTANT:
to_return = std::stoi(node.value);
break;
case ast_node_t::PARAMETER:
to_return = scopes.back().at('%' + node.value);
break;
case ast_node_t::VARIABLE: {
bool found = false;
for (auto i = scopes.rbegin(); i != scopes.rend(); i++) {
auto tmp = i->find(node.value);
if (tmp != i->end()) {
to_return = tmp->second;
found = true;
break;
}
}
if (!found && reported.insert(node.value).second)
fail("unknown name '" + node.value + "'");
} break;
case ast_node_t::OPERATOR: {
switch (operator_map.at(node.value)) {
case operator_t::ADD:
to_return = expand_node_to_data(node.children[0]) +
expand_node_to_data(node.children[1]);
break;
case operator_t::SUB:
to_return = expand_node_to_data(node.children[0]) -
expand_node_to_data(node.children[1]);
break;
case operator_t::MUL:
to_return = expand_node_to_data(node.children[0]) *
expand_node_to_data(node.children[1]);
break;
case operator_t::DIV:
to_return = expand_node_to_data(node.children[0]) /
expand_node_to_data(node.children[1]);
break;
case operator_t::XOR:
to_return = expand_node_to_data(node.children[0]) ^
expand_node_to_data(node.children[1]);
break;
case operator_t::AND:
to_return = expand_node_to_data(node.children[0]) &
expand_node_to_data(node.children[1]);
break;
case operator_t::OR:
to_return = expand_node_to_data(node.children[0]) |
expand_node_to_data(node.children[1]);
break;
case operator_t::NOT:
to_return = ~expand_node_to_data(node.children[0]);
break;
default:;
break;
}
break;
};
default:
std::cerr << "ERROR: THIS NODE SHOULD NOT BE EXPANDED TO DATA!!!"
<< std::endl;
break;
}
return to_return;
}
std::string r8asm::ast::expand_node_to_string(const ast_node &node) {
return node.value;
}
#define EMPTY_CODEBLOCK \
{ \
r8asm::ast_node_t::CODEBLOCK, "", {} \
}
// TODO: FILL THE BLANK
#define ROT8_NODE(INS) \
{ \
r8asm::ast_node_t::ROT8, std::string("rot8_") + INS, {} \
}
r8asm::ast_node r8asm::ast::expand_node_to_ins(const ast_node &node) {
ast_node to_return = EMPTY_CODEBLOCK;
switch (node.type) {
case ast_node_t::ROT8: {
/*
ROT8
value: rot8_ins
*/
to_return.children = {node};
switch (rot8_map.at(node.value)) {
case rot8_t::STP:
dataptr++;
break;
case rot8_t::BTP:
dataptr--;
break;
default:
break;
}
} break;
case ast_node_t::REPEAT: {
/*
REPEAT
children[0]: count
children[1]: codeblock
*/
for (data count = expand_node_to_data(node.children[0]); count > 0; count--)
for (const auto &i : expand_node_to_ins(node.children[1]).children)
to_return.children.push_back(i);
} break;
case ast_node_t::MACROCALL: {
/*
MACROCALL
value: macro_name
children: arguments
*/
std::map<std::string, general_data> tmp_scope = {};
for (auto i = 0; i < node.children.size(); i++)
tmp_scope.insert_or_assign('%' + std::to_string(i + 1),
// %1 in macro means children[0]
expand_node_to_data(node.children[i]));
scopes.push_back(tmp_scope);
if (macros.find(node.value) == macros.end())
fail("unknown macro '" + node.value + "'");
else
for (const auto &it : expand_node_to_ins(macros.at(node.value)).children)
to_return.children.push_back(it);
scopes.pop_back();
} break;
case ast_node_t::CODEBLOCK: {
/*
CODEBLOCK
children: ins
*/
for (const auto &i : node.children)
for (const auto &ins : expand_node_to_ins(i).children)
to_return.children.push_back(ins);
} break;
case ast_node_t::BUILTIN: {
/*
BUILTIN
value: type
children: args
*/
if (builtin_map.find(node.value) == builtin_map.end()) {
fail("unknown builtin '." +
node.value.substr(std::string("builtin_").size()) + "'");
return to_return;
}
switch (builtin_map.at(node.value)) {
// WARNING: node.value HAS BEEN USED!!! DO NOT CONSUME IT AGAIN!!!
case builtin_t::ANCHOR: {
/*
ANCHOR
children[0]: var_name
*/
scopes.back().insert_or_assign(expand_node_to_string(node.children[0]),
dataptr);
} break;
case builtin_t::TP: {
/*
TP
children[0]: destination
*/
addr destination = expand_node_to_data(node.children[0]);
if (destination > dataptr)
for (addr i = 0; i < destination - dataptr; i++)
to_return.children.push_back(ROT8_NODE("stp"));
else
for (addr i = 0; i < dataptr - destination; i++)
to_return.children.push_back(ROT8_NODE("btp"));
dataptr = destination;
// stp or btp might be created
// so dataptr must be updated at the same time.
} break;
case builtin_t::XOR: {
/*
XOR
children[0]: argument
WARNING: argument bigger than ((1<<CELL_SIZE)-1) will be cut off
e.g.
children[0] -> 5(0b101)
when define CELL_SIZE 2, only the last 2 bit will be noticed,
and 5 means 0b01(1) here.
then the node will be expanded like this:
flb
ror
ror
*/
data d = expand_node_to_data(node.children[0]);
for (auto i = 0; i < scopes[0].at("_CELL_SIZE"); i++) {
if (d & 1)
to_return.children.push_back(ROT8_NODE("flb"));
to_return.children.push_back(ROT8_NODE("ror"));
d >>= 1;
}
} break;
case builtin_t::LOOP: {
to_return.children.push_back(ROT8_NODE("stp"));
to_return.children.push_back(ROT8_NODE("biz"));
to_return.children.push_back(ROT8_NODE("btp"));
// >[<
} break;
case builtin_t::ENDLOOP: {
// Consume one '1' from the auxiliary cell and pull the next bit down.
// Without the ror, the rnz could only ever see the bit that flb just
// cleared, so a .loop over 0b111 ran once instead of three times
// (SPEC: "consecutive 1s starting from the LSB").
to_return.children.push_back(ROT8_NODE("stp"));
to_return.children.push_back(ROT8_NODE("flb"));
to_return.children.push_back(ROT8_NODE("ror"));
to_return.children.push_back(ROT8_NODE("rnz"));
to_return.children.push_back(ROT8_NODE("btp"));
// >-+]<
} break;
case builtin_t::VAR: {
/*
VAR
children[0]: var_name
children[1]: var_value
*/
scopes.back().insert_or_assign(expand_node_to_string(node.children[0]),
expand_node_to_data(node.children[1]));
} break;
default:
break;
};
} break;
default:;
break;
}
return to_return;
}
#undef ROT8_NODE
#define ROT8_BC_TO_CHAR(bc) ("><+-[].,"[static_cast<int>(bc)])
std::string r8asm::ast::expand_root() {
auto rot8_ins = expand_node_to_ins(root);
std::string rot8_tape = "";
for (const auto &i : rot8_ins.children)
rot8_tape += ROT8_BC_TO_CHAR(rot8_map.at(i.value));
return rot8_tape;
}
#undef ROT8_BC_TO_CHAR
std::string r8asm::export_rot8() { return main_tree.expand_root(); }
bool r8asm::ast::import_macro(const std::string &macro_name,
const ast_node &node) {
return macros.insert_or_assign(macro_name, node).second;
}
#define POINTS_AT_DIRECTIVE(iter, TYPE) \
(iter->tokens[0].type == token_t::DIRECTIVE && \
directive_keywords.at(iter->tokens[0].value) == directive_t::TYPE)
r8asm::ast_node r8asm::parse(const token_stream &stream) {
ast_node to_return = EMPTY_CODEBLOCK;
token_stream tmp_codeblock_stream = {stream.filename};
/*
ast_node tmp_codeblock_node;
std::vector<ast_node> *destination = &to_return.children;
std::vector<ast_node> *last_destination = nullptr;*/
for (auto it = stream.lines.begin(); it < stream.lines.end(); it++) {
switch (it->tokens[0].type) {
case token_t::DIRECTIVE: {
/*
directive will be tokenized like this:
macro raw_add
0 1
or:
macro raw_add 2 + 4
0 1 2 3 4
(though [2] [3] [4] won't be used)
if it's a rep block:
rep 1 + 1
0 1 2 3
if it's a include line:
include filename
0 1
*/
if (directive_keywords.find(it->tokens[0].value) ==
directive_keywords.end()) {
main_tree.fail("unknown directive '%" + it->tokens[0].value + "'");
break;
}
switch (directive_keywords.at(it->tokens[0].value)) {
// match an entire operation (not a cut for arguments) first
case directive_t::MACRO: {
std::string macro_name = it->tokens[1].value;
tmp_codeblock_stream.lines = {};
depth_t layer = 0;
// now it points at %macro line
for (it += 1; !(POINTS_AT_DIRECTIVE(it, ENDMACRO) && (layer == 0));
it++) {
if (POINTS_AT_DIRECTIVE(it, MACRO))
layer++;
else if (POINTS_AT_DIRECTIVE(it, ENDMACRO))
layer--;
tmp_codeblock_stream.lines.push_back(*it);
}
// now it points at %endmacro line
main_tree.import_macro(macro_name, parse(tmp_codeblock_stream));
} break;
case directive_t::REP: {
// build subtree for argument of rep
token_line buffer = {it->number, {}};
for (auto token_it = it->tokens.begin() + 1; // where argument begins
token_it < it->tokens.end(); token_it++)
buffer.tokens.push_back(*token_it);
/*
REPEAT
children[0]: count
children[1]: codeblock
*/
to_return.children.push_back({r8asm::ast_node_t::REPEAT, "", {}});
to_return.children.back().children.push_back(
parse_single_arg(buffer)); // count will be pushed here.
tmp_codeblock_stream.lines = {};
depth_t layer = 0;
// now it points at %rep line
for (it += 1; !(POINTS_AT_DIRECTIVE(it, ENDREP) && (layer == 0));
it++) {
if (POINTS_AT_DIRECTIVE(it, REP))
layer++;
else if (POINTS_AT_DIRECTIVE(it, ENDREP))
layer--;
tmp_codeblock_stream.lines.push_back(*it);
}
// now it points at %endrep line
to_return.children.back().children.push_back(
parse(tmp_codeblock_stream)); // codeblock will be pushed here.
} break;
case directive_t::INCLUDE: {
std::string filename = "";
auto tp = it->tokens.begin() + 1;
// now tp points at the LQUOTE
for (tp += 1; tp->type != token_t::RQUOTE; tp++)
filename += tp->value;
// now tp points at RQUOTE
import_file(filename, main_tree.CELL_SIZE);
// import_file has already said why if it failed; the error flag is
// set, so this file will not be reported as assembled.
} break;
case directive_t::SYNTH: {
// %synth <name>
// params <n>
// in %1 %2 %3
// out %4 %5
// map <2^|in| numbers>
// %endsynth
const std::string name = it->tokens[1].value;
ast::synth_spec spec;
depth_t layer = 0;
for (it += 1; !(POINTS_AT_DIRECTIVE(it, ENDSYNTH) && layer == 0); it++) {
if (POINTS_AT_DIRECTIVE(it, SYNTH))
layer++;
else if (POINTS_AT_DIRECTIVE(it, ENDSYNTH))
layer--;
if (it->tokens.empty())
continue;
const std::string &kw = it->tokens[0].value;
if (kw == "params") {
spec.params = std::stoi(it->tokens[1].value);
} else if (kw == "inputs" || kw == "outputs") {
std::vector<int> &dst = (kw == "inputs") ? spec.in : spec.out;
for (size_t i = 1; i < it->tokens.size(); i++)
dst.push_back(std::stoi(it->tokens[i].value) - 1);
} else if (kw == "map") {
for (size_t i = 1; i < it->tokens.size(); i++)
spec.map.push_back(std::stoi(it->tokens[i].value));
} else {
main_tree.fail("unknown line '" + kw + "' inside %synth");
}
}
auto prog = r8asm_synth_program(spec.params, spec.in, spec.out,
spec.map, name);
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";
for (const auto &i : prog) {
std::cerr << "\t.tp %" << i[0] + 1 << "\n\tbiz\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";
}
}
} break;
default:
break;
}
} break;
case token_t::BUILTIN: {
/*
BUILTIN
value: type
children: args
*/
/* like this:
builtin_var pos1 15
0 1 2
*/
to_return.children.push_back(
{r8asm::ast_node_t::BUILTIN, it->tokens[0].value, {}});
// build subtree for argument(s) of builtin
token_line buffer = {it->number, {}};
for (auto token_it = it->tokens.begin() + 1; // where argument begins
token_it < it->tokens.end(); token_it++)
buffer.tokens.push_back(*token_it);
auto args = parse_args(buffer).children;
for (const auto &arg_it : args)
to_return.children.back().children.push_back(
arg_it); // though all string args are treated as VARIABLE, I guess
// builtin_var will read children[0].value successfully.
} break;
case token_t::MACROCALL: {
/* like this:
raw_add 2 4 4 + 2 ( 4 + 4 ) pos1 pos1 + 2
0 1 ...
*/
to_return.children.push_back(
{r8asm::ast_node_t::MACROCALL, it->tokens[0].value, {}});
// build subtree for argument(s) of macro
token_line buffer = {it->number, {}};
for (auto token_it = it->tokens.begin() + 1; // where argument begins
token_it < it->tokens.end(); token_it++)
buffer.tokens.push_back(*token_it);
/*
MACROCALL
value: macro_name
children: arguments
*/
auto args = parse_args(buffer).children;
for (const auto &arg_it : args)
to_return.children.back().children.push_back(arg_it);
} break;
case token_t::ROT8: {
to_return.children.push_back(
{r8asm::ast_node_t::ROT8, it->tokens[0].value, {}});
} break;
default:
break;
}
}
return to_return;
}
#undef POINTS_AT_DIRECTIVE
#define UNRELATED_TO_LEFT(present_token) \
(it != line.tokens.begin() && \
((present_token->type == token_t::LPAREN || \
present_token->type == token_t::STRING || \
present_token->type == token_t::PARAMETER || \
(present_token->type == token_t::OPERATOR && \
(present_token->value == "op_neg" || \
present_token->value == "op_not"))) && \
(!((present_token - 1)->type == token_t::OPERATOR || \
(present_token - 1)->type == token_t::LPAREN))))
r8asm::ast_node r8asm::parse_args(const token_line &line) {
ast_node to_return = EMPTY_CODEBLOCK;
// arguments will be storaged in to_return.children
std::vector<token_line> raw_args;
std::list<token> buffer;
for (auto it = line.tokens.begin(); it != line.tokens.end(); it++) {
if (UNRELATED_TO_LEFT(it)) {
raw_args.push_back({line.number, {}});
while (!buffer.empty()) {
raw_args.back().tokens.push_back(buffer.front());
buffer.pop_front();
}
}
buffer.push_back(*it);
}
if (!buffer.empty()) {
raw_args.push_back({line.number, {}});
while (!buffer.empty()) {
raw_args.back().tokens.push_back(buffer.front());
buffer.pop_front();
}
}
for (const auto &it : raw_args)
to_return.children.push_back(parse_single_arg(it));
return to_return;
}
#undef UNRELATED_TO_LEFT
r8asm::ast_node r8asm::parse_single_arg(const token_line &line) {
ast_node to_return;
std::stack<ast_node> data_stack;
std::stack<ast_node> symbol_stack;
depth_t right_assoc_depth = 0;
auto deal_with_assoc = [&data_stack, &symbol_stack, &right_assoc_depth] {
while (right_assoc_depth) {
auto unary_op = symbol_stack.top();
symbol_stack.pop();
unary_op.children.push_back(data_stack.top());
data_stack.pop();
data_stack.push(unary_op);
right_assoc_depth--;
}
};
for (auto it = line.tokens.begin(); it < line.tokens.end(); it++) {
switch (it->type) {
case token_t::LPAREN: {
depth_t layer = 0;
token_line buffer = {line.number, {}};
for (it += 1; !((it->type == token_t::RPAREN) && (layer == 0)); it++) {
if (it->type == token_t::LPAREN)
layer++;
else if (it->type == token_t::RPAREN)
layer--;
buffer.tokens.push_back(*it);
}
data_stack.push(parse_single_arg(buffer));
deal_with_assoc();
} break;
case token_t::STRING: {
{
if (r8asm_strtools::is_integer(it->value))
data_stack.push({r8asm::ast_node_t::CONSTANT, it->value, {}});
else
data_stack.push({r8asm::ast_node_t::VARIABLE, it->value, {}});
}
deal_with_assoc();
} break;
case token_t::PARAMETER: {
data_stack.push({r8asm::ast_node_t::PARAMETER, (it->value), {}});
deal_with_assoc();
} break;
case token_t::OPERATOR:
// precedence: NEG = NOT
// > MUL = DIV
// > ADD = SUB
// > AND
// > XOR
// > OR
{
#define GET_PRECEDENCE(op_key) \
(main_tree.op_precedence_map.at(main_tree.operator_map.at(op_key)))
switch (main_tree.operator_map.at(it->value)) {
case ast::operator_t::NOT: // unary operators
{
right_assoc_depth++;
symbol_stack.push({ast_node_t::OPERATOR, it->value, {}});
} break;
default: // now all of them are binary operators
{
while ((!symbol_stack.empty()) &&
GET_PRECEDENCE(it->value) >=
GET_PRECEDENCE(symbol_stack.top().value))
// e.g. pushing + while here's already a * in symbol_stack
{
auto tmp_op = symbol_stack.top();
symbol_stack.pop();
auto tmp_arg = data_stack.top(); // 2nd arg got
data_stack.pop();
tmp_op.children.push_back(data_stack.top()); // 1st arg pushed
data_stack.pop();
tmp_op.children.push_back(tmp_arg);
data_stack.push(tmp_op);
}
symbol_stack.push({ast_node_t::OPERATOR, it->value, {}});
} break;
}
}
#undef GET_PRECEDENCE
default:
break;
}
}
while (!symbol_stack.empty()) {
auto tmp_op = symbol_stack.top();
symbol_stack.pop();
auto tmp_arg = data_stack.top(); // 2nd arg got
data_stack.pop();
tmp_op.children.push_back(data_stack.top()); // 1st arg pushed
data_stack.pop();
tmp_op.children.push_back(tmp_arg);
data_stack.push(tmp_op);
}
to_return = data_stack.top();
return to_return;
}
#undef EMPTY_CODEBLOCK
#define OPERATORS ("+-*/^~&|")
std::vector<r8asm::token_line>
r8asm::token_stream::lex(const std::string &char_stream) {
std::vector<token_line> to_return;
std::istringstream iss(char_stream);
std::string str_buffer;
line_number num = 0;
bool next_will_be_remark = false;
const std::map<std::string, std::string> operator_map = {
// without "-"
{"+", "op_add"}, {"*", "op_mul"}, {"/", "op_div"}, {"^", "op_xor"},
{"&", "op_and"}, {"|", "op_or"}, {"~", "op_not"}, {"-", "op_sub"},
};
while (std::getline(iss, str_buffer)) {
std::vector<token> token_buffer = {};
bool start_of_line = true;
bool lquote_appeared = false;
for (std::string token_val = r8asm_strtools::peel(str_buffer);
token_val != ""; token_val = r8asm_strtools::peel(str_buffer)) {
if (lquote_appeared && token_val[0] != '\"')
token_buffer.push_back({r8asm::token_t::STRING, token_val});
else {
if (start_of_line) { // it's the first token in the line
start_of_line = false;
if (token_val[0] == '.') // builtin
token_buffer.push_back(
{r8asm::token_t::BUILTIN, "builtin_" + token_val.substr(1)});
// e.g. .var -> builtin_var
else if (token_val[0] == '%') // directive
token_buffer.push_back(
{r8asm::token_t::DIRECTIVE, token_val.substr(1)});
// e.g. %macro -> macro
else if (token_val[0] == ';') // remark
next_will_be_remark = true;
else if (raw_rot8_ins.find(token_val) != raw_rot8_ins.end()) // rot8
token_buffer.push_back({r8asm::token_t::ROT8, "rot8_" + token_val});
else // macro
token_buffer.push_back({r8asm::token_t::MACROCALL, token_val});
} else { // it's a part of argument
if (!next_will_be_remark) {
if (token_val[0] == ';') // remark
next_will_be_remark = true;
else if (token_val[0] == '%') // parameter
token_buffer.push_back(
{r8asm::token_t::PARAMETER, token_val.substr(1)});
else if (token_val[0] == '"') { // quote(filename)
if (!lquote_appeared) {
lquote_appeared = true; // only %include will use quotes, they
// won't appear again
token_buffer.push_back({r8asm::token_t::LQUOTE, token_val});
} else
token_buffer.push_back({r8asm::token_t::RQUOTE, token_val});
} else if (token_val[0] == '(')
token_buffer.push_back({r8asm::token_t::LPAREN, token_val});
else if (token_val[0] == ')')
token_buffer.push_back({r8asm::token_t::RPAREN, token_val});
else if (std::string(OPERATORS).find(token_val[0]) !=
std::string::npos) // operator
token_buffer.push_back(
{r8asm::token_t::OPERATOR, operator_map.at(token_val)});
else
token_buffer.push_back({r8asm::token_t::STRING, token_val});
}
}
}
}
num++;
if (!token_buffer.empty())
to_return.push_back({num, token_buffer});
next_will_be_remark = false;
}
return to_return;
}
#undef OPERATORS
bool r8asm::import_file(const std::string &filename, size_t cell_size) {
token_stream stream(filename);
if (!stream.ok) {
main_tree.fail("cannot open '" + filename + "'");
return (false);
}
// Before parsing: %include asks main_tree.CELL_SIZE for the width to hand
// to the included file, and that used to answer 0 because the size was
// only set at the end of this function.
main_tree.set_cell_size(cell_size);
for (const auto &token_it : parse(stream).children) {
main_tree.root.children.push_back(token_it);
}
return (!main_tree.error);
}
+92
View File
@@ -0,0 +1,92 @@
#include "r8forge/r8asm.hh"
// ---------------------------------------------------------------- %synth
//
// A synth block is a macro whose body the assembler synthesises. The search
// runs once while the file is parsed; the resulting block sequence becomes
// ordinary macro body lines with %1..%n parameter references, so everything
// after that goes through the normal, well tested macro expansion.
template <int P>
std::vector<std::array<int, 3>>
r8asm_synth_run(const std::vector<int> &in, const std::vector<int> &out,
const std::vector<int> &map, const std::string &name) {
using V = r8veritas<P>;
V v;
v.initialize_nicknames();
v.initialize_tp_paths();
// the input cells are the low parameters, so the stat index already is the
// input combination
const size_t n = size_t(1) << P;
const unsigned in_mask = (1u << in.size()) - 1u;
typename V::stat start{}, target{};
for (size_t i = 0; i < n; i++) {
const unsigned c = unsigned(i) & in_mask;
start[i] = typename V::cell(i);
unsigned val = c; // input cells keep their value
for (size_t k = 0; k < out.size(); k++)
if ((unsigned(map[c]) >> k) & 1u)
val |= 1u << out[k];
target[i] = typename V::cell(val);
}
auto tt = v.make_truthtable(start, target);
typename V::options opt;
opt.max_depth = 5;
const auto res = v.solve(tt, opt);
std::cerr << "r8asm: %synth " << name << ": ";
if (!res.found) {
std::cerr << "no program up to " << opt.max_depth << " layers\n";
return {};
}
std::cerr << res.program.size() << " layers"
<< (res.proven_optimal ? " (shortest)" : "") << ", " << res.states
<< " states, " << res.seconds << "s\n";
std::vector<std::array<int, 3>> out_ins;
for (const auto &i : res.program)
out_ins.push_back({int(i.sacrifice), int(i.mask), int(i.or_mode)});
return out_ins;
}
std::vector<std::array<int, 3>>
r8asm_synth_program(int params, const std::vector<int> &in,
const std::vector<int> &out, const std::vector<int> &map,
const std::string &name) {
if (params < 1 || params > 8) {
std::cerr << "r8asm: %synth " << name << ": supports 1..8 parameters\n";
return {};
}
if (in.empty() || map.size() != (size_t(1) << in.size())) {
std::cerr << "r8asm: %synth " << name
<< ": map must have 2^inputs entries\n";
return {};
}
for (size_t i = 0; i < in.size(); i++)
if (in[i] != int(i)) {
std::cerr << "r8asm: %synth " << name << ": input %" << i + 1
<< " must be %" << i + 1 << " (inputs come first)\n";
return {};
}
switch (params) {
case 1:
return r8asm_synth_run<1>(in, out, map, name);
case 2:
return r8asm_synth_run<2>(in, out, map, name);
case 3:
return r8asm_synth_run<3>(in, out, map, name);
case 4:
return r8asm_synth_run<4>(in, out, map, name);
case 5:
return r8asm_synth_run<5>(in, out, map, name);
case 6:
return r8asm_synth_run<6>(in, out, map, name);
case 7:
return r8asm_synth_run<7>(in, out, map, name);
default:
return r8asm_synth_run<8>(in, out, map, name);
}
}
+18
View File
@@ -0,0 +1,18 @@
#include "r8forge/r8asm.hh"
#include <iostream>
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "usage: r8asm_test <file.r8asm>" << std::endl;
return (2);
}
r8asm a;
if (!a.import_file(argv[1], 8))
return (1);
std::string tape = a.export_rot8();
if (a.failed())
return (1);
std::cout << tape;
return (0);
}