clb_ones turns a count into that many ones, and these two macros spend those ones
one per iteration, so a tape can loop a number of times that only exists at run
time:
clb_ones N C T F
loop C
... body ...
endloop C
\loop c\ is .tp c + biz + set_0 + ror: test the low bit, spend it, rotate the
next one into place. \endloop c\ is .tp c + rnz. No .anchor is used, so the
pair nests, and endloop puts dp back on the counter whatever the body did with
it; the body must not touch c, and c is all zeros once the loop is over.
Checked with verify_loop.r8asm (939 characters): N = 0..11 makes the body run
exactly N times, A = N and C = 0 -- including N = 0, where biz skips the body
entirely. Nesting checked too: an inner loop rebuilt from a copy of its count
gives NO * MI (11 * 11 = 121, and 0 when either count is 0).
One trap found on the way, written into SPEC 5.1: in .r8asm source a loop is
spelled biz/rnz, not [ / ] -- the brackets are the tape encoding, and writing
them makes the assembler say " unknown macro [ \.
29 lines
977 B
Plaintext
29 lines
977 B
Plaintext
%include "asm/ones.r8asm"
|
|
|
|
; 动态循环:循环次数是**运行期**才知道的值,不是汇编期常数。
|
|
;
|
|
; 0 号 cell 放次数 N(`r8forge_derive ... -1 0=N` 给),clb_ones 把它变成 N 个 1
|
|
; 的计数器 C,然后 loop/endloop 按 C 里 1 的个数跑 —— 每轮吃掉一个 1。
|
|
; 循环体每轮给 A 加一,所以跑完 A = N、C = 0。
|
|
;
|
|
; r8forge_derive verify_loop.r8asm -1 0=5 # out 应该是 5 0
|
|
; r8forge_derive verify_loop.r8asm -1 0=0 # out 应该是 0 0(一圈都不跑)
|
|
; r8forge_derive verify_loop.r8asm -1 0=11 # out 应该是 11 0
|
|
;
|
|
; 注意这里的"11 次"跟 `%rep 11` 的区别:那个在汇编期就定死了,这个能由前面
|
|
; 算出来的数据决定 —— 比如"乘以 MUL 的位数""输入字符串多长"这种。
|
|
.var N 0
|
|
.var C 1
|
|
.var T 2
|
|
.var F 3
|
|
.var A 4
|
|
|
|
clb_ones N C T F ; C = N 个 1
|
|
|
|
loop C
|
|
clb_inc_ip A T ; 每轮干一点活;这里就是 A += 1
|
|
endloop C
|
|
|
|
output A
|
|
output C
|