master
35
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
0c75772cbb |
geometry: the ring size becomes a build option, and the machine takes 64 cells
259 was never part of the machine, just the historical default, so kDefaultMemoryCells is now R8FORGE_MEMORY_CELLS (1..65536, default 259) with a range guard in CMake, the same way the cell width already worked. All five VMs read it from geometry.hh, so nothing else had to change. Measured the highest cell each tape in the tree actually touches by walking its > and < and recording the peak (no tape does a < at cell 0, so none of them depend on wrapping): calc 51, hello 49, signed_demo 34, term 27, and the asm/test.r8asm self test 155, because it lays every macro cell block out side by side. So a 64 cell ring runs every program we ship; only the self test needs the default. Verified: the full ctest suite is 8/8 at both 128 and 64 cells (11 bit); at the hardware geometry of 8 bit plus 64 cells the widthfree label is 5/5, and the calculator tape is byte for byte identical to the 259 cell build and its sessions take the same 166348 steps. The self test also produces identical output at 64 cells but 216 more steps, because its high cells fold back onto low ones -- which is why SPEC section 1.2 states the rule: ring size must be at least the highest cell a program touches plus one. Hardware payoff: at 64 cells dp is a 6 bit counter whose wrap is free, so the TTL build loses its modulo-259 comparator logic (four to five chips), the RAM needs 64 bytes, and the drum shrinks to 8 tracks by 64 cells (at 3000 rpm that is 52 s for a calculator session, so it wants to spin faster). hardware.md is updated to the 8 bit / 64 cell machine throughout. |
||
|
|
12a2254078 |
docs: a design note for building the machine out of silicon
docs/hardware.md turns the ISA into hardware requirements and works out what a physical ROT-8 needs. The load-bearing observation is that nothing in the instruction set can observe time -- no counters, no interrupts, and the I/O behaviours are "block until a character" and "latch the cell" -- so any implementation that reproduces the same sequence of (ip, dp, cells, output) is the same machine, at any clock rate and any number of cycles per instruction. That is what makes the build tractable: a microcoded sequencer, slow memory or even a drum are all legal. The note pins the parts that are easy to get wrong: the exact scan boundaries for [ and ] (the ] case jumps back onto the [ itself so it re-tests, which the reference rot8.c gets right and a naive implementation gets wrong), the halt condition, cells starting at zero, and the input convention -- , blocks until a character arrives and an explicit EOF reads as 0, otherwise every interactive read would return zero and the program would exit at once. Budget: 3 bits per instruction, so the flagship tape is 23.4 KB of ROM and the calculator at 11 bits is 27.6 KB; the data ring is 259 cells by W bits at most 518 bytes. Two consequences: the instruction pointer needs at least 17 bits because the calculator now assembles to 73624, past the historical INS_SIZE of 65536, and the 32 bit calculator (126 KB) does not fit the block RAM of the small boards. Three carriers are compared: FPGA first (Tang Nano 9K, about 58 KB of BSRAM, a weekend of work), discrete TTL as the real machine (25-35 chips, 0.25-0.5 M instructions per second, a few weeks) and electromechanical as the showpiece (a drum with 11 tracks and 259 cells per track, read and write heads one cell apart so a read-modify-write costs one cell time: 22 s for a whole calculator session at 3000 rpm). The verification plan leans on what already exists: a packer into the 3 bit format, the RTL testbench compared against tape_run step by step, then the panel single-stepped against an exported trace. Nothing is implemented; the note ends with the decisions that come first -- which carrier, which width (8, 11 or 16), program storage, and whether the physical tape form matters. The first concrete step would be M0: the packer plus a rot8.v testbench, which needs no hardware purchase and gives all three carriers the same golden model. |
||
|
|
1513111689 |
synth: measure whether the address-aware metric can shrink a real program
It cannot. The calculator assembles to 73624 characters in the default flat metric and 73940 with --synth-chars (identity layout), 316 more. Three reasons, now written down in SPEC section 3.7: * the travel term 2*(hi-lo) is translation invariant, so moving a group of cells farther or nearer changes nothing; only a permutation or a spread can, and the contiguous identity layout is already the tightest of those; * the library blocks are expanded at dozens of call sites with different addresses, so a single layout line is a guess that the real sites rarely match; * the model still ignores the hop between blocks, and the exact metric tends to pick programs with more blocks (six blocks for the adder table against five, 82 emitted characters against 87 -- five characters, which the other tables give back and more). Cell placement is the lever that works, and it is already spent: the terminal front end first put its borrowed classifier cells at 52..57 (77164 characters) and moving them into 20..29 gave 73624, minus 3540. Five single-cell moves on the current map were measured too (T and DEPTH to 17, HAVE and CNT to 52, S2 back to 52) and every one is longer: +182, +2900, +92, +134, +3810. So the map is a local optimum and the only way down from 73.6k is to drop features. The experiment left three metric-0 cache entries behind; they were deleted, so the committed cache still holds only what the flat metric needs. |
||
|
|
d0fd127048 |
build: the 32 bit toolchain builds, and 8/16 bit byte tests really pass
Two separate things hid behind "32 bit works": * tests/byte_op_test.cc could not compile at 32 bits at all (`1 << 32` in a constexpr plus an int typed mask), so the whole 32 bit build stopped there -- only `r8forge` and the core library came out. kCellMod is now clamped at 31+ bits and main() prints "skipped" above 16 bits (every sweep there is 2^W rows) and exits green. All ten targets build at 32 bits with MSVC, and the same tree builds clean on a Gentoo box with GCC 16 -- the missing <cstring> in asm_test.cc that stopped GCC first is in the previous commit. * the digit drivers hardcoded a 4 cell window, so byte_op_test's digits / digits_signed / undigits failed at every other width (16 bits wants 5 digits, 8 bits 3). drv/digits.r8asm, drv/digits_signed.r8asm and drv/undigits_byte.r8asm now derive D = _CELL_SIZE * 30103 / 100000 + 1 and space their cells by it, and the C++ side uses the same kDigits instead of a literal 4 (including the T/F cells clb_digits_signed leaves behind). With that, byte_op_test passes at 8, 11 and 16 bits (the 16 bit run takes about 450 s) and above 16 it skips. Two more width bugs fell out on the way: the divmod divisor sweep used 1000 and 2047 unconditionally (they wrap at 8 bits), and the undigits garbage guard OR'ed in bits above the cell, which at 8 bits turned '0'+digit into a value over 255. test_divmod_signed also divided by the recovered divisor without re-checking it, and at 8 bits the boundary value 1024 wraps to 0 -- that was a hard crash (divide by zero), not a failure. CMakeLists.txt now refuses -DR8FORGE_CELL_SIZE outside 1..32 at configure time; the range used to be a comment, so an out of range width was discovered as a compiler error in whichever file shifted by it first. geometry.hh and SPEC section 13 record that 32 is the ceiling because every VM stores a cell in uint32_t -- going further means widening all five VMs, the assembler's immediate type and ROT-8-viz's rot8_data. Also recorded there: the %synth cache is keyed by the truth table, not the width, so a 32 bit build hits the committed entries (0.4 s for the flagship tape of 227075 characters). A full cold rebuild takes ~500 s on a 44 thread machine, 479 s of which is the single 6 parameter full adder table. |
||
|
|
0c218abf32 |
calc: a 3 cell RPN stack -- nesting now works
The two register machine (A accumulator + P pending operand) could not nest:
"1 2 + 3 4 * + ." printed 0007 because the second operator overwrote the
first. The calculator now keeps a 3 cell stack (S0 is the top), operators run
immediately (pop two, push one), '.' is a real peek (repeated '.' shows the
same value, and it no longer flushes anything), and ',' clears both the stack
and the depth.
Depth is counted in DEPTH because the unary minus rule needs it: '-' is unary
iff the stack is empty. The previous "the previous character was an operator"
rule is wrong for a stack machine -- in "1 2 + -" the minus has to be a binary
subtraction (popping an empty cell yields 0, and 0 - top is exactly a
negation); treating it as unary would silently swallow the sign. The
"have == 0" rule from the original plan was already wrong for the old machine
("2 * -5" would lose its minus).
Sizing was driven by the tape: every push/pop is one copy per stack cell
(~500 characters), and the file has to stay under 65536. So 3 cells instead
of the 16 the TODO dreamed of: push is two copies (S2<-S1, S1<-S0), an
operator is two more (S1<-S2, then the result), and the new number is written
straight into clb_undigits' target cell (it erases N itself) so the extra
"result -> top" copy disappears -- that one was worth 540 characters. S2 sits
in cell 33, the freed OP cell: putting it at 51 cost 3.7k in walking alone.
64983 characters (was 62624) and 246142 steps for "12 34 + ." (was 280645 --
the old settle-the-pending-OP block is gone). The file header carries the
measured session list, the nesting cases, the stack move order (high to low,
or the source gets overwritten) and the older "2047 3 / ." caveat; docs/calc.md
gets the stack section, and SPEC 5.4/7.10 now point at DEPTH instead of NEED.
|
||
|
|
10f164b480 |
docs: the signed wrappers in SPEC, AGENTS, README and TODO
SPEC gains 7.10 with both contracts, the five design points and the measured tape lengths; 5.4 stops saying "implementation pending" and spells out why the range is asymmetric -- |N| can be outside the signed range while still fitting unsigned, so 1024 has to print -1024 and the absolute value cannot be done by clearing the sign bit. Numbers re-measured on this machine, because some had drifted: the flagship is 62351 characters / 202159 steps (documented as 62513 / 206491), --opt takes it to 56338, the calculator is 62624, the byte level test is 23 items over 22 macros, and asm/ has 55 macros in 23 files. tests/widths.ps1 no longer compares the viz's serial output below 8 bit cells: the viz prints one number per OUT there, so the 7 bit "viz FAILED" was the script's expectation, not the tape -- the calculator itself passes at 7 bits through r8forge_derive, and the same failure reproduces with the previous calculator (checked against HEAD in a temp worktree). The TODO gains the open question of whether the flagship should keep the 65536 limit at all, plus the evidence that a 16 bit tape of 96052 characters runs fine in the viz. |
||
|
|
723b8285dd |
docs: record the signed number plan in AGENTS, SPEC and TODO
The four decisions are settled and the work is not done, so each fact goes where it
belongs:
SPEC 5.4 two complement, the sign bit is _CELL_SIZE-1 (-1024..1023 at 11 bits,
-128..127 at 8 bits, symmetric, so no |MIN| trap), display -0042,
truncating division (the remainder takes the sign of the dividend),
silent wraparound. Addition, subtraction and multiplication need no
change: the arithmetic is already modulo 2^W.
TODO three independently verifiable steps -- clb_digits_signed (sign test
via clb_sub_nc against HALF = 2^(_CELL_SIZE-1), negate a copy, then the
existing digits), clb_divmod_signed (magnitudes, unsigned divide, signs
reapplied), and the calculator unary minus when HAVE is clear. Each
step lists its acceptance sweep.
AGENTS a short pointer so the next session sees the big queued thing.
The width trap is called out in all three: HALF must be %rep _CELL_SIZE; a literal
11 would misread the sign bit on an 8 bit machine.
|
||
|
|
3543003a78 |
digits: reorder the scratch block -- 22% fewer steps, 15% less tape
The profile said 77% of clb_digits' steps are pointer moves, so the layout of its 13 cell scratch block (S..S+12) is the cost. The block is one rigid 7 cell unit (clb_divmod owns its internal order: Rhi,Sd,Bo,Cm=Bc,Ci,buf,NR) plus six free units, so the legal space is 5040 permutations. All 5040 were assembled and run (minimal driver, value 2047): old: TEN Q R [block] counter T F new: T1 R [block] TEN Q F counter tape 13,717 -> 11,717 chars (-14.6%) steps 145,114 -> 113,264 (-21.9%) pointer moves 111,958 -> 80,108 (-28.4%) non-move steps identical (33,156) Full 2048 value sweep: worst 164,843 -> 123,731 (-24.9%), mean 144,904 -> 112,552 (-22.3%), better on all 2048 values. The old layout ranked 3459/5040. Two things worth remembering. First, ordering the units by the wrapper's first visit order is *worse* than the old layout (150,748 steps): first visit ignores revisit frequency -- the counter is touched once per round, TEN is copied into Bc every round, T1 is hammered by clb_add_ip's carry chain. Second, the n-1 lower bound is not reachable here: 74% of the steps still execute inside clb_divmod's block, whose order is not clb_digits' to choose, so this lever is now exhausted (that is what the exhaustive search proves). Min tape is not min steps either: block-first BQTRT1F1C gives the shortest tape (10,713) but 123,890 steps. Tape counts a .tp once, steps count its execution. Ripple: asm/test.r8asm 64,513 -> 62,513 chars, 236,439 -> 206,491 steps, INS_SIZE headroom ~1k -> ~3k; --opt 58,060 -> 56,350; calc --opt 52,857; calc_op 77,356 -> 69,324 chars / 599,090 -> 476,170 steps. Verified: ctest 8/8, byte_op_test 21 items (digits 2048/2048), examples_test 18, --opt assembles, SPEC 7.7/10.2 + AGENTS + README + docs/calc.md + docs/divmod.md numbers updated. New driver drv/digits_layout.r8asm keeps the measurement honest (one clb_digits call, no output, value fed as 0=2047). |
||
|
|
55ab5dfebd |
examples: the terminal tape -- prompt, echo, newline, backspace, EOF
examples/term.r8asm is the "type at it and it answers" program: it prints "> ", then
echoes every character the machine reads, prints a fresh prompt after each newline,
and answers a backspace with space + backspace so the cursor erases the glyph.
EOF (the 0 that inp returns when the input is gone) erases the loop quota, so the
loop ends and the tape runs off its end after one final newline.
tape 3467 characters, 4743 steps for a two line session (the calculator is 62585)
Measured (derive and tape_run, then the reference machine's serial output):
in hi out 62 32 104 105 10 "> hi\n"
in hi<LF>ok out 62 32 104 105 10 62 32 111 107 10 two prompts
in h<BS>i out 62 32 104 8 32 8 105 10 the 8 32 8 pair
All three character streams agree with ROT-8-viz byte for byte (bar CRLF).
r8forge_examples_test passes all 18 examples.
One thing worth recording: my brief for this said "a body entered on LSB==0 needs no
clear" -- that is backwards, `[` *jumps* on LSB==0, so bodies are entered on LSB==1.
Following it inverted the dispatch (EOF fired with C=0x68) and it took a
`tape_run --trace` to see it; the file now documents the real rule next to the loop.
|
||
|
|
a1f88e3d25 |
asm: raw_puts_dyn -- print a buffer whose length is only known at run time
A terminal has to echo the line the user just typed, and that length is a cell, not a constant; clb_puts cannot do it because .tp takes a literal address. So this one walks MAX compile time slots and decides per slot whether to print: CNT starts as a copy of LEN, clb_nonzero turns "CNT != 0" into the flag F, and the print happens inside `biz F` with the countdown *inside* the guarded body as well. That last detail is the whole bug this round: with clb_dec_ip outside the guard, a CNT of 0 wrapped to 2047 on the first skipped cell and the rest of the buffer came out (LEN=0 printed E F G H). The fix is also why the driver covers LEN = 3, 0 and 8 -- the zero case is what caught it. drv/puts_dyn.r8asm 13376 chars, out 65 66 67 65 66 67 68 69 70 71 72 (ABC, nothing, ABCDEFGH) reference machine "ABCABCDEFGH" 6306 steps Also learnt: `copy` takes two arguments (%this is the source), and it wants a clean buffer -- the first version passed three and then reused a dirty T, which showed up as a countdown that started from the wrong value. Not in asm/test.r8asm: an 8 slot version costs thousands of characters and the flagship is about a thousand under the 65536 limit. SPEC 5.3 records the contract and that exception; the macro count is 53. |
||
|
|
f7ac81b06f |
asm: clb_puts and load -- printing a sentence, and the constant helper
clb_puts REG LEN prints LEN consecutive cells as characters (the low 7 bits, which
is what serial OUT sends). LEN has to be an assembly time constant: .tp takes a
literal address here, so "print until the cell is zero" is not expressible -- the
walk would leave the data pointer somewhere else. Each character costs two .tp
plus one out (three or four tape characters), uses no extra cell and leaves the
source cells alone.
load N V is the helper every driver was writing by hand (erase then .xor): .xor is
an exclusive or, so a second load without the erase would mix with the old value.
drv/puts.r8asm 198 chars, in-family check: out 72 73 33 72 (HI! plus the
untouched source cell)
examples/hello.r8asm 727 chars, out 72 69 76 76 79 44 32 82 56 33, and the
reference machine prints "HELLO, R8!"
Both are documented in SPEC 5.2; the macro count goes 48 -> 50 and the examples 16
-> 17. The flagship tape is untouched (64513) because asm/test.r8asm still has its
own local load -- same body, and lib's definition comes first, so nothing changed.
|
||
|
|
b497bf0637 |
examples: the desk calculator -- 12 34 + . -> > 0046
The five stage drivers are now one program. examples/calc.r8asm is a two
register desk calculator: digits build a number, + - * / set the pending
operator, . prints the accumulator (`> 0046` + newline) and , clears it. EOF (the
0 that inp returns when the input runs out) erases the loop counter, so the loop
ends and the tape simply runs off its end.
in 12 34 + . out 62 32 48 48 52 54 10 (> 0046) 314777 steps
in 2047 3 / . out 62 32 48 54 56 50 10 (> 0682) 362281
in 7 6 * . out 62 32 48 48 52 50 10 (> 0042) 299352
in 9 4 - . out 62 32 48 48 48 53 10 (> 0005) 292030
both of the first two in one session 659759 steps
62585 characters, under ROT-8-viz's 65536 for the first time in this series, so
the whole calculator can be cross-checked against the reference machine later.
tape_run and derive agree, r8forge_examples_test passes all 16 examples, ctest 8/8.
Four deliberate departures from docs/calc.md, each forced by a measurement:
* settle before loading the new operand, and `.` settles too -- the literal
order printed 0034 for 12 34 + . because the space arrives before the + and
overwrites A; * the operator is one-hot (1 2 4 8) so settlement is four flat
mutually exclusive biz blocks; * the loop quota is refilled each round
(clb_ones can only make _CELL_SIZE ones, 11 here) instead of a fixed 128;
* three cell moves worth ~24k of tape: clb_undigits scratch 35..45 -> 5..15
(next to the window it decodes), result/display target 0 -> 20 (adjacent
scratch makes the %synth blocks shorter), 35..45 reused as one shot flags.
Also found a trap worth remembering: a biz body that ended with `.tp B1; set_0`
(condition cell is FLAG) has net displacement +2, and only on the skipped path
does it desynchronise every later .tp -- the symptom was `-` and `,` sending the
tape into the weeds. Net displacement 0 on both paths, always.
|
||
|
|
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 ?. |
||
|
|
90feedb37b |
32 bit cells: widen the VMs to uint32_t, fix the mask at 32, make width a build option
All five R8Forge machines stored a cell in uint16_t, so anything above 16 bits
was silently truncated even though geometry.hh (and the viz) allow 1..32; and
`(1 << cell_size) - 1` for _CELL_MAX was undefined at 32.
* cells and out/input buffers are uint32_t in derive, tape_run, byte_op_test,
examples_test and synth_test (r8veritas*.hh keep their uint16_t search
state -- that is node ids, unrelated)
* kDefaultCellMask and the injected _CELL_MAX special-case 32 instead of
shifting by 32
* width is now a build option: -DR8FORGE_CELL_SIZE=<1..32> (CMake cache var,
added as a compile definition), so a whole toolchain of another width is one
configure away; build*/ is ignored so those trees do not leak into git
Verified: 11 bits unchanged (tape 64513, byte_op ok); a 16 bit build passes
synth_test 8/8 and byte_op_test (65536 exhaustive pairs); a 32 bit build passes
synth_test, verify_clb_bit_add_nc and assembles full_add to the same 95 chars.
Exhaustive 32 bit is 2^64 pairs -- that stays sampled, not verified.
SPEC 13 checklist now says five VMs / uint32_t / the 32 bit mask case.
|
||
|
|
ae268b9442 |
Interactive I/O: teach the VMs INP, and let examples declare their input
The library can read characters now that the viz defaults to serial ASCII, but
R8Forge's own machines could not: r8forge_derive, r8forge_tape_run and the
examples harness all skipped ',' ("input is not modelled"), so an interactive
program could only be run through ROT-8-viz -- the wrong end of the dev loop,
and nothing in CI could cover it.
Three small pieces:
* INP (',') reads the next scripted character (low 7 bits) and 0 once the
text runs out, in tests/tape_run.cc, src/derive.cc and the examples VM.
r8forge_tape_run and r8forge_derive take -i/--input "<text>", so an
interactive program is run and checked exactly like any other:
r8forge_tape_run t.rot8 -i "12+34="
r8forge_derive calc.r8asm 0 -i "12+34="
* examples_test learns an optional `; in ...` header next to `; out`:
the characters after the marker are fed to INP before the run. The marker
must be the first word after ';' so "include" in a comment is not eaten.
* examples/echo_chars.r8asm: the smallest interactive program -- read four
characters, print them back. in R8F! -> out 82 56 70 33, 8 characters,
8 steps.
Verified the same tape three ways: tape_run -i "R8F!" -> 82 56 70 33,
derive 0 -i "R8F!" -> same, rot8_test --input R8F! -> prints R8F. With no
input at all INP reads 0, which is how every non-interactive example keeps
running unchanged.
Baseline: examples_test is now 15 examples + asm/test.r8asm.
|
||
|
|
a82d95658e |
docs: one home per fact -- README as the front door, SPEC as the contract, AGENTS as the manual
The three documents had grown to 2038 lines and quoted each other: 2199 appeared
seven times, 3977 ten times, AGENTS carried a 200-line copy of SPEC's byte-level
tables while README carried another 155-line copy still showing 8-bit-era numbers
(clb_add_nc 688, clb_not_ip 17, ...) that are wrong at 11 bits.
Split by responsibility, keep every fact exactly once:
README.md front door: what it is, 30-second build+run, directory map, where
to read next 547 -> 143 lines
SPEC.md the contract: %synth, geometry, every macro's signature / cells /
tape length / who verifies it, test matrix, boundaries, maintenance
901 -> 807 lines
AGENTS.md the manual: hard rules, build and self-check commands, the traps,
current state, next candidates, do-not-touch list
590 -> 132 lines
Long-form reasoning moves into docs/ instead of being dropped:
docs/divmod.md the shift-restore division story (was SPEC 14, 102 lines;
renumbered 1..6, SPEC keeps a pointer and the references in
SPEC 7.6 and asm/divmod.r8asm now point there)
docs/byte-ops.md the byte-level design history (was README's 155-line section,
rewritten with 11-bit numbers since the old ones were
measured at 8 bits)
Also fixes what the dedupe exposed: SPEC no longer claims only the multiplier has
a step bound, and raw_sub's comment no longer repeats the retracted "1.48M steps"
figure. Every section reference in the tree resolves; the baseline still passes
(asm/test.r8asm 64513 characters, 21 byte-op items, 14 examples, 48 macros).
|
||
|
|
ad45823768 |
AGENTS/SPEC: cross-checks with ROT-8-viz now need -n
ROT-8-viz switched its default I/O to serial ASCII (cells >= 8 bits) with the old decimal numbers behind -n/--numbers, so the handoff notes that tell the next session to compare numeric OUT streams against rot8_test have to say -n. Also records the new commit hash of that repo (a083a34) and that its default is serial now, which is exactly what the ASCII from clb_digits wants. Checked: rot8_test.exe -n on the asm/test.r8asm tape gives the same 93 values as r8forge_tape_run. |
||
|
|
c4048132cc |
asm/undigits: the inverse of clb_digits (ASCII decimal -> integer)
clb_digits could turn a number into four ASCII digits but nothing could turn
them back, so a program that stored or received a decimal string had no way
home. clb_undigits REG N S is that way back:
clb_digits N REG S ; 1234 -> 49 50 51 52
clb_undigits REG N S ; 49 50 51 52 -> 1234
Same number of digit cells as clb_digits writes (floor(W*log10 2) + 1, four at
11 bits), each read as its low 7 bits, so leading zeros are fine and garbage in
bits 7 and above is ignored. No validity checking, exactly like clb_digits: a
cell that is not '0'..'9' yields a deterministic but meaningless number, and the
documentation says so.
Horner in a runtime loop, one clb_mul in the whole tape:
N = 0 ; repeat 4: N = N*10 + digit ; shift the digit cells down one
9642 characters (minimum driver) -- smaller than clb_digits, because the reverse
direction needs no division.
Three things worth remembering, all found by testing rather than reasoning:
* c ^ 48 == c - 48 for '0'..'9' (the top two bits cancel, the low four are
identical), so subtracting '0' is one assembly time `.xor 48`: no
subtraction, no constant cell.
* The low-7-bit mask is `ror` 7, then set_0+ror per bit for the rest: the total
rotation is W, so the cell ends up facing the same way. The first version
wrote `rol; set_0; ror` in a %rep and cleared the same bit four times -- it
looks right and is undetectable on inputs whose high bits are already 0
(measured: 0|5<<7 came through as 688).
* The round counter must be erased before it is built: set_1 only clears the
bit it rotates to, so high ones left in the cell turn into extra rounds
(measured: dirty scratch gave 1234 -> 1564).
Tests and docs:
* r8forge_byte_op_test gains test_undigits: all 2048 values x {clean, garbage
in bits 7+} = 4096 cases, worst 36,481 steps.
* examples/undigits_demo.r8asm: "1234" -> 1234, "0007" -> 7, and a
digits -> undigits round trip on 2047; examples_test runs it like the rest.
* asm/test.r8asm calls it too (round trip inside the digits section). That
pushed the file over ROT-8-viz's 65536 instruction limit, so the redundant
second raw_add case, the reversed raw_sub case and the standalone divmod
section are gone -- every macro is still called at least once, and the file
is 64513 characters / 236439 steps / 93 outputs now.
* SPEC 7.9 (contract + the three traps), 10.2, 10.3 and 11, the AGENTS byte
table / verified list / naming table / baselines, and the README example
table all updated.
|
||
|
|
eacf6c01da |
r8forge: add -q / --quiet for a tape-only stdout
Assembling a library file prints one `%synth ...: cached, N blocks` line per
block (21 of them for asm/test.r8asm), plus search timings and the occasional
temp-directory notice. That is useful when working on the searcher and noise
when the tape is the output:
r8forge -q examples/full_add.r8asm > full_add.rot8
-q keeps stdout to the tape alone: cache hits, the layer/tape search lines and
the "temp dir is not writable, using ..." fallback are silenced. Errors are
not: a missing file, an unknown macro, no program up to N layers, a tape search
that fell back to the layer answer and "cannot write the synthesised macro
anywhere" all still go to stderr with the same exit code. Quiet means "don't
natter", not "hide the failure".
Implementation follows the existing per-run switches: ast::quiet, the
r8asm::set_quiet(bool) setter, one more parameter on r8asm_synth_program (the
prints live in synth.cc) and the temp-directory notice in r8asm.cc. The CLI
parses -q and --quiet anywhere among the arguments.
Verified: -q examples/full_add.r8asm and -q asm/test.r8asm produce byte
identical tapes to the normal run (95 / 58722 characters), stderr drops from 1
line / 21 lines to 0 bytes, and -q on a missing file or an unknown macro still
prints the error and returns 1.
SPEC 3.7, the README cost-model section and the AGENTS %synth list document it.
|
||
|
|
2e6d9cee86 |
asm/test.r8asm: call every macro, exercise every language feature
The old test.r8asm was a three round hash: `clb_add_nc` + `clb_mul`, nothing
else. It proved "add and multiply are enough for a hash" and it was the file
every session was told to check, but a regression in, say, clb_divmod or raw_sub
could not show up there.
It is now the library's kitchen sink instead: one call per standard macro,
grouped from the smallest to the biggest
A lib set_0 set_1 erase rol step back .anchor copy bit_copy
copy_to_buffer bit_copy_to_buffer clb_bit_mov
B bit slices clb_bit_add_nc clb_bit_inc_nc bit_raw_add/inc/and/or/xor
clb_bit_and/or/xor
C raw_* raw_add raw_inc raw_and raw_or raw_xor raw_sub (operands kept)
D clb_* clb_add_nc clb_inc_nc clb_neg_nc clb_sub_nc clb_not_ip
clb_inc_ip clb_neg_ip clb_dec_ip clb_nonzero clb_add_ip
E big clb_ones + loop/endloop, clb_divmod, clb_digits
F language a user %macro that uses %rep and %for, .var arithmetic,
two inline %synth blocks (map and stat, both cache hits)
G the old hash, now two rounds
Each call is followed by `output`, so the OUT stream is the fingerprint.
examples_test now runs this file too and compares it with the `; out` line in
the header (it already did that for examples/), which makes the file an actual
assertion instead of a length in the docs: an example that stops printing what
its header says fails the test.
Numbers: 58722 characters, 215169 steps, 100 values. r8forge_derive,
r8forge_tape_run and ROT-8-viz's rot8_test produce the identical stream (the
last six values are the hash: 1322 5 82 0 1786 94).
Two layout decisions come from that cross check:
* The tape has to stay under 65536 instructions: that is ROT-8-viz's
INS_SIZE (include/rot8/rot8.h) and read_tape truncates silently past it.
An earlier version of this file was 76047 and the viz stopped after 99 of
its 104 outputs, which is how the limit was found.
* So the hash keeps two rounds and the two rounds share one clb_mul scratch
block (erased in between) instead of carrying three separate ones.
The hash's own rules are unchanged: the multiplier stays 141 because it is the
historical value, not because small operands must sit in MUL any more.
SPEC 10.2, the AGENTS baseline/self-check/table and the README build snippet
are updated to the new numbers and to the 65536 limit.
|
||
|
|
b666799950 |
%synth: make the tape search thread count a run option (-j N)
The tape search always used std::thread::hardware_concurrency() workers with no
way to ask for fewer (or more). It is now a run option like the cost model:
r8forge -j N <file.r8asm> N workers
r8forge --synth-threads=N <file.r8asm> same thing
0 (the default) means one worker per hardware thread, as before.
r8asm::set_synth_threads(unsigned) is the C++ side; the CLI parses -j,
--synth-threads and --synth-threads=. The layer search stays serial (it only
takes seconds and has no split), so the knob only affects the expensive tape
search, which splits by first block (see r8veritas_phase.hh).
The search line on stderr now ends with ", N threads", which makes the setting
verifiable without timing: with a freshly written table (params 4, or4) and the
cache entry removed between runs,
-j 1 -> 230 states, 0.0009s, 1 threads
-j 4 -> ..., 4 threads
--synth-threads=2 -> ..., 2 threads
(nothing) / -j 0 -> ..., 32 threads (hardware_concurrency here)
Documented in SPEC 3.7, README's cost model section and the AGENTS %synth
section. asm/test.r8asm is unchanged at 28729 characters; byte_op_test,
examples_test (all 13), macro_docs, synth_test (95 chars, 8/8) and
r8forge_derive all still green.
|
||
|
|
b4ea79ba91 |
%synth: the cost model is a run option, not a per block metric line
`metric chars|flat|blocks` inside %synth meant the same truth table could be
searched twice for two call sites, and every library block had to spell out
`metric flat` to avoid the default. The cost model belongs to the whole
assembly, so it is one now:
r8forge <file.r8asm> flat (layout free), the default
r8forge --synth-chars <file.r8asm> charge the real .tp walk
flat stays the default because a library block is expanded at dozens of call
sites with different layouts: only a layout free result can share one cache
entry, and it is usually within a few percent (full_add: 95 vs 90 characters).
The chars search is far more expensive (full_add: 415M states, ~21 minutes,
~10 GB), which is exactly why it should be asked for on the command line.
`metric blocks` goes with it: block count is a poor proxy for tape length (and
it was only another way to ask for mode layers).
Implementation: the metric lives in the assembler (ast::synth_metric, default
1) and is set through r8asm::set_synth_metric() before import_file; the CLI in
tests/asm_test.cc parses --synth-chars / --synth-flat. The cache key already
carried metric, so the committed entries still hit: assembling the library and
asm/test.r8asm gives byte identical tapes (28729 characters, byte_op_test all
green, all 13 examples green, synth_test still 8/8).
A `metric` line now fails with a message that names the flag instead of being
silently ignored. examples/full_add_flat.r8asm and full_add_flat_spaced.r8asm
are removed: they only existed to demonstrate the per block metric (the flat
default makes them copies of full_add.r8asm).
Also repairs the mojibake in README's metric section: an earlier tool wrote
\x0c / \x08 / \x0d where \f, \b and \r belonged, which ate characters out of
"flat", "blocks", "biz/flb/rnz" and "rnz". The section is rewritten for the
flag, and the %synth numbers in README/SPEC/AGENTS now match what the tree
prints.
New cache entry c16bf083bb0ccbc8.txt is full_add's stat table with mode layers
+ flat, which full_add_stat.r8asm now produces.
|
||
|
|
66ed7bc263 |
SPEC/AGENTS: why the bit level wrappers must keep their set_0
A question that came up: the %synth stat tables already carry every parameter's
initial value, so shouldn't bit_raw_* stop clearing its output cells first?
No -- and the reason is in the searcher, not in the table.
compress_stat_space() drops the bits whose initial value never changes the
target and canonicalises them to 0 in the start state. The bit slice tables
are periodic in exactly those bits (the old hand written implementation cleared
them before working, and the derived table records that), so the search never
had to handle "the output cell already holds a 1": the block is only proven for
a cleared cell. The wrapper's set_0 is what puts the call site inside the
block's domain.
Measured by removing all nine of them (seven wrappers plus clb_bit_or and
clb_bit_xor):
raw_add / raw_and / raw_or / raw_xor ... still 65536/65536 ok
clb_mul 62064/65536 wrong
clb_divmod 14742/16384 wrong
clb_digits 2048/2048 wrong (one of them HANGs)
The rotation driven macros survive because they write the result at bit 0 and
rotate it away immediately, so the output LSB is 0 anyway; mul and divmod copy
accumulators around and really do feed a 1 back into the slice. Dropping the
set_0 would save three characters per cleared bit, which is exactly why someone
will try it again.
Reverted the experiment and wrote it down: SPEC gains 3.6 (compression
semantics and this trap, with the numbers), 6.1 gets the pointer line, and
AGENTS gets an entry in the "already confirmed dead ends" list.
|
||
|
|
3f4149c9d0 |
examples: one runnable routine per macro group
SPEC is the contract and drv/ is what the tests sweep, but there was no place
that showed a reader how a group is actually used. examples/ now has one stand
alone program per group, each ending in output calls:
base_macros.r8asm S5 set_0 vs erase, rol/ror, copy vs bit_copy vs
clb_bit_mov, step
bit_adder.r8asm S6 4 bit ripple carry adder built from
clb_bit_add_nc, then bit_raw_add for the
preserving variant
byte_raw_ops.r8asm S7.1 raw_add/raw_inc/raw_and/raw_or/raw_xor/raw_sub,
printing the operands afterwards to show the
whole point of the family: they survive
byte_clobber.r8asm S7.2 clb_add/sub/neg/inc_nc (operands eaten) and the
S7.3 clb_and residue (240 & 204 -> B = 12)
byte_in_place.r8asm S8 not/inc/neg/dec/add_ip and clb_nonzero
sum_loop.r8asm S5.1 clb_ones + loop/endloop: 1+2+...+N, count from
data rather than from the assembler
mul_demo.r8asm S9 82*141 and 2047*2047
divmod_demo.r8asm S7.6 2047/10 and 2047/1 (the case that used to hang),
reusing the scratch block on purpose
digits_demo.r8asm S7.7 1234 and 7 -> four ASCII digits
Every header carries a `; out 1 2 3` line: the expected OUT stream, so the
file itself says what it prints. The new r8forge_examples_test target runs all
of examples/*.r8asm and compares that line with the real output (a file without
the marker counts as a failure), printing the tape length and step count on the
way. That makes examples the second place after byte_op_test that checks
behaviour instead of just "it assembles", and keeps the examples from rotting as
the macros change. The six %synth examples get the marker too: their inputs are
all zero, so they print 0 0.
All 15 examples pass. The values in the headers were checked with
r8forge_tape_run (the second interpreter) as well as the test's own machine.
Docs: SPEC S10.3 has the table and the convention, S11 gets the test row, and
README gets a short section plus the layout list. AGENTS records the examples
in the handoff baseline and the "verified" table.
|
||
|
|
c2cd0e827f |
clb_divmod: shift-and-restore division instead of repeated subtraction
Repeated subtraction ran N/D rounds and hit the 5M step ceiling for D = 1
(2047/1 hangs outright); it also cost 2.46M steps for 2047/2. Binary long
division is fixed at _CELL_SIZE rounds whatever the operands are:
R = 0 ; Q = 0
repeat _CELL_SIZE: R = (R << 1) | next bit (rol N hands the bits out
MSB first and restores N
after W rounds)
if R >= D: R -= D ; quotient bit = 1
The one non obvious part is the comparison. R needs W+1 bits after the shift,
but the high bit (H, the bit rol wraps out of Rlo) only has to decide the
commit: H = 1 means R >= 2^W > D, so commit = H | Bo, where Bo is raw_sub's "no
borrow" (Rlo >= D). SPEC 14's Shi = H & Bo is always 0 under the invariant "R
< D at the start of every round" (H = 1 and Bo = 1 together would need R >= 2D),
so that clb_bit_and and its copy do not exist in the built version.
Signature is now clb_divmod N D Q R S: N and D survive, Q and R each get their
own cell (the old version ate N into the remainder), and S is a 7 cell scratch
block (Rhi, Sd, Bo, Cm, Ci, buf, NR). Only S+5 (the copy buffer) has to be
clean on entry; the rest is rewritten or used as a single bit, which is what
lets clb_digits pass the same dirty block back in every round.
The order that cost clb_mul two reworks is the delicate bit: rol Rlo wraps its
top bit into bit 0, so clb_bit_mov has to move that bit into Rhi (which also
clears it) before bit_copy injects N's bit. bit_copy (not clb_bit_mov) is what
keeps N intact.
Measured on drv/divmod.r8asm (11 bit):
repeated subtraction shift-and-restore
2047/10 495,986 28,593
2047/2 2,461,650 31,997
999/7 340,086 28,661
2047/1 HANG (>5M) 32,383
Small N/D get slower (fixed W rounds) -- the same trade clb_mul made. Worst
case over the sweep is 32,383 steps; the tape grows 4189 -> 4499 characters.
About the numbers in SPEC 14 / AGENTS: the 1.48M steps claimed there do not
reproduce on this tree. Measured before the change, 2047/10 was 495,986 and
clb_digits(2047) was 740,695, so the docs now carry the measured values and say
where the old figure came from.
clb_digits keeps its shape (one divmod in a 4 round loop, written digits shift
up by one cell), with S grown to 13 cells: TEN, quotient, remainder, the 7
divmod scratch cells, the loop counter and add_ip's T/F. 2047 goes from
740,695 to 145,138 steps (worst 164,867) and 10829 -> 13717 characters. It
needs its own %include "asm/add_ip.r8asm" now: that used to arrive through the
old divmod.
Tests: test_divmod sweeps 8 divisors x all 2048 dividends (16384 pairs; the old
76 sample table is a subset) and also asserts N and D come back unchanged;
test_digits sweeps all 2048 values. Both print the worst step count.
Two traps found on the way:
* r8forge_derive (and byte_op_test/synth_test) checked the assembler error flag
before export_rot8(), but an unknown macro or a bad .tp target is found while
the tree is *expanded*: a missing %include left a truncated tape that still
ran and printed a plausible wrong answer (all four digits came out '0'). All
three now check after the export.
* raw_sub's comment claimed Bo = 1 means A < B; the code (and clb_sub_nc) mean
A >= B. Comment fixed, behaviour untouched.
Also adds drv/div_shift.r8asm, the single step check for the cross cell shift
plus injection, and records the measurements in SPEC 7.6/7.7/14 and AGENTS.
|
||
|
|
a2154ee9ac |
SPEC 14: the shift-and-restore divider, worked out before it is built
The divider rewrite is a multi-round build (the cross cell shift cost clb_mul two
reworks), so the design went into SPEC first. The one non obvious part is the
comparison: R needs W+1 bits, but it does not need a W+1 bit subtraction.
With R = (Rhi:Rlo) and D < 2^W, compute S = Rlo - D and Bo = (Rlo >= D) with
raw_sub, and then
commit (R >= D) is Rhi | Bo
the new high bit is Rhi & Bo
All four cases check out (Rhi = 0, Bo = 0 is exactly R < D, no commit). So a
W bit subtract plus one bitwise OR and one AND replaces the W+1 bit machinery.
Also recorded: the state layout, the per round skeleton, why N is rotated with
rol (it hands out the bits most significant first and restores itself after W
rounds), the four pitfalls, and the acceptance checklist (same 76 sample pairs
against the current clb_divmod, step counts before/after, and clb_digits going
from 1.48M steps to tens of thousands).
raw_sub (the previous commit) is what makes this possible at all: the divisor
has to survive every round.
|
||
|
|
9a9ca48d9a |
raw_sub: a subtraction that keeps its operands
clb_sub_nc eats A and B, so the repeated subtraction divider has to copy both every round (two 495 character copies, about five hundred steps each) -- that is where clb_divmod's 1.48 million steps for 2047 comes from. Binary long division compares against the same divisor every round and cannot afford that, so it needs a non destructive subtract first. raw_sub A B S Bo Bc Ci buf is three useful lines: copy ~B, set Ci = 1, then raw_add (which already preserves its operands). S = A + ~B + 1 = A - B, and A and B are untouched. About 2900 characters, 7 cells, 9 sampled cases correct. One trap measured: do not flip Bo at the end to turn a carry into a borrow -- clb_not_ip complements the whole cell, so 0 becomes 2047 and 1 becomes 2046. Bo keeps the library's existing meaning instead: 1 means A >= B (no borrow), same as clb_sub_nc's carry. This is step one of replacing clb_divmod's O(N/D) loop with shift-and-restore division at O(cell_size) rounds (11 instead of 205 for 2047, so roughly forty times fewer steps for maybe a few hundred extra characters of tape). |
||
|
|
91e3fed537 |
r8asm %for: repetition with a loop variable
clb_digits needed to name a different cell every round, which %rep cannot do: it
copies identical text N times and has no loop variable, and there is no %if
either, so the three shift steps were spelled out by hand and the macro was
only correct for 11 bit cells.
%for k 3 ; k is 0, 1, 2 inside the body
step k
%endfor
%for <name> <count> binds <name> to 0..count-1 as a compile time constant that
any expression can use: %rep counts, .tp targets, macro arguments. The loop
scope is a copy of the current scope plus the name, so a %for inside a macro
body still sees that macro's %1, %2, ... %rep and %for nest in each other
(both closers count as a closer). %rep itself is untouched.
With it, clb_digits lost its hardcoded chain: the digit count, the shift count
and now the constant builds (tails written as _CELL_SIZE - 5 / _CELL_SIZE - 3)
all follow _CELL_SIZE. Checked at 16 bits with a five cell region: 4660 gave
'0' '4' '6' '6' '0' and 7 gave '0' '0' '0' '0' '7', so the count really did
become five. 65535 hangs in clb_divmod (6553 rounds, over the 5M step budget)
-- that is the divider's O(N/D), not digits. Back at 11 bits everything is
unchanged: all eleven values, hash 28729, byte_op and docs green.
SPEC 3.5 documents the directive; it is a local extension like %synth.
|
||
|
|
a515e823d1 |
clb_digits: integers become a four digit ASCII string
clb_digits N REG S writes '2' '0' '4' '7' into REG..REG+3 for 2047 -- ASCII
digits, most significant first, fixed width four, zero padded, which is what
was asked for after the ASCII/order/source questions.
divmod appears once, wrapped in a loop that runs four times. The first
version dispatched each digit to its own cell with four branches and a one-hot
flag handoff, and only the first branch ever fired; the digits themselves were
right (checked by printing N after every division: 204, 20, 2, 0). Rather than
keep chasing that, the dispatch is gone: each round shifts the digits already
written one cell up (high to low, so nothing gets clobbered) and the new digit
always goes to REG+0. Four rounds later REG+0..3 are thousands, hundreds, tens,
ones in that order. Simpler, two nesting levels less, four cells less, and it
works: 0/1/7/10/42/99/100/512/1000/1234/2047 all correct.
Two real traps found on the way, both now in the macro comments and SPEC:
* copy's buffer cell must be *clean*: a dirty buffer makes the copy produce
0 (measured: Q = 4, buffer = 0x7f8 -> N = 0). The library only says the
buffer is borrowed, never that it has to be zeroed.
* building a constant cannot be done as 'set a bit, rotate, set another,
rotate': the second rotation carries the first bit away. Walk the ring
once instead -- W rotations, set_1 at each target bit, then back home.
10829 characters with a minimal driver (13743 with the four outputs), 16 cells
in total, and r8forge_byte_op_test's test_digits covers all 11 values.
|
||
|
|
4a5bd836a8 |
clb_divmod: nine parameters down to four
Complaint received and agreed with: nine cells to pass for a division is not an
interface anybody wants to type. Two things made it possible to shrink:
* .tp and macro arguments accept address expressions (measured: .tp A+1
assembles, and set_0 A+1 expands to .tp A+1 inside the callee). So the
four scratch cells can be passed as one block: clb_divmod N D Q S uses S,
S+1, S+2 and S+3.
* BUF and X were unnecessary: copy already has sources and destinations to
spare that are dead at the moment they are needed, and clb_inc_ip can take
a cell that the probe is about to overwrite.
So the signature is now clb_divmod N D Q S -- three data cells and one scratch
base -- and the tape dropped from 5839 to 4189 characters on the way, because
the scratch cells now sit next to each other and every .tp walk got shorter.
Still correct: all 76 sampled pairs (2047/10 = 204 7, 7/10 = 0 7, 10/10 = 1 0,
1234/100 = 12 34, 999/7 = 142 5, 2047/2047 = 1 0), and the O(N/D) limit is
unchanged.
|
||
|
|
0b96b76104 |
clb_divmod: division and modulo, so digits have something to stand on
The library had add, subtract (with a free compare in its carry), negate,
increment, decrement, multiply, and the bit ops -- but nothing that divides.
Asking for a decimal expansion without it means inlining a division per digit,
which is where the 11k character estimate came from.
clb_divmod N D Q W V T Ci X BUF leaves Q = N div D and N itself as the
remainder, eating D. Plain repeated subtraction:
Q = 0
while N >= D: N -= D ; Q += 1
Two things it took to get right:
* clb_sub_nc eats both operands, and the subtraction cannot alias (measured:
clb_sub_nc A B A Ci with A=15 B=10 gives 0), so each round needs copies of
N and D. Two of the three copies are pure overhead, but they are in the
loop body, which appears once.
* The first round has to be able to do nothing. Setting T = N and Q = -1
before the loop makes the first commit a no-op and lets the phantom count
cancel out, so the probe can live at the *bottom* of the loop and appear
only once. Without that the probe is duplicated and the tape grows by
about 1.3k.
5839 characters with a minimal driver (5845 with the two outputs), 9 cells,
all 76 sampled pairs correct in r8forge_byte_op_test. Runtime is O(N/D): the
worst case 2047/1 crosses the 5M step budget and hangs, so the test keeps
N/D <= 600 and SPEC says so. Division by zero is undefined, D >= 1 is the
caller's job.
Next: clb_digits on top of this, which needs a shared loop plus per-cell
conditional writes (computed addressing does not exist here) rather than four
copies of divmod.
|
||
|
|
b89fcb0588 |
SPEC 5.1: do not replace an assembly time counter with clb_ones
Asked for, then stopped mid-flight: the tempting refactor was to build
clb_mul's round counter with clb_ones + loop/endloop instead of
%rep _CELL_SIZE { set_1; ror }. It is the wrong direction and worth writing
down so the next attempt does not get as far:
assembly time %rep _CELL_SIZE { set_1; ror } 55 characters
run time clb_ones (~770) + loop/endloop (~10) + building _CELL_SIZE
as a value, about 850 characters, 4 more cells, tens of
thousands of extra steps
Same for the alignment trap: %rep N { set_1; ror } leaves the run of ones at
the top of the cell, so biz sees bit0 = 0 and the loop never starts -- N < W
needs one rol after the %endrep. clb_mul only escapes it because its N is
_CELL_SIZE, i.e. the whole cell is ones.
|
||
|
|
3cfdad4313 |
loop/endloop: the other half of clb_ones, runtime loop counts
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 [ \.
|
||
|
|
bfad4b5d34 |
clb_ones: unary expansion, a count becomes that many ones
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).
|
||
|
|
54ddf9b0e7 |
SPEC.md: the %synth grammar and every standard library macro's contract
R8Forge had no spec of its own: the language lives in r8asm_rev/SPEC.md, the assembler
and the search were documented in README.md, and the macro contracts were only in the
comments above each %macro. This adds SPEC.md, pointed at the standard library:
* what this spec covers and what stays upstream (so the two do not drift);
* the five parameter types, the naming prefixes/suffixes, and the measurement
convention for tape lengths (a minimal driver, contiguous cells, no output lines);
* %synth: the full grammar, what map and stat mean, the three metrics, the cache key
and kModelVersion rule, and the four limits (8 params, 8 layers, no byte level
tables, no unconditional flip);
* all 41 macros in asm/ in tables with signature, which cells they eat, cell count,
tape length and implementation (hand written or %synth block + its stat table);
* the warts: clb_and leaves B & ~A behind while clb_or/clb_xor are clean, layout being
silently ignored when its length is not params, and set_0 clearing one bit only;
* a verification matrix saying which test proves what, and the known dead ends.
Every number in the tables was measured for this commit with one uniform driver
(measure_macros.ps1 shape, deleted afterwards), e.g. clb_not_ip 22, clb_add_ip 722,
clb_mul 3964 minimal vs 3977 through drv/mul_byte.r8asm. AGENTS.md and README.md now
point at SPEC.md instead of saying the %synth docs only live in the README.
|