Commit Graph
23 Commits
Author SHA1 Message Date
dsh 2f79898e3d In place increment in two cells, 74 characters, by counting rotations in the
scratch cell's bits

I said a two cell in place increment was impossible.  It is not.  The version in
asm/inc_ip.r8asm does A = A + 1 with A and one scratch cell, 74 characters,
256/256 exhaustive, and there is a two cell in place negate on top of it:

    clb_not_ip A       A = ~A      1 cell    17 chars   256/256
    clb_inc_ip A T     A = A + 1   2 cells   74 chars   256/256
    clb_neg_ip A T     A = -A      2 cells   90 chars   256/256

against clb_inc_nc (3 cells, 430) and clb_neg_nc (3 cells, 448).  Five times
shorter, one cell less.

Both of my earlier impossibility arguments were about a *specific* algorithm, the
per bit carry ripple, and I stated them as if they covered the problem.  The one
worth remembering is the synthesis one, which is still true: a synthesised block
has exactly one condition cell, so it cannot tell (A=1, Ci=0) from (A=1, Ci=1),
and all four in place tables answer "no program up to 8 layers".  The hand
written argument was simply wrong.

The algorithm that works does not test the carry per bit at all:

1. `[ ... ]` already means "while the low bit is set", so clearing the run of
   low ones is a loop that falls out on the first zero (flb + ror);
2. flip that zero to one -- skip it when the input is all ones, which is exactly
   the wrap-around case;
3. rotate the rest of the way.

What is left is "how many rotations remain", with only two cells.  The counter
goes into the scratch cell's bits: T starts as 0xFF, and every rotation does
set_0 then ror, which eats one 1 -- the length of the run of ones is the number
of rotations left.  Three characters per step, and a full turn counts to eight.

The wrap case falls out for free: when the input was 0xFF the counter is spent
exactly then, so step 2 is skipped and the answer is 0.

Two smaller notes.  The dp rule from the last commit is what these macros had to
respect -- every conditional body returns to its own condition cell -- and
`[ ... ]` consuming its condition is only a problem when the condition is data;
here it is the counter.  And I mangled asm/inc_ip.r8asm once with a PowerShell
Get-Content / Set-Content round trip (the trap AGENTS.md warns about) and had to
rewrite it with the editor; no other file was touched.

byte_op_test is twelve operations now, still exhaustive, still under a second.
2026-11-07 09:40:05 +08:00
dsh eedd9a33a6 Negate and subtract invert the whole byte first instead of bit by bit
Asked why an in place complement does not exist, given that in place inversion
does.  The inversion half is now hoisted out of the per bit loop, which is both
simpler and shorter:

    clb_neg_nc A S Ci = clb_not_ip A ; clb_inc_nc A S Ci     468 -> 448
    clb_sub_nc A B S Ci = clb_not_ip B ; clb_add_nc A B S Ci   725 -> 707

and the unsigned complement through the same macro (carry in at 0) drops 467 ->
447.  B is eaten by the add anyway, so inverting it in place costs nothing.  The
per bit `flb` wrappers (clb_bit_neg_nc, clb_bit_sub_nc) are gone with them, so
macro_docs_test now counts 35 macros.

What does not work is the other half: there is no in place increment, so the sum
still has to land in S.  Two independent reasons, both written down:

* A synthesised block has exactly one condition cell, so it cannot tell
  (A=1, Ci=0) from (A=1, Ci=1) -- and that distinction is the whole carry rule.
  All four in place tables answer "no program up to 8 layers".
* Hand writing cannot do it with two cells either: `[ ... ]` is the only one shot
  conditional this ISA has, and it eats the bit it tests, while in place
  increment needs both cells' bits alive at the same time.

So one cell buys the ones' complement only; a two's complement negate costs three
(A, S, carry).  tests unchanged and green: ten byte level operations, 1666
character test tape, 8/8 full adder, fibonacci.

Also: the docs quoted clb_neg_nc at 468 and clb_sub_nc at 725, now 448 and 707.
2026-11-07 09:20:44 +08:00
dsh 557e2a1c38 In place: the ones' complement takes one cell and 17 characters
Asked whether two's complement can be done in place.  The negate cannot, but the
inversion half can and is absurdly cheap, so it is a macro now:

    clb_not_ip A        A = ~A, one cell, 17 characters, 256/256

`%rep 8 { flb; ror }` -- flip the low bit, rotate the next one down, eight times
puts the byte back where it started.  The same result through clb_neg_nc with its
carry at 0 costs 467 characters, because that path runs a synthesised slice once
per bit.

The in place two's complement itself: tried four tables and none of them exist.

    A <- ~A ^ Ci        A <- A ^ Ci        A <- A ^ B ^ Ci     A <- A ^ ~B ^ Ci
    no program up to 8 layers (all four)

Two separate reasons, both worth keeping:

* Synthesis cannot: a block has exactly one condition cell.  In place increment
  has to tell (A=1, Ci=0) -> (1,0) from (A=1, Ci=1) -> (0,1); A is the same in
  both and only Ci differs, and one condition cannot look at two cells.
* Hand writing cannot either (2 cells): `[ ... ]` is a while loop and the only
  one shot conditional this ISA has, and it eats the bit it tests.  In place
  negate wants "flip the low bit every round, then decide the carry from it",
  so both cells hold live bits and the test destroys one.

So a negate still has to land in a separate S (clb_neg_nc, 3 cells); one cell
buys the ones' complement only.  byte_op_test is ten operations now, AGENTS.md
and README.md carry the distinction and the two reasons.
2026-11-07 09:16:44 +08:00
dsh 026ad82455 The nc macros take a real carry in, they do not seed it themselves
They used to write the carry cell themselves -- set_0 inside clb_add_nc, set_1
inside clb_inc_nc / clb_neg_nc / clb_sub_nc -- which made the parameter a lie: a
cell the caller passes and the callee overwrites is not a carry input, it is a
scratch cell wearing a carry's name.  It also ruled out the thing a carry is for:
multi byte arithmetic.  The carry out of the low byte could not be handed to the
high byte, because the high byte's call would zero (or one) it first.

Now the macros only read it, and the caller decides:

    clb_add_nc A B S Ci     S = A + B + Ci      Ci = 0 plain add, or chained
    clb_inc_nc A S Ci       S = A + Ci          Ci = 1 gives A + 1
    clb_neg_nc A S Ci       S = ~A + Ci         Ci = 1 gives -A, Ci = 0 gives ~A
    clb_sub_nc A B S Ci     S = A + ~B + Ci     Ci = 1 gives A - B, Ci = 0 A-B-1

which also turns the negate into two operations for free: two's complement
negation at Ci=1 and the ones' complement (~A) at Ci=0.  The second one has its
own driver and test now (drv/raw_not_nc_byte.r8asm).

The drivers set the bit explicitly before the call, which is where that
instruction belongs -- the tapes end up the same length as before (688/430/468/725
instead of 693/433/471/730: one setup instruction moved out of the macro).

All nine byte level operations still pass, and the docs (AGENTS.md, README.md and
the four file headers) now state the carry in contract instead of describing a
constant.
2026-11-07 09:12:47 +08:00
dsh 5f0ce78861 Two's complement: negate and subtract, 3 and 4 cells
clb_neg_nc  A -> -A           3 cells  471 chars   256/256
    clb_sub_nc  A - B             4 cells  730 chars   65536/65536

Both are "invert, then add", which is all two's complement needs:

    -A      = ~A + 1
    A - B   = A + ~B + 1

so the carry cell starts at 1 (that bit is the +1) and each bit flips its input
with one flb right before the slice reads it.  Subtraction's carry out turns out
to be "no borrow": 1 when A >= B, so the same macro answers an unsigned
comparison for free.  Negation's carry is 1 only for A == 0, where -0 is 0 but
does carry out.

The bit level wrappers come along too: clb_bit_neg_nc (flb + clb_bit_inc_nc) and
clb_bit_sub_nc (flb + clb_bit_add_nc).

Tried first, and it does not work: a slice that inverts its own input.  The
table S = ~A ^ Ci, carry = ~A & Ci with 3 params answers

    r8asm: %synth clb_bit_neg_nc_synth: no program up to 8 layers

That is a model limit, not a search budget problem: a synthesised block
"sacrifices one cell, conditionally flips others", so when A is 0 the whole
block is skipped and S can only keep the 0 the wrapper gave it -- while inverting
needs S = 1 exactly then.  Unconditional flip is not expressible, so the flip has
to stay outside the slice.  Both facts are in the file comment and in AGENTS.md.

byte_op_test now covers nine operations, exhaustive, 0.72 s:

    raw_add/and/or/xor  65536 each      raw_inc  512
    clb_add_nc 65536    clb_inc_nc 256
    clb_neg_nc 256      clb_sub_nc 65536

macro_docs_test: 36 macros in 12 files, all in the house format.
2026-11-07 09:06:43 +08:00
dsh 4be8aa15ad Byte level add and increment with 4 and 3 cells: clb_*_nc
The nc slices do drive a rotation, so two more library macros fall out of them:

    clb_add_nc  A + B -> S, carry in/out in one cell   4 cells   693 chars
    clb_inc_nc  A + 1 -> S, carry in/out in one cell   3 cells   433 chars

against raw_add (6 cells, 1647) and raw_inc (5, 1214).  Both are in
r8forge_byte_op_test now, exhaustive: 65536 and 256 combinations, all pass.
clb_inc_nc has to start its carry cell at 1 -- that bit is the "+1"; the add
version starts at 0.  A rotation driver reads the low bit, throws it away and
rotates, so eating the operands is exactly what it wants.

This retracts a sentence that has been in the tree for a while: "rotation needs
A and B preserved".  It does not.  Preserving them is a separate wish (raw_*
grants it, with two more cells).  AGENTS.md said the wrong thing in the do not
retry list; that bullet now says what was really measured, which is only that a
4 cell slice asked to *preserve* A and B has no solution up to 8 layers.

Renamed for the same reason: bit_add_nc -> clb_bit_add_nc, bit_inc_nc ->
clb_bit_inc_nc, verify_add_nc.r8asm -> verify_clb_bit_add_nc.r8asm,
verify_inc_nc.r8asm -> verify_clb_bit_inc_nc.r8asm.  Measured what the prefixes
actually separate here:

    bit_raw_and  A=1 B=1 -> cells 0=1 1=1 2=1   operands preserved, has tmp
    bit_raw_add  A=1 B=1 -> cells 0=1 1=1 4=1   operands preserved, has buf
    clb_bit_and  A=1 B=1 -> cells 2=1           operands eaten, no tmp
    clb_bit_add_nc A=1 B=1 -> cells 2=1 3=1     operands eaten, no tmp

so raw means "the caller passes the scratch cell" and those variants happen to
keep their inputs, while clb means the inputs are gone.  These slices eat A and
B, so they are clb.

One self inflicted mess to own up to: I rewrote AGENTS.md with a PowerShell
Get-Content / Set-Content round trip, which on this machine decodes UTF-8 as GBK
and wrote the file back as mojibake.  Restored it with git checkout -- AGENTS.md
and redid every edit through the editor.  The work rule in AGENTS.md now names
that exact trap instead of only warning about -Encoding ascii.

Green: test.r8asm 1666, full_add 8/8, both verify_*.r8asm, byte_op_test
(65536x4 + 512 + 65536 + 256), macro_docs_test 32 macros in 10 files, fibonacci.
2026-11-07 09:03:08 +08:00
dsh adb3c8d71a bit_raw_add_nc is now bit_add_nc, and here is a 3 cell increment slice
The rename: the four cells of that slice all carry meaning -- A and B are
inputs, the third is a carry that is read on the way in and written on the way
out, the fourth is the sum.  There is no scratch cell, so SPEC.md's `raw`
("the caller passes the scratch cell") does not apply and the name now says so.
Measured before renaming: A=0 B=0 carry-in=1 gives S=1, so the cell is an input,
not a spare.

The cache survived the rename because the key is model version + params + mode +
metric + the resolved table (src/synth.cc), never the block name:
"bit_add_nc_synth: cached, 5 blocks".

verify_raw_add_nc.r8asm is now verify_add_nc.r8asm.

New asm/raw_inc_nc.r8asm, asked as an experiment ("can we even make one"):
bit_inc_nc, a 3 cell increment slice -- A, carry in/out, S -- three parameters
instead of raw_inc's five.  Table 0 4 4 2 0 4 4 2 resolved to a 4 block program
that was already in the cache, emitted tape is 54 characters, and all four input
combinations check out:

    A=0 carry=0 -> S=0 carry=0      A=1 carry=0 -> S=1 carry=0
    A=0 carry=1 -> S=1 carry=0      A=1 carry=1 -> S=0 carry=1

so S = A ^ Ci and the carry becomes A & Ci, with A eaten -- the same shape as
bit_add_nc, and like that one it cannot drive a byte level rotation (the operand
is consumed).  verify_inc_nc.r8asm drives it.

AGENTS.md: the two slices are in the self check list, the verified table and the
naming table; the "every macro" doc check now counts 30 macros in 10 files.
2026-11-07 08:53:25 +08:00
dsh 87ab064121 Delete the duplicate slice file, and say what the carry cell really is
asm/raw_add_nc4.r8asm carried the same 4 cell table as asm/raw_add_nc.r8asm --
same stat line, same metric, only the wrapper was named bit_add_nc4 -- and
nothing included it.  Gone; raw_add_nc.r8asm stays, it is the one
verify_raw_add_nc.r8asm and the docs point at.

While looking at it: is the third parameter a scratch cell, and does the slice
have a carry input at all?  Measured with verify_raw_add_nc.r8asm:

    A=0 B=0 carry-in=0 -> S=0 carry-out=0
    A=0 B=0 carry-in=1 -> S=1 carry-out=0
    A=1 B=1 carry-in=1 -> S=1 carry-out=1

so the cell is read on the way in and written on the way out -- a carry input
and a carry output sharing one cell, not a scratch.  All four parameters carry
meaning, which is why the `raw` in bit_raw_add_nc is history rather than
something SPEC.md asks for (raw = the caller passes the scratch cell).  AGENTS.md
now spells that out instead of repeating "and the scratch cell is passed by the
caller", which was wrong for this one.

The macro count in the docs drops to "every macro" rather than a number, so
adding or removing one does not leave a stale count behind.

Everything still green: test.r8asm 1666, full_add 8/8, verify_raw_add_nc,
byte_op_test 65536x4 + 512, macro_docs_test 29 macros in 9 files, fibonacci.
2026-11-07 00:26:03 +08:00
dsh 56ea288cd6 Tidy the standard library's macro docs, and check them by machine
Audited all 30 %macro in asm/.  The format was already followed almost
everywhere -- the doc block sits above the %macro, or above the %synth block
that generates its body -- but four things were wrong:

  raw_and.r8asm  the two doc blocks still carried the old names (bit_and, and)
  raw_xor.r8asm  raw_xor's first two parameters were typed Unit, not Cell
  lib.r8asm      step / back / output had no type at all ("%1: step_count")

and two files still repeated the retracted claim that set_0 only converges on 0
and 1 (raw_add_nc.r8asm, raw_add_nc4.r8asm).  Those now say what set_0 really
does -- it clears the low bit -- and stay on the point that matters for a bit
level slice: A, B and the carry must be single bits because the searched
program only tracks the low K bits.

Parameter types are now a closed set: Cell, CellBit, Unit, UnitBit, Count
(Count is for step/back's repeat count).  It is written down in AGENTS.md
together with the format, so the next macro has something to copy.

New r8forge_macro_docs_test checks the format instead of trusting review: a doc
block must exist, its ";   Macro <name>" line must match the macro, the number
of documented parameters must equal argc, and every type must be one of the
five.  Negative tested by deleting a parameter line and by renaming a block --
it reports both and exits 1.

Also fixes a real annoyance found while running the checks: %synth writes its
generated macro to the system temp directory and imports it.  That write fails
intermittently on this machine (same directory, cmd can write, r8forge cannot;
cause unknown), which turned every assembly into "cannot open ...synth.r8asm".
The body is now built in memory and written to the temp directory or, if that
open fails, to the working directory, with one stderr line saying so.

Full suite green: test.r8asm 1666 characters, full_add 8/8, verify_raw_add_nc,
byte_op_test 65536x4 + 512, macro_docs_test 30/30, fibonacci prints its ten
numbers.
2026-11-07 00:23:28 +08:00
dsh e30725247e Delete the one bit per cell layer
It was written from a wrong diagnosis.  Because the interpreters in this repo
read biz/rnz as a whole cell zero test, every packed byte program looked hung,
and the conclusion was "byte level arithmetic has to be one bit per cell".
With the interpreters fixed (86a54aa) that reason is gone: raw_add does the same
job with 6 cells instead of 32, and this repository had already deleted the same
approach once before for the same reason.

Removed: asm/byte_add.r8asm, asm/pack_byte.r8asm, examples/add8.r8asm,
examples/add8_inc.r8asm, tests/byte_add_test.cc and its CMake target.
AGENTS.md and README.md stop listing them and each keeps one paragraph saying
the direction was tried and dropped, so the next person does not add it back.

Still green after the deletion:

    asm/test.r8asm        1666 characters, 7/7 cache hits
    full_add              8/8 combinations
    verify_raw_add_nc     assembles
    byte_op_test          raw_add/and/or/xor 65536 each, raw_inc 512
    fibonacci             1 1 2 3 5 8 13 21 34 55
2026-11-07 00:07:34 +08:00
dsh 43390efe8a Byte level add, one bit per cell: 65536 combinations ok
The rotation based byte layer never ran.  Measured with r8forge_derive -2:

    raw_add   A=0,B=0 / 1+1 / 3+5 / 1+0   out empty (step limit hit)
    raw_add   A=127,B=130                 out 0 0 0 0 0, everything destroyed
    raw_and   0xF0 and 0xCC, 1 and 1, 0 and 5   out empty
    copy      A=5                         out empty (A=0 returns fine)

Not "only operand preservation is missing": set_0 (= [-]) cannot clear a cell
that holds more than one bit, and biz only answers "is this whole cell zero",
because ror does not change zero-ness.  So the bits of a packed byte are
unreadable, and the whole ror + set_0 layer has no future.  The docs now say
that instead of blaming operand preservation.

What replaces it is one bit per cell:

  asm/byte_add.r8asm   8 bit adder.  Bit i owns four adjacent cells at base+4i:
                       A, B, carry (in -> out), scratch.  The synthesised four
                       cell slice bit_raw_add_nc does the bit, clb_bit_mov moves
                       the carry into the next quartet.  A doubles as the
                       accumulator, so calling byte_add again continues the sum.
  asm/pack_byte.r8asm  eight flags -> one byte, the only direction that works.
                       bit_raw_flip_if consumes a flag into flipping bit 0 of an
                       accumulator that may already hold bits (no set_0 there).
  examples/add8.r8asm  a+b, 1308 characters.  A shared carry cell layout needs
                       only 25 cells but was measured at 2517: paying .tp travel
                       eight times beats saving seven carry cells.
  examples/add8_inc.r8asm   add 1 three times, proving the block composes.
  tests/byte_add_test.cc    r8forge_byte_add_test: runs the tapes on the ROT-8
                       machine over every input pair, 0.3 s.

Also: AGENTS.md gains the measurement table, the third instruction set
constraint (packed bytes are unreadable), the new files, and the note that
build/ has to be rebuilt with the VS bundled cmake -- scoop's 4.4 reconfigures
it and dies with "No preprocessor test for PellesC".
2026-11-06 23:40:14 +08:00
dsh 505ff509eb Rotation and synthesised slices do not mix; naming fixed
Tried the rotating byte level driver with the 4 cell slice.  It cannot work, and
the search says why: rotation needs A and B preserved, because every round reads
their current bit, while a synthesised program consumes its operands.  Rewriting
the table to keep A and B and letting %synth search it gives

    no program up to 8 layers

so 'read without destroying' does not exist in this block model at four cells.
The hand written bit_raw_add can do it (loops), which is exactly why the original
library rotates inside the macro and the synthesised one cannot.

What is committed instead:

  asm/raw_add_nc.r8asm   bit_raw_add_nc, the destroying 4 cell slice, flat cost
                         27 against bit_raw_add's 38, with the naming and the
                         comment format of lib.r8asm:

                            ;   Macro bit_raw_add_nc
                            ;   %1: CellBit A
                            ;   %2: CellBit B
                            ;   %3: CellBit Ci
                            ;   %4: CellBit S

                         The synth body is named bit_raw_add_nc_synth, so the
                         'raw' in the name marks the macro that takes cells.

  verify_raw_add_nc.r8asm  feeds A, B, Ci to one slice and prints sum and carry:
                         8/8 combinations correct, 78 characters.

The rotation limitation is written into the file header so it is not retried
blind, and the library still assembles from cache (1666 characters, 7/7).
2026-11-06 23:24:27 +08:00
dsh c6bfaca349 Drop the bit per cell adders, keep the slice
Splitting every bit into its own cell bought nothing: the 25 cell adder was a
workaround for a workaround, and it made the cell count worse than the hand
written library it was meant to improve on.

Removed: raw_add_nc (5 cell, broken driver), raw_add_nc3 (the 3 cell dead end),
raw_add_bits4, raw_add_bits8, raw_inc_bits8, verify_add8, verify_inc8.

Kept:
  asm/raw_add_nc4.r8asm            the 4 cell slice, flat cost 27 against the
                                   6 cell full adder's 38, with the two
                                   constraints written down (only the low K bits
                                   are modelled, and set_0 only converges on 0/1)
  verify_bit_add_nc4.r8asm         driver that feeds A, B and the carry to one
                                   slice and prints sum and carry, 8/8 correct

The byte level stays with the hand written library, which rotates inside the
macro and keeps whole bytes in a cell; that is 6 cells for an 8 bit add instead
of 25, at the price of not being synthesised.  %synth earns its keep on the small
bit macros (asm/test.r8asm 1714 -> 1666 characters), not on byte level tables
where the 2^16 entry truth table would be hopeless anyway.
2026-11-06 23:17:19 +08:00
dsh d480c001b1 Three cells for the destructive slice: tried, impossible here
Writing the sum back into A's cell would drop the separate S cells and cost no
extra instructions -- the driver would even get simpler.  So it was worth
trying, and it does not work: %synth reports

    no program up to 5 layers

and raising the layer bound to 8 does not help either:

    no program up to 8 layers

So the obstacle is not runtime cost, it is feasibility: three cells cannot do
' two inputs plus a carry in -> a sum plus a new carry' in this instruction
model, the same class of limit that stopped clb_bit_and.  Keeping the four cell
slice (and the 25 cell bit-per-cell adder) is the right call, and the file is
committed with that conclusion written into it so nobody retries it blind.

The layer bound is now 8 rather than 5 (src/synth.cc), since 5 was low enough to
call some feasible tables impossible; a feasible table still costs the same,
only a hopeless search takes 60% longer before giving up.

Cache untouched: restored from git after the experiments, asm/test.r8asm still
assembles from it in a fraction of a second, 7/7 hits, 1666 characters.
2026-11-06 23:09:45 +08:00
dsh 32b16eb077 Base addresses instead of 25 parameters
The eight bit adder took 25 macro arguments because every cell address was
passed in.  That was laziness: .tp accepts expressions, so the macro can take
four base addresses and add the offsets itself.

    raw_add_bits8 0 8 16 24     ; A0..7 at 0, B0..7 at 8, S0..7 at 16, carry at 24
    raw_inc_bits8 0 8 16        ; a0..7 at 0, s0..7 at 8, carry at 16

The bodies are unchanged apart from '%1 + 1' style addresses, so the tapes and
the behaviour must be identical, and they are: add8 still 2550 characters, inc8
still 1514.

Re-verified after the change, on the built in machine:
  add8  7 sums (100+50, 128+127, 200+55, 43+199, 255+0, 1+1, 0+0)  7/7
  inc8  7 values (0, 1, 5, 127, 200, 253, 254)                     7/7

Also committed two verify_*.r8asm drivers so the numbers are reproducible.
2026-11-06 23:07:09 +08:00
dsh 1b8ff08455 Eight bit adders and increments, one bit per cell
raw_add_bits8   A0..A7, B0..B7, S0..S7, carry = 25 cells
raw_inc_bits8   a0..a7, s0..s7, carry       = 17 cells

Both follow the same protocol as the four bit version: no rotation, every cell
holds a single bit, one slice per bit, and the final carry is dropped because
the caller promises the result fits.

The increment slices down to 3 cells -- a, carry (in -> out), s -- and %synth
finds cost 25 in 4 blocks for it: s = a^Ci, carry = a&Ci.  Its table was written
as 8 entries because a 3 parameter stat line wants 2^3 values, and the s bit in
the index does not matter, so the four entry pattern repeats.

One mistake worth recording: set_1 takes no arguments and acts on the current
cell, so 'set_1 %17' silently did nothing and the carry started at 0 instead of
1 -- which made 1+1 give 1 instead of 2 while 42+1 and 200+1 looked fine, since
only the low bit was affected.  The driver now does '.tp %17' then 'set_1'.

Verified on the built in machine:
  raw_add_bits8  9 sums (100+50, 128+127, 200+55, 254+1, ...) 9/9
  raw_inc_bits8  9 values (0, 1, 5, 15, 127, 200, 253, 254, ...) 9/9

Tapes: 2550 and 1514 characters.
2026-11-06 23:02:09 +08:00
dsh 7cf2fabeb7 A bit per cell adder, and it works
The chained version kept every bit in one cell and rotated, which broke the rule
that set_0 needs a cell holding 0 or 1.  This one gives each bit its own cell
instead:

    %1..%4  A0..A3      %5..%8  B0..B3
    %9..%12 S0..S3      %13     carry

    erase carry
    bit_add_nc4 A0 B0 carry S0
    ... one slice per bit, no rotation at all
    last carry dropped (assumes A+B fits)

No rotation means every cell stays a bit, which is the invariant set_0 needs.
Verified against the built in machine over eight sums including 0+0, 1+1,
15+0 and 9+6: 8/8 correct, and the cell dump after a run shows only the S bits
set, so the operands and the carry are consumed as the table says.

Cost: it needs three cells per bit plus the carry (13 for 4 bits, 25 for 8)
instead of 4 rotating cells, and the expansion is longer because each slice now
has a fixed pair of operands.  That is the price of not breaking the invariant,
and it is why the original hand written library rotates inside the macro instead:
it keeps whole 8 bit cells and loops over the bits itself.
2026-11-06 22:06:58 +08:00
dsh cbadc3936a Document what set_0 really is
Checked instead of assuming, and it explains the chained hang:

    '-'  flb  flips bit 0                    cells[dp] ^= 1
    '['  biz  if the cell is zero, jump past the matching ']'
    ']'  rnz  if the cell is not zero, jump back to the matching '['

so set_0 = [ - ] is 'while the cell is not zero, flip its lowest bit', which only
terminates for 0 and 1.  Measured with the cell dump: X=5 goes 5 -> 4 -> 5 -> 4
until the step limit, X=0x80 never changes, and in both cases the tape never
reaches the next instruction.  erase = %rep 8 { set_0; ror } hangs on the same
set_0, so it cannot clear an arbitrary cell either.

That is the whole story of the 8 bit chain: after a slice and a ror the S cell
holds 0x80, the next wrapper calls set_0 on it, and there is no way out.  The
slice itself is fine, as the dump showed (A and B fully cleared, carry a clean
0/1).

Consequence: a cell always holds one bit in this world, so clearing has to
happen while it still is a bit, not after it has been rotated out.
2026-11-06 22:04:46 +08:00
dsh 13b831ec8b A 4 cell adder slice: the carry borrows the scratch cell
Asked why the slice still needs 5 cells.  It does not: the scratch cell was
doing nothing the carry could not do, so the 4 cell version is

    p1..p4 = A, B, carry (in -> out), S

and the table says S = A^B^Ci, carry = AB|AC|BC, A and B consumed.  %synth
finds cost 27 in 5 blocks for it -- the same tape length as the 5 cell version
(cell count is not part of the cost metric, only the instructions are) but one
cell cheaper, 73 characters for a single slice.

All eight input combinations verified through the built in machine.

Diagnosis of the chained hang, from dumping the cells after one slice plus the
ror rotation:

    A=1 B=0  ->  cells: 4=80        (only the rotated sum bit survives)
    A=1 B=1  ->  cells: 1=1         (only the carry)

so a slice leaves A and B fully clear, and the carry is a clean 0/1.  The dirty
one is S: after the rotation its bit 7 is set, and set_0 in the next slice does
not remove it -- the dump after two slices shows 4=81 and, worse, the tape then
runs off the end instead of reaching 'output S'.

So the fix is not in the slice but in the driver: it must not rotate the sum
into a cell that the next slice clears, or must clear the whole cell (set_cell,
not set_0 over the modelled bits).  That is the next step, together with
re-checking whether set_0 is the right primitive here at all.
2026-11-06 21:31:04 +08:00
dsh 18bf78273e A 5 cell adder that ignores carry in and out
The idea: for an adder whose operand sum is known not to overflow, there is no
need for a separate carry in cell or a carry out cell -- the carry can live in
one cell and be overwritten each bit, and the final carry is simply dropped.
That takes the slice from 6 cells (A, B, Ci, S, Co, tmp) down to 5 (A, B,
carry, S, tmp).

The slice was not hand written: the table was derived from S = A^B^Ci and
carry = AB|AC|BC, and %synth searched it with metric flat:

    bit_add_nc_synth: tape cost 27 in 5 blocks   (1891406 states)
    bit_raw_add_synth (the 6 cell full adder):   tape cost 38 in 5 blocks

so 11 units of the metric cheaper, about 29%, plus one cell less per slice.

Verified: all eight input combinations of a single slice are correct through the
built in machine (A, B, Ci -> S), including the all zero one.

Known limitation, found rather than guessed: the synthesised program only
touches the low K bits of each cell, the bits the truth table knows about.  The
caller therefore has to hand it cells whose high bits are zero.  Chaining slices
with ror breaks that: the rotated cell keeps bit 7, and a block that loops until
its cell reaches zero can never get there.  So the 8 bit raw_add_nc hangs; the
slice itself is fine, the driver needs to move each bit into a clean cell first.

Also added: r8forge_derive <file> -1 addr=value ... runs a tape with chosen cells
and prints OUT, which is how the slice was checked.
2026-11-06 21:19:19 +08:00
dsh 14af0ca6ff Standard library: flat metric, cache pre-warmed and committed
Every synth block in asm/ now says 'metric flat', so the seven block bodies are
optimised without the .tp walk and therefore do not depend on where the caller
puts its cells.  The resulting bodies are cached in .r8forge_cache/ and the
cache is committed, so a fresh clone assembles the library without waiting for
a single search.

asm/test.r8asm: 1674 -> 1666 characters.

The seven tables were re-derived after the switch and all match the hand written
implementations bit for bit (bit_raw_add still 0 9 10 19 12 21 22 31 repeated,
bit_raw_inc 0 5 6 11, and so on), so this is a pure length win.

One caveat: bit_raw_add's flat search still runs out of state budget (700M, the
table stops fitting in a laptop) and falls back to the layer answer, which is
what got cached for it.  The other six converge in milliseconds; the whole warm
up took 396 seconds, almost all of it that one block.
2026-11-06 18:55:18 +08:00
dsh 30089af06d Rewrite the bit macros as %synth blocks
The eight bit-level macros in asm/ are now synthesised instead of hand written.
Their tables were not typed in by hand: r8forge_derive (new, src/derive.cc)
runs the OLD implementation over every input combination and reads the cells
back, so the replacement is bit-for-bit identical, quirks included.  big two
findings:

  * a synth block assumes the parameters that do not take part in the
    computation start at 0 (that is what compress_stat_space means).  These
    macros are called repeatedly inside a loop, so S/Co/tmp arrive dirty; each
    one now has a thin %macro wrapper that clears them and then calls the
    synthesised body.  With that, bit_raw_add derives to exactly the old table
    (0 9 10 19 12 21 22 31 repeated) and bit_raw_and to 0 1 2 7 repeated.
  * clb_bit_and stays hand written.  Three parameters leave no scratch bit and
    "and" needs both inputs alive at once, so it needs nested biz; the searcher
    exhausts nine layers over three planes without finding anything.  That is
    the model's expressive limit, not a shallow search.

asm/test.r8asm assembles to 1674 characters, down from 1714, with identical
block semantics.

%synth results are cached in .r8forge_cache/ keyed by the table, so the
twenty minute tape search happens once per table rather than once per build.

Note on verification: r8forge_derive validates one block at a time, which is
what the tables above are.  The little VM inside it is not solid enough to
vouch for whole programs (fibonacci prints two numbers instead of ten), so
"the whole library still computes the right answer end to end" is NOT verified
here -- that needs the real ROT-8 virtual machine.
2026-11-06 11:04:29 +08:00
dsh 19cbfb36f6 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.
2026-11-05 23:59:15 +08:00