Files
ww/selfhost/CLAUDE.md
Hojun-Cho 46edb8db4a w6c+selfhost+lib: cgen quality batch + lib Hare-shape graduation
Six fixes across the toolchain, surfaced by lib/lisp porting work.

  1. f64 compound assigns (`acc += d`, `-=`, `*=`, `/=`). Both stages
     load slot → X1, OP X0 into X1, store back (ADDSD/SUBSD/MULSD/
     DIVSD are reg-reg only). Previous MOVSD-overwrite dropped the
     OP. Locals and top-level lets.

  2. Top-level `[N]u8` arrays + `&arr[i]`. let_emit_size grows a
     TY_ARRAY branch so zero-init DATAW lands; cgindex / N_INDEX
     store / `&base[i]` all detect a global array base and use
     LEAQ name(SB) instead of LEAQ (BP). TK_AMP no longer pre-
     evaluates the operand as a value-load — `&base[i]` computes
     base + i*esz directly. Unblocks Hare's static-buffer pattern:
     strconv.{u64,i64,f64}tos graduate to module-level `*_buf`
     arrays and return owned views.

  3. Cross-module `pkg.Enum.MEMBER`. Nested N_DOT chains that
     don't fold to a known shape now emit `MOVQ <leaf>(SB), AX`
     (mirrors the bare-IDENT unresolved fallback), so isolation
     probes — and the test 990 cgen-match floor — stay consistent
     across stages. strconv exposes `base` as a real `enum i32`;
     callers updated. The `main` exemption (linker entry-point
     keeps bare name even when not exported) mirrors C-side
     collectmods into selfhost cgendecl.

  4. Sum-typed parameter ABI. lib/bytes.{index,rindex} take
     `(u8 | []u8)` needle; lib/strings.byteindex / rbyteindex take
     `(str | rune)` needle (Hare-shaped; the byte-wise misnomer
     `index` is dropped). tagged_arg_size cap bumps to 48 (6 int
     regs), with a new partial-fit branch on the callee: when an
     N-word tagged arg overflows remaining regs, fill what fits and
     stitch the rest from positive BP offsets. scanlocals MCASE
     handles slice binds (24B) and walks each arm with a saved /
     restored seenmark set so two arms naming the same local each
     get their own slot — matches cstage's per-arm scope reset.

  5. 4-reg tagged-return ABI (AX=tag, DX=word0, CX=word1, R8=word2),
     up from 3 regs. Slice-payload variants (`([]T | E)`, slot 32B)
     round-trip ptr/len/cap end-to-end. Every receive site updates:
     let-init via cgwidentaggedstore, match scrutinee spill, cgindex
     tagged-element load (both N_IDENT and fallback bases),
     pushargsrev tagged-ident arg (reads word count from slot size),
     cgreturn slice variant in the shuffle path.

  6. `expr: TaggedAlias` is a widening, not a re-interpret. C cgen +
     selfhost cgwidentaggedstore peel an N_CAST whose destination IS
     the union — so cgexpr's natural shape (str: AX=ptr, BX=len;
     slice: AX=ptr, BX=len, CX=cap) is consumed by the matching
     concrete-variant branch instead of being misread as a tagged
     AX/DX/CX triple. Inner casts to a concrete variant (`7: i32`)
     keep their type for proper tag lookup. `[N]Alias` arrays
     resolve element size via slotsize + aliaslookup, and aliaslookup
     strips a `pkg.` prefix so cross-module references work.

lib/fmt grows `formattable = (i64 | str | bool | rune)` plus
`printv` / `printlnv` taking an explicit `[]formattable` slice (the
receive side of Hare's `args: formattable...`). Call-site variadic
gather isn't wired — callers either hand-build the slice or compose
strconv.i64tos + strings.concat.

700_e2e: 114 → 123 rows (f64 compound, top-level u8 arrays + `&buf[i]`,
pkg.Enum.MEMBER, sum-typed (str|rune) and (u8|[]u8) params, 4-reg
slice-return ABI, formattable array). 26/26 tests, bootstrap stable
through ww4.
2026-05-13 08:05:01 +09:00

4.3 KiB

selfhost — ww reimplementation of the toolchain (wcc, w6c, w6a, w6l, ww, wwdump). Compiled by the C bootstrap (../cmd/); the goal is to eventually compile itself.

Identifiers: Plan 9 style. lowercase, words run together (newbuf, tcpsock, parsefile). No snake_case.

Syntax and idioms: Hare-shaped. Trailing ;, = after fn/type signatures, export for visibility, match/?/! for tagged-union errors. Consult ref/hare/ for canonical signatures and error-handling patterns before inventing your own.

The C bootstrap's cgen has known silent-miscompilation traps. They produce wrong runtime behavior, not compile errors. When porting C → ww here, default to the workarounds:

  1. amalloc(n) with n < struct size silently corrupts neighbours. No error — the bump arena hands out n bytes and field writes overflow into the next record. When introducing or growing a struct, audit every amalloc(_, n) call site and over-size (we routinely pass 48 for a 40-byte struct). Symptom: linked-list prepends lose all but the most recent entry.

Fixed (no workaround needed):

  • def NAME: str = "..." field access. .len/.ptr on an Sdef ident now inline the literal length / strlit address rather than reading BP+8. See cmd/w6c/cgen.c N_DOT.
  • Two-level field write through pointer field: r.sym.isdyn = 1 where r.sym: *T now stores. The chained-N_DOT N_ASSIGN branch evaluates the inner pointer and stores at *(ptr + field.offset). See cmd/w6c/cgen.c N_ASSIGN and selfhost/cmd/wcc/cgenexpr.ww cgassign.
  • Tuple return (scalar, str) (24B). Returns now follow an AX:DX:CX convention: AX = scalar elem, DX = str.ptr, CX = str.len. Receive sites all destructure off the same regs regardless of positional order: let n, s = call(); // ww comma form let (n, s) = call(); // Hare-style paren form let t: (i64, str) = call(); // positional t.0 / t.1.len Wwstage parser + cgen are byte-identical to C cgen on these shapes. See cmd/w6c/cgen.c N_RETURN/N_LET/N_DOT/N_MLET, lib/ww/parse/{stmt, expr}.ww and selfhost/cmd/wcc/{cgenstmt,cgenexpr,cgenutil,cgendecl}.ww.
  • f64 compound assigns (acc += d, also -= *= /=) on locals and top-level lets. Both stages now load slot into X1, OP X0 into X1 (ADDSD/SUBSD/MULSD/DIVSD register-register), and store X1 back. See cmd/w6c/cgen.c N_ASSIGN float-IDENT branch and selfhost/cmd/wcc/cgenexpr.ww cgassign float local/global.
  • Top-level [N]T arrays. The cstage cgen now emits a zero-init DATAW slot and accesses go through LEAQ name(SB); previously the array was filtered out by let_emit_size and arr[i] fell through to LEAQ (BP), BX (off-by-frame). let_isarray mirrors the selfhost N_TARRAY path in letemitsize.
  • &arr[i] (address-of an index). Both stages now compute base + i*esz without a trailing dereference; the previous TK_AMP path pre-evaluated the operand as if it were a value-load. Unblocks Hare's let s = string { data = &buf, ... } static-buffer shape. See cmd/w6c/cgen.c N_UN TK_AMP and selfhost/cmd/wcc/cgenexpr.ww cgun TK_AMP.
  • Tagged-union return ABI is now AX=tag, DX=word0, CX=word1, R8=word2 (was AX/DX/CX, 3 words). Slice-payload variants ((slice | E), slot 32B) round-trip end-to-end. Every receive site (let-init, match scrutinee spill, cgwidentaggedstore for call-source, cgindex tagged-element load, pushargsrev tagged- ident arg) reads the fourth word when slot size > 24. See cmd/w6c/cgen.c N_RETURN / cg_widen_tagged_store and the matching selfhost cgenstmt / cgenutil / cgenexpr branches.
  • expr: TaggedAlias is a widening, not a re-interpret. cgwidentaggedstore peels an N_CAST whose destination IS the union itself, so cgexpr's natural register shape (str: AX=ptr, BX=len) is consumed by the str-payload branch instead of being misread as a tagged AX/DX/CX triple. Inner casts to a concrete variant (7: i32 in (i64 | i32)) keep their type so the scalar branch picks the right variant tag.
  • [N]Alias arrays read element size through slotsize so an aliased tagged variant (e.g. [3]fmt.formattable) takes its full 24B stride per element, not the 8B fallback. selfhost/cmd/wcc/cgenutil.ww slotsize N_TARRAY follows aliaslookup on a TNAME element, and aliaslookup strips a pkg. prefix so cross-module references resolve.

If a port "should work" but the binary is wrong, suspect these first.