Files
R8Forge/docs/calc.md
T
dsh b2ba20b885 vms: raise the step cap from 5M to 20M
5 million steps was picked when the worst macro (clb_add_ip with B=2047) sat just
under a million, so it caught hangs quickly.  The interactive programs changed the
arithmetic: one printed line of the desk calculator costs about 225k steps (40k
for clb_undigits, up to 32k for the operation, ~141k for clb_digits), which is only
about twenty lines before the cap, and examples_test applies the same cap to every
example.

At roughly 2.3e8 steps per second a 20M cap costs 0.09 s when a program really does
run away, and byte_op_test (the only place that runs 465k programs) is unchanged --
so the safety net stays cheap while a session gets four times the room.

docs/calc.md, docs/divmod.md, docs/byte-ops.md and SPEC's "500 ?" mentions now say
2000 ?.
2026-11-11 11:04:14 +08:00

3.9 KiB
Raw Blame History

桌上计算器(RPN)设计与分阶段计划

目标:examples/calc.r8asm —— 一条长驻的纸带,跑了就是一个计算器:

> 12 34 + .
46
> 2047 3 / .
682
> ,

条件已经齐了:inp 在三份 VM 里都有实现、tape_run/derive 能用 -i 喂输入、例程头部能写 ; in(examples_test 会把那串字符交给 inp)。

1. 命令协议

输入 动作
'0'..'9' 攒进 4 位数字缓冲(遇到终止符一次性 clb_undigits 换成整数,压栈)
'*' '+' '-' '/' 弹两个、算、压回
'.' 打印栈顶(clb_digits + 4 个 output)
',' 清栈
其它(空格/回车) 忽略(作为数字的终止符)
0(EOF) erase 掉循环计数器,主循环结束,纸带自然跑完

六个命令字符 * + , - . / 正好是 0x2A..0x2F 连续,数字是 0x30..0x39,所以:

t = C - 0x2A                     ; 命令: 0..5  数字: 6..15
数字  <=> C 的 bit4 == 1         ; 一次 ror×4 + biz
命令号 = t                       ; 0=* 1=+ 2=, 3=- 4=. 5=/

2. 内存地图

cell 用途
0 C:当前字符
1 T:分派/临时
2..3 A、B:运算操作数
4 HAVE:栈里有没有数(0/1)
5 CNT:主循环计数器(开机造 W 个 1)
6..9 数字缓冲 D0..D3(ASCII,右对齐)
10..12 栈指针之外的栈深度标志?——v1 固定 4 深,见 §4
16..26 库草稿(mul/divmod/digits/undigits 的 S)
32..43 常量区(开机造一次):TEN(10)、'0'(48)、11 个 1、2047、~10

3. 分阶段计划(每步都能单点验证)

每个驱动都放在 drv/,用 r8forge_derive drv/<名字>.r8asm 0 -i "..." 跑,; out 逐项核对。

  1. drv/calc_lex.r8asm:只做分派。喂 "0 5 9 + - . , *",输出"这是数字(d) / 这是命令(k)"。 验证点:bit4 判断 + t 的取值范围。
  2. drv/calc_num.r8asm:"12"+终止符 → 整数 12(4 位缓冲右移 + clb_undigits)。 验证点:"0" "9" "10" "2047" 四个输入。
  3. drv/calc_disp.r8asm:整数 → > 提示符 + 4 位 ASCII + 换行。
  4. drv/calc_op.r8asm:12 34 + → 46(+ - * / 各一次)。
  5. examples/calc.r8asm:主循环 + EOF 退出 + ; in/; out 头部,进 examples_test。

4. 栈:v1 固定 4 深,不用指针

.tp 是汇编期常量,没有间接寻址,所以不要做动态栈指针。v1 就用 4 个固定格 S0..S3: 压栈 = 整体往高地址挪一格(copy 从高到低,3 格),弹栈 = 反向。深度超过 4 就不管 (压第 5 个覆盖最底下的,像老式计算器)。

代价:每次压/弹 3 个 copy ≈ 1.5k 字符纸带 + 每字符几百步。如果觉得贵,v0 可以只做两格 (A、B),先把 12+34= 跑通,再加栈。

5. 步数预算(按 11 位实测的每例代价)

动作 步数
攒一个数(clb_undigits) ≤ 36,481
+/-(clb_add_nc/clb_sub_nc) ~2.5k
*(clb_mul) ≤ 20,300
/(clb_divmod) ~28,600
打印(clb_digits) ≤ 164,867

一行 12 34 + . ≈ 36k×2 + 2.5k + 165k ≈ 240k 步。examples_test 的上限是 2000 万步, 所以会话控制在 10 行左右(或把打印换成"里程表"版本,见下)。

6. 已知的坑(都在库里踩过)

  • 条件体的身体必须回到自己的条件格(净位移 0),否则 .tp 全错位;
  • copy 的缓冲格必须干净(脏了结果是 0);
  • 用 loop/endloop 计数器时,erase 计数器就能提前退出(EOF 就这么退);
  • 库宏每轮都重建 TEN 和轮数计数器 —— 这个终端的常量区(cell 32..43)就是为了把这些 搬到循环外,v2 再让 clb_undigits/clb_digits 支持"外部常量"版本。