Commit Graph

262 Commits

Author SHA1 Message Date
d9f097250b lib/ww/lex + w6a/parse: amalloc β grow → alloc([], n)! (β-1)
Phase 0 first β-batch. 4 amalloc sites across 2 β grow loops:
 - lib/ww/lex/lex.ww:570,592 lexstr string-literal escape buf
 - selfhost/cmd/w6a/parse.ww:513,548 DATA "..." escape-payload buf

Both follow the established α-per-alloc shape with loop logic left
manual: `*u8 = amalloc(_, cap): *u8` → `[]u8 = alloc([], cap)!`,
inner copy `nb[i] = old[i]` unchanged (slice indexing emits identical
asm to *u8 indexing — no .len bounds compare), `.ptr` extracted at
the *u8 consumer (s.ptr, pr.bytes). Bear-trap N/A — byte count tracked
in locals (nb, blen), slice .len = 0 never read.

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-21 09:14:39 +09:00
f2ea7fccec selfhost/cmd/w6l/dynout+obj: amalloc → alloc([], N)! (α/γ-11)
Phase 0 eleventh α/γ-batch. ~23 amalloc sites:
 - w6l/dynout.ww: 22 (~18 α u8 ELF section buffers + 3 γ pointer
   arrays — dynsyms []*lsym, sosused []*lso, vernameptrarr []*u8)
 - w6l/obj.ww:346 standalone α hdrsize u8

All single-shot fixed-count (NOT β grow as originally classified
in the phase0-mapper audit). α: `[]u8 = alloc([], N)!` + .ptr at
the dwr*/drd*/dbcopy callees. γ: element-count was bytes/8.

obj.ww:346 keeps the `*u8` legacy alias via `let mb: *u8 = mbs.ptr;`
since `armember.data` is `*u8` and gets stored across the function;
heap memory survives the local slice header (no GC, process-exit
reclaim).

Verified 132/132 incl. 992_w6l_ww + 995_self_rebuild + 996_dyn_ww
byte-identity.
2026-05-21 08:37:12 +09:00
c91d684708 selfhost/cmd/ww+w6l/main.ww: amalloc → alloc([], N)! (α-10)
Phase 0 #8 tenth α/γ-batch. 14 amalloc sites:
 - ww/main.ww: 11 (path bufs in importpathform/locatein/peekpackage/
   expanddir/arenadupcstr/builddirmodulepath/buildsearchpath + γ
   names/nlens in enumeratedir)
 - w6l/main.ww: 3 (resolvelib cstr+NUL paths)

α: *u8 → []u8 + .ptr at consumer; γ: **u8 / *u64 → []*u8 / []u64
with element-count alloc (was bytes/8).

Verified 132/132 + 995_self_rebuild byte-identity. ~27 amalloc
sites remain across 5 files; most blocked on #7 (astrndup),
#8 (β grow loops in w6a/parse, w6a/obj, w6l/dynout), #10 (cgoutarena).
2026-05-21 04:36:20 +09:00
6ff38f52bb lib/ww: migrate 5 typed amalloc sites to alloc(T{...})! (typed-9)
Phase 0 critical lib/ww/ gap (frontend used by BOTH cstage + wwstage,
not covered by phase0-mapper's selfhost/cmd/ audit). 5 typed-struct
amalloc sites + 1 γ pointer-array + 1 α byte buffer:

 - lib/ww/ast.ww newnode (node, 20 fields, was 208u64 over-sized)
 - lib/ww/typ.ww newtype (tinfo, 13 fields, was 112u64 over-sized)
 - lib/ww/typ.ww tinfocachebind (tinfocacheent, was 32u64 sizelint-ok)
 - lib/ww/sym.ww newscope (scope, 6 fields, was 64u64) + buckets γ
 - lib/ww/sym.ww scopedefineinmodule (sym, 10 fields, was 112u64)
 - lib/ww/parse/parse.ww joindotted (α []u8 + .ptr extract)

Retires 4 rule-7 over-sized amalloc workarounds plus a #36
tinfocacheent sizelint-ok. WHY-comments documenting the workarounds
are dropped (no longer applicable — alloc(T{...})! sizes from the
type table).

ast.ww newnode's `fval = 0: f64` carries a 3-line WHY comment naming
the 990_selfhost TK_FLOAT-count diff probe (lex.ww:382 precedent for
the same cast pattern). Bare `0.0` here would shift the dump-diff
token-input scope and break 990's byte-identity probe.

β grow loops in lib/ww/lex/lex.ww:570,592 deferred — separate sweep.

Verified 132/132 + 995_self_rebuild byte-identity. Net -63 lines.
2026-05-21 04:18:52 +09:00
a3e4c6942f selfhost/cmd/wcc/check.ww: arenau64tos amalloc → alloc([], 24)! (α-9) 2026-05-21 03:26:23 +09:00
4f4504d10a selfhost/cmd/w6a/parse + lib/ww/lex: amalloc → alloc([], N)! (α-8)
Phase 0 #8 eighth α-batch. 3 sites:
 - w6a/parse.ww:198 nextline newline-hit branch
 - w6a/parse.ww:208 nextline EOF-no-newline branch
 - lib/ww/lex/lex.ww:457 float underscore-strip buffer

All α: alloc([], n+1)! + p[k] indexing + .ptr at the consumer
(`return buf.ptr, n` for parse; `parsef64(clean.ptr, j)` for lex).
No struct-field shape change, no escape.

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-21 03:14:04 +09:00
4972ab4a5c cgen: loop/yield/defer fixed-max buffers raw-ptr → []T (#9)
Phase 0 #9. cgen struct fields loopendbuf/loopcontbuf/yieldbuf/
deferbuf change from `*str`/`**node` over-allocated arena chunks
to `[]str`/`[]*node` slices. The 4 alloc sites in cgeninit drop
the byte-count form (`LOOP_MAX*24u64`, `DEFER_MAX*8u64`) for
element-count (`LOOP_MAX: u64`, `DEFER_MAX: u64`). 10 caller
sites in cgenstmt.ww/cgenexpr.ww use `[i]` indexing which works
identically for slice-shaped struct fields.

Two-line let-then-assign idiom for the 4 inits is a real checker
limitation: alloc's element-deferred `[]u8` → `[]T` retype only
fires in let-init (checkletassign N_TSLICE LHS), and cglet's
alloc-slice writeback shortcut (cgenstmt.ww:577) only fires in
let-init too. Direct `c.field = alloc([], N)!` would silently
emit a scalar alloc with a junk slice header. Filed #49 for the
checker enhancement; the let-then-assign is Hare-idiomatic in
the meantime.

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-21 02:58:30 +09:00
0f011661b6 cmd: α-6 amalloc → alloc([], N)! (cgen mklabel/mkscratchname/internstrlit)
Phase 0 #8 sixth α-batch. 3 sites in selfhost/cmd/wcc/cgen.ww — all
runtime-N byte buffers returning a `*u8` via a constructed str.
Same shape as 7c2403c's cgenutil.ww:108 mkvarargname conversion.

Remaining cgen.ww amalloc: :541-546 (LOOP_MAX/DEFER_MAX context-
struct arrays → task #9, struct-field type change) and :700
(cgoutarena package-global → task #10, memio.dynamic refactor).

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-21 02:28:58 +09:00
7c2403cc4c cmd: α/γ-5 rt.malloc/amalloc → alloc([], N)! (w6l stack-promotes + cgenutil mkvarargname)
Phase 0 #8/#11 small batch. 4 sites:

w6l/main.ww δ stack-promotes (3):
 - :67 appenddec — 16B → [16]u8
 - :106 islinkable — 8B → [8]u8, &mp[0] to os.read
 - :176 isso — 20B → [20]u8, &mp[0] to os.read

wcc/cgenutil.ww:108 mkvarargname α (1):
 - amalloc → alloc([], n)!. Standard slice indexing
   (`p[k]` not `p.ptr[k]`) — ww's slice subscript has no
   bounds check (cgenexpr.ww:816-856 in cgindex), same
   shape as the dup pilot (4c07ef0).

Closes #11 (arenau64tos was re-routed via #8 separately;
the δ-shape was the genuinely trivial case). Advances #46.

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-21 02:17:50 +09:00
368b85ea33 cmd: α/γ-4 rt.malloc → alloc([], N)! (w6a/w6c/w6l file slurps + sized bufs)
Phase 0 #8 fourth α-batch. 10 α/γ conversions across 6 files:
 - w6a/main.ww slurp (1)
 - w6c/main.ww slurp (1)
 - w6l/dyn.ww slurpso (1)
 - w6l/obj.ww slurp (1)
 - w6l/dynout.ww filebuf at :661 (1; threads .ptr through ~50
   dwr*/dbcopy callees — that's the 139-line w6l/dynout diff)
 - w6l/out.ww hdr at :92 (1)
 - w6l/main.ww 4 sites: bufp + γ {inputs, libdirs, lflags} (4)

Deferred:
 - w6l/main.ww 3× 16/8/20-byte δ fixed-bufs at :67/:106/:176 →
   stack-promote in a separate sub-task.
 - w6l/obj.ww :113/:135 β text-buffer growth → memio.dynamic refactor.

Pattern unchanged from 47918d3/00d88ff/e9eb67d: `alloc([], N: u64)!` +
`buf.len = N: i32;` + `buf.ptr` for callees taking `*u8`. γ uses
element-count (was bytes): `maxinputs: u64` not `maxinputs*8u64`.

Verified 132/132 + 995_self_rebuild byte-identity. Advances #45.
2026-05-21 01:59:58 +09:00
e9eb67de04 cmd: α/γ-3 rt.malloc → alloc([], N)! (ww/wwdump main)
Phase 0 #8 third α/γ-batch. 33 sites total: 32 in selfhost/cmd/ww/
main.ww (driver) — 22 α `*u8` byte buffers + 10 γ `**u8` pointer
arrays — and 1 α in selfhost/cmd/wwdump/main.ww (file-slurp buffer,
previously amalloc).

Patterns:
- α: `let buf: []u8 = alloc([], N: u64)!; buf.len = N: i32;` then
  `buf.ptr` to extract `*u8` for callees that still take raw pointer
  (cstrinto/byteinto/readall/getdents64/...).
- γ: `let arr: []*u8 = alloc([], N)!; arr.len = N;` element-count
  semantics (was bytes; ww slice alloc takes element count).

i32 .len cast: ww's slice.len is i32 so `.len = N` from a u64
source requires an explicit `: i32` cast or silent-zero results.

The previously-flagged `out = rt.malloc(PATH_MAX): *u8` reassignment
in dobuild migrates cleanly: locally allocate `outbuf: []u8`, then
`out = outbuf.ptr` to preserve the `*u8` shape for the else-branch
from defaultoutpath. No GC + process-exit reclaim makes the bare
.ptr lifetime-safe (no free path needed).

0 sites deferred. Verified make test 132/132 + 995_self_rebuild
byte-identity. Advances #44.
2026-05-21 01:27:27 +09:00
47918d3ced lib: drop _unsafe convention; rename fromutf8_unsafe → frombytes; strings α-batch (concat/join/lpad/rpad)
CLAUDE.md rule 9 amended with the explicit carve-out: ww is C/Plan-9-
lineage — no GC, no "safe" baseline to be unsafe relative to — so the
Hare `_unsafe` suffix flags an axis ww doesn't have. The convention
is dropped wholesale in lib/.

Concrete changes:
- lib/strings: `fromutf8_unsafe` → `frombytes` (pure reinterpret). The
  validating sibling `fromutf8` is deleted entirely (28 lines, plus its
  84-line fromutf8_cases test). Callers that need validation write the
  two lines inline at the IO source: `utf8.validate(b)?;
  let s = strings.frombytes(b);`. `fromutf8` name reserved for a future
  true validating helper.
- lib/strings α-batch: concat/join/lpad/rpad migrate from
  `rt.malloc(N): *u8` to `alloc([], N)!` + `buf.len = N;` +
  `return frombytes(buf);`. Same dup-pilot pattern (4c07ef0). Task #41.
- lib/memio header comment trimmed: drops a stale reference to
  "lib has no fromutf8 today"; cites the rule-9 carve-out instead.
- Caller renames across selfhost combined.ww files (auto-regen) +
  cgenutil.ww comment ref.

Rule-11 disclosure on the bundle: the rename and the α-batch are
nominally separable concerns (symbol-naming policy vs amalloc→
alloc-slice migration), but they touch the same 4 functions in
lib/strings/strings.ww — the α-batch's first emission of `frombytes`
postdates the rename. The α-batch was applied on top of the rename
sweep mid-flight by the pre-commit reviewer; splitting them back
out is fiddly text surgery for marginal bisect value. The rename is
the primary concern; α-batch is one entry in #8's sized-slice
migration.

Verified: make test 132/132, 995_self_rebuild byte-identity holds.
Closes #42; advances #41.
2026-05-21 00:35:14 +09:00
4c07ef0552 lib/strings/dup: rt.malloc → alloc([], n)! slice form
Pilot for task #8 (runtime-N alloc API). `alloc([], n)!` yields a
slice with cap=n, len=0; explicit `buf.len = s.len;` lifts the len
before the fromutf8_unsafe reinterpret. Same shape as
ref/hare/strings/dup.ha:15 modulo ww not yet having `append`
(task #36) — open-coded byte loop in lieu of static-append.

Verified 132/132 + 995_self_rebuild byte-identity. Pattern is the
template for the next α-category sites (concat/join/lpad/rpad/...).
2026-05-20 23:38:03 +09:00
a376ec89eb lib/rt: rename rt_alloc → rt_malloc; rt.alloc → rt.malloc
Hare's canonical runtime allocator is rt::malloc with linker symbol
rt.malloc (ref/hare/rt/malloc.ha:27,78). ww kept the dot→underscore
Plan 9 convention (CLAUDE.md rule 4) so the linker symbol becomes
rt_malloc; the lib/rt exported function name becomes malloc; ww
callers say rt.malloc(...).

The language builtin keyword stays `alloc(T)!` — unchanged from Hare
(ref/hare/hare/lex/token.ha:21 ltok::ALLOC, parse/expr.ha:398
builtin()). The rename only touches the lowered linker symbol and the
exported function name behind it; the user-facing syntax for
heap-allocation is identical to Hare.

Surface:
- rt/alloc.s: TEXT rt_alloc → TEXT rt_malloc, labels updated
- lib/rt/malloc.ww: @symbol("rt_malloc") fn malloc(...) (was rt_alloc/alloc)
- rt/ensure.ww: local FFI decl + call site updated to malloc; `!` dropped
  on the direct FFI call (rt_malloc returns *void, not a tagged union)
- 18 .ww callers: rt.alloc(...) → rt.malloc(...)
- cstage cmd/wcc/check.c + wwstage selfhost/cmd/wcc/check.ww
  alloc-builtin suppression gate routes through ffi_resolve("malloc")
  for the lowering; the user-shadow check still keys on the BUILTIN
  KEYWORD "alloc" since that is what `alloc(...)` parses as. Adding
  "malloc" to the user-shadow check was unnecessary and was reverted
  during pre-commit review.
- cstage cmd/w6c/cgen.c: 2× ffi_resolve("alloc") → ffi_resolve("malloc")
- wwstage cgenexpr/cgenstmt: 2× ffiresolve(c, "alloc") → ffiresolve(c, "malloc")
- Test fixtures (700_e2e, 758_cgalloc_str_field, 990_selfhost, 992_w6l_ww,
  selfhost/test/tagged_ptr_ret.ww): updated inline ww sources to the new
  decl + call form

This is commit 2 of 3 in the lib/rt extraction (#38). Commit 3 closes
the OOM contract — return type becomes nullable *void and the builtin
lowering null-checks + propagates nomem.

Verified 132/132 + 995_self_rebuild byte-identity (5 wwstage tools
round-trip identical) + make clean cold rebuild.
2026-05-20 22:11:34 +09:00
d68d3c7eb4 lib: extract rt module from os, sweep imports
Hare puts runtime allocation in rt::, not os:: (ref/hare/rt/malloc.ha:27,
README). ww's `@symbol("rt_alloc") fn alloc(n: u64) *void;` lived at
lib/os/os.ww as a historical bootstrap shortcut; this commit relocates
it to a new lib/rt/malloc.ww and sweeps every site that depended on
`import os` for the alloc decl over to `import rt`.

This is commit 1 of 3 in the lib/rt extraction (#35):
  1. (this) move decl, sweep imports — preserves shape
  2. rename rt_alloc → rt_malloc (#38)
  3. nullable return type + OOM-propagating builtin lowering (#39)

No rename here. Symbol stays rt_alloc, function stays `alloc`, return
stays *void. Behavior identical — same ffi resolution outcome, just
sourced from a different module file. The rt::ensure runtime helper at
selfhost/rt/ensure.ww is its own compilation unit with a local decl and
is untouched.

Side effect: every wcc cgen file used `rt` as a local *node variable
name for "return type." `import rt;` shadows the module, so each
selfhost/cmd/wcc/{check,cgenstmt,cgenexpr,cgenutil}.ww site renamed
to `rtyp`. Mechanical follow-through; only the wcc module-import was
forced to do this rename.

Verified 132/132 + 995_self_rebuild byte-identity (5 wwstage tools
round-trip byte-identical).
2026-05-20 20:39:52 +09:00
a1ee817906 selfhost/cmd/ww/main.ww: 3× ".\0" amalloc → stack [2]u8
dobuild/dorun/dotest each allocated a 2-byte heap "." prefix buffer via
amalloc, set dot[0]='.'; dot[1]=0; passed dot as *u8 to a callee, then
let the arena chunk live forever. The dot pointer never escapes the
function — every callee chain (resolvemodule, cstrendswithlit,
rundirtests/runsingletest) byte-copies its input into a fresh arena
allocation before returning, never storing the original pointer.

Replace with `let dot: [2]u8 = ['.': u8, 0u8]; ... &dot[0]`. Both
stages allocate a fresh frame slot per let at function-frame entry
(localoff cstage / localadd wwstage), so the slot lives across the
synchronous callee.

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-20 19:28:59 +09:00
b060822bd8 selfhost/cmd/ww/main.ww: migrate visitadd strnode amalloc to alloc(T{...})!
Phase 0 batch 4. Single typed-struct site in the driver. Retires the
32u64 over-size workaround on a 24-byte strnode (selfhost/CLAUDE.md
trap #1 — amalloc < struct corrupts the next slot).

14 other amalloc sites in ww/main.ww are runtime-N path/name buffers
(13 → task #8) and 3 fixed-max ".\0" prefix buffers (→ task #9).
wwdump/main.ww's 1 site is a runtime-N file-size buffer (→ task #8).

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-20 19:12:10 +09:00
65c92e2c8d selfhost/cmd/wcc/cgen.ww: migrate 16 amalloc sites to alloc(T{...})!
Phase 0 batch 3b. collect* paths + intern + localadd/alloc/addstack.
Retires five rule-7 over-sized amalloc workarounds at :245 (enumtype
80→72), :265 (enummember), :918 (strlit), :1653 (fnret 80→72), :2060
(ffi) — alloc(T{...})! sizes from the type table, so the magic-byte
paranoia comments (the #35 block) go away with the literals.

Deferred: 3 internstrlit *u8 runtime-N buffers (#8), 4 LOOP_MAX/
DEFER_MAX fixed-max arrays at :541-546 (#9), 1 cgoutarena package-
global at :700 (#10).

Net -68 lines. Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-20 18:58:00 +09:00
1798ef02ef selfhost/cmd/wcc: migrate 2 cgenutil amalloc sites to alloc(T{...})!
Phase 0 batch 3a. structinfo registration + fieldinfo per-field in
registerstruct (cgenutil.ww). Both relied on amalloc-zero for fields=nil
and totsize=0 (structinfo) and finext=nil (fieldinfo); MAP_ANON-zero
covers the same slots.

check.ww:842 (arenau64tos 24B scratch) deferred to #11.
cgenutil.ww:108 (mkvarargname runtime-N) deferred to #8.

Verified 132/132 + 995_self_rebuild byte-identity.
2026-05-20 18:39:24 +09:00
104ba3cc0a selfhost/cmd/{w6a,w6l}: migrate 10 amalloc sites to alloc(T{...})!
Phase 0 batch 2. Sites: w6a/parse.ww (asym, aprog, aoperand ×2),
w6l/main.ww (lnk), w6l/obj.ww (defent, armember, lobj, lrel ×2).

obj.ww's hdrsize *u8 buffer at line 344 + 7 other runtime-N byte
buffers across the three files (path bufs, n+1 cstr copies, cap
realloc) stay deferred to #8.

Verified via 991_w6a_ww + 992_w6l_ww + 995_self_rebuild +
996_dyn_ww byte-identity. make test 132/132.
2026-05-20 18:25:38 +09:00
469ec85551 selfhost/cmd/{w6a,w6l}: migrate 6 amalloc sites to alloc(T{...})!
Phase 0 batch 1. Six typed-struct allocations switch from
amalloc(arena, NNu64): *T over-sized byte counts to alloc(T{...})!
with partial struct literal initialization. MAP_ANON-zero from
rt_alloc covers any field the literal omits — same contract the
amalloc bump arena provided via its explicit zero loop, but
without the rule-13 size literal at the call site.

Converted:
 - w6a/asm.ww  addreloc, addrelocdata, addfixup (areloc, afixup)
 - w6l/sym.ww  intern (lsym)
 - w6l/dyn.ww  loadso (lso), lexport

lexport's `if (vernamecs == nil) { e.version.ptr = nil;
e.version.len = 0i32; }` branch dropped — MAP_ANON-zero provides
the empty-version slot for free; the inverted `if (vernamecs !=
nil)` only takes the dcstrtostr path.

w6l/sym.ww:20 comment updated from "amalloc-zeroing" to
"alloc-zeroing gives 0, not -1" so the documented mechanism
matches the call.

w6a/obj.ww's 2 remaining amalloc sites (bufinit + bufgrow) are
runtime-N *u8 byte buffers, deferred to #8 (runtime-N alloc API).

Verified via 991_w6a_ww + 992_w6l_ww + 995_self_rebuild +
996_dyn_ww byte-identity. make test 132/132.
2026-05-20 18:07:32 +09:00
d617a698b0 selfhost/cmd/wcc: route cgalloc field-store foff through emitdispreg
Four ad-hoc emit sites in cgalloc's N_STRUCTLIT field-store loop
(cgenexpr.ww:2770-2802) wrote the displacement via
emitint(foff: i64); emitline("(REG)\n"), producing 0(REG) for
foff=0. cstage's txt.c:130-134 omits the zero displacement, so
ww2.s (cstage compiling wwstage) and ww3.s (wwstage compiling
wwstage) would diverge the moment any selfhost site migrates to
alloc(T{...})!. Dormant today only because selfhost source has
no alloc(T{...})! yet.

Route the four sites through emitdispreg (cgen.ww:786), the
existing SSoT that already omits zero displacement.

Extends test/wcc/758_cgalloc_str_field.c with 4 table-driven
asm_disp_rows pinning the displacement text for {str/int/f64
at offset 0, str at offset 8}. Internal subtest count: 16 → 20.
The 3 foff=0 rows fail without the fix.
2026-05-20 17:41:41 +09:00
4c51bce244 selfhost/cmd/wcc: route cgalloc CALL through ffiresolve
Wwstage's cgalloc hardcoded `CALL rt_alloc(SB)` at cgenexpr.ww:2747 and
cgenstmt.ww:647. Cstage already routes through ffi_resolve("alloc")
at cmd/w6c/cgen.c:4149 — when a fixture lacks the @symbol("rt_alloc")
decl in scope, cstage falls back to `CALL alloc(SB)` while wwstage
still emits `CALL rt_alloc(SB)`. The divergence is dormant in
ww build (combined.ww always pulls lib/os/os.ww's decl) but activates
under direct `w6c file.ww` and any other single-file path.

Replace the hardcoded line with the ffiresolve(c, "alloc") pattern
already used for user-function calls. The @symbol decl in lib/os/os.ww
is unchanged and propagates via the combine step.

Extends test/wcc/758_cgalloc_str_field.c with 4 table-driven asm rows
that compile a fixture via direct w6c (no combine) and `cmp` the
CALL <sym>(SB) line between stages. The 3 noscope rows fail without
the fix and pass with it; the withsym row pins the positive ffi-hit
path. Test count internal: 12 → 16; total make test: 132/132.
2026-05-20 17:18:32 +09:00
af1549d9c5 selfhost/cmd/wcc: cgalloc str-field store + regression test
wwstage cgalloc N_STRUCTLIT branch emitted MOVQ AX,foff(BX) for every
non-float field. For a str field the cgexpr result is (AX=ptr, BX=len)
and the single MOVQ clobbered BX with the heap pointer, dropping len.
Mirror cmd/w6c/cgen.c:4184-4190: isstrtype branch routes through CX
so BX=len survives. TY_STR only — slice/tagged/fn-pair have the same
gap on both stages (task #23, parked behind Phase 2).

New test/wcc/758_cgalloc_str_field.c is table-driven (6 rows), fails
without the fix under wwstage with predicted exit codes.
2026-05-20 16:51:32 +09:00
f80927201b tools/sizelint + CLAUDE.md rule 13: gate hardcoded size literals
Drew's Hare-discipline framing: "no hardcoded size literals anywhere in
the compiler." This session spent 32 commits sweeping after-the-fact
and STILL kept introducing new bypass sites in our own structural
work (A.5's tupleelemslot/fieldslotsize most recently). The cure is a
gate that catches new violations at commit time, not a deeper sweep.

tools/sizelint (sh+gawk):
- Always-on: `.size = NN` / `->size = NN` / `prim(...,"name",NN,...)`.
- Context-gated literals (NN(u64|i64) and `return NN`) in files or fns
  matching size|slot|elem|field|stride|paramfield|tinfo|primtype|
  slotsize|letemit|tagged.
- Allow-list via `// sizelint-ok: <reason>` or `/* sizelint-ok: ... */`.
- Comment strip happens after allow-list match so prose mentions of
  16/24 stay quiet.

Makefile: `test: all sizelint $(TESTS)` so the gate runs before any
binary builds.

CLAUDE.md rule 13 documents the discipline + escape hatch + optional
pre-commit-hook symlink.

Audit caught 3 real cstage bugs (cmd/wcc/check.c resolve_type:1002,
1079, 1531 hardcoded `tt->size = 16` / `= 32` for tagged-with-ptr and
tagged-with-slice payloads — should read `8 + sub.size`). Fixed
inline; behavioral no-op today (pt->size=16, st->size=24, sub.size=24
match the prior literals) but the SSoT seam carries forward through
#1/#34/#65.

8 SSoT-seed allow-lists added (cstage type.c ty_str/ty_slice prim
factories; wwstage primtypesize/tyslicesize; lib/ww/typ.ww tystr +
slice fields + their main.combined.ww mirrors). One amalloc-overalloc
allow-list at lib/ww/typ.ww:273 cites pending #36 (typed amalloc).

#66 filed for extending the filter once #65 routes lib/bytes +
lib/getopt's sizeof(slice) / sizeof(option) literals through SSoT —
naive line-pattern extension would false-positive on 22+ ELF wire-
format sites in dynout.ww.

131/131 + 994 + 995 + bootstrap green with `make sizelint` exit 0.
2026-05-20 15:22:21 +09:00
03b7336cae selfhost/cmd/wcc + lib/strings: restore SSoT routing for str/slice tinfo helpers
Phase A.5's tupleelemslot / fieldslotsize hardcoded 16u64 for TY_STR
and 24u64 for TY_SLICE — bypassing the tinfo.size SSoT seeded by
lib/ww/typ.ww:189 (the very pivot they were introduced to consult).
Route those four arms through pt.size / ft.size so #1 (str→24) and
#34 (slice graduation) land as a one-line bump at the seed.

lib/strings/stringstest.ww carried 12 `(cap: u64) * 16u64` strides
missed by #43's sweep over strings.ww + shlex.ww; convert to
`* size(str): u64` so the #42 fold owns the constant. Doc comments
in strings.ww (freeall + splitn) updated to the same SSoT form.

No-op at today's str.size=16 / slice=24: tinfo.size already matches
the literals these arms had baked in. Reviewer's pre/post asm-identity
probe (struct{i64,str,i64} + (i32,str,i32) tuple + bare str) shows
zero-byte diff. 131/131 + 994 + 995 + bootstrap (ww2==ww3==ww4) green.

Forward-link to #1 (str→24B bump) and #64 (sizelint pre-commit gate);
#65 filed for lib/bytes + lib/getopt sibling sites the reviewer
surfaced. Forward of #64 will catch any future regressions of this
class.
2026-05-20 14:55:36 +09:00
9fd79cdc33 selfhost/cmd/wcc + lib/ww: tinfo.slotsize SSoT + module-name TNAME fallback (Phase A.5)
A.4 left 74 fallback hits, all TNAME-flavored — 71 TNAME → TY_STRUCT
(natural-align vs slot-padded mismatch) + 3 module-name TNAME quirks
(`let l: lex;` where lex is both struct and imported module).

tinfo gains a slotsize: u64 field (96 → 104 bytes; amalloc bumped
to 112B per rule-7). size(T) stays Hare-natural at the user level;
cgen's slot storage now reads ti.slotsize for kinds where the two
differ. tinfofornode populates both:

- TSTRUCT: existing natural-align walk for r.size; new size-derived
  align walk (sz≥8→8, ≥4→4, ≥2→2) for r.slotsize, rounded to 8.
  Mirrors cgenutil.ww:2192-2218 registerstruct exactly.
- TTUPLE: parallel via tupleelemslot helper (primitives→8, str=16,
  slice=24, ptr/fn/chan/i64/u64/int/uint/uintptr/f64=8, composite
  →pt.slotsize, void=0).
- TARRAY: typearray sets slotsize = sub.slotsize * n. [N]i32 stays
  4N (natural); [N]Triplet lifts to 16N (slot-padded). Reverts
  A.4's r.size override since slot-pad now lives in slotsize.
- TFN/TENUM/TTAGGED/nullable: explicit slotsize. Default trail
  `if r.slotsize == 0 then r.slotsize = r.size` catches TBANG.
- New fieldslotsize(ft) helper mirrors registerstruct's per-field
  rule (struct→ft.slotsize, array→ft.slotsize, primitive→ft.size,
  tagged→ft.size).

slotsize fast-path (cgenutil.ww) reads ti.slotsize for TY_STRUCT,
TY_TUPLE, TY_ARRAY; ti.size stays correct for PTR/SLICE/CHAN/FN/
STR/TAGGED/VOID (size == slotsize for those). Narrow scalars still
pad-to-8 at the read site (moving into slotsize would break
[N]i32 stride).

lib/ww/sym.ww adds scopelookuptype(s, name) — same FNV bucket+parent
walk as scopelookup but filtered on skind==SK_TYPE. resolvealias
calls it when bare-leaf scopelookup returns non-TYPE (e.g., the
SK_USE/SK_MOD short-circuit case). Fixes `let l: lex;` (mod=leaf)
AND `let t: tok;` (mod≠leaf, tok lives in package lex).

Post-A.5 fallback: 0 across full bootstrap. Reviewer's stricter
metric (zero fast-path MISSES when tinfo IS stamped) also 0;
remaining FB_NIL hits are value-expression nodes the checker
doesn't yet stamp — A.6 candidate.

Ragged-tail probe `struct{inner=3*i32, mark:i32}`: ti.size=16
(natural), ti.slotsize=24 (slot-padded). Cstage emits [N]<ragged>
stride=16 on the same source — latent divergence filed as #63.
Not exercised by selfhost, so bootstrap byte-identity holds today.

131/131 + 994 + 995 + bootstrap (ww2==ww3==ww4) all green.
2026-05-20 14:30:55 +09:00
e37b76710a selfhost/cmd/wcc: TARRAY struct-stride + cache-bind resolved body (Phase A.4)
A.3 left wwstage slotsize at 134 fallback hits. Per-kind breakdown:
N_TARRAY 33 + N_TNAME 101 (of which 71 resolve to TY_STRUCT, 3 to
module-name quirks, 27 already had tinfo populated and were spurious
fallbacks via missed cache hits).

tinfofornode N_TNAME: existing arm already reached the resolved body
via aliaslookup → tinfofornode recursion (reviewer-61a3's "isn't
reaching body" hypothesis disproved by per-name instrumentation). A.4
binds the resolved-body node into the cache too — mirrors A.2's
TSTRUCT/TFN/TTUPLE/TTAGGED cycle-break pattern so future calls on
either node short-circuit.

tinfofornode N_TARRAY: when sub.kind == TY_STRUCT, round sub.size up
to 8 before stride. Mirrors registerstruct's slot-padded element
stride (cgenutil.ww:2156-2165 / :2233). Primitive elements stay
natural (slotsize's TARRAY walker also keeps them natural).

slotsize fast-path adds TY_VOID (size 0) and TY_ARRAY (gated on
alen > 0 so `[_]T` keeps routing through letslotsize). TY_STRUCT
deferred to A.5: tinfofornode TSTRUCT uses per-field natural-align
so size(T) stays natural at user level, but registerstruct uses
size-derived align with nested structs slot-padded — diverges on
ragged-tail shapes (`{inner=3*i32, mark: i32}` gives natural=16 vs
totsize=24). Proper A.5 design is a tinfo.slotsize SSoT distinct
from tinfo.size.

Module-name TNAME quirks (`let l: lex;` where lex is both a struct
and the imported module): resolvealias short-circuits on SK_MOD,
n.type_ stays nil, falls through to AST walker which structlookups
correctly. 3 hits in tree. A.5 work alongside TSTRUCT.

Post-A.4 fallback: wwdump 134→45, w6a 17→12, w6l 6→6, ww 12→11
(reviewer also measured w6c at 40). Total 169→74 across the corpus
(56% reduction). All 74 are TNAME → TY_STRUCT or module-name quirks.

131/131 + 994 + 995 + bootstrap (ww2==ww3==ww4) byte-identical.
2026-05-20 13:42:15 +09:00
82c1948239 selfhost/cmd/wcc + lib/ww/typ: nullable fold + slot-pad fast-path (Phase A.3)
A.2's slotsize fast-path covered PTR/SLICE/CHAN/FN/STR but bailed on
TAGGED (no nullable fold) and on primitives (cstage let_emit_size pads
to 8B for slot storage; tinfo.size is natural width). Fallback hit
count under wwdump build was 2187. A.3 closes both gaps.

tinfo gains a `nullable: i32` field (fits the existing 4B pad, struct
stays 96B). tinfofornode's N_TTAGGED arm detects `(*T | void)` (exactly
2 variants, one N_TPTR, one bare N_TNAME "void" — aliased or !void-
wrapped void don't match) and folds to size=8, align=8, nullable=1.
Mirrors cmd/wcc/check.c:412-426.

slotsize fast-path re-adds TY_TAGGED (safe now) and gains a primitive-
pad branch: BOOL/RUNE/I8-I64/U8-U64/INT/UINT/UINTPTR/ENUM/F32/F64 →
return 8. Padding lives at the read site; tinfo.size remains a faithful
natural-width SSoT. TUPLE/TSTRUCT/TARRAY deliberately stay on the
fallback because per-field stride is registerstruct.totsize, not
tinfo.size.

Post-A.3 fallback hit count: 134 (94% reduction from A.2's 2187).
Reviewer's per-kind breakdown: N_TNAME 101 (alias-to-struct chains)
+ N_TARRAY 33 (struct-element rounding) account for all remaining
hits. Both A.4 work.

Probes: `(*i32 | void)` byte-identical between stages with the
8B nullable encoding. `(*i32 | nomem)` correctly does NOT fold
(nomem ≠ bare void). `(*i32 | !void)` correctly does NOT fold
(N_TBANG isn't N_TNAME).

131/131 + 994 + 995 + bootstrap byte-identical (ww2==ww3==ww4).
2026-05-20 12:51:22 +09:00
a78b26c2d3 selfhost/cmd/wcc: extend tinfo coverage + graduate slotsize fast-path (Phase A.2)
tinfofornode (check.ww) covers six more kinds:
- N_TARRAY: typearray on recursed element, size = esz * elen.
- N_TFN: 8B/8B; recurse on ret.
- N_TENUM: storage size/align (default i32 → 4B). Mirrors cstage
  check.c:531-542.
- N_TTUPLE: raw element sum + max-align. Mirrors check.c:329-345.
- N_TSTRUCT: per-field align, round total to maxalign. Mirrors
  check.c:280-340 / :468-527.
- N_TTAGGED: 8B tag + (max(variant)+7)&~7, al ≥ 8. Mirrors
  check.c:347-435.

Cycle-prone arms (TFN/TTUPLE/TSTRUCT/TTAGGED) pre-bind the in-progress
tinfo into the cache BEFORE recursing on subfields so self-referential
shapes (`type node = struct { next: *node, … }`) terminate. Pre-fix
wwdump_ww segfaulted on its own combined source.

More population sites in exprtype: every primitive literal arm
(N_FLOATLIT/N_STRLIT/N_RUNELIT/N_TRUE/N_FALSE/N_VOIDLIT/N_NIL —
A.1 only had N_INTLIT), N_IDENT (propagate from sym.decl.lhs.type_,
eagerly tinfofornode + cache if not yet visited), resolvewalk type-expr
stamping, and resolvefnbody now recurses into N_PARAM.lhs (pre-#61 the
param type-exprs were never walked — every param had nil type_).

slotsize (cgenutil.ww) gains a fast-path: when n.type_ is set AND the
kind is PTR / SLICE / CHAN / FN / STR, return ti.size: i32 directly.
The fallback walker stays alive for primitive scalars, enums, named
structs, inline composites, TARRAY — those need cstage's let_emit_size
slot-pad-to-8 contract (cmd/w6c/cgen.c:691-720) which tinfo doesn't
carry. A.3+ moves padding into the fast-path.

TY_TAGGED *not* in the fast-path (reviewer-61a2 caught this) —
tinfofornode's TTAGGED arm doesn't implement cstage's nullable-pointer
fold (check.c:412-426: `(*T | void) → 8B`). Self-host code happens not
to use that shape today, but the divergence would land latent. Pull
TAGGED until A.3 folds nullable into tinfofornode.

A.2 fallback-hit count under wwdump build: 1554 fast vs 2187 fallback —
partial graduation; expected. 131/131 + 994 + 995 + bootstrap
byte-identical (ww2==ww3==ww4).
2026-05-20 12:17:16 +09:00
93ac65ba0a lib/ww/typ + selfhost/cmd/wcc/check: tinfo-on-node infrastructure (Phase A.1)
Foundation for audit §1.8 — wwstage cgen recomputes type sizes at every
site instead of reading n.type_ like cstage does (cmd/wcc/check.c sets
n->type via cexpr; cgen reads n->type->size). The scattered literals
this session has been chasing (#43, #60, etc.) are the symptom; this
chain is the cure.

A.1 is infrastructure only — no cgen-site graduation yet. Subsequent
A.2+ sub-commits collapse each walker family (slotsize, elemsize,
fieldsize, isstrtype, istaggedtype, ...) onto n.type_ reads.

lib/ww/typ.ww:
- tinfocacheent struct (key, val, cnext) — sea-of-stars per rule 12.
- tinfocache: *tinfocacheent field on tctx (now 25 fields).
- tinfocachelookup / tinfocachebind — head-prepend linked-list ops.

selfhost/cmd/wcc/check.ww:
- tinfofornode(c, n) *tinfo — covers N_TNAME primitive (singleton
  lookup), N_TNAME alias (recurse via resolvealias), N_TBANG
  (unwrap+recurse, iserror dropped — graduate alongside the first
  cgen reader that needs it), N_TPTR/N_TSLICE/N_TCHAN (recurse on
  sub, call typeptr/typeslice/typechan).
- exprtype N_INTLIT arm now sets e.type_ = tinfofornode(c, tn). Only
  population site in this commit; every other arm unchanged.

Empirically verified via temp probe that tinfofornode is reached and
returns non-nil on `let x: i32 = 42;`. Strict scope: zero cgen reads
of n.type_; primtypesize/slotsize/etc. still drive size queries.

131/131 + 994 + 995 byte-identical to caa72f2.
2026-05-20 10:40:12 +09:00
caa72f2365 cmd/w6c+selfhost/wcc: route cgparam/MLET/spill sizes through SSoT
#43 (8e93b31 + 087c85c) routed many sizeof(str) / sizeof(slice)
sites through primtypesize / tyslicesize / ty_*->size, but missed
the cgparam regs-fit, cgparam stack-stitch, cgmlet mixed
scalar+str receive, and vararg slice gather paths in both stages.
A bare #1 bump (str→24B) on top of #43 reds ~60 tests because
those paths still hardcoded 16/24.

Cstage:
- cgen.c:7360-7361 cgmlet: sz0/sz1 → (int)u0->size / (int)u1->size.
- cgen.c:7557 cgparam regs-fit: slice|is_str → (int)pu->size.
- cgen.c:7586 cgparam stack-stitch: same.
- cgen.c:4368 cgcall vararg gather: localoff slice descriptor →
  (int)vsu->size (the cstage twin of cgenexpr.ww:3084).

Wwstage:
- cgendecl.ww:225, :243 cgfnparams: 16 → primtypesize("str"): i32.
- cgenexpr.ww:3084 cgcall vararg gather: 24 → tyslicesize(): i32.

Plus a latent-bug fix at cgenstmt.ww cglet :1031 / :1040: the
str-init and slice-init arms dispatched on size only. Under #1's
str→24, both arms would have fired on a str let (duplicate
MOVQ BX,off+8 + bogus MOVQ CX,off+8). Added isstrtype / isslicetype
kind gates mirroring cstage cgen.c:6439's
`type_isstr(lt) && sz == ty_str->size`. Zero asm change today
because the size constants implicitly disambiguate at 16 vs 24.

Probe with temporary #1 bump (str.size=24) confirms 990_selfhost +
994_w6c_ww go green — the cgen-routing slice for #1 is now
closed. Remaining red under bump is lib/ww/typ.ww's parallel SSoT
seed + stringstest cap*16u64 strides + w6l_ww runtime SIGSEGV;
all tracked separately.

EIGHTBYTES register-count sites (cgen.c:7553-7554, cgendecl.ww:224
/:260) intentionally NOT touched — those are str ABI in-flight
3-reg work (task #34), not slot-width SSoT.
2026-05-20 10:08:15 +09:00
087c85c3cf selfhost/cmd/wcc: route remaining wwstage size dispatch through SSoT
Followup to 8e93b31 (#43).  Audit caught dispatch-gate sites the
sweep missed:

  - cgen.ww letpreintern's `sz == 16` str-let detector — would
    desync from emitletdataw's matching `sz == primtypesize("str"):
    i32` strlit-init branch under #1.
  - cgenstmt.ww cglet str-init MOVQ-BX gate and slice-init MOVQ-BX/CX
    gate (and the belt-and-suspenders N_TSLICE shape check at l.607).
  - cgenexpr.ww cgindex str-element loads (3 sites: globalarr,
    baselocal, generic fallback) and the matching cgassign N_INDEX
    str-element write pair (BX spill + post-index store).

All gates now read `primtypesize("str"): i32` / `tyslicesize(): i32`,
so #1's ty_str.size bump propagates through the same two-place edit
the original commit advertised.  Combined files (w6c/wwdump) updated
in lockstep.

131/131 + 994 + 995 byte-identity green; smoke.combined.ww (lib-only
consumer) emits the same asm pre vs post, confirming the change is
SSoT routing only (no behaviour shift).
2026-05-20 09:06:50 +09:00
8e93b31088 cmd/w6c+selfhost/wcc+lib: route sizeof(str)/sizeof(slice) through SSoT
Audit §1.1/§1.2 cataloged 17 wwstage sites hardcoding 16 for sizeof(str)
and ~10 hardcoding 24 for sizeof(slice), plus 4 cstage str-size sites
and the cstage let_emit_size str/slice arms.  Each new size constant
required ~30 edits in both stages to bump cleanly — task #1 (str → 24B
{ptr,len,cap}) can't land until the literal sweep is done.

Track A — wwstage codegen (selfhost/cmd/wcc/*):

  - check.ww introduces two stateless helpers next to astsize:
    primtypesize(nm)  — primitive-name → byte size (i64; -1 unknown)
    tyslicesize()     — slice-header bytes (i64; 24 today)
    astsize now reads both for its N_TNAME-primitive and N_TSLICE arms,
    so the size(T) fold gets the SSoT for free.
  - cgen.ww, cgenutil.ww, cgenstmt.ww, cgendecl.ww: every `return 16`
    / `esz = 16` / `sz0 = 16` for str, every `return 24` /
    `localadd(c, _, 24, _)` for slice, plus the matching `sz == 16` /
    `sz == 24` / `for (i < 16/24)` gates in the global-let DATAW emit,
    route through primtypesize / tyslicesize.
  - Direct delegation slotsize→astsize would require restructuring
    astsize to drop its *checker dep (resolvealias) — the leaf
    primitive/slice cases factor out cleanly, the alias-chain leaves
    diverge because cgen's aliaslookup/structlookup tables and check's
    scope chain aren't unified yet (§1.8, task #50 follow-up).  Sharing
    the leaf table satisfies the SSoT promise without that refactor.

Track B — cstage (cmd/w6c/cgen.c):

  - let_emit_size's TY_STR/TY_SLICE arms drop the hardcoded 16/24 and
    fall to `(int)u->size` like the existing TY_STRUCT/TUPLE/TAGGED arms.
  - N_LET cgstmt's per-kind `sz` cascade collapses to a single
    `if (lu->kind ∈ {ARRAY,SLICE,STR,STRUCT,TUPLE,TAGGED}) sz = lu->size`.
  - N_LET cgexpr's match-bind primitive sizing: `bsz = (int)bu->size`
    drops the TY_STR/TY_SLICE special-cases (same outcome — ty_str/
    ty_slice already have ->size set by type.c).
  - Three `sz == 16` / `let_emit_size(d->type) != 16` gates against the
    str slot width route through ty_str->size.

  Cap-offset sites (cgen.c:2440/1994/3206/5517 `delta = 16` for
  slice's .cap field-write) intentionally NOT touched: 16 there is the
  *offset of .cap inside a slice header*, structurally always 16
  regardless of str.size.  #1 doesn't move the slice layout.

Track C — lib/ user code:

  - lib/strings.freeall + appendstr, lib/shlex.freepartial + appendstr:
    the four `16u64` literals (per-str-element stride for rt_ensure and
    os.free) become `size(str): u64`.  Check-time fold via #42's
    intercept resolves to 16 today; #1 reroutes via the bumped tinfo.

After this commit, bumping ty_str to 24B for task #1 requires editing
exactly two places (cmd/wcc/type.c:64 ty_str.size, plus check.ww
primtypesize's "str" arm) for the SSoT to propagate.

Verification:
  - 131/131 tests pass.  994_w6c_ww + 995_self_rebuild byte-identity
    holds — each replacement evaluates to the same constant the
    literal had today, so cgen output is unchanged.
  - selfhost source's `size(str): u64` folds at check time (cstage
    cmd/wcc/check.c:907-960 for the C-bootstrap of selfhost; wwstage
    check.ww:898-942 for the rebuild path), no runtime call introduced.
2026-05-20 08:50:40 +09:00
3ec944a67f selfhost/cmd/wcc/check+test: fold size(T)/align(T)/offset(e.f) at check time
Mirror cstage cmd/wcc/check.c:907-960. Three typed-builtin
intercepts that cstage already had:

- size(T) — folds to a literal integer at check time from a
  newly-introduced astsize walker over the type AST. Mirrors the
  size computation in cstage resolve_type at check.c:286-528.
- align(T) — same, via astalign.
- offset(e.f) — folds the byte offset of field f in e's struct
  type via astoffset. Peels exactly one N_TPTR for `p.field`.

seedprimitives registers the three names as SK_FN nil; exprtype's
N_CALL arm gates on a same-module shadow check (per #23 alloc
precedent) and consumes the parser-planted type-expression arg.
The fold is in-place — foldtointlit mutates N_CALL into N_INTLIT
so cgen sees a plain integer. resolvewalk's N_CALL trigger
invokes exprtype so the fold fires from non-let contexts too
(e.g. inside `if (size(T) != …)`).

selfhost/test/smoke.ww gains a probe-8 block: size/align/offset
assertions across str, primitive widths, ptrs, slices, and
two structs (`point`, `mixalign`) covering both no-padding and
i8+i64 natural-align padding cases.

Known divergences NOT in #42 scope:
- size((*T|void)) ≠ 8 on the cstage nullable-ptr fold (#13 family,
  unreachable through current grammar).
- 8B-struct bare-let zero-init wwstage skip vs cstage emit (#59).
- Same-module shadow gate added here, cstage has none — sibling
  shape to #26 (free/append/len gates).

Closes the original chain that started with the user's call to
fix the structural debt — six precondition fixes (#51, #52, #53,
#55, #56, #50) landed before this fold could safely live in the
check pass. Unblocks #43 (sweep literal 16s → size(str)) and #1
(str → 24B becomes one line).
2026-05-20 05:22:57 +09:00
c58d3511e8 selfhost/cmd+test: run check before cgen in wwstage drivers
w6c_ww and wwdump_ww (-c mode) silently passed source into cgen
without type-checking it; any type error flowed through as broken
asm with exit 0. Mirror cstage cmd/w6c/main.c:73-75: between the
parse-error gate and cgeninit, install typesinit + checkinit +
checkfile + `if (ck.errs > 0) return 1;`. Cgen path unchanged —
drivers own check, cgen owns emit (checkfile not idempotent due to
installdecl scopedefine).

The wire-up was blocked by five latent check.ww divergences from
cstage, all landed first: cross-module type refs (#51), enum-int
reinterprets (#52), per-block scoping (#53), nominal-first
tagged-variant inclusion (#55), and same-module N_IDENT callee
preference (#56). With those clear, the broader exercise of
check across every selfhost driver reaches 131/131 first try.

994_w6c_ww grows by one row: a trivially-wrong `let x: i32 =
"hello";` smoke pins both stages to exit-non-zero. Pre-#50 it
emitted 202 bytes of broken asm with exit=0.

Unblocks #42 (size/align/offset wwstage intercepts) and the
audit-§1.8 UP-polarity refactor (node.type_ population can now
land in the same check pass we just wired up).
2026-05-20 04:52:16 +09:00
3fa5ccd5ae selfhost/cmd/wcc/check: same-module preference on N_IDENT callee lookup
exprtype's N_CALL callee resolution used flat scopelookup, returning
the first match in the bucket regardless of caller module. Two
modules exporting fns with the same leaf name (e.g. alpha.foo i64
+ beta.foo str) caused bare-leaf callees inside one of them to pick
the other's fn, then false-positive at return type.

Cstage cexpr N_IDENT routes through scope_lookup_prefer(c->cur,
c->cur_mod, name) which short-circuits to the same-module hit
before falling through to flat scope. Mirror at check.ww:675 —
splits N_IDENT vs N_DOT so the latter keeps flat scopelookup and
the explicit module qualifier path stays distinct (tracked as #58).

c.curmod is already tracked by checkfile pass 2 (check.ww:1240-1241),
so this is a one-call swap on the N_IDENT branch. No plumbing.

Reviewer cascade probe across all 131 .ww/.combined.ww files in
lib/ + selfhost/ shows lib/memio/memiotest.combined.ww drops 4
spurious "let: not assignable" lines as a side effect, with no new
errors. Net improvement.
2026-05-20 04:42:50 +09:00
9fed4ca492 selfhost/cmd/wcc/check: nominal-first compare in tagged-variant inclusion
isassignable's tagged-variant inclusion was resolvealias-unwrapping
both src and each variant before typeeqast. Two NAMED structs (e.g.
`(void | err)` with src=`err`) both flattened to N_TSTRUCT and
typeeqast's conservative struct branch returned false — false
positive on the assignability.

Cstage variant_match (cmd/wcc/check.c:90-100) compares TY_NAMED
pointer-identically, so the nominal name short-circuits before any
body inspection. Mirror: try typeeqast on unwrapbang'd src vs
unwrapbang'd variant first (catches the N_TNAME nominal match),
fall through to resolvealias + structural compare for anonymous-
union variants only.

Reviewer's negative probe (different types modA.err vs modB.err
with same leaf name) still correctly rejects — the parser joins
pkg.alias into one TNAME string, so modA.err ≠ modB.err at the
nominal level.

Bare-vs-qualified residual (cstage admits `(void | M.err)` ← bare
`err` inside module M; wwstage still rejects) tracked as #57. Not
hit by any current fixture; unblocks #50 (after #56) and #42.

131/131 + 4 lines of pre-existing pessimism cleared in
selfhost/cmd/wcc/check.ww's own resolution.
2026-05-20 04:34:57 +09:00
01775f2ccc selfhost/cmd/wcc/check: per-block scope push/pop in resolvewalk
resolvewalk had no per-block scoping: inner-block `let i: u64`
persisted past the block end and shadowed the outer `let i: i32`,
which then false-positived as u64→i32 not-assignable on the next
reference. The TODO at the N_LET tail explicitly deferred per-block
scoping; this discharges it.

N_BLOCK case mirrors cstage cmd/wcc/check.c:1559-1566: save c.cur,
newscope under saved, walk body via n.list, restore. Sole exit is
the return after restore — push/pop balanced by structure.

All 5 selfhost main.combined.ww files (wwdump, w6c, w6a, w6l, ww)
now resolve clean via wwdump_ww -r. Reviewer's independent probe
across every .combined.ww outside ref/ confirmed no cascade: only
selfhost/cmd/ww went 1→0 (the targeted bug); the other 14
files-with-errors are pre-existing assignability/match-typing
issues unrelated to scope resolution.

Discharges TODO at N_LET tail. Same-scope dup detection
(`let a=1; let a=2;` in one block) stays queued behind #11.
Unblocks #50.
2026-05-20 04:13:49 +09:00
1b7fde21cd selfhost/cmd/wcc/check: enum<->int reinterpret bypasses tagged check
Wwstage checkisas fell straight through to the tagged-union arm on
`enum_val as i32` reinterprets, false-positiving on every enum→int
cast in lib/ (lib/time/instant.ww, lib/os, lib/os/lseek). Cstage
admits these at cmd/wcc/check.c:1346-1357: when N_TYPEASSERT has
LHS-or-RHS enum AND both ends are integer-typed, the target type
returns without the tagged check. `is` (TYPETEST) stays rejected —
cstage gates only N_TYPEASSERT.

isinttypeast helper covers N_TENUM + i8..i64/u8..u64/int/uint/
uintptr/rune. Excludes floats so `enum as f64` still rejects.
N_TYPEASSERT branch in checkisas detects enum on either side via
resolvealias-unwrap, gates on both-ends-int, returns target type
before the tagged-union check.

4/5 selfhost main.combined.ww files now resolve clean via
wwdump_ww -r. Residual on selfhost/cmd/ww tracked as #53
(separate checkletassign u64→i32 path).
2026-05-20 03:57:47 +09:00
c7c756d9c8 selfhost/cmd/wcc/check: resolve cross-module type refs in is/as
resolvealias only walked N_TNAME with unqualified names; cross-module
type aliases (parser emits them as one TNAME with str="pkg.alias"
via parse.ww:258-265 joindotted) returned the AST verbatim, and
checkisas at :1098-1108 then flagged "operand is not a tagged union"
on every `match (x: lib.maybe) { ... }` shape.

resolvealias now recognizes the joined-dotted form: split on the
rightmost '.', scopelookupinmodule(c.cur, head, leaf), recurse if
the body is itself an alias. Mirrors cstage resolve_typename at
cmd/wcc/check.c:74-83.

scruttype gains an N_DOT scrutinee arm — `match (pkg.var) { ... }`
or `pkg.var is T` now resolve through scopelookupinmodule. Module
head gating distinguishes top-level imported sym refs from struct
field access (both spell as N_DOT in the AST).

Standalone correctness fix; surfaces no current fixture failure
(those were enum-int reinterprets, tracked separately as #52). Sets
up #50 to wire checkfile into the wwstage cgen pipeline once #52
also lands.
2026-05-20 03:42:13 +09:00
cd44cc1893 lib/strings+test: port replace per Hare
ref/hare/strings/replace.ha:46-66. Two-pass byte scan: pass 1 counts
non-overlapping needle hits via bytes.hasprefix, pass 2 allocs the
result []u8 at exact size and copies chunks + replacement. Single
nomem propagation site at the alloc — ww's append builtin aborts
on OOM (#11), so the per-chunk append(...)? form Hare uses is not
available; the exact-size single alloc is equivalent in spec.

total==0 returns {nil,0} to dodge rt_alloc(0) per #47.

Empty needle is intentionally ungated and loops forever — that's
Hare's behavior at ref/hare/strings/replace.ha:31 (i += len(needle)
is 0; hasprefix("") always matches). Hare-faithful divergence,
documented at the site.

multireplace deferred to #49 — its (str, str) variadic gather hits
#39 in variadic-param position. Filed and blocked accordingly.
2026-05-20 02:46:22 +09:00
f8770d1502 selfhost/cmd/wcc/cgenutil+test: slotsize zero for void, recurse N_TBANG
Wwstage's slotsize had a catch-all `return 8` for any N_TNAME where
primsize's `> 0` guard failed. `primsize("void") == 0` (correct —
void is zero-sized per cmd/wcc/type.c:46), so void landed on the
catch-all. (void | !void) then sized as `8 (tag) + max(8, 8) = 16`
instead of `8 + 0 = 8`, and the phantom payload word made
cgwidentaggedstore spill DX for the let-init — diverging from
cstage's `8`-byte slot.

Two narrow additions per rule 10 (align wwstage DOWN to cstage):
1. N_TBANG case at the top of slotsize, recurse on .lhs. Mirrors
   cstage resolve_type N_TBANG which copies the underlying type's
   size unchanged.
2. `void => 0` in N_TNAME BEFORE the primsize guard, so the SSoT
   matches cmd/wcc/type.c:46.

757_letbind_void_bang_void exercises three shapes — void-arm,
invalid-arm, full natural-form fromutf8 — and pins cstage/wwstage
asm byte-identity per row.

lib/strings/strings.ww fromutf8 WHY-comment drops the Bug-B
SIGSEGV caveat (measurement artifact: original test linked without
rt/start.s; RET popped argc). Keeps #19 dependency for the
eventual collapse to `utf8.validate(in)?`.

Hare matches ww's design (void zero-sized, !T inherits T's
layout); this is a pure wwstage implementation gap, not a
divergence to argue about.
2026-05-20 02:27:17 +09:00
6d006da26c lib/strings+test: graduate fromutf8 + bytesub to validating return
fromutf8(in: []u8) (str | utf8.invalid) and the bytesub form per
ref/hare/strings/utf8.ha:22 and sub.ha:59. bytesub keeps its byte
asserts (ww extension over Hare; predates #7).

fromutf8 walks the utf8 decoder via utf8.next rather than the
shorter `utf8.validate(in)?` form. Two compiler bugs in the way:
cross-shape `(void | invalid) → (str | invalid)` propagation is
#19, and (void | !void) match-bind locals diverge between stages /
str→union lift SIGSEGVs in cstage — both filed as #48. The
decoder-walk form bypasses both and matches what
ref/hare/strings/utf8.ha actually does in source.

getopt.ww:314 caller updated to match the new (str | invalid)
return; bi+1 cannot hit a continuation byte in well-formed argv
(bi is a just-matched ASCII flag), so abort spells the precondition.

bytesub_cases rewritten as exhaustive match; new rows cover
start-on-continuation and end-on-continuation invalid arms plus an
end==s.len bypass. fromutf8_cases is new — Hare vector + edge
bytes + multibyte parity rows.
2026-05-20 02:02:28 +09:00
e03a6281d6 lib/strings+test: port dupall from Hare
ref/hare/strings/dup.ha:26-35. Returns ([]str | nomem); duplicates
every str in the input slice via the now-graduated alloc-slice
builtin (#45 unblocked `let s: []str = alloc([], n)?`). Loop body
uses appendstr because `[]str` element is 16B and the bare `append`
builtin truncates (#11) — pre-allocated cap=s.len means rt_ensure's
grow branch never fires.

Defer-rollback omitted: with `dup()` still unchecked (graduation
tracked by #46), the only nomem source is the initial slice alloc,
so there is no partial state to roll back. Will revisit when #46
lands.

Empty-input early-return short-circuits via {nil,0,0} because
rt_alloc(0) is an mmap of 0 bytes which the kernel rejects with
-EINVAL — Hare hands back a sentinel. Localized at the call site
pending #47.

Tests assert independent allocations at every index of multi-element
inputs, including a multibyte row.
2026-05-20 01:30:12 +09:00
4d4ad36b70 cmd+selfhost+test: relax alloc-slice element-type pin via LHS retype
`alloc([], n)` synthesizes ([]u8 | nomem) at expression level — that's
fine, since the slice form only legitimately appears in let-init
position where the LHS carries the real element type. In clet, after
type-checking the rhs, peel any N_TRYPROP/N_TRYUNW wrapper, match the
alloc-slice AST shape with the same-module shadow gate (from #23),
and retype the call's tagged return to ([]T | nomem) where T is the
declared LHS element. Then assignability sees []T vs []T and accepts.

Cgen N_LET shortcut gains a viatryprop arm next to the existing
viatryunw — on rt_alloc returning null, emits the tagged-return
nomem propagation (MOVQ $nidx, AX; epilogue) instead of exit(1).
nidx comes from cg_tag_for_variant on the enclosing fn's return type,
matching the existing TRYPROP propret path.

Wwstage mirrors all four hunks (check.ww + cgenstmt.ww). Promotes the
previously-silent conf=false skip into a confident accept.

Unblocks #6 (dupall) and lays the path for #4/#7. Byte-identity
holds modulo the pre-existing #44 alloc/rt_alloc symbol divergence.
2026-05-20 01:09:16 +09:00
30a0856fe5 selfhost/cmd/wcc/cgenstmt+test: emit slice-form alloc let-init shortcut
Cstage's cmd/w6c/cgen.c:6363-6411 special-cases `let s: []T =
alloc([], n)!;` to inline rt_alloc + null-check + exit(1) + slice
header build, avoiding a generic call-then-store path. Wwstage's
cglet had no mirror — pre-#31 the path was rejected at check, but
once #31 made the check side accept it, the cgen side would have
silently miscompiled. Mirror added at cgenstmt.ww cglet rhs head,
emitting byte-identical asm.

Element size goes through elemsizeofc so str (16), structs, and
tagged aliases all match cstage's lu->sub->size uniformly — the
defensive path matters because check today only allows []u8, but
relaxing that is its own task.

Test exercises the path: writes to s[0] and s[15], reads back. Would
SIGSEGV on a junk header. 994 + 995 byte-identity green.
2026-05-20 00:28:27 +09:00
6f10c832a4 selfhost/cmd/wcc/check+test: reject bare alloc(v) at let-init in wwstage
Cstage's check.c:981-1006/1052-1082 builds a real (*T|nomem) /
([]T|nomem) return type for the alloc builtin; wwstage was returning
nil from exprtype's N_CALL arm (alloc is SK_FN with decl=nil under
seedprimitives), and checkletassign early-returned on nil src,
silently accepting `let p: *T = alloc(v);` without `!`. Stage
asymmetry that #30 papered over until now.

Three coordinated edits in check.ww:
- exprtype N_CALL: synthesize N_TTAGGED{N_TPTR{argt}, nomem} or
  {N_TSLICE{u8}, nomem} for bare alloc (same-module gated, mirrors
  cstage check.c:981-985 / task #23).
- exprtype N_TRYUNW: project the success variant so `let p:*T =
  alloc(v)!;` resolves rhs to *T.
- isassignable: tagged → non-tagged is unconditionally not
  assignable, forcing match/?/!.

950_selfcheck.c rows pin both ptr and slice forms.
2026-05-20 00:03:43 +09:00
dd27ce3339 lib/strings+test: re-port index str-arm to dual-iterator rune walk
Old shape ran byteindex then rewound to count runes — two passes,
different algorithm from Hare. New `indexstring` mirrors
ref/hare/strings/index.ha:59-81: one outer iterator over the
haystack, an inner iterator re-seated from it for each candidate
match, both walking rune-by-rune. Returns the rune-index of the
first match, or void.

Rest-iterator copy is field-wise rather than `let rest_iter =
s_iter;` because the local-to-local copy of the 3-field iterator
struct diverges between stages today (#41 — 993_ww_ww and
995_self_rebuild byte-diverge when written the natural way).
WHY-comment cites #41 with the precise failing tests.

Tests pin the rune-vs-byte distinction at i=2 and i=4 with 3-byte
kana, plus self-match, empty-needle, empty-haystack, and a no-match
multibyte row from ref/hare/strings/index.ha:119.
2026-05-19 23:11:01 +09:00
18fe1a7a31 lib/strings+test: 0-arg trim strips ASCII whitespace per Hare
The 0-arg ltrim/rtrim/trim used to return input unchanged. Hare's
0-arg form strips [' ', '\n', '\t', '\r'] (ref/hare/strings/trim.ha:6).
Aligned by delegating to bytes.ltrim/bytes.rtrim with the whitespace
set spread inline at the call site — the obvious `let ws = whitespace[0:4]`
shape produces a slice whose ptr does NOT alias storage (#40).
N-arg forms (strip-specific-runes) untouched.

Test rows retargeted to Hare's canonical inputs from trim.ha:78/85
so '\r' is exercised alongside ' '/'\t'/'\n'.
2026-05-19 22:52:23 +09:00