New macro in asm/ones.r8asm: clb_ones A B T F leaves B = 2^A - 1, i.e. A
consecutive ones starting at the low bit, and eats A (it is spent as the
counter). The contract only holds for A <= _CELL_SIZE and is not checked, as
asked: 0 -> 0, 1 -> 1, 4 -> 0x0F, 7 -> 0x7F, 11 -> 0x7FF (all ones).
The loop is "shift and stuff a one in":
B = 0
while A != 0: B = 2B + 1 ; A -= 1
In this machine `2B + 1` is exactly `rol` + `set_1`: the left rotation brings
B's top bit round to the low bit and set_1 overwrites it. A is spent as the
counter instead of being copied (a copy is 495 characters), the loop body
appears once so the length does not depend on A, and the run time is O(A) with
A <= cell size.
The other sizing option was measured and rejected: start from 1, rotate A
times, then clb_dec_ip once. That drops set_1 from the body but pays 132
characters for the decrement and 44 for the erase, so it comes out 128 longer.
* tests/byte_op_test.cc: test_ones walks every A the contract covers
(0..kCellSize), which is the whole domain once the range is the caller's
job; 742 characters with the driver, 828 with a minimal one.
* drv/ones.r8asm: the driver the test uses.
* SPEC.md 7.5: the contract, the algorithm, and the two identities worth
remembering -- clb_inc_ip turns n ones into 2^n, and building it the other
way round costs more than it saves. Macro counts bumped to 42.
* AGENTS.md: the tables, plus the naming row (destructive computation whose
result lives in another cell, so no _ip suffix).
18 lines
369 B
Plaintext
18 lines
369 B
Plaintext
%include "asm/ones.r8asm"
|
|
|
|
; clb_ones 的驱动:0 号 cell 放数量,B 是展开结果。
|
|
;
|
|
; r8forge_derive drv/ones.r8asm -2 0=7 # B 应该是 0x7F = 127
|
|
; r8forge_derive drv/ones.r8asm -2 0=0 # B 应该是 0
|
|
;
|
|
; out 依次是 A(被吃成 0)和 B(从末位起 A 个 1)。
|
|
.var A 0
|
|
.var B 2
|
|
.var T 1
|
|
.var F 3
|
|
|
|
clb_ones A B T F
|
|
|
|
output A
|
|
output B
|