Latent #21 has two surface shapes — register polarity in cgun
TK_AMP N_INDEX's complex-base arm, and indexbaseesz's
over-broad .ptr pseudo-field gate — that share a single semantic
path: &N_DOT[N_INDEX] where the inner N_DOT cannot be peeled
into a plain ident base. Polarity-A (cgenexpr.ww) lifted to
cstage's three-line shape; stride-B (cgenutil.ww) narrowed so
the .ptr arm only fires on actual str/slice inners and falls
through to the generic struct-field arm for struct N_TNAME
bases. The fixes compose at the same call site (esz from
indexbaseesz, then the IMULQ-or-elide gate, then complex-base
emit), so splitting them into two commits would leave a
half-fixed intermediate — neither half stands alone as a
bisect-clean closure. Sentinel 755_amp_dot_idx exercises both
shapes across 4 stride classes (slice-elem 24, struct-elem 16,
u8 stride-1 elide, i64 stride-8); pre-fix 5/12 fail, post-fix
12/12 ok. Latent silent miscompile in lib/memio + lib/bufio's
.ptr[i] shape also unmasked.
Cstage and wwstage share the latent: check.c's N_INDEX bespoke
TY_PTR-over-TY_SLICE clause peeled the slice in `*[]T[i]` and
returned the element of the element, while wwstage's elemsizeof
had no N_TSLICE arm for the post-N_TPTR-peel elem and fell to
the 8B catch-all. Splitting leaves one stage broken on the
exact `*[]T[i]` shape the new 754 sentinel asserts byte-identical
between stages (rule 11). The companion 24B per-element copy
emit is a separate codegen wedge already pinned inline at
cmd/w6c/cgen.c:6518; out-of-scope here and noted in the fixture
header.
Structural close of the #4-trio convenience-wrapper audit. Session-6's
#4-trio + #11/#16 graduated individual lookup helpers (fnret/fnparams/
enum/struct/def) to same-module-first via *mod variants. The close
didn't enumerate every cgcall-context callsite — convenience wrappers
that take a *node callee and probe its return shape via bare-leaf
fnretlookup stripped the N_DOT module hint, same wedge shape as #16
(callee_variadic_param, d9b0c90) through a different family of
consumers.
Eight LATENT sites in selfhost/cmd/wcc fixed (each mirrors #34's
nodeisslice two-arm route — N_IDENT uses cmod=c.curmod, N_DOT uses
cmod=callee.lhs.str, terminal call routes through fnretlookupmod):
- cgenstmt.ww cgreturn forwardtagged probe
- cgenstmt.ww cgmlet tuple-return shape probe
- cgenexpr.ww cgdot fn-rvalue probe (mod.fn LEAQ)
- cgenexpr.ww cgtryprop succisstr probe
- cgenexpr.ww cgtryunw succisstr probe
- cgenutil.ww callsretsize (sret arg-prep)
- cgenutil.ww inferletcalltype (let x = f()? tnode)
- cgenutil.ww rhstaggedabicall N_CALL branch
cstage carries no sister bug: cmd/w6c/cgen.c reads every callee
return shape from the typed n->lhs->type per TY_FN sig. Mirror of
#4d/#28/#31/#34/#16 cstage no-sister notes.
753_convwrap_audit: table-driven sentinel exercising cgmlet's tuple-
shape probe. alpha exports foo() (i64, str); beta exports foo()
(i64, i64); main calls beta.foo() — source order puts alpha LAST so
alpha.foo prepends to head of c.fnrets, pre-fix bare walk picks
alpha's str-branch dispatch for beta's call. Post-fix routes to
beta.foo via fnretlookupmod. Asserts MOVQ\\tCX, absent in main.run
TEXT (no str.len store; would fire pre-fix). Remaining 7 sites
covered structurally by shape-mirror — single wedge shape, single
exercise.
make test 127/127; ww2==ww3==ww4 byte-id holds via 995_self_rebuild.
Latent silent miscompile surfaced by worker-strcontains3 attempting
strings.contains tagged-variadic graduation: wwstage cgcall's
callee_variadic_param helper (cgenutil.ww:60-70) consumed the N_DOT
callee's leaf via callee.str but routed bare fnparamslookup — bypassed
the module hint at callee.lhs.str. When two modules export same-leaf
fns with differing variadic shapes (e.g. strings.contains(str|rune)...
+ bytes.contains scalar (u8|[]u8)), the bare walk returned the wrong
fn's params for arg-prep while the CALL targeted the correct
module-qualified symbol — ABI mismatch.
Direct sister of #34 (049ebc1) which graduated fnret's N_DOT arm
through fnretlookupmod. #4d's commit body (862715d) explicitly
deferred callee_variadic_param's *mod re-routing pending "future
stdlib port introducing a tagged-vs-scalar or variadic-vs-non-variadic
same-leaf N_DOT collision shape." This is that surfacing.
cgenutil.ww: split callee_variadic_param on callee.kind. N_IDENT stays
on bare fnparamslookup (same-module-first post-#4d). N_DOT routes
through fnparamslookupmod(c, callee.str, callee.lhs.str), pattern-
identical to cgcall's N_DOT branch at cgenexpr.ww:2922-2935.
Cstage cmd/w6c/cgen.c:4279-4302 reads callee params via typed AST
(n->lhs->type + cu->params) — module-aware natively, no sister
change needed (mirrors #4d/#28/#31/#34 cstage no-sister notes).
752_modparam_callee: table-driven 3 rows x 2 stages = 6 fixtures.
cross_module_same_leaf_variadic_vs_scalar (the wedge),
same_module_same_leaf (no-regress), bare_leaf_no_collision (control).
#17 filed for the wider convenience-wrapper audit (enumerate all
wwstage cgen* helpers that take *node and do bare-leaf lookups; sweep
for N_DOT-arm omissions). This commit is narrow to callee_variadic_param.
make test 126/126; ww2==ww3==ww4 byte-id holds via 995_self_rebuild.
pushargsrev's widening detection was N_IDENT-only — N_INDEX of a
sum-typed slice element fell through to the scalar widening branch,
which hardcoded the param's first-variant tag (MOVQ $1, AX) and
pushed AX as a single scalar word. Callees that match-dispatched
on the runtime tag always ran the static-guess arm on garbage.
cstage knew the arg's type via check.c so its widen[] flag stayed
off and the natural-push tagged-arg arm pushed CX/DX/AX (high → low)
high → low. wwstage now mirrors via two narrow arms in pushargsrev:
the aistagged guard treats N_INDEX-of-sum-typed-element matching
the param slot as already-tagged, and the natural-push fallthrough
emits PUSHQ CX / DX / AX for the same shape. Both arms gate on
istaggedtype(indexvaluetnode(arg)) so literal- and ident-source
sum args stay on their existing paths.
Sentinel 749_sumtype_forward table-drives the three forward shapes
(N_INDEX, N_IDENT, literal) and asserts per-stage runtime plus a
byte-id window over the callsite asm.
Combined.ww regen for wwdump_ww and w6c_ww follows the cgen source
change; smoke.combined.ww unaffected.
Tests: 123/123 pass; bootstrap fixed point holds (ww2==ww3==ww4).
Subsumes #36. Drop wwstage scanlocals pre-pass; both stages converge on
first-use+fail-loud frame growth, rule-10 polarity DOWN to leaner side.
#36's surfaces (frame-total divergence on match-arm case-let; sibling
offset divergence in variadic+iter+match-prev compositions) close
naturally — running-max c.frame includes every first-use binding.
selfhost/cmd/wcc: add atlocals persistent @-prefix registry surviving
cgblock save/restore; add cgoutbuf/cgoutmode/cgout_enable/disable/flush
for deferred prologue (emit body to buffer, finalise c.frame, then
TEXT/SUBQ + flush); localadd @-prefix dedups against atlocals +
fail-louds on size-grow (rule 7 — no silent truncate); cgreturn-tagged
routes through @retscr (was colliding with @tagscr on arg-widen sizes);
variadic gather esz uses raw primsize (rune->4) not slotsize (rune->8)
— matches cstage and fixes the #36 sibling runtime miscompile in
non-leaf variadic+iter+match-prev callees.
cmd/w6c/cgen.c: drop the over-allocation hack ("for byte-id with
wwstage scanlocals reservation") since wwstage no longer over-reserves;
add fail-loud on @sretscr size-grow; @tagscr sites pass actual slot_sz
instead of stale c.tagscrsz.
748_size_strategy_convergence: table-driven 4 rows x 2 stages
(tag_variadic_runearm, trim_iter_match_prev, variadic_gather_rune_stride,
leaf_baseline). Each exercises a #36 surface shape; 8/8 ok.
Net -1565 lines. Sister latents filed as cosmetic (cs/ws frame size
drift on multiple-variadic-call fns): labelseq drift + varargseq
stuck at 0 — both bootstrap-byte-id safe (ww2==ww3==ww4 holds since
both ww2 and ww3 are wwstage outputs).
make test 122/122; ww2==ww3==ww4 byte-id holds via 995_self_rebuild.
Class A silent miscompile, surfaced by landing strings.slice in
Hare's natural delegation form `fromutf8_unsafe(utf8.slice(begin,
end))` (ref/hare/strings/iter.ha:75). strings.slice itself returns
str, so the inner utf8.slice (cross-module N_DOT) call's cgcall
return-ABI fixup hit post-#4e fnretlookup's same-module-first walk
and grabbed strings.slice's own str return — emitted a spurious
`MOVQ DX, BX` after the cross-module CALL even though utf8.slice
returns []u8 (selfhost/cmd/wcc/cgenexpr.ww cgcall return-ABI fixup,
line 3249-3261 pre-fix). Every other consumer of cgcall:3249's
str-shuffle decision sat on the same bare-leaf table and was
silently miscompiling on the same collision shape pre-#34.
Sibling: nodeisslice + nodeisstr N_CALL arms in
selfhost/cmd/wcc/cgenutil.ww were N_IDENT-only — for a cross-
module N_DOT call returning a slice or str, pushargsrev fell
through to the natural 1-word PUSHQ AX, dropping the `.len`
(and `.cap` for slices) of the return value when consumed as a
call arg. strings.slice's body passes utf8.slice's []u8 result
to fromutf8_unsafe; pre-fix wwstage pushed 1 word vs cstage's
3, breaking the receiver's slice-3-pop drain.
Cstage carries no sister bug: cmd/w6c/cgen.c reads return shape
from the typed `n->lhs->type` (TY_FN sig) for both str-shuffle
and slice-/str-arg push counts — module-aware via the typed AST,
sidestepping any bare-leaf table. Mirror of #4e's cstage-no-
sister-bug note.
Fix: route cgcall return-ABI fixup + nodeisslice/nodeisstr N_CALL
arms through fnretlookupmod with `callee.lhs.str` (N_DOT
qualifier) or `c.curmod` (N_IDENT). Mirror of #28
fnparamslookupmod / #31 fnretlookupmod N_DOT re-routing.
Remaining bare-leaf fnretlookup consumer sites (~8 sites across
cgenexpr/cgenutil/cgenstmt/cgendecl listed in task #34a) stay
on the graduated bare-leaf path — none of the present-corpus
N_DOT leaf collisions have return-shape divergence at those
sites. A future stdlib port introducing a return-shape-divergent
same-leaf N_DOT collision will need the *mod re-routing — filed
as #34a sibling-latents.
Bundled three concerns per rule 11: cgcall fix, nodeisslice/
nodeisstr fix, and strings.slice retire + sentinel. (a) alone
leaves strings.slice byte-id breaking on slice-arg push count.
(b) alone leaves a phantom MOVQ DX, BX on the inner cross-
module CALL. (c) alone fails 995_self_rebuild without (a)+(b).
The three cannot land separately bisect-cleanly; the 745
sentinel pins the primary repro (cgcall str-shuffle) which
sentinel-flips on a cgcall:3257 revert.
745_fnret34_modshadow pins the fix with 1 row: caller.slice
returns str (same leaf as the cross-module callee, divergent
return shape); caller.run calls myutf8.slice returning []u8.
Asserts CALL myutf8.slice present inside caller.run TEXT +
`MOVQ DX, BX` anti-check on each stage plus cs-vs-ws byte-id.
strings.slice retired in lib/strings/strings.ww: the deferral
block becomes the natural Hare delegation form with two local
utf8.decoder reconstructions for the iterator endpoints — ww
has no anonymous-embed (parallel to the existing `move` helper).
iter_slice_cases mirrors ref/hare/strings/iter.ha:110-127;
sidesteps the Hare `let t = s;` iterator-copy via fresh
strings.iter() to stay clear of #35's sibling latents.
119/119 ok. ww2 == ww3 == ww4 byte-id holds.
Wwstage's N_INDEX-lhs cgassign dispatch chain had a triple-site
N_DOT base gap (sister latents filed during #24 / #27 review):
Read (#28): `obj.mat[i][k]` over a struct field mat: **u8.
cgindex routes the outer N_INDEX's N_INDEX base through
indexvaluetnode; the recursion bottomed out at the inner
N_INDEX's N_DOT base with bt=nil. esz fell through to 8 +
signed_elem to false — wwstage emitted a stray outer
`MOVQ $8, CX; IMULQ CX, AX` plus `MOVQ (AX), AX` (8-byte
read over a 1-byte u8) instead of cstage's bare
`MOVZBQ (AX), AX`.
Write (#30): `obj.arr[i] = v` over a struct field arr:
[N]Tagged (e.g. (i64|str)). cgassign's N_DOT-base arm
computed esz via indexbaseesz but never set elemtn, so the
tagged-element store gate missed and the 24-byte tagged slot
was overwritten by a single scalar MOVQ — wrong-width store
+ tag/payload junk in the upper 16 bytes.
Cstage walks `n->lhs->type` directly via the typed AST
(cmd/w6c/cgen.c idx_eff + the N_INDEX-lhs N_ASSIGN branch).
Wwstage now mirrors via indexvaluetnode, which #24 (aa8ca47)
introduced for the N_INDEX-base case; #28/#30 graduate it for
N_DOT base via the existing dotfieldtnode helper.
Bundle graduates N_DOT base for the entire N_INDEX-lhs cgassign
chain: (a) indexvaluetnode in cgenutil.ww handles N_DOT base via
dotfieldtnode; (b) cgassign N_DOT-base arm in cgenexpr.ww calls
indexvaluetnode for elemtn; (c) scanlocals N_DOT-base arm in
cgendecl.ww parallels the existing N_IDENT arm for tagscr-bump.
Splits are bisect-incoherent: (b)-alone clobbers locals via
under-sized frame, (a)-alone leaves the write path with wrong
elemtn, (c)-alone has no consumer. Only the triple delivers a
complete N_DOT-base graduation matching #24's N_INDEX-base
pattern.
Cstage's first-use+fail-loud strategy for @tagscr (#26 commit
069548d) handles the N_DOT-base shape naturally; the scanlocals
N_DOT arm is wwstage-specific. Long-term rule-10 convergence
(wwstage DOWN from scanlocals to first-use+fail-loud on BOTH
stages) is filed as task #15.
Class A wwstage cgen UNDER. No in-tree consumer; sister latents
filed during #24 + #27 reviews. Test 741_dotbase_chained pins
the dispatch + cstage-byte-identical asm for both rows.
Sister latent (filed): indexbaseesz has no N_TARRAY arm for
scalar struct-field array writes — `s.arr: [N]i32` scalar write
falls through to esz=8 on wwstage. No in-tree exerciser; tight
scope kept here.
115/115 ok. ww2 == ww3 == ww4 byte-id.
Wwstage cgindex's base-inspection (cgenexpr.ww) only computed esz/
signed_elem when base.kind == N_IDENT or N_DOT. For a chained
`names[i][k]` (names: **u8) the outer N_INDEX has base.kind ==
N_INDEX; esz fell through to the default 8 so the outer load
emitted `MOVQ (AX), AX` over a 1-byte u8 plus a stray
`MOVQ $8, CX; IMULQ CX, AX` scaling on the outer index that cstage
doesn't emit. Wrong-width-narrow-load: the byte was read as 8 bytes
(reaching into adjacent memory) and the outer offset multiplied by
sizeof *u8 instead of sizeof u8.
Cstage walks n->lhs->type directly via the typed AST
(cmd/w6c/cgen.c idx_eff → eff->sub->size at N_INDEX). Wwstage
needed the parallel via indexvaluetnode — return the value-type
of an N_INDEX expression by stripping one element layer off base's
type, recursing for chained inner. cgindex's else-if chain now
adds the N_INDEX arm: call indexvaluetnode + elemsizeofc/
elemissignedc.
Class A wwstage cgen UNDER. Surfaced first time the codebase
exercised the **T[i][k] shape — through expanddir in
selfhost/cmd/ww/main.ww (post-#22 dir-enum, commit 9e0816e). The
workaround there split names[i][k] into `let nm: *u8 = names[i];
nm[k]` to route through the bare-pointer index path. Retired in
this commit: expanddir uses the natural chained form since the
read path is now byte-identical across stages.
Bundling justification (rule 11): the workaround retirement is
the in-tree verification this fix works — without retiring,
neither bootstrap byte-id nor 995_self_rebuild exercises the
chained read shape. Test 739_chained_index pins cstage-byte-
identical asm for **u8 (MOVZBQ load, 1 inner-stride-8 IMULQ pair,
no outer scale) + **i32 (MOVSXD load, inner $8 + outer $4 IMULQ
pairs).
Sister latents filed (no in-tree consumer, no probe):
Task #27 — cgassign chained-write N_INDEX: write path
`names[i][k] = v` for **u8 has the same dispatch gap. Selfhost +
lib grep is empty.
New latent (filed during review) — cgindex N_DOT base on chained
index: `obj.mat[i][k]` over a struct-field base falls back to
esz=8. indexvaluetnode currently handles N_IDENT + N_INDEX bases
only.
113/113 ok. ww2 == ww3 == ww4 byte-id.
User-mandated language redesign: source files declare their own
namespace via the new `package <name>;` keyword and pull dependencies
via `import <path>;`. Both keywords use Plan-9 `.` separator (user
override on Hare's `::` — `import encoding.utf8;`). Internal token-
kind enum values TK_MODULE=86 and TK_USE=17 kept stable for 990
wwdump byte-diff symmetry; only kwtab strings + tokname spellings
rotated. Executables (selfhost/cmd/{ww,w6c,w6a,w6l,wwdump}/main.ww)
declare `package main;` per Go convention; lib/ + selfhost/cmd/wcc/
files declare their parent-dir basename.
One-commit bundle per the brief's all-at-once directive: a per-stage
split breaks bootstrap byte-id mid-rewrite (cstage with new keyword
can't parse old `module`/`use` files and vice-versa). Body documents
the bundle per rule 11.
Two retained divergences from the user's stated ask, both filed per
rule 7 / rule 8 with inline task pointers at the deferred sites:
Task #22 — Directory-as-module enumeration in the driver. User
asked: "module is combination of files in directory" (golang/hare
shape). After this commit lib/ww/{ast,sym,typ}.ww all declare
`package ww;` but are still pulled into the compilation unit via
explicit sibling `import` chains (sym.ww does `import ast;` etc.),
not via dir enumeration. The cstage scaffold for true dir
enumeration was drafted and reverted because the symmetric wwstage
port requires a ww-side opendir/readdir wrapper around getdents64
(~150-200 lines new ww). Inline citation at locate_import_in /
locatein in both stages points to task #22.
Task #23 — Parser strict missing-`package` error. The original
brief mandated: parser errors when a .ww source omits `package
<name>;` as its first non-comment item. Softened here to silent-
default because 63 test wrappers (200_parse, 100_lex, 300_check,
400_w6c, ..., the inline-source-fragment family) build ad-hoc ww
source strings that lack `package` and the strict error cascaded
into 60+ test failures. Migration is mechanical-sed but deferred
so this commit ships green. Inline citation at parsefile in both
stages points to task #23.
Node.module renamed to Node.nmod and modent.module to modent.nmod
in wwstage source — the field name `module` would collide with the
freshly-reserved TK_MODULE token. The rename is left in place as
clean separator between AST-field-name and reserved-keyword
namespaces. Cstage's n->module retained — C has no `package` or
`module` keyword.
rt/ensure.ww deliberately ships WITHOUT a package declaration so
its `export fn rt_ensure` keeps the bare linker symbol; adding
`package rt;` would mangle to `rt.rt_ensure` and break libwwrt.a
linkage. Documented at the file head.
111/111 ok (110 + new 738_module_decl sentinel). 995_self_rebuild
byte-id holds (ww2 == ww3 == ww4). All 5 frozen
selfhost/cmd/*/main.combined.ww regenerated under the new driver.
CLAUDE.md rule 5 amended with the language-layer divergence note.
Class A silent miscompile, latent until two modules export the same
struct leaf name. Wwstage's structlookup (selfhost/cmd/wcc/cgenutil.ww)
walked c.structs head-first by sname, returning the FIRST match.
cgdot's *struct field-load branch handed it inner.str (the bare
leaf from a parsed N_TPTR whose inner is N_TNAME) and the head-pick
silently emitted the wrong-module field offset — a displacement
against BX that loaded whatever the colliding-module struct happened
to align there. Cstage carries no sister bug: resolve_typename
(cmd/wcc/check.c:65) already routes bare-leaf TY_STRUCT names
through scope_lookup_prefer per c->cur_mod, and cgen.c reads
fi.foff off the typed Sym — cs vs ws asm diverged on every bare-
leaf collision but no in-tree corpus declares two same-leaf
structs, so 995_self_rebuild stayed green (same surfacing pattern
as #4a enumlookup post-strings).
Fifth leaf of the trio leaf-name lookup graduation (after #27
aliaslookup, #28/#31 fnparams/fnretlookupmod, #4a enumlookup):
structlookup grows a same-module-first walk before the head-walk
fallback, mirroring aliaslookup's two-pass shape. No structlookupmod
variant — pkg.S collapses at parse time (lib/ww/parse/parse.ww
joindotted) into a single N_TNAME str routed through the existing
embedded-dot smod==pkg branch, so there's no cgdot-style N_DOT
consumer surface to add a *mod variant for (deferred per rob until
one surfaces). No cstage symmetric fix needed for the same reason
the bug doesn't surface there.
734_struct_modshadow pins the fix with 2 rows: row 1 bare-leaf in
module M must fold against M's own S even with another module's
same-leaf S at the head of c.structs (asserts the matching field-
load disp inside the right TEXT sym + bad disp NOT-presence anti-
check + byte-id between stages); row 2 pkg-qualified alpha.S
from inside alpha is defensive coverage of the pre-existing
embedded-dot smod==pkg branch — same path pre/post-fix (no
sentinel-flip on this commit), pinned here so a future regression
to the embedded-dot lookup is caught.
Wwstage matchscrutt now mirrors cstage's typed-AST scrutinee-type
lookup for module-qualified mod.fn(...) callees, restoring per-arm
tag dispatch on cross-module shadowed-name 4-arm matches. Class A
runtime miscompile, silent across collectfnrets shadowing — was
the 8th unmask of session 5.
Pre-fix: wwstage's matchscrutt N_DOT branch (cgenutil.ww:2061)
called `fnretlookup(c, callee.str)` — name-only resolution.
collectfnrets prepends to c.fnrets, so when a caller fn (e.g.
lib/strings's `next`) shadows a callee fn-name (utf8's `next`),
the prepend chain has the caller's narrower tagged return at the
head. matchscrutt then resolved the scrutinee type to the WRONG
tagged shape, and variantindex lookups for arms past the
shadowing caller's variant count returned -1 → want=0 →
match-arm `CMPQ $0, AX` for arms 2 and 3 on a (rune | done |
more | invalid) probe. Effect: arms 2/3 silently unreachable
even when the runtime tag matched, falling through to default.
Cstage gets the scrutinee type via the checker-set callee type
on the N_DOT node, so picks the correct utf8.next return shape.
Polarity catalog: wwstage UNDER — fnretlookup missing module-
preferring discipline. **Third leaf in the same trio**: #27
(aliaslookupmod), #28 (fnparamslookupmod), #31 (fnretlookupmod).
Pattern is recurring; full graduation of all leaf-name lookups
to same-module-first is a candidate for STATUS-3 task #1
variant-widen consolidation refactor (deferred to next session
opener per rob).
Fix: new fnretlookupmod helper in cgen.ww (same-module-first
walk, fallback to existing first-match — cell-for-cell mirror
of fnparamslookupmod from #28). matchscrutt N_DOT branch
extracts `cmod` from callee.lhs.str and routes through the
helper. Other 13 fnretlookup callsites untouched per #28's
"fix only what has a real consumer" discipline. fnret.fmod
field + collectfnrets f.fmod assignment already landed in #28.
Surfaced by lib/strings commit-2 pre-flight: probe iter+next
shape calls utf8.next; the probe's own `fn next` shadows
utf8.next at the c.fnrets head. Bootstrap-stable because no
selfhost-corpus path shadows a fn name across modules with a
wider tagged return on the shadowed side; lib/strings.iter
pulling utf8.next under wwstage was the first exerciser.
Filed follow-up (NOT in scope here): #32 wwstage runtime stomp
on utf8.next via *iterator caller — separate Class A surfaced
by 929 direct utf8.next regression row design. #31's fix is
correct in isolation; #32 blocks lib/strings commit 2 (#30).
Tests:
- 728_match_4arm_cross_module pins distinct CMPQ $K, AX tags
in TEXT b.next via bitmap covering [0..arms), robust to
arm ordering. Three cross-module shadowed-name shapes × cmp
-s byte-id. Sentinel-flip-verified: revert fnretlookupmod
route → 3/6 wwstage fixtures fail "arm K repeats tag $0
(collapse)".
- 929_match_4arm_cross_module_run runtime-pins 6 rows × 2
stages per-arm exit-code shape: 3/4/5/6-arm boundary,
mixed (i32|str|rune|u8), reverse arm-order in match source.
Confirms bug follows fnretlookup-resolved type, not match
source order.
102/102 ok. 995_self_rebuild stays green (ww2==ww3==ww4 byte-id).
Wwstage's cglet skipped MOVQ $0 for sz=8 slots that cstage
zero-inits unconditionally — !void error types (utf8.invalid)
and void-alias variant tags (utf8.done / utf8.more) drifted
byte-id post-utf8 + lib/strings; promotes STATUS-3 #22 from
latent to bootstrap-blocking. Cstage emits MOVQ $0, -K(BP) in
the prologue for any sz=8 let-decl slot via the natural
type-fallthrough; wwstage's `typeis8byteprimitive` helper
returned false on N_TBANG and on N_TNAME pointing to an alias
that resolves to void, so the gate never fired and the slot
stayed uninitialised.
Polarity catalog: wwstage UNDER — `typeis8byteprimitive`
classifier too narrow at N_TBANG and void-alias N_TNAME.
Convergence wwstage → cstage's natural sz=8 fallthrough (rule
10). N_TBANG arm recurses on inner type (cmd/wcc/check.c:290
resolve_type copies T's kind, only sets iserror — so !T is
8B iff T is 8B); void-alias N_TNAME resolves through alias-
recursion the same way.
Tests:
- 724_letdecl_zeroinit pins MOVQ $0, -K(BP) presence between
function prologue and body on canonical !void and void-
alias rows, plus cmp -s byte-id between stages per row.
Filed follow-up (NOT in scope here): #25 wwstage 8B struct
without rhs still under-emits (structlookup != nil short-
circuits the classifier). Same family as STATUS-4 #36 primsize
composite-aware sizing. No in-tree consumer.
96/96 ok. 995_self_rebuild stays green (ww2==ww3==ww4 byte-id).
Wwstage call-arg-emit recognized slice args only when source was
IDENT/SLICE/CAST/DOT. For N_CALL returning []T the natural-push
fallthrough emitted one PUSHQ AX (lost .len/.cap) and cgcall's
pop-count under-drained by 2 words — corrupting R8/R9 and every
subsequent arg. Class A runtime miscompile with stack misalignment
and 3-POPs-of-garbage at the receiving call. Sister to #21
(tagged-CALL arg) but for plain []u8 slice, not tagged-variant —
wwstage's pushargsrev grew the tagged-CALL arm at #21 and never
grew the plain-composite arm.
Surfaced by lib/strings landing's `bytes.X(toutf8(in), p)` call
sites: 995_self_rebuild's wwstage rebuild tripped on byte-id
divergence at w6c_ww + wwdump_ww emit. 967_bytes_run was green
because `ww run` exercises the cstage path. Corpus-coverage-blind
on the wwstage side until lib/strings pulled the chain through
wwstage compilation.
Fix is minimal: `nodeisslice` (selfhost/cmd/wcc/cgenutil.ww) gains
an N_CALL arm structurally identical to the existing N_CALL arm in
`nodeisstr` (only swap: isslicetype for isstrtype). The downstream
natural-push slice path (PUSHQ CX/BX/AX, extra=2 pop-count) was
already correct — it just needed the N_CALL-of-slice-return shape
to be recognized as a slice. pushargsrev and cgcall untouched.
Polarity catalog: wwstage UNDER — missing N_CALL arm in slice
shape recognition. Convergence wwstage → cstage per rule 10
(cstage reads typed-AST `type_isslice` natively).
Tests:
- 723_composite_call_arg pins the 3-PUSH order (CX, BX, AX)
between `CALL view` and next CALL on canonical `f(g())` shape,
plus cstage vs wwstage cmp -s byte-id.
- 927_composite_call_arg_run runtime-pins 7 rows × 2 stages =
14 fixtures: canonical, slice-CALL + let-slice (hasprefix
shape), two composite-CALL args (arg-shift collision),
middle-argpos, nested composite-in-composite, slice + scalar
pop-count mix, tagged-CALL regression alongside (confirms
#21 still holds).
95/95 ok. 995_self_rebuild stays green (ww2==ww3==ww4 byte-id).
Class A wwstage cgen miscompile, silent until wwstage path engaged.
Pre-fix wwstage's name-keyed flatvariantidx returned -1 for `[]T`
variants (pat.str empty on N_TSLICE), so cgmatch and
cgtagvariantidx collapsed every `(scalar | []T)` arm to tag 0.
Internally consistent within wwstage; cstage's structural
`type_eq` (cmd/w6c/cgen.c:466 cg_tag_for_variant) matched
correctly. Bootstrap stayed green because no selfhost-corpus path
exercises `(scalar | []T)` until lib/bytes / lib/strings landing
pulls bytes.index through wwstage compilation — 967_bytes_run
uses `ww run` (cstage only), so the wwstage path was never
exercised.
Polarity catalog entry: wwstage UNDER (missing N_TSLICE dispatch
arm in variantindex lookup), not REVERSE — worker's deeper read
corrected rob's initial diagnosis. cstage's structural type-eq is
the leaner-correct side; wwstage converges to it per rule 10.
Fix: new `flatslicevariantidx` helper in cgenutil.ww keyed on
N_TSLICE shape walking pat.lhs against vt.lhs alongside the existing
name-keyed flatvariantidx; extend `taggedvariantindex` shape-fallback
with a `wantslice == ivisslice` axis alongside the existing str
axis; route N_TSLICE in cgenexpr.ww's cgtagvariantidx (is/as)
and cgmatch (case) through the helper. No edits to cgenmatch's
dispatch codegen (CMPQ/JNE/spill) — that's symptom, the bug is
in the variantindex lookup.
Surfaced the 7th corpus-coverage-blind unmask of session 5 (sister
shape to STATUS-4 #11 / #14 / #21 wwstage UNDER family). Latent
within lib/bytes (a6abac2) since landing today; 967_bytes_run's
cstage-only `ww run` driver kept it dormant.
Tests:
- 722_match_slice_variant pins cmp -s byte-id between stages
for the canonical (u8|[]u8), reverse-order ([]u8|u8), and
three-arm (u8|[]u8|str) shapes.
- 926_match_slice_variant_run runtime-pins 7 rows × 2 stages
(cstage + wwstage drivers): canonical, reverse-order, and
other scalar-vs-slice-of-same-primitive matrices (i8|[]i8,
i32|[]i32, u64|[]u64, rune|[]rune), three-arm with str.
Verifies both arms reachable and payload survives.
Filed follow-ups (latent, NOT in this commit's scope):
- flatslicevariantidx falls back to first slice slot when no
element-name matches; `([]u8 | []i32)` would mis-route. No
in-tree consumer.
- 926 missing nested ((u8|[]u8) | i32) row per rob's spec.
- 3-arm 32B tagged sequential-push payload corruption (both
stages, asm byte-id passes, only 9xx runtime catches).
- Chained inline pick() over 32B 3-arm slot (both stages,
bind-to-let workaround documented at 926 row).
93/93 ok. 995_self_rebuild stays green (ww2==ww3==ww4 byte-id).
Class B shared miscompile pre-fix: cstage skipped the CALL emit at the
receive site (frame collapsed, exit 11); wwstage emitted CALL but
truncated 32B return to AX only (slice payload garbage, segfault on
g.b[0]). Both stages now lower plain TY_STRUCT > 24B through the SysV
sret discipline: caller pre-allocates dest, passes &dest in RDI as a
hidden first-arg (user args shift to SI/DX/CX/R8/R9/+stack), callee
saves RDI to @sretarg at the prologue and writes through it, returns
RDI in RAX. Surfaced by lib/encoding/utf8 pre-flight when the
Hoehrmann decoder (32B) hit 698_cgreturn_struct.c's OUT-OF-SCOPE
marker.
Scope: plain TY_STRUCT > 24B only — tagged unions, tuples, str, slice
keep their existing register-return ABIs. `return f()` forwarding
from a sret callee is fail-loud-not-wired (compile-time error in
both stages, follow-up filed); the workaround `let r = f(); return
r;` is wired and byte-identical. Discard-context calls (`f();` of an
sret-returning function) share a per-fn single-slot @sretscr;
consecutive discards reuse the same slot.
698_cgreturn_struct.c's OUT-OF-SCOPE marker retired in the same
commit; three positive rows (32B quad, 32B decoder, 40B five) now
assert the sret discipline across both stages via byte-id diff.
Tests:
- 721_sret_struct_return pins three asm-presence sentinels per
row: (a) LEAQ -K(BP), DI immediately before CALL at the receive
site, (b) MOVQ -K(BP), AX before RET in the callee (sret return-
the-pointer), (c) negative-assert no MOVQ AX, -K(BP) capture for
return type >8B. Three rows × both stages × cmp -s byte-id.
- 925_sret_struct_return_run runtime-pins 7 rows × 2 stages
including the collision row (25B+ struct BOTH returned AND passed
by-value as arg — catches arg-shift, sister site to #11), nested
struct payload, slice payload, reassign-receive, N_IDENT return
rhs.
89/89 ok. 995_self_rebuild stays green (ww2==ww3==ww4 byte-id).
Wwstage call-arg-emit recognized tagged args only when the source
was an IDENT (already-materialized var). For N_CALL returning a
tagged-union, the natural-push path mis-routed: AX (tag) pushed
twice, AX clobbered with widentag(=0) between pushes, DX (payload)
dropped entirely. After POP, DI ← 0, SI ← tag — both reversed and
the payload word lost. Class A runtime miscompile, masked by zero
in-tree call sites of the shape until lib/encoding/utf8's iterator
API surfaced it via pre-flight A probe.
Fix aligns wwstage DOWN to cstage (rule 10). cgenutil.ww:pushargsrev
aistagged guard now fires for N_CALL whose callee returns a tagged
whose slot matches the param's tagged slot (mirrors cmd/w6c/cgen.c:
4216-4221's type_eq guard), and the natural-push fallthrough adds a
tagged-CALL arm pushing R8/CX/DX/AX high→low by slot size (mirrors
cmd/w6c/cgen.c:4373-4387). cgenexpr.ww:cgcall's per-arg pop-count
picks up the same taggedcallslot helper so the next arg's POPQ
doesn't land on residual tag/payload words.
Sister-family to #11/#14 in the variant-widen ABI chain — call-site/
caller-side surface, distinct from callee-side #11 (param decompose)
and scratch-side #14 (return slot). Fifth corpus-coverage-blind
unmask this session (catalog: i64 div/mod CQO #16; wwstage IDENT-
local /= no-op #16-B2; cstage signed-DATA module-scope #19; wwstage
silent-zero arrays #19 mirror; #21 call-arg DX drop).
Test: 720_tagged_call_arg asm-presence row (PUSHQ DX appears
between CALL and next CALL, before PUSHQ AX) + 924_tagged_call_arg_
run 9xx semantic row (5 rows: 4-variant CALL-source, 4-variant
IDENT-source regression guard, 2-variant ptr/err, multi-arg tagged
+ scalar). Bootstrap byte-id (ww2 == ww3 == ww4) holds.
Initializing a tagged-union variant slot with a runtime f64 source
(let, cast, fn call, unary, struct field, etc.) stored the i64 bit
pattern in the payload, not the float bit pattern. cgexpr leaves f64
in X0; the existing scalar-fallback MOVQ-from-AX wrote whatever was
last in AX (typically pre-conversion integer or stale residue).
Worker-fmtfloat surfaced this during #17 pre-flight (probe at
.ai/probe_f64_union_widen.ww). Blocks #17 fmt.float dispatch arm.
TK_FLOAT literals were coincidentally correct because the lowering
loads bits into AX before passing through X0 — the literal_1_0 test
row pins that as the principled MOVSD path now.
cstage cg_widen_tagged_store: add fld_isfloat arm between the slice
and scalar fallbacks. Emit MOVSD (f64) / MOVSS (f32) from X0 to the
payload offset, then the tag MOVQ. Mirrors existing str/slice/
structlit field-flow dispatchers.
Wwstage cgwidentaggedstorebp: mirror via exprfloatkind. Resolves a
secondary gap by looking up the variant tag directly via
flatvariantidx(c, dt, "f64"/"f32") — rhstargetname has no N_FLOATLIT
/ N_CALL / N_DOT branch and would fall through to str-fallback
returning tag 0.
No in-tree consumer triggered this pre-fix (no f64 in any tagged
union yet) — hence latent silence. arr[i]= and append() have the
same class gap but no in-tree exerciser today; same shape if/when
[N]f64 / []f64 land.
Test 715 (tagged_widen_f64): 7 rows × 2 stages = 14 fixtures with
bit-pinning via *u8 punning. literal_1_0 (regression lock-in),
cast_1_f64, call_makeone, unary_neg_f64, ident_f64, field_f64
(rob's extra row), i64_rhs_still_integer (negative control).
Diagnosable 0/1/2 return codes distinguish pass / wrong-tag /
wrong-payload.
ww2 == ww3 == ww4 byte-identical post-fix.
wwstage's taggedvariantindex returned -1 (caller maps to 0) for
N_IDENT returns of an aliased mixed-variant union. Cstage returned
the correct variant index. Cross-stage divergence — root cause of
worker-fmtparser's "reads bool-true as false" symptom in the #18
repro chain. Worker-18 dodged it by dropping 707's asm byte-id
loop; #20 re-enables it.
Unwrap at entry: resolvetagged peels N_TNAME alias chains down to
the underlying N_TTAGGED before the variant-index walk. Direct-
tagged callers are unchanged (resolvetype is a no-op on non-N_TNAME).
Mirrors nodeisstr's shape — same class of wwstage-no-typed-AST gap
tracked by #11.
Test 707 grows from 6 → 9 rows; new rows pin tag=0/1/2 (i64/str/
bool) explicitly so a future variant-reorder can't hide behind a
coincidentally-correct tag=0. Asm byte-identity loop re-enabled
(disabled by #18); now exercises both #18 (ABI words) and #20
(variant-index) fixes — rows 2/3/6 also probe str/bool divergence.
995_self_rebuild green confirms wwstage source itself has no
latent aliased-tagged-return that would have surfaced as a self-
divergence.
Closes STATUS latent #1: @tagscr shared 24B reservation across the
four tagged-scratch sites (cgreturn, pushargsrev, cgindex
tagged-elem, pointer-rooted struct-field tagged write). Any fn that
needed >24B (e.g. slice-in-tagged-field 32B) silently overflowed
into the neighbor frame slot. Surfaced concretely as getopttest's
errortable wwstage exit 16 after #37 fixed the upstream gaps.
c.tagscrsz: i32 on the cgen struct is the single source of truth.
tagscrbump(c, need) in scanlocals raises the max across all 4
reservation sites and returns the frame delta. All emit sites
(cgreturn / pushargsrev / cgindex / cgwidentaggedstore pointer-
rooted) read c.tagscrsz instead of hardcoded 24. Mirrors the existing
cgwidentaggedstore precedent; @tagbase keeps its 8B scanseenmark
dedup (always 8B, correct).
Unmasked latent bug (now fixed): scanlocals's pointer-rooted struct-
field tagged-write detection uses localfindnode(c, base.str) to
resolve the *struct base. For `fn fill(h: *holder)`, h's scan-time
stub from scanseenmark had tnode=nil, so the @tagscr reservation
never fired. Pre-#38 the hardcoded 24B masked this; #38's correctly-
sized slot exposed it. cgfn's param scan loop now sets
c.locals.tnode = scanp.lhs after scanseenmark so localfindnode
resolves param types at scan time.
Test 714 (tagged_return_scratch): 4 rows × 2 stages = 8 fixtures.
Direct adjacency repro; match-arm field-by-field read; **mixed-
sizes-one-fn** (16B pushargsrev widen + 32B cgreturn widen in the
same body — pins the lockstep invariant that a sibling site can't
undersize the shared slot); call-site struct-payload widen. Row 3
specifically would regress if a future refactor ever forgets to
route an emit site through c.tagscrsz.
982 getopt_run green through both stages (was the original surface);
995 self_rebuild byte-id holds.
The original #37 symptom (worker-34's `..findflag` mangle) cannot
reproduce on master — was a runtime miscompile misattributed to a
link-time issue. Investigation surfaced three real wwstage cgen
gaps in the N_INDEX-through-struct-field family, sister bugs to
#34 (N_INDEX N_IDENT-base) and #36 (primsize-default-to-8).
1. `indexbaseesz` slice-element stride defaulted to 8 for named-
struct elements. `&opts.ptr[i]` for `opts: *[]option` computed
MOVQ $8 instead of $24. Fix: route slice case through
`elemsizeofc(c, innert)`; ptr-to-named-struct via structlookup.
2. `cgun TK_AMP N_INDEX` ignored N_DOT base. `&p.ptr[i]` left
esz=8 because only N_IDENT base was handled. Mirror cgindex's
existing N_DOT arm.
3. `nodeisstr` N_INDEX arm only walked N_IDENT bases. `cmd.argsptr[i]`
for `argsptr: *str` returned false; pushargsrev dropped the
.len half at call sites. Add N_DOT-base arm that walks the
struct field's pointee.
Test 713 (struct_field_index): 3 rows × 2 stages = 6 fixtures, one
per fix shape. Runtime-only; bootstrap byte-id (995_self_rebuild)
covers cross-stage drift.
Residual: getopttest's errortable still fails through wwstage with
a slice-of-str-via-&arr[expr] miscompile. Filed as task #38.
wwstage's nodeisstr (cgenutil) didn't recognize N_INDEX-of-[N]str.
cgindex emitted only the ptr-half MOVQ when the result was used as
a str arg (call, .len access, str streq), so the .len half read
stack residue. Surfaced by worker-21 during #21 dev — pre-#21
slotsize=24B masked the read-side defect; post-#21 (16B stride)
exposed it. cstage's typed-AST node_isstr handles this naturally;
wwstage's untyped pattern walks the base ident's tnode shape.
Added N_INDEX arm to nodeisstr: walk the indexed base's tnode
through N_TARRAY / N_TSLICE / N_TPTR.lhs, return isstrtype on the
element. Mirrors cgindex's own base-type walk byte-for-byte in
shape so the two now agree on load-shape decisions.
Not covered (separate bugs, separately filed):
- N_UN(TK_STAR) of *str — cgun itself never loads .len into BX.
- tuple `.1` of str — N_TTUPLE path has its own load shape.
- alias-typed base (`type a = [N]str`) — N_TNAME isn't peeled; cgindex
doesn't peel it either, so agreement holds. Outside #34 scope.
Test 711: 3 new rows — barelet_index_call_arg (streq direct arg),
nested_call_index_arg (f(g(argv[i])) — nested-call recursion),
barelet_index_len_arg (sister regression-pin for cgindex element
stride in bare-let context; pins a different code path that was
already correct post-#21).
The pre-existing wwstage `..findflag(SB)` symbol-mangling bug in
getopttest wwstage build is filed as task #37, not in this commit's
scope.
[N]str array literals wrote only the .ptr half of each element.
cstage used esz=16 from `lu->sub->size` and a single per-element
MOVQ → .len trailed uninitialized stack residue. Wwstage was worse:
primsize("str")=0 fell through to esz=8, so element i+1's ptr-MOVQ
clobbered element i's .len slot, scrambling everything.
Worker-18 sidestepped during #18 by rewriting array primer rows to
[N]i64.
cstage cgen.c N_ARRLIT TY_STR branch: emit AX → base+i*16 then
BX → base+i*16+8. Repeat-`...` path mirrored. type_isstr handles
TY_UNTYPED_STR + TY_NAMED-aliased-str.
Wwstage cgenstmt.ww: isstrel flag conditionally drives the two-MOVQ
store in both the per-element walk and the repeat fill. The dispatch
loop was refactored to unify FIELD/ellipsis branches via isellip,
cleaning up the duplicated arms.
Wwstage cgenutil.ww slotsize/letslotsize: TNAME-"str" element gets
esz=16, replacing the primsize=0 → 8B fallback. Without this the
frame collapsed to 24B for [3]str.
Slice (24B), struct, tuple, tagged element arrays have the same root
cause but distinct width/layout concerns — deferred to #35 per rob.
Test 711 (arrlit_str_full): 7 rows × 2 stages = 14 fixtures —
str_lens_3el, str_ptrs_3el, str_repeat_5el (TK_ELLIPSIS), bool_3el,
rune_3el, i32_3el, i64_3el. Rune relies on the pre-existing esz==4
→ MOVL path (incidental correctness); sibling slot types pinned as
regression nets.
Followups filed: #34 (wwstage cgindex truncate on [N]str bare-let
read side, surfaced by this fix), #35 (composite element types),
#36 (primsize-returns-0-default-to-8 cleanup).
Sister bug to #17 / #18. The structlit-fill helper handled nested
N_STRUCTLIT field values but a struct-typed field whose VALUE is an
N_CALL (call returning a struct, #4 cgreturn ABI) fell through to the
cgexpr-then-AX-store path — landing AX=first qword and silently
dropping DX/CX. For 16B/24B inner returns the trailing 8B/16B stayed
zero (whatever was in the destination slot beforehand).
Fix: a new N_CALL+struct branch in cg_structlit_fill / cgstructlitfill,
placed between the nested-N_STRUCTLIT recursion and the scalar
cgexpr fallthrough. Emits cgexpr -> BX reload (non-BP modes only) ->
MOVQ AX/DX/CX x full + sized tail (MOVL/MOVW/MOVB) per #4's receive
shape.
INVARIANT (commented inline both stages): between cgexpr(N_CALL) and
the AX/DX/CX stores below, no instruction may touch AX/DX/CX. Only
the BX reload (MOVQ srcoff(BP),BX or LEAQ name(SB),BX) is safe.
Sized-tail dispatch is {1->MOVB, 2->MOVW, 4->MOVL, else MOVQ}. Unlike
the scalar fallthrough — which still uses the {1/4/else MOVQ} shape
to stay byte-identical with cstage pending #13 — the new branch is
correctness-by-construction: MOVW for tail==2 only fires on call-rhs
shapes that didn't compile before, and both stages emit it
symmetrically (705's 10B inner row pins this).
Guard `fsz <= 24 && fsz%8 in {0,1,2,4}` mirrors #4's cgreturn ABI:
>24B falls through (sret deferred), and fsz%8 in {3,5,6,7} would need
shift-store — also unsupported by #4. Filed as task #21 (covers both
cgreturn and call-rhs's identical gap).
Two #15 sidesteps, both documented inline:
1. wwstage's fi.fsz for an inner-struct field is slot-padded
(8-rounded), not natural — using it would emit 2x MOVQ where
cstage emits MOVQ+MOVL for a 12B inner. The new wwstage branch
uses structnaturalsize(csi) to recover the natural size, matching
cstage's fl->type->size (check.c hands the helper natural sizes).
This sidesteps #15 without touching its scope.
2. The outer struct's totsize diverges across stages when
maxalign<8 (wwstage rounds to 8 universally; cstage to maxalign).
The 705 test rows pin `x: i64` on the outer to force outer
maxalign=8, keeping BP offsets stable across stages. Test-side
sidestep only; also #15 territory.
Files:
- cmd/w6c/cgen.c cg_structlit_fill extended
- selfhost/cmd/wcc/cgenutil.ww cgstructlitfill mirror
- selfhost/cmd/{w6c,wwdump}/main.combined.ww auto-regen
- test/wcc/705_nested_call_rhs.c 8 rows, table-driven; pins cstage
exit + wwstage exit + .s byte-identity. Tail widths 0/4/2/1, dst
modes DST_BP + DST_PTR_LOCAL, shallow + 3-deep.
- Makefile 705 wiring
Test: 65/65 PASS. 994_w6c_ww + 995_self_rebuild PASS (byte-identity
holds — load-bearing).
Sister fix to #17. The BP-rel helper from #17 covered N_LET /
N_ASSIGN N_IDENT-lhs / N_RETURN; the four N_ASSIGN N_DOT-lhs
structlit walks still went through the inline `cgexpr(field.lhs);
store-AX-sized` shape and silently dropped trailing bytes when a
struct-typed field's value was itself an N_STRUCTLIT. Affected dot
flavors: single-dot via_ptr / global / BP-rel and the chained-dot
walker (depth >= 2, all three root flavors).
Extend `cg_structlit_fill_bp` / `cgstructlitfillbp` into
`cg_structlit_fill` / `cgstructlitfill` taking a destination mode
(DST_BP / DST_PTR_LOCAL / DST_GLOBAL = 0/1/2), srcoff (PTR_LOCAL),
srcname (GLOBAL), and disp accumulator. `disp` grows by foff on
descent; srcoff/srcname stay constant across the call tree. The
pre-#17 wrappers are preserved byte-identically by delegating with
mode=DST_BP — 995_self_rebuild byte-identity holds for the no-
nested-STRUCTLIT case that selfhost source actually uses.
The non-BP modes reload BX before the ELLIPSIS zero-fill loop AND
before every field store (tagged, scalar, and the cgexpr leaf).
This is correctness-by-construction — cgexpr clobbers BX between
fields, and the redundant reload only fires on shapes that didn't
compile before. The four dot-flavor sites in each stage now compute
their dst mode + disp and call the shared helper (reducing each
from ~80-130 inline lines to ~5-12 lines of dispatch).
Stage signature asymmetry: cstage threads Local** for cgexpr; ww-
stage takes explicit totsize because #15 (split totsize into
naturalsize + slotsize) is still pending and the dot sites need
structnaturalsize while the BP-rel sites need si.totsize. Both
asymmetries are documented in the helper docstrings.
704 covers 8 rows (24 checks: 8 cstage exits, 8 wwstage exits, 8
cstage-vs-wwstage .s byte-identity diffs): 6 dst-flavors (single-
dot local/ptr/global, chained-dot local/ptr/global) plus single-
local 3-deep and single-ptr 3-deep to pin disp threading through
the helper's recursion and through DST_PTR_LOCAL BX reloads.
The nested struct-typed CALL rhs in field-walks has the same shape
as the STRUCTLIT bug fixed here but the helper only handles
STRUCTLIT — tracked as task #20.
Pre-existing landmine surfaced by #5. For a struct literal whose
field value is itself an N_STRUCTLIT of a struct-typed field, the
inline field-walk did `cgexpr(field.lhs); store-AX-sized`. cgexpr
has no whole-struct-in-register convention, so the nested literal
landed AX = first qword and the trailing bytes silently stayed zero
(or stack garbage). Three BP-relative sites in each stage hit it:
N_LET, N_ASSIGN N_IDENT-lhs, and N_RETURN N_STRUCTLIT.
Fix: shared cg_structlit_fill_bp (cstage) / cgstructlitfillbp
(wwstage) helper handles TK_ELLIPSIS autofill, tagged-field
widening, float vs scalar store dispatch, AND recurses on
struct-typed N_STRUCTLIT field values at bp_off + field_off. All 3
sites in each stage now call the helper instead of the inline walk.
Scalar store dispatch is the explicit {1->MOVB, 4->MOVL, else MOVQ}
shape (not fieldstoreop, which would emit MOVW for fsz==2) to stay
byte-identical with cstage pending task #13. Sister N_ASSIGN N_DOT
structlit walks (via_ptr / global / BP-relative-through-N_DOT) keep
their inline walk and still drop nested-STRUCTLIT silently — tracked
as task #18.
703 covers 6 rows: let_nested_i64, let_nested_3deep, let_nested_i32,
let_nested_middle (i64; switch to i32 once #15 lands),
assign_ident_nested, return_nested. 995_self_rebuild byte-identity
preserved.
Receive side of #4's cgreturn ABI (aee8149) for TY_STRUCT lvalues of
size <=24B. Producer materialises rhs into AX=bytes[0..7], DX=[8..15],
CX=[16..23], zero-padded to 24B; receive sites here read the regs and
write only `declared sz` bytes — MOVQ for full 8B chunks plus a sized
tail (MOVL/MOVW/MOVB) by the *declared* struct size. ASYMMETRY: do NOT
mirror the sender's three uniform MOVQs, else trailing 1..7B chunks
overrun the next local slot. Tail chunks in {3,5,6,7} are unreachable
under WW struct align rules (size%align==0) and fall through.
Five sites wired in each stage (cstage cgen.c, wwstage cgenexpr.ww +
cgenstmt.ww), call-result + structlit rhs at each:
- N_LET `let s: T = bar()` / `= T{...}` cgenstmt cglet
- N_ASSIGN N_IDENT-lhs `s = bar()` / `= T{...}` cgenexpr cgassign
- N_ASSIGN single-DOT local-base `o.f = ...`
- N_ASSIGN single-DOT ptr-base auto-deref `p.f = ...`
- N_ASSIGN single-DOT global-base `g.f = ...`
- N_ASSIGN chained-DOT depth>=2 `o.m.in = ...`
(The four dot-flavors share one shape pattern, hence "5 sites".) Where
the dst addr needs scratch (ptr-base/global-base/via_cx), it is loaded
into BX after the call so CX stays as the third value word; for
structlit field-walks BX is reloaded before each store since cgexpr
clobbers AX/BX between fields.
wwstage needed a new `structnaturalsize(si)` helper (cgenutil.ww):
si.totsize is mis-named — it's slot-padded to 8 by registerstruct for
stack-slot use, while the receive ABI wants the type's natural size
(max(foff+fsz)). Splitting si.totsize into naturalsize + slotsize is
tracked as the wwstage struct sizing follow-up (task #15); until that
lands, the helper recovers the natural size at receive sites.
Test 701_cgassign_struct.c (18 rows, 3 checks each — cstage value,
wwstage value, asm byte-identity), wired in Makefile after 698. The
headline ASYMMETRY case is the 20B `{i32×5}` row: sender pads to 24B
via three MOVQs, receiver writes MOVQ AX +0, MOVQ DX +8, MOVL CX +16.
A regression to a MOVQ tail there overruns 4B past the slot and
flips the exit-code check.
smoke.combined.ww is the auto-regen ride-along of strings.freeall
landing in 714d089 (worker-shlex).
Pre-existing gaps surfaced and tracked separately (not fixed here,
out of scope):
- task #16: silent drop of `(*p).f = ...` explicit-deref dot lhs.
- task #17: silent zero of nested STRUCTLIT field in N_LET / N_ASSIGN
initializer — the field_chain and field_global test rows use
explicit field writes (`o.m.t = 10i64;`) rather than nested
literals as a fixture-level workaround.
- task #9: module-name-mangle for fn labels avoided in the
field_global_call fixture by `let g: outer;` (no init).
make test: 59/59. 994_w6c_ww + 995_self_rebuild PASS — bootstrap
byte-identity is the load-bearing proof for this commit's scope.
Tags structinfo/enumtype with originating module; exact-match first,
then split pkg.X and filter by smod/emod. Without this, two modules
with same-leaf-name struct/enum types collapsed to whichever entry
appeared first in the chain.
Wired into 696_modtype_leaf_collision via a wwstage run_pos using
ww_ww (negative case omitted: w6c_ww has no checkfile pass). Updated
the test's Makefile deps to include the wwstage binaries.
Audited the rest of the lookup family — fnretlookup, fnparamslookup,
deflookup don't need the same treatment: the parser emits N_DOT.str
(call/field name) as the leaf only, and fnparamslookup is only
invoked with N_IDENT.str. Dotted module-qualified function calls go
through the module-mangling path instead.
Typed-int literal assigned into a tagged-union slot (`h.e = 42i64;` where
e: (i32 | i64)) wrote tag = 0 (the i32 slot) instead of tag = 1 (the i64
slot). Cstage was correct: parse.c parseprimary copies tok.tsuffix onto
N_INTLIT, check.c stamps node.type = ty_i64, and cg_widen_tagged_store →
cg_tag_for_variant walks variants matching by structural type_eq —
ty_i64 lands at index 1. Wwstage had two gaps:
1. The parser (lib/ww/parse/expr.ww parseprimary) read p.curuval and
p.curtext from the current token but never the tsuffix field. Token-
side capture has been in place since the lexer's `i8/i16/.../u64/f32/
f64` glue suffix landed (lib/ww/lex/lex.ww sets out.tsuffix); the
parser side was missed. So an N_INTLIT for `42i64` carried tsuffix=""
into cgen. Mirror of cmd/wcc/parse.c parseprimary's `n->tsuffix =
t.tsuffix` line. Same plumb for N_FLOATLIT.
2. Wwstage has no checker stage to stamp N_UN's type from its inner
expression's type. `-42i64` parses as N_UN(MINUS, N_INTLIT(42,
tsuffix="i64")) and rhstargetname stopped at N_UN, returning "" and
falling through to taggedvariantindex's "first non-str variant"
fallback — which picked tag 0 (i32) for any numeric rhs in an
(i32|i64) union. Cstage's cunop returns the inner type for
TK_MINUS / TK_PLUS / TK_TILDE so the N_UN gets ty_i64 stamped
naturally; wwstage gets the equivalent via an explicit peel in
rhstargetname, recursing into rhs.lhs for these three ops. The
recursion also covers nested unary (`- -42i64`), which parseunary
builds as N_UN over N_UN over N_INTLIT.
The lib/ww/parse change is mirrored in selfhost/cmd/{w6c,wwdump}/
main.combined.ww so the bootstrap snapshot stays consistent with the
working frontend source. parser.curtsuffix is a new str field; refill
copies t.tsuffix into it; parseprimary TK_INT / TK_FLOAT copy it onto
the new node before advance.
Cstage handled both `42i64` and `-42i64` correctly already; no cstage
mirror needed.
Test 694_tagged_store_intlit — eleven rows running on both stages: i64
lit in (i32|i64); i32 lit (existing-working pin); i64 lit in
(i32|i64|str) with the str fallback at tail; u8 lit at head of
(u8|i32|i64); i64 lit at tail of (u8|i32|i64) with a +100 marker so
mis-binding into u8 can't masquerade as success; negative-i64 lit
(N_UN MINUS peel + sign extension through match-arm bind);
unary-plus i64 lit (N_UN PLUS peel); bitwise-not i64 lit (N_UN TILDE
peel; `~0i64 == -1i64`); nested unary `- -42i64` (recursion through
two N_UN levels); direct `let x: ev = 42i64;` (cglet's tagged-init
code path, separate write site from cgassign's field-write);
negative-control str field (pins the existing str-fallback path
through rhstargetname).
Pre-fix run on wwstage: 8/11 rows fail (every typed-i64 case including
all three unary operators, nested unary, and the direct let-init);
cstage 11/11 pass. Post-fix: 22/22 across both stages. make test
41/41. Bootstrap ww2 == ww3 == ww4 byte-identical.
cgdot of a tagged-union struct field previously dropped the AX/DX/CX/R8
payload-register convention used by tagged-union returns: cstage's
direct-struct branch stopped at CX (size > 16) and never loaded R8
(slice-payload variants, slot 32B); the via_ptr branch had no TY_TAGGED
handler at all, falling through to fldloadop and yielding only the tag
in AX. The N_DOT scrutinee fallback in N_MATCH similarly stored only AX
into the spill slot. Wwstage cgdot had no TY_TAGGED branch in any of
the direct, *struct, or top-level-global field-load paths, and cgmatch's
non-ident scrutinee branch didn't recognise N_DOT — dispatch always
computed want = 0 and the spill scratch was hardcoded 24B. The combined
effect: any code reading `s.taggedfield` and consuming more than one
quadword of the payload saw garbage in the upper halves.
Cstage: extended the direct-struct TY_TAGGED branch with an R8 load for
size > 24 (CX still loaded last so global LEAQ-into-CX rooting
survives), added a parallel TY_TAGGED handler to the via_ptr (TY_PTR
inner TY_STRUCT) field branch, and extended the N_DOT scrutinee spill
fallback in N_MATCH to write DX/CX/R8 alongside AX.
Wwstage: new cgloadtaggedfield helper emits the four-register load with
CX-last ordering, and dotfieldtnode resolves a field's declared type
node for a local-ident or *struct base. cgdot grew three TY_TAGGED
branches (direct local, *struct deref staging in BX, top-level global
through CX). cgmatch's non-ident-scrutinee branch grew an N_DOT type-
extraction path mirroring the N_CALL / N_INDEX shapes and now sizes the
@match_spill slot from slotsize(scrutt) so slice-payload variants don't
overflow the historical 24B alloc. rhstaggedabicall accepts N_DOT so
`let copy: ev = h.e;` and tagged-arg call sites pass through the
tagged-source spill branch of cgwidentaggedstore.
Out of scope for #28 and left as separate latents: wwstage's match-arm
bind for a TY_STRUCT-typed variant copies only 8B (cstage falls back
to bu->size; wwstage's bsz=8 default), and the variant-index lookup
for an i64 literal in (i32 | i64) picks the wrong tag on the write
side. Both surface in struct-payload tagged unions and merit their
own tasks; the new test rows steer clear so #28's fix verifies
end-to-end on scalar / str / slice payloads.
Test 693_dot_tagged_source — three variant shapes (16B i64, 24B str,
32B slice) read from direct local, *struct param, top-level global,
and let-init round-trip. The 32B-slice rows verify v.cap (R8 / +24)
so dropping the upper-word load isn't masked by len-only checks; the
top-level-global row routes the write through *p because the direct
global-LHS tagged store is a separate wwstage gap (followup). Three
negative controls (untagged i32 / str / slice fields) keep the new
TY_TAGGED guard from shadowing the existing field-load paths. Wired
into make test; 37 tests total. Bootstrap ww2 == ww3 == ww4
byte-identical.
Extended cg_widen_tagged_store (cstage) / cgwidentaggedstore (wwstage)
to take a base_reg/basereg parameter so the primitive supports non-BP
destinations. Cstage extends body in-place via via_outer gate +
spill+scratch+copy-out; wwstage splits into wrapper (non-BP) +
cgwidentaggedstorebp (BP-only) to dodge the no-goto constraint. New
N_ASSIGN field TY_TAGGED branch routes through the primitive for all
rhs shapes.
Scope-adjacent: fieldsize recurses through N_TTAGGED via slotsize and
TNAME-aliased-to-tagged via aliaslookup. Needed for the test fixtures.
Wwstage read-side N_DOT-of-tagged-field source is filed as task #28;
test rows use mark-canary verification until that lands.
Read-side fix dual to fldloadop: signed-narrow local/global ident loads
now MOVSXD/MOVSWQ/MOVSBQ from the slot instead of raw MOVQ. Deref-stores
(MOVL/MOVW/MOVB) no longer corrupt downstream i64 widens. Compound RMW
restructured to gate direct-mem ADDQ/SUBQ on load_op == MOVQ. Top-level
lets use LEAQ+indirect (w6a doesn't expose MOVSXD/MOVSWQ/MOVSBQ for
D_EXTERN).
dotchainresolve out-params restored to natural *i32 (workaround retired).
selfhost/CLAUDE.md graduated.
cstage cmd/w6c/cgen.c gained the missing N_DOT N_INDEX-lhs branch.
Covers both [N]*Struct and [N]Struct via fldloadop. wwstage already
handled [N]*Struct since 7c75dd2; refactored to mirror cstage exactly
and added [N]Struct. The spill workaround in dotchainresolve stays
(Pike rule); task #14 retires it as a follow-up.
Wwstage cgassign N_DOT(N_INDEX,...) silent store-drop discovered in
scope, filed as task #16.
type_isunsigned recurses TY_ENUM and includes TY_RUNE on both stages.
13 LOAD + 6 STORE ladder sites (cstage) plus 4 more wwstage stragglers
in cgindex/cgforrange collapsed to fldloadop/fldstoreop helpers. N_CAST
narrow gate symmetrised; task #1's literal-kind workaround retired.
bool kept out of type_isunsigned, special-cased in field helpers.
Retroactively fixes a u32 mis-sign-extend in deref-compound (sz=4
hardcoded MOVSXD), pinned by new 660_field_signed row.
Loop-shaped spine walker for value-struct chains (o.i.a) and slice/str
pseudo-fields (s.buf.len), read+write, both stages. SB-fallback at the
catch-all preserved for unresolved module-qualified idents.
Follow-ups filed: tasks #7-#10 (wwstage >6-arg frame over-alloc, chained
array-elem field BX loss, & through chained DOT, signed sub-word field
loads zero-extend).
Seven fixes across the toolchain, plus three new lib/hash modules
(adler32, crc16, crc32) that surfaced them.
1. `~x` on u8/u16/u32 left the upper bits set: NOTQ inverts the
whole 64-bit register and nothing trimmed it back to type
width, so a returned `u16` would compare 64-bit against a
typed literal and disagree. Both stages now mask after NOTQ
for narrow unsigned: AND $0xFF/0xFFFF for u8/u16, MOVL r,r for
u32 (ANDQ $0xFFFFFFFF sign-extends imm32 and is a no-op).
Signed narrows stay sign-extended and need no fix-up. See
cmd/w6c/cgen.c N_UN TK_TILDE and selfhost cgenexpr.ww cgun
TK_TILDE with new nodeprimwidth helper.
2. w6a had no D_CONST immediate path for ANDQ / ORQ. cgen would
emit `ANDQ $65535, AX` and the rr encoder silently wrote
`21 /r` with garbage reg fields — the mask never happened.
Added `81 /4` (AND) and `81 /1` (OR) imm32 paths in both
cstage and selfhost w6a. The ~width fix above depends on this.
3. `s: []u8` cast as a direct fn argument produced a 0-length
slice. cgexpr for N_CAST left (AX=ptr, BX=len) from the str
source but never set CX (cap), and the arg-push fallback only
pushed AX. cgcast now synthesises CX=BX when target is slice
and source is str; node_isslice / arg-push recognise
cast-to-slice and emit the full (cap, len, ptr) triple. Both
stages.
4. `*[N]T` element-store used 8-byte stride + MOVQ regardless of
T's width. Indexing `buf: *[4]u16` would step 8 bytes and
write 8 bytes per element. Added idx_eff (drills *[N]T → T)
in cstage and the matching pointer-array drill in selfhost
elemsizeof. Also added MOVW / MOVZWQ / MOVSWQ to w6c, w6a,
and selfhost mirrors so 2-byte element stores/loads use the
right opcode (was falling through to MOVQ and trailing 6 bytes
into the next slot).
5. Slicing a top-level fixed array (`g[0:n]` where `g: [N]T` is
a global) computed the base from BP instead of the symbol —
localfind returned 0 and the cgen treated it as a local at
offset 0. Both N_SLICE-as-expression (cgslice) and N_SLICE-
as-call-arg paths now check let_islet / letvartnode and emit
LEAQ name(SB) when the base is a global array (or MOVQ
name(SB) for a global slice/pointer base). Both stages.
6. Top-level `let arr: [N]T = [v0, v1, ...]` link-failed on
cstage — emit_lets bailed when it saw N_ARRLIT init on an
array type, and the sz==8 scalar path then misemitted any
8-byte-sized array (e.g. [4]u16, [8]u8) as a single quad.
emit_lets now walks N_ARRLIT, evaluates each element as an
int/rune/bool/nil literal, packs per-element bytes
little-endian, and honours the trailing `...` repeat marker.
Selfhost already handled the literal-init path; fixed the
parallel sz==8 duplicate-DATAW emit on its side (the array
and the scalar paths both fired, last write winning at link
but the duplicate broke cross-stage byte-identicality on user
code with this shape).
7. w6a's per-line input buffer was a 1KB stack `char buf[1024]`.
A `DATAW` for a [256]u16 emits ~2080 bytes on one line, which
truncated mid-escape; the assembler then re-parsed the
remaining tail as garbage opcodes ("unknown opcode"). Bumped
cstage w6a to a 32K static buffer (selfhost w6a already
allocated per-line via amalloc).
lib: lib/hash/adler32, lib/hash/crc16, lib/hash/crc32 — pure
buffer-subset shape (matching lib/hash/fnv), with per-module
*_test.ww runnable via `ww test lib/hash/<name>`. Adler-32 plus
CRC-16 (CCITT/CMDA2000/DECT/ANSI) and CRC-32 (IEEE/Castagnoli/
Koopman) cover Hare's reference vectors bit-for-bit. Wired into
test/wcc/900_stdlib.c. .gitignore: lib/**/*.s,*.o so `ww test`
droppings stay untracked.
`make test` (26/26), `make bootstrap` (ww2≡ww3≡ww4), and per-module
`ww test` all pass. cgen output is byte-identical across cstage and
selfhost for every repro that previously diverged.
Param-decl `name: T...` (Tparam.variadic=1, type []T), call-site
gather of N args into a fresh `[N]T`, forward via `xs...`, full
selfhost mirror, and lib/fmt graduated to the Hare shape.
Frontend:
- parse: `T...` after a param's type stamps Node.op=TK_ELLIPSIS
and breaks out (variadic must be last).
- check: resolve_type N_TFN / build_fn_type wrap the param type
as []T and set tp->variadic. N_CALL accepts either a tail of
args assignable to T (gather) or a single `xs...` spread of
[]T (forward); both bypass the "too many args" check on the
variadic slot.
- type: type_eq compares Tparam.variadic.
Cgen (cstage):
- call site: when the callee has a variadic last param,
materialise the tail args into a frame-resident `[N]T` via
localoff, write a 24B slice descriptor (ptr,len,cap), and
splice a synthesised N_IDENT into args[] so the downstream
widen/eval/pop loops see one slice slot. Tagged-element types
route each store through cg_widen_tagged_store. Forwarding
skips gather: the N_SPREAD wrapper is replaced with its inner
slice expression. Empty form writes {nil,0,0}. args[] / widen[]
bump from 16 to 64 to accommodate Hare's mixed-arg printers.
Selfhost mirror:
- lib/ww/parse: `T...` mark on N_PARAM.op.
- cgen: varargseq counter on Cg; scanlocals reserves
@vararg_d_N + @vararg_sl_N per variadic call (seq recorded on
N_CALL.uval so cgcall picks the same names). cgcall does the
same gather/forward and N_IDENT splice. cgfnparams treats
variadic params as 24B slice slots via a synthesised TSLICE
tnode. pushargsrev skips the tagged-widen detection for
variadic params (effective type is []T, not tagged).
- rhstargetname now recognises N_TRUE/N_FALSE/N_RUNELIT and
typed N_INTLIT so the variant-tag lookup finds bool/rune/iN
variants instead of falling through to "first non-str" (which
misassigned tag 0 to bool in tagged unions like formattable).
lib/fmt graduated: print/println/fprint/fprintln/errorln/fatal
take `args: formattable...`. Bare `error` (no -ln) is skipped —
the leaf name collides with strconv's `type error = !(invalid |
overflow)` under the driver's flat namespace.
Tests: 5 new e2e rows (plain gather, zero-arg, tagged element,
forwarding, fmt.println end-to-end). lib/CLAUDE.md workaround
paragraph replaced with the Hare-shape description.
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.
Closes the remaining tagged-union gaps after the prior two commits:
1. Tagged element in an array/slice (cstage). N_INDEX load now reads
slot words into AX/DX/CX, matching the tagged-return ABI so match
/ call-arg / let-init paths consume `arr[i]` uniformly. N_INDEX
store routes through a scratch slot + cg_widen_tagged_store +
byte-copy to &arr[i], so the full widening machinery (scalar /
str / struct payload / tagged subset / nullable fold) lights up
for element writes too.
2. Selfhost mirror — the cgen widen helpers (struct payload,
tagged-subset, spread-flatten) C cgen has had for two commits
finally land in selfhost:
cgwidentaggedstore — single writer for nullable / tagged ident /
tagged via AX:DX:CX / struct (lit + ident) /
str / scalar source shapes.
cgwidentagremap — CMPQ-chain tag remap for variant-subset.
rhsstructpayload — struct-name predicate; filters `!void` /
`!i32` aliases that share N_STRUCTLIT shape
but aren't structs.
rhstaggedident,
rhstaggedabicall — source-shape predicates.
flatvariantidx — spread-aware variant index lookup. Walks
`(...inner | T)` entries by resolving the
alias and inlining the inner's variants so
wwstage's tag order matches the check.c
flattening cstage does at type resolution.
cglet tagged init, cgassign tagged-ident reassign, cgreturn struct
/ subset payload, pushargsrev struct payload, cgindex tagged
element load, cgassign N_INDEX tagged element store all delegate
to these. cgmatch picks up scrutt from N_INDEX bases (element
type) and uses flatvariantidx for case dispatch.
3. Selfhost frame accounting: scanlocals reserves a 24B @tagscr slot
when the body contains a tagged-arr store, a struct-payload
tagged return, or a struct-payload call arg — dedup'd via
scanseenmark so multiple sites share one slot. N_LET stubs now
carry tnode so walk-time type checks see the array element type.
slotsize TARRAY learned to size tagged / struct / ptr / aliased
elements (was 8B-default for anything not N_TNAME-primitive,
undersizing tagged-element arrays).
Scalar / str call-arg widening keeps its direct-push fast path
(no scratch), so wwstage's asm on selfhost source remains
byte-identical to cstage's — 993/995 still pass.
700_e2e: 9 new rows — scalar/str/struct/subset/nullable variants in
arrays and slices, plus pass-arg / let-init / return / match shapes.
Tagged-union widening already fired for `let r: (str|rune) = "...";`,
`r = "...";`, and `return "..."` from a tagged-returning fn — but not
at call sites, so `fn f(x: (str|rune))` couldn't be called with a bare
str or rune. The arg was pushed as its own static type (2 words for
str, 1 for rune) while the callee's slot expected 3 (tag + payload).
C cgen: at the call boundary, look up the callee's declared param
type per arg. When the param is TY_TAGGED and the arg is a concrete
variant, materialise (tag, value-words, padding) sized to the param's
tagged_arg_size — then the existing pop-into-arg-regs logic picks it
up. Nullable `(*T | void)` collapses to a single 8B push.
selfhost: fnret now carries the params head alongside rtype (amalloc
bumped to 48); pushargsrev takes the matching param node and runs the
same widening sequence per arg. The pop drain in cgcall already
handled extra slot words, so no change needed on that side.
Verified with a smoke covering str/rune literals, typed locals,
pre-existing tagged-local pass-through, and nullable widening from a
raw pointer. Selfhost emits byte-identical asm to C cgen on the test.
`type error = !(invalid | overflow)` miscompiled — istaggedtype
only matched N_TTAGGED directly, so an `e: error` param spilled
as 8B scalar and the match's slot+8 read trailed into saved BP.
Mirror isstrtype's alias+bang unwrap; add resolvetagged() for
is/as/match sites that need the inner N_TTAGGED. Frame scan
counts via slotsize so wwstage stays byte-identical to cstage.
Unblocks lib/strconv.strerror.
Surfaced via examples/lisp, which had to work around the following in
source. Each lowering now matches cstage on the same shape.
- cgassign / cgdot: two-level field through a non-pointer sub-struct.
`(*L).cur.kind = k` (cur a struct-by-value field of L) silently
dropped the store; the corresponding read fell into the SB-symbol
fallback and the linker reported `undefined reference to kind`. The
two new branches resolve outer-field offset + inner-field offset
and emit a single direct store/load at the combined slot, both for
T-by-value and *T-base shapes.
- cgdot: `xs[i].field` chains the trailing field load through the
N_INDEX result for [N]T / []T / *T element-of-struct-ptr. The
cgforrange loop variable now carries the elem tnode so the same
fast path covers `for (let x .. xs) { x.field }`.
- cgindex / cgassign: top-level `[N]T` array and `*T` pointer used
as an index base. cgindex now emits LEAQ name(SB) (array) or
MOVQ name(SB) (pointer) with the correct element scaling; without
this the fallback emitted neither base and walked off the saved
BP slot. Adds letvartnode() helper, an N_TARRAY branch to
letemitsize so the array shows up in c.lets, and an N_TARRAY
initialiser path in emitletdataw that lays the literal bytes into
DATAW.
- cglet / scanlocals: infer the local's tnode for an unannotated
`let x = f()` / `let x = f()?`. inferletcalltype() reads the
callee's declared return; `?` and `!` strip to the success variant
so a tagged-union let allocates the full 24B slot and the
struct-field dispatch in cgdot/cgassign sees the right type.
letslotsize now defers to slotsize on the inferred type.
- slotsize: follow type aliases for tagged-union variants. With
`type parserr = !str;`, the variant slot was 8B instead of the
required 16B; the tagged let stomped on the next slot at the
AX/DX/CX spill.
- cgreturn: tagged-union return forwarding. `return f();` where f
also returns a tagged union now passes the (tag, payload1,
payload2) triple through unchanged instead of re-wrapping it.
- cgreturn / cglet / taggedvariantindex: dispatch by variant name
with module-qualified-vs-bare matching, and recognise N_STRUCTLIT
as the variant tag for `return eof{};`. cgexpr default emits
`MOVQ $0, AX` so the surrounding return shuffle isn't left with
a stale AX.
- isstrtype / nodeisstr: resolve through `!T` aliases. `parserr =
!str` was not propagating the str-shape to the rhs check and the
MOVQ BX,CX shuffle was being dropped from str-typed local
returns.
- exprfloatkind: recognise `p.field` as f64/f32 when the struct
field is so declared, so `v.fval: i64` lowers to CVTTSD2SI on X0.
- cgassign: str field on a direct struct local writes both halves.
`L.src = s;` previously dropped s.len.
- cgcall: pop into the int reg window only up to 6 (DI..R9); rest
stays on the stack and the caller emits ADDQ to clean up.
cgfnparams accepts >6-arg signatures by registering the overflow
params at positive BP offsets (16+8*k(BP)), no spill instruction
emitted.
All 26 harness tests pass; bootstrap reaches a byte-stable fixed
point at ww3 == ww4.