Commit Graph

426 Commits

Author SHA1 Message Date
877a1af6d3 cgen: str tuple-positional element read -> 3-word -- Phase 2 C4.6 S3 (both stages)
Reading a str-typed tuple element by position (t.N) loaded 2 words (ptr,len), dropping cap -- the C4.6 coda with NO adjacent slice-element arm to mirror. Author the 3-word triple directly to the canonical {ptr,len,cap} ABI (AX,BX,CX off the BP frame slot; add cap->CX at +16). Kind-gated (TY_STR / isstrtype, never size==24). cstage==wwstage byte-identical -- cross-stage identity is the correctness oracle here, since there is no local slice sibling.

test/wcc/935: table-driven runtime .cap-survives over let s = t.1; poison rides the return ABI (R8) into the slot's cap word; a CX-clobbering call ensures a 2-word read cannot coincidentally pass. fail-before/pass-after verified INDEPENDENTLY on both stages.

main.combined.ww regenerated via the canonical make path (md5-stable).
2026-05-24 14:22:25 +09:00
634cbefc22 cgen: str chained-*struct field read -> 3-word -- Phase 2 C4.6 caseB (both stages)
The chained N_DOT path (o.p.f, depth>=2, base AX) still loaded a str-typed field as 2 words, dropping cap -- the C4.6 sibling deferred to caseB. Fold the str case onto the adjacent 3-word slice-field arm (widen kind-gate: cstage type_isstr, ww typeisstr; never size==24). Emits len->BX+8, cap->CX+16, ptr->AX+0 LAST (AX is the base). cstage==wwstage byte-identical; the slice arm is unchanged for slices.

test/wcc/934: table-driven runtime .cap-survives over the chained read; the row interposes a CX-clobbering call so a 2-word read cannot coincidentally pass on stale CX (per the 933 discriminator lesson). Verified fail-before/pass-after on both drivers.

main.combined.ww regenerated via the canonical make path (md5-stable).
2026-05-24 13:57:20 +09:00
90deeb3821 cgen: str N_DOT field read -> 3-word {ptr,len,cap} -- Phase 2 C4.6 (both stages)
Reading a str-typed struct field loaded only 2 words (ptr,len), dropping the cap word. Fold the str-field read onto the adjacent proven slice-field arm by widening its kind-gate to include str (type_isstr/isstrtype, never size==24). Sites: S1 direct struct field (local BP + global CX base) and S2 field through a *struct local (pst.f). cstage==wwstage byte-identical; the slice-field arms stay unchanged for slices.

C4.6 bundles the S1 local-field fold with a FORCED global-field lift -- the rule-11 reason they cannot split: cstage reads a field with ONE unified base_reg arm, so folding str covers local AND global together. For byte-id, ww's global field path must then lift in the SAME commit -- but ww splits local/global and its global arm has no slice sibling, so it is authored as ww's own local slice-field arm retargeted to the CX base (cap->CX last, base survives). The underlying cstage-unifies / ww-splits field-arm divergence is a separate filed structural follow-up, not resolved here.

test/wcc/933: table-driven runtime .cap-survives over local/global/*struct field reads, both drivers; verified fail-before/pass-after. The local-field row interposes a CX-clobbering call so a 2-word read cannot coincidentally pass on stale CX (the field store otherwise leaves the cap word lingering in CX).

main.combined.ww regenerated via the canonical make path (md5-stable), per the 1140a59 precedent.
2026-05-24 13:31:58 +09:00
97707155ae cgen: str N_INDEX read -> 3-word {ptr,len,cap} -- Phase 2 F2 (both stages)
str element value read at N_INDEX dropped the cap word (2-word ptr,len load); str is 24B {ptr,len,cap} since 1140a59. A new named helper cgslicehdr (both stages) loads the full 3-word header and is called by the N_INDEX str-element sites, kind-gated type_isstr/elemisstr -- never size==24, since str and slice collide at 24B. The base-targeting word loads last (clobber-safe). cstage==wwstage byte-identical. The #9 typeassert leaf is split out to F2b (it needs a wwstage spill twin first).

test/wcc/932: table-driven runtime .cap-survives probe over both N_INDEX base forms and both drivers; verified fail-before/pass-after. NNN<950 mirrors the 928 precedent -- the fixtures are self-contained (/tmp, no imports), so rule-14's selfhost-sibling race does not apply.

main.combined.ww regenerated via the canonical make path (md5-stable) and committed alongside source, per the 1140a59 precedent.
2026-05-24 12:27:15 +09:00
fb4c567e0d wcc: populate str.sub = u8 -- Phase 2 F1 foundation (both stages)
str IS []u8 (#1 landed the 24B layout); F1 populates the element type
so the step-3 checker collapse can read str.sub instead of special-
casing TY_STR. No reader consumes str.sub yet, so this is byte-id-
neutral: every shared ->sub reader a TY_STR value can reach is
invariant under NULL->u8 -- u8 is unsigned + size-1, matching the
prior NULL-defaults (size->1, signed->0, isstr/istagged->false); the
only ->size derefs are guarded behind esz>1, which stays false for
str.

Verified inert: compiling a fixed source with the pre- and post-F1
compilers emits byte-identical asm on both stages; cross-stage
byte-id holds and full make test (135 tests incl. 990-997) is green.

cstage cmd/wcc/type.c, wwstage lib/ww/typ.ww; combined.ww regenerated
via the canonical make path.
2026-05-24 09:34:54 +09:00
4db680690a test/wcc/928: runtime coverage for str byte-index (C2) + str-into-tagged-union (C4.8) 2026-05-24 09:19:20 +09:00
b416e7114e cgen: fold str tagged-variant payload store onto slice arm (both stages)
Phase 2 step 4. The str and slice tagged-union payload stores were
byte-identical adjacent arms (3-word ptr/len/cap @ slot+8/+16/+24 +
tag) since #1 made str a 24B {ptr,len,cap}. Delete the dedicated str
arm and widen the slice arm's gate to accept str (cstage type_isstr,
wwstage nodeisstr). One site, both stages. Byte-id-neutral: str now
flows the identical slice arm; full test incl 990-997 green.
2026-05-24 09:00:53 +09:00
a5ca21ddba cgen: str index-stride via type table, not literal 1 (both stages)
Phase 2 step 2. The N_INDEX element-stride for str hardcoded esz=1;
route it through the type table (cstage ty_u8->size, wwstage
primtypesize("u8")) so str's element width tracks the u8 SSoT. When
the TY_STR collapse (Phase 2 step 5) folds str onto the slice-of-u8
path, these sites need no second edit. Byte-id-neutral: u8 size is 1,
so emitted stride is unchanged; full test (incl 990-997 byte-id
gates) green.
2026-05-24 09:00:36 +09:00
1140a590bf wcc: str -> 24B {ptr,len,cap}, 3-reg ABI -- parity with []u8 (both stages)
A ww `str` becomes a 24-byte {ptr,len,cap} value, identical in layout to
[]u8 -- the enabling prerequisite for the Phase 2 `str == []u8` collapse.

Both stages, atomically:
- ty_str 16->24B; str value flows 3-reg AX/BX/CX (was 2-reg); str literals
  emit cap (=len).
- str in a tagged union grows to a 32B slot, using the AX/DX/CX/R8 4th-word
  path already used by 32B slice-variant unions -- str-variant is now
  structurally identical.
- tuple (scalar,str) return: 4-reg AX/DX/CX/R8 + 32B receive, extending the
  existing type-keyed return (no sret).
- str == []u8 for index and .ptr/.len/.cap, kind-gated where size-based
  dispatch collided at 24B; cstage and wwstage mirror exactly.
- table-driven runtime coverage: test/wcc/928_str_abi_run.c.

Cannot be split (rule 10/11): a 24B str and a 16B str cannot coexist across
the two compiler stages without breaking byte-identity, so the size change
and every dependent ABI/codegen site land in one atomic commit, both stages.

Known follow-ups (zero corpus impact, tracked): str-literal global .cap
static-init; >16B struct by-value (pre-existing); tagged-union
match-scrutinee stage divergence (pre-existing).
2026-05-24 08:11:14 +09:00
d9345555c0 rt: bump-over-mmap allocator (rt_segmalloc + rt_free no-op)
rt_malloc was a bare mmap-per-call wrapper: every allocation, even a
32-72B AST/symbol node, consumed a page-rounded 4KB region and was
never freed. w6a/w6c emit ~4 such nodes per .s line, so assembling a
145K-line file burned ~625K pages (~2.5GB); test 995's 5 concurrent
self-rebuilds then OOM'd. The defect is linear and str-independent --
the str->24B codegen merely enlarged .s files past the cliff.

Replace it with the no-free SUBSET of Hare's allocator
(ref/hare/rt/malloc.ha): 2MiB chunk-bump (CHUNKSZ malloc.ha:24, ALIGN
malloc.ha:14), oversized (>CHUNKSZ) requests direct-mmap'd. The
bin/freelist/META machinery exists only to support free, which ww does
not have, so it is omitted. Policy lives in rt/malloc.ww; the raw mmap
primitive stays in rt/alloc.s as rt_segmalloc -- Hare's malloc/segmalloc
split.

rt_free becomes a documented no-op (os.free re-exports it for the public
API, so the symbol must stay); rt/ensure.ww drops its now-impossible
reclaim. Zero-init is preserved: the bump never reuses memory, so every
byte is fresh MAP_ANONYMOUS-zeroed.

w6a_ww on a 145K-line .s: 2165MB -> 28MB (~glibc parity, C w6a 24MB).
.o output byte-identical; both stages emit identical asm. make test
134/134.
2026-05-24 07:15:38 +09:00
f45caf1cd9 selfhost/cmd/wcc: index-base esz from n.type_.size + delete indexbaseesz (#72, A.6.3k)
The N_INDEX node carries the checker-stamped element tinfo (#60 arc); cgindex,
cgun TK_AMP, and cgassign now read the element stride off that .type_.size
instead of indexbaseesz's manual N_DOT-pseudo-field + structlookup walk,
retiring the helper (0 callers, ~96 LOC). Aligns down to cstage's
idx_eff(base->type)->sub->size (cmd/w6c/cgen.c:3517-18, natural element size) --
strictly more cstage-faithful than indexbaseesz's totsize/slotsize derivation
(byte-id held only because firing shapes have totsize==natural; cstage reads
natural and ww-old==cstage, so the flip is structural). Each site keeps its
nil->default-8 fallback; cgindex stays esz-only (signed_elem unset for the
N_DOT base, as before).

Closes the A.6.3 cgenutil-collapse arc: every type/size/offset query in cgen
now reads the checker-stamped tinfo, and the AST-walker / structinfo-walk
helpers it replaced (dotfieldtnode, indexvaluetnode, rhstargetname,
dotinnerstructptr, indexbaseesz) are retired. make test 134/134, byte-id
990-997 hold. Coverage: 713/741/755 + self-rebuild.
2026-05-24 03:16:14 +09:00
0763377806 selfhost/cmd/wcc: dotchainresolve walks tinfo.fields (#71, A.6.3j)
The chained value-struct spine-walker resolved root + total offset + leaf
type via structinfo/fieldinfo (slot-padded foff). Swap its guts onto the
stamped root-ident type_: peel TY_NAMED to TY_STRUCT (one TY_PTR hop for a
*struct root) and accumulate tfield.offset down the spine, mirroring cstage's
cur->lhs->type fields walk (cmd/w6c/cgen.c:3156-3216 write, :1955-2030 AMP/
read). Leaf out-param becomes *tinfo; the three callers read leaf-ness via
typeis*/loadopsz, and the cgassign struct-terminal recovers the struct name
from the leaf tinfo's NAMED wrapper for the still-structinfo cgstructlitfill.

Root classification (local/ptr/global) is unchanged, so the firing set and
addressing mode stay byte-identical; the global-root path remains its pre-
existing shared breakage (#27), untouched. Natural tfield.offset equals the
old slot-padded foff for every shape the byte-id gate exercises -- and since
cstage already reads the natural offset and ww-old==cstage held, the flip is
structurally identical, not coincidental.

Latent (off-corpus, byte-id-neutral): the tinfo-peel now fires the str/slice
pseudo-leaf on an aliased-str/slice field where the old structinfo path
bailed -- a faithful-toward-cstage gap closure, filed for a probe + sentinel.

make test 134/134, byte-id 950+990-997 hold.
2026-05-24 02:35:53 +09:00
6971f57356 selfhost/cmd/wcc: collapse chained-dot offset-emit onto tinfo.fields + delete dotinnerstructptr (#70, #12)
Both chained-*struct-field sites (cgdot read, cgassign store) read the inner-
struct layout off the stamped inner-dot tinfo (peel NAMED->under, TY_PTR->.sub
->NAMED->under->TY_STRUCT) and walk tinfo.fields for offset + per-field type,
replacing dotinnerstructptr's structinfo re-walk + structlookup. Type dispatch
(str/slice/float, load/store op) keys on tfield.type_ via the existing *tinfo
predicates; ft.slotsize reproduces the old fieldsize exactly (== size for all
kinds reached here except struct/array). cstage parity: cgen.c:1653-1655
(read fl->offset), 2514/2541 (store f->offset).

Behavior-preserving: a strict per-level gate (every chain dot must peel through
a *struct, root must be N_IDENT && localfindnode != nil) reproduces
dotinnerstructptr's EXACT locals-only-with-all-*struct-intermediates firing set
-- a by-value intermediate dot bails to the identical pre-existing generic path.
asm is byte-identical (990-997 hold; both the strict gate and the looser
superset tested 134/134, confirming the corpus has no by-value-intermediate
chain). Deliberately NOT widened past the old set: global-root and by-value-
intermediate chained dots stay on their old paths -- the global case is a
pre-existing SHARED base-eval defect (cstage mis-evals the global base as
(BP)->segfault; wwstage no-stores), filed #27 to fix in both stages together.

dotinnerstructptr deleted (0 callers). Offset now sources from tinfo.fields
(natural layout) vs old structinfo (slot-padded); they coincide for flat
structs (all reached here), with nested-by-value-struct divergence pre-existing
and left to #57/#6/#7 territory.
2026-05-24 01:41:05 +09:00
e5092709e4 selfhost/cmd/wcc: drop indexvaluetnode from cgassign + delete 3 retired AST-walkers (#69, #61d)
cgassign's two element-store sites (N_DOT and N_INDEX index targets) fed the
index node into indexvaluetnode to recover the element type. The tagged-store
machinery reads tinfo directly post-#68, so both sites now read the checker-
stamped element tinfo via lhs.type_: esz from .size (mirror #60), tagged gate
via the shared istaggedtype/slotsize/cgwidentaggedstore path (all NAMED-
peeling). cstage parity: cgen.c:3507-3523 (idx_eff(base->type)->sub->size).
The new esz reads the element's natural .size, where the old elemsizeofc
routed struct elements through slotsize -- so a padded-struct chained-index
store (`[][]Point`) now matches cstage's ->size instead of diverging; that
shape is untested (#7 indexbaseesz territory), so this is faithfulness, not
a corpus change.

With cgassign migrated, indexvaluetnode has zero external callers; dotfieldtnode's
sole caller was indexvaluetnode; rhstargetname is self-recursive only -- all
three retired (-132 LOC). This closes the A.6.3 AST-walker arc: the *node
type-resolvers that existed because tinfo was lossy on nominal identity are
gone, now that Phase-N (#63-#68) built the TY_NAMED layer and every consumer
reads the stamped tinfo. make test 134/134, byte-id 950+990-997 hold.
2026-05-24 00:16:14 +09:00
901ddf20b9 selfhost/cmd/wcc/cgenutil: tagged-store machinery reads tinfo.params (#68)
cgwidentaggedstore/storebp/cgwidentagremap took a type *node and re-derived
the tagged shape via resolvetagged + N_TTAGGED.list walks. Migrate them onto
the stamped tinfo (the store-side parallel of #66's match-side flip): dst is
now the tagged *tinfo (peel TY_NAMED->du, gate TY_TAGGED), variant lookup +
tag-remap read tinfo.params by typeeq, mirroring cstage cg_widen_tagged_store
/ cg_widen_tag_remap / cg_tag_for_variant (cmd/w6c/cgen.c:1273/1177/503). The
N_CAST widening test flips from surface-name streq to `castu==dt || (castu
tagged && typeeq(castt,dst))` (cgen.c:1295).

Node-form flatvariantidx/taggedvariantindex become thin shims over new tinfo
cores (flatvariantidxt/taggedvariantindext) so node-side callers (cgreturn
cgenstmt:269, pushargs cgenutil:192) are untouched. The 9 cgwidentaggedstore
callers pass node.type_ (each already istaggedtype/slotsize-gated). resolvetagged
is retained for its 7 match-side callers.

Incidentally retires two latent ww-vs-cstage divergences, both byte-id-neutral
on the corpus: the old N_CAST test set castisdst for ANY N_TTAGGED regardless
of type equality (cstage guards on type_eq), and the old remap walked the
UNflattened src.list (cstage walks the flattened params). Unblocks cgassign's
indexvaluetnode drop (#69/#61d). make test 134/134, byte-id 990-997 hold.
2026-05-23 22:57:13 +09:00
aec48e8c13 selfhost/cmd/wcc: matchscrutt returns scrutinee node, gate on istaggedtype (#67)
matchscrutt's N_DOT branch resolved the field type via the dotfieldtnode
AST walk + resolvetagged; post-#66 the N_DOT node carries the field tinfo
on .type_, so return the scrutinee node directly and let cgmatch gate on
istaggedtype(scrutt) instead of scrutt.kind == N_TTAGGED. All six scrutt
consumers read .type_ (peeling TY_NAMED), none reads node structure, so a
value node vs a type node is invisible downstream; the istaggedtype guard
preserves the old nil-for-non-tagged contract.

Symmetry-improving (rule 10): cstage derives the dispatch type from s->type
with one unconditional NAMED-peel (cmd/w6c/cgen.c:4847-4850; the N_IDENT
check at :4854 is only the slot-offset fast-path). The old dotfieldtnode
required base.kind == N_IDENT -- a restriction cstage never had -- so the
chained-dot widening this enables matches cstage (out-of-corpus, #14).

Drops matchscrutt's dotfieldtnode caller (external callers 2->1; the
indexvaluetnode:1084 internal recursion remains, and the cgassign tagged-
store sites still need the node-keyed resolvetagged machinery, so neither
walker is deletable yet -- store-migration + #61d follow). N_DOT-match
coverage: 693/694/695/700/744 (runtime). byte-id 990-997 unchanged, 134/134.
2026-05-23 21:55:52 +09:00
3036ba766d selfhost/cmd/wcc: type-key tagged variant match (#66, Phase-N step 3)
The user-ruled B-full semantic change: flip tagged-union variant matching
from surface-NAME to TYPE-identity (typeeq over tinfo.params), mirroring
cstage cg_variant_match (cmd/w6c/cgen.c:451). A cross-module `a.T` != `b.T`
and `type linerr=!str` != str are now distinguished by the per-decl TY_NAMED
pointer (Phase-N #64). ww has no type_assignable, so the untyped/loose arm
keeps the str/slice shape fallback (rule-10 align-down). The 5 helpers
(flatvariantidx, flatslicevariantidx, taggedvariantindex, cgtagvariantidx,
cgmatch dispatch) flip; nomem propagation (NAMED-name scan, no source value)
and the f64 widen arm (float-kind classification, no pattern node) are not
arm-by-value discrimination and stay name/kind-keyed.

The flip requires value nodes to carry nominal identity. exprtype's
N_STRUCTLIT arm stamped the flattened body, so `overflow{}` (overflow=!void)
got TY_VOID and missed its variant -- fixed to stamp the per-decl NAMED
(mktname(lhs.str) -> tinfofornode reuses the #64 NAMED build/cache, same ptr
the union variant resolved to), mirroring the N_CAST/N_IDENT arms + cstage.
Returns the body node unchanged (only e.type_ rides NAMED); struct-lit layout
is unaffected -- cgstructlitfill is structlookup(name)-keyed, never reads
NAMED.fields. The fix now hits all `T{}` stamps, kept byte-id by the #63/#65
structural-walker peels.

931_variant_typekey_run: table-driven, both stages, /tmp-isolated. Two rows
widen an alias-FIRST variant from a call (no surface name): `(linerr|str)`
str-via-call -> idx 1, `(ec|i32)` i32-via-call -> idx 1. Empirically
discriminating: FAILS pre-flip (wwstage falls to the leading-shape variant,
exit 10; cstage exit 0) and PASSES post-flip -- locking in the capability
byte-id can't reach (the corpus has no name-key/type-key-disagreeing
co-variant, which is why name-keying survived).

make test 134/134 (byte-id 990-997 green; 995 self-rebuild green).
2026-05-23 21:22:24 +09:00
0fde4beeb4 selfhost/cmd/wcc: peel NAMED in elemissignedc + refresh #63 comments (#65)
#64 flowed per-decl TY_NAMED wrappers, falsifying two #63-era assumptions
surfaced in the flip review.

elemissignedc read ti.sub for element signedness without peeling TY_NAMED;
a NAMED-of-indexable would read NAMED.sub (nil) instead of the underlying's.
Add the transitive peel ahead of the .sub read, mirroring cstage idx_eff's
type_unwrap (cmd/w6c/cgen.c:790) before eff->sub (:3518-3520). Byte-id-neutral:
every aliased indexable in-tree has a u8 element (typeissigned=false either
way). Independent .sub/.under inventory confirms elemissignedc was the sole
structural reader missing a peel (castsrcprim + TK_AMP already NAMED-guarded;
typeis* handle element NAMED via .under recursion; typeeq is nominal by
design and must not peel).

Refresh the 5 #63 peel-site comments (slotsize, fieldsize, nullableptrtag,
tupleelemslot, fieldslotsize): the peel now actively fires (#64 builds NAMED)
rather than being a no-op; byte-id holds because NAMED collapses to the
alias-invariant underlying.

make test 133/133 (byte-id 990-997 green).
2026-05-23 19:54:00 +09:00
3866ea24f5 selfhost/cmd/wcc/check: build per-decl TY_NAMED in tinfofornode (#64, Phase-N step 2)
tinfofornode's TNAME arm collapsed aliases to their underlying tinfo; flip
it to build a per-decl TY_NAMED wrapper cached on sym.type_, so every TNAME
resolving to the same decl yields one tinfo pointer -- ptr-identity =
nominal identity. Mirrors cstage's two-phase type_named (cmd/wcc/check.c:
1900-1929, resolve_typename :60-88): create the NAMED, pre-bind sym.type_
BEFORE resolving under (self-ref cycle-break, e.g. `type node = struct
{next: *node}`), then patch under + copy size/align/slotsize off the
immediate body. CHAINS not flatten (`type a=b` gives under=NAMED(b)),
matching resolve_typename returning the inner NAMED.

aliassym factored out of resolvealias for the one-level decl lookup;
resolvealias delegates and is behaviorally identical.

Semantically INERT until typeeq consumes nominal identity (step 3, #16) --
live type equality today is the AST-keyed typeeqast, and typeeq has no live
callers. The #63 structural-walker peels + cstage-mirrored single-if peels
keep all tinfo.kind sites correct with NAMED flowing -- byte-id 990-997
unchanged (133/133, independently re-confirmed on a quiescent tree).
2026-05-23 19:33:04 +09:00
ae6a59a355 selfhost/cmd/wcc: peel TY_NAMED in 5 structural walkers (#63, Phase-N step 1)
Phase-N prerequisite (additive, byte-id unchanged). slotsize / fieldsize /
nullableptrtag (cgenutil) and tupleelemslot / fieldslotsize (check) read
size/slot/kind off a tinfo without peeling TY_NAMED. Once Phase-N step 2
(#64) makes tinfofornode build per-decl TY_NAMED wrappers, an unpeeled
reader would misbehave (fall through to 8 / take natural size not slot /
miss NAMED-of-tagged). Prepend a transitive `for (t != nil && t.kind ==
tykind.TY_NAMED) { t = t.under; }` peel + nil re-guard at each, mirroring
cstage's `while (t->kind == TY_NAMED) t = t->under` and the recursive
typeis* predicates.

Additive no-op today: tinfofornode still collapses aliases, so no NAMED is
ever built and the loop never executes. byte-id 990-997 unchanged (133/133).

Audit (worker + reviewer, independently, across all selfhost/cmd/wcc/*.ww
+ lib/ww/*.ww): these 5 are the ONLY non-peeling structural walkers. typeis*
recurse on .under; typeeq is nominal by design (ptr-identity, the step-3
goal); typeisuntyped cannot receive a NAMED; check.ww type constructors and
localloadop read only .size/.slotsize, which typenamed copies from .under so
they stay numerically correct on a NAMED without peeling.
2026-05-23 18:44:12 +09:00
e0c0f75b2a selfhost/cmd/wcc/check: flatten tagged spreads + iserror on tinfo.params (#61a)
A.6.3 #61 prerequisite (additive, no consumer changes). The tagged-variant
machinery (taggedvariantindex / flatvariant* / cgwidentagremap / cgmatch)
is AST-keyed -- it walks N_TTAGGED.list and spread-flattens `...inner` at
read time. To migrate it onto tinfo.params (#61b/c) the chain must first
carry the flattened variant set + per-variant error mark, matching cstage's
Type.params / Type.iserror.

tinfofornode's TTAGGED arm now splices `...inner` tagged spreads into
ti.params (dealias one NAMED level, require TY_TAGGED, inline its already-
flattened variants in declaration order) -- mirror of cstage check.c:366-389.
Each variant gets an iserror flag via varianterr (TBANG / `!`-aliased).
size/align stay accounted off the surface member so ti.size is byte-identical
to before; the flatten + iserror have zero readers this commit (the lone
TY_TAGGED params reader, nullableptrtag, only fires on 2-variant nullable
unions with no spreads).

iserror rides the shared tparam struct rather than a sidecar: a cstage-mirror
divergence from harec, which carries no per-variant flag (models `!T` as a
STORAGE_ERROR type node, ref/harec/include/types.h:144, src/types.c:151-159).
Faithful port filed as #62. Spread-only flatten (cstage check.c:373 also
flattens non-spread anonymous-nested unions) is a known symmetry gap, inert
in bootstrap, tracked for #61b.

make test 133/133 (quiescent tree, byte-id 990-997 green).
2026-05-23 17:36:39 +09:00
38d6eb667c selfhost/cmd/wcc: inline N_INDEX elem tinfo at 3 tagged push/index sites (#60)
pushargsrev and cgindex re-derived an index element's type via
indexvaluetnode (a base->TPTR/SLICE/ARRAY .lhs AST walk). The checker
stamps the element type on the N_INDEX node itself (indexresult,
check.ww:1710; N_INDEX is in the asserttyped gate), so read n.type_
directly at the 3 sites that only need tagged-ness + element size/sign:
  cgenutil pushargsrev L178/490: pass the N_INDEX arg to istaggedtype/
    slotsize (arg.type_ is the element tinfo).
  cgenexpr cgindex L726: esz = n.type_.size, signed = typeissigned(n.type_).

Polarity DOWN per rule 10: cstage has no indexvaluetnode -- it reads
base->type->sub->size directly (cmd/w6c/cgen.c:2070-2071, :3518). The new
path reads element natural size (tinfo.size == primsize: rune=4, u8=1,
str=16, slice=24), matching cstage; it also retires two latent elemsizeofc
divergences (elemsizeofc returned slotsize N*8 for *[N]i64 / 2D-array
elements where cstage uses sub->size=8) -- those shapes are absent from
self-compile, so byte-id stays green.

indexvaluetnode is NOT deleted: its remaining callers at cgenexpr
L3720/3729 feed cgwidentaggedstore -> resolvetagged -> resolvetype, still
node-keyed (nil for non-N_TNAME). Deleting it waits on the resolvetagged
-> tinfo migration (#11).

make test 133/133 (byte-id 990-997 green, independently re-confirmed on
quiescent tree).
2026-05-23 17:04:31 +09:00
827a05e548 selfhost/cmd/wcc/cgenutil: exprprimresolved N_DOT off dotfieldtnode (#59)
exprprimresolved's N_DOT arm derived a struct field's prim width+sign by
walking the field's declared *node (dotfieldtnode + typenodeprimresolved
alias recursion). Read the checker-stamped tinfo instead, mirroring cstage
castsrcprim N_DOT (cmd/w6c/cgen.c:323-344): the base's n.lhs.type_ must
resolve to a struct (peel NAMED->PTR->NAMED, require TY_STRUCT) before the
field counts -- excluding pseudo-fields .len/.cap/.ptr (stamped i32/*T at
check.ww:1987-2004; their base is TY_SLICE/TY_STR/TY_ARRAY, never TY_STRUCT,
so the guard yields sz=0) and tuple positionals, which stay sz=0 to preserve
995 byte-id. The field's width/sign comes from the N_DOT's own n.type_
(check.ww:2012), one NAMED peel then typeisint?size:0. Bool exclusion is
now free via typeisint(bool)=false, dropping the old streq("bool") arm.

Polarity DOWN per rule 10: cstage castsrcprim already reads the stamped
type. typenamed() has zero callers in wwstage (tinfofornode collapses all
alias depth to the body), so no tinfo carries kind TY_NAMED -- the NAMED
peels are dead/inert, output matches cstage.

Removes one dotfieldtnode caller (3->2; remaining cgenutil 1073, 1871).
typenodeprimresolved retained (3 callers: cgenutil 1459/1465, cgenexpr 431).
Part of the dotfield* consumer-migration arc.

make test 133/133 (quiescent tree, byte-id 990-997 green). Coverage:
710_cast_enum_movl rows struct_field_rt + pseudo_field_clamp + bool_to_i8.
2026-05-23 16:10:46 +09:00
8ccda588c6 selfhost/cmd/wcc/cgenutil: trim rhstaggedabicall N_DOT onto n.type_ (#58, A.6.3i-phase-2)
rhstaggedabicall's N_DOT arm re-derived the field type via dotfieldtnode
(a base-ident-only structlookup walk) then asked istaggedtype. The
checker now stamps the field's resolved type on the N_DOT node itself
(check.ww struct-field arm), so read src.type_ directly. typeistagged(nil)
is false, preserving the old ft==nil bail.

Polarity DOWN per rule 10: cstage's gate was already wide. cg_widen_tagged_
store reads src->type inline, NAMED-resolved, then tests TY_TAGGED
(cmd/w6c/cgen.c:1302-1305) -- no standalone helper. Pre-trim wwstage's
gate was NARROWER (dotfieldtnode required base==N_IDENT, firing only for
`ident.field`); reading src.type_ also fires for chained-dot bases
(`a.b.c`) since the checker stamps N_DOT.type_ at any depth. This aligns
wwstage UP to cstage's existing coverage. Byte-id 990-997 green confirms
the widened shape does not occur in bootstrap sources -- byte-id-neutral.

Drops one dotfieldtnode caller; the *node-returning callers
(typenodeprimresolved, indexvaluetnode, matchscrutt) stay until their
consumers migrate to *tinfo (the closing dotfield* deletion follows once
none need *node). First clean slice of that consumer migration; same
g/h-style stamp read as #55/#56.

Known pre-existing gap (filed, not introduced here): neither stage's
chained-DOT read path has a tagged-union leaf branch, so a chained-dot
tagged ABI source would store stale DX/CX/R8. Symmetric across stages
(byte-id stays green); the retained `cgdot loads AX=tag, DX=word0, ...`
comment is accurate only for ident.field bases.

make test 133/133 (quiescent tree, byte-id 990-997 green).
2026-05-23 15:41:31 +09:00
6c9a3b369e selfhost/cmd/wcc/check: populate tinfo.fields + .tupleelems (#57, A.6.3i-phase-1)
Phase 1 of A.6.3i: populate the field chain in tinfofornode's TSTRUCT
and TTUPLE arms so Phase 2/J/K (#58/#59/#60) can retire dotfieldtnode,
dotinnerstructptr, dotchainresolve, and indexbaseesz off their AST-keyed
structinfo walk and onto a tinfo read. Direct analog 26724fe (#50 phase
1, A.6.3f-a) for the head/tail append-list pattern.

TSTRUCT walks n.list's N_TFIELD chain in lockstep with the existing
natural-layout offset accumulator: alloc tfield {name, type_, offset,
tnext}, link head/tail, set r.fields after the loop. Mirrors cstage
cmd/wcc/check.c:468-527. Harec cite: ref/harec/include/types.h:109-115
struct_field and ref/harec/src/type_store.c:314-347 struct_init_from_atype.
Anonymous-embed promotion not populated here (#13 per the cstage cite
at check.ww:1263).

TTUPLE adds a new ttupleelem struct {type_, offset, tnext} on a new
tinfo.tupleelems slot, distinct from .fields per Rob's call: harec
splits struct_field vs type_tuple at types.h:109-115 vs :122-126
because tuples are positional/anonymous and struct members are named,
and the name="" idiom #50 reused for tagged-variants-on-tparam would
conflate two semantic axes. Diverges from cstage cmd/wcc/check.c:329-345
which stores tuple positionals on t->params (Tparam, no offset, consumer
recomputes by walking at cgen.c:5723-5750); storing the offset matches
the A.6 stamp-once-read-many arc Phase 2/J/K consume. Offset is raw-sum
(no per-element padding) matching cstage cgen.c:5723-5750, distinct
from harec's add_padding at type_store.c:561.

Purely additive: r.fields and r.tupleelems have zero readers today.
Phase 2/J/K consume. make test 133/133 (worker port); test-unit 124/124
post comment-only review trim.
2026-05-23 15:13:07 +09:00
8d4a9700a0 selfhost/cmd/wcc/cgenutil: collapse slice+str N_DOT arms (#56, A.6.3h)
nodeisslice + nodeisstr each walked base->struct->field on N_DOT,
gated on `base.kind == nkind.N_IDENT` (with dotinnerstructptr and
dotchainresolve fallbacks for chained / value-struct cases) --
duplicating cstage at the AST level while silently dropping
multi-level chains rooted at non-IDENT/DOT bases (e.g. `t.1.field`
for a tuple positional). After A.6.2 the checker stamps n.type_ on
every N_DOT (check.ww:1947-1996 pseudo-field, struct-field, and
tuple-positional arms), and A.6.3b landed typeisstr / typeisslice.
Both arms collapse to one tinfo read.

Polarity DOWN per rule 10: cstage was already aligned. cgen.c:168-170
node_isstr = type_isstr(n->type); cgen.c:182-184 node_isslice =
type_isslice(n->type). Wwstage was the laggard; this brings wwstage
to cstage's leaner shape, mirroring A.6.3g (8da1414).

Silent-false coverage gain: multi-level chains and tuple-positional
bases (`t.1.field` for a str element) now resolve via the checker
stamp instead of returning false. The "Not covered: tuple-positional"
bullet in nodeisstr's docstring is removed accordingly. dotchainresolve
itself is untouched -- still used by cgenexpr (cgdot read-path, &-of
address-of, structlit BP write-back). Byte-identity (994/995) is the
gate.

make test 133/133 ok. Net cgenutil.ww -110.
2026-05-23 14:39:05 +09:00
8da14147b3 selfhost/cmd/wcc/cgenutil: collapse N_DOT arms onto n.type_ (#55, A.6.3g)
nodeisunsigned + exprfloatkind each manually walked base->struct->field
on N_DOT, gated on `base.kind == nkind.N_IDENT` -- duplicating cstage's
behaviour at the AST level while silently dropping the nested-N_DOT case
(`a.b.c` returned the conservative default). After A.6.2 the checker
stamps n.type_ on every N_DOT expression (check.ww:1973 struct-field
arm of exprtype), and A.6.3a/b landed the tinfo helpers (typeisunsigned,
isfloattype/isf32type) that the inner reads already use. Both arms
collapse to one tinfo read.

Polarity DOWN per rule 10: cstage was already aligned. cmd/w6c/cgen.c:
2330-2331 reads type_isunsigned(n->lhs->type) directly; cgen.c:152-156
node_isfloat = cg_isfloat(n->type); cgen.c:195-199 node_isf32 =
type_isf32(n->type). No exprfloatkind-equivalent walker exists in
cstage -- it is pre-A.6.2 wwstage scaffolding. Wwstage now reads the
same shape as cstage on N_DOT.

Nested N_DOT (a.b.c) now resolves to the field type instead of returning
the conservative default. Byte-identity (994/995) confirms the codegen
matches cstage on the test set -- cstage was already getting nested-dot
right via checker-stamped n->type, wwstage was the laggard.

make test 133/133 ok. Net cgenutil.ww -41 / +3.
2026-05-23 13:59:06 +09:00
908875682a selfhost/cmd/wcc/cgenutil: collapse nullableptrtag onto tinfo.params (#50 phase 2, A.6.3f-b)
Phase 2 of A.6.3f, closing A.6.3 entirely (a/b/c/d/e/f-a/f-b all
landed). With #50 phase 1 (26724fe) populating TY_TAGGED.params,
nullableptrtag retires its AST-keyed predecessor: walk ti.params,
strip TY_NAMED via .under on each variant, return idx of first
TY_PTR.

Mirrors cstage cmd/w6c/cgen.c:404-416 line-for-line. Source-order
semantics preserved by phase 1's append-tail head/tail
construction (head = first n.list variant). For a `(*T | void)`,
*T-first → returns 0; void-first → walks past void (vt.kind==
TY_VOID, no match), *T at idx 1 → returns 1.

Two paths the new tinfo-keyed body handles that the AST walk
missed (cstage parity, dead-in-bootstrap today, parallel to #49
TY_TUPLE / #51b typed-float corrections):

  - Aliased *T variant: `type ip = *int; let x: (ip | void);` —
    cstage cgen.c:415 strips TY_NAMED via .under; new wwstage
    body mirrors. Bootstrap has zero aliased-ptr-variant
    callsites today (`grep "^type [a-z]+ = \*"` yields only an
    out-of-union test/uses.ww case).
  - void-first ordering: cstage walks past TY_VOID and finds *T
    at idx 1. Same in wwstage. No test/wcc fixture exercises
    void-first today.

Outer-type TY_NAMED strip (cstage cgen.c:409 `if t->kind==TY_NAMED
t = t->under`) intentionally skipped: tinfofornode for N_TNAME
already resolves the alias and returns the underlying tinfo
unwrapped — `typenamed` is declared at lib/ww/typ.ww:238 but has
zero producers in selfhost today. The strip would be a no-op
under current invariants. Tracked as part of #13 (TTAGGED
normalization parity) for when wwstage starts producing
TY_NAMED.

Net +30 LOC across cgenutil.ww + two .combined.ww bundler regens
(new function body is ~14 lines vs ~4; new WHY comment shorter
than the pre-graduation note's 7).

Byte-identity (994/995) is the gate; full make test green at
133/133 confirms.
2026-05-23 02:21:53 +09:00
26724feefb selfhost/cmd/wcc/check: populate TY_TAGGED.params (#50 phase 1, A.6.3f-a)
Phase 1 of Rob's two-phase A.6.3f pattern: populate the variant
chain in `tinfofornode`'s TTAGGED arm so phase 2 (#50b) can retire
`nullable_ptr_tag`'s AST-keyed walk in cgenutil onto a tinfo read.
Per b8e5a92 (A.6.3b) commit body: "nullableptrtag stays AST-keyed
for now — tinfofornode doesn't populate TY_TAGGED.params … so the
tinfo equivalent of cstage cgen.c:405 nullable_ptr_tag can't read
params today."

Restructure the TTAGGED arm into a single pre-pass: walk `n.list`,
resolve each variant via tinfofornode, alloc `tparam{name="",
type_=vt, tnext=nil}`, link head/tail, accumulate maxsz + al
inline. Set `r.params = head` after the loop. AST-level nullable
fold runs after, before size assignment — kept AST-keyed (not
ported to cstage's tinfo-level `kind==TY_VOID && !iserror` check)
because wwstage tinfo carries no `iserror` field; that's an honest
data-shape divergence (filed in passing as part of #13's TTAGGED
normalization arc).

Mirrors cstage cmd/wcc/check.c:347-435 — same head/tail append-
list construction, same Tparam reuse across struct-fields /
tuple-fields / fn-params / tagged-variants (sea-of-stars per
rule 12 — one record, four consumers, no per-kind variant of
the param node). Diverges from harec's array+id-sort at
ref/harec/include/types.h:128-132 / ref/harec/src/type_store.c:
431-432; rule 10 anchors wwstage byte-id to cstage, not harec.

Purely additive: ti.params has zero readers on TY_TAGGED today
(typeeq walks params only for TY_FN/TY_TUPLE; cgenutil's
nullableptrtag is still AST-keyed; #50b will consume). Byte-
identity (994/995) unchanged at 133/133 — pre-impl risk audit
by ken-thompson came back zero, confirmed by full make test.

A latent divergence wwstage doesn't cover (never-drop /
...spread / dedup / single-variant collapse — see cstage type
set normalization at check.c:393-432) is pre-existing and out
of #50's scope; tracked as #13. Phase 2 nullableptrtag is a
linear walk for the first TY_PTR variant in a 2-variant
nullable, indifferent to ordering and dedup, so it does not
need #13 closed first.

Net +12 LOC per file across check.ww + two .combined.ww
bundler regens.
2026-05-23 01:51:29 +09:00
883665e962 selfhost/cmd/wcc/cgenutil: collapse fieldsize onto tinfo (#49, A.6.3e)
fieldsize selected the slot-padded byte width of a struct field's
type-AST via the same TBANG/TNAME/TPTR/TSLICE/TARRAY/TTAGGED walker
shape slotsize used pre-#48 — with TNAME branching into
structlookup, enumlookup, and aliaslookup to follow the AST chain
back to a primitive size or struct totsize. After A.6.2 stamping
+ #48's slotsize collapse, the same data is reachable through
the populated tinfo:

  TY_STRUCT / TY_ARRAY → ti.slotsize
  TY_TAGGED / TY_SLICE / TY_STR → ti.size
  TY_PTR / TY_FN / TY_CHAN → 8
  primitives + TY_ENUM + TY_TUPLE → ti.size (catch-all > 0)
  fallback → 8

cstage SSoT is `f->type->size` at cmd/w6c/cgen.c:1386, :1656, :2515,
:2535 — wwstage routes through ti.slotsize for composites (the
#48 verdict centralizes the slot-pad rule on tinfo) and through
ti.size where natural width and in-struct width coincide.

Two latent behavior fixes ride alongside the collapse, both
cstage-parity and dead-in-bootstrap (995 byte-id is the regression
gate, currently green at 133/133):

  - TY_TUPLE-typed struct field: old walker had no TTUPLE arm and
    fell through to 8; cstage `f->type->size` reads the natural
    sum (e.g., 24 for `(i64, str)`). New code reads ti.size,
    matching cstage.
  - !T-typed struct field: old walker had no TBANG arm and fell
    through to 8; cstage iserror-passthrough returns the inner
    type's size. tinfofornode strips N_TBANG (check.ww:1154-1161)
    so the new dispatch sees the inner ti directly.

No fixtures in selfhost exercise either case today; both fixes
are pre-correct for future code that does.

Body went from ~47 LOC to ~16 LOC. `c: *cgen` retained unused for
callsite stability (slotsize / localloadop precedent, a828c03 /
68219a1). Two callsites in cgenutil.ww:1870 + cgenexpr.ww:3594
untouched.

Dot-chain helpers (dotinnerstructptr, dotfieldtnode,
dotchainresolve) are split off as #49b — they walk a cgen-side
`structinfo` table keyed by field name + offset, and tinfo.fields
is not yet populated by check.ww's TSTRUCT/TTUPLE arms. Parallel
structure to #50's TY_TAGGED.params gap; treat as a separate
populate-then-port pair.

Net -48 LOC across cgenutil.ww + two .combined.ww bundler regens.
Full make test green at 133/133.
2026-05-23 01:28:38 +09:00
a828c036d0 selfhost/cmd/wcc/cgenutil: collapse slotsize onto tinfo (#48, A.6.3d)
slotsize selected the slot-padded width for a frame slot via an AST
walker over TBANG / TPTR / TFN / TCHAN / TSLICE / TTUPLE / TTAGGED /
TNAME / TARRAY / TSTRUCT — duplicating the size + slot-pad math
tinfofornode already runs at check time. With A.6.2 stamping every
N_T* kind's n.type_, plus #61 A.5 splitting tinfo.slotsize from
tinfo.size, the dispatch collapses to a kind switch over the
populated tinfo:
  - TY_VOID → 0
  - TY_PTR/SLICE/CHAN/FN/STR/TAGGED → ti.size (size == slotsize for
    these kinds)
  - TY_STRUCT/TUPLE/ARRAY → ti.slotsize (slot-padded by check.ww's
    TSTRUCT/TTUPLE/TARRAY arms with the same field-pad / stride
    rules cgenutil's registerstruct uses)
  - primitives → catch-all 8 (pad-to-8 lives at the read site, not
    in ti.slotsize, so [N]i32 stride stays 4)

Ww-to-Hare divergence (deliberate, team consensus): Hare's struct
type carries only `size` (ref/harec/include/types.h:134-137); QBE
handles slot padding downstream. ww emits Plan 9 amd64 asm directly,
so slot-padding is part of the ww calling convention and belongs on
the type table. Cstage scatters pad-to-8 inline at ~30+ localoff
sites + the `(su->kind == TY_TAGGED) ? su->size : 16` tagged-spill
pattern at cmd/w6c/cgen.c:4850 / :5193 — that scattering would be a
rule-13 (no hardcoded size literals) violation in ww. Centralizing
on tinfo.slotsize IS the rule-13-compliant shape; #61 A.5 put it
there, and #48 just consumes it. Rule 9 is lib/-scoped; tinfo is
compiler-internal (already diverges via node.type_ as a checker
invariant Hare/harec lacks). Rule 10 covers inference power, not
data shape — byte-identity (994/995) holds at 133/133.

Body went from ~150 LOC AST walk to ~15 LOC tinfo dispatch. Two
nil guards (typn == nil, ti == nil) fall through to 8 — same outcome
as cstage's `(t && t->size > 0) ? sz : 8` defensive shape.
`c: *cgen` retained unused for callsite stability (localloadop
precedent, 68219a1).

Net -453 LOC across cgenutil.ww + two .combined.ww bundler regens.
Follow-up filed: grow cstage Type.slot_size symmetrically and
sizelint-ok-annotate the surviving inline 8s until ported.
2026-05-23 00:55:44 +09:00
68219a119c selfhost/cmd/wcc/cgenutil: collapse localloadop onto tinfo (#47, A.6.3c)
localloadop selected MOVBQSX/MOVBQZX/MOVSWQ/MOVL/MOVQ for scalar
local/let loads via an AST walk down TBANG/TENUM/TNAME-alias chains,
re-consulting aliaslookup and ending in fieldsize + fieldissignedc.
Three precursors retire the walk: #53 (e3237d1, scopelookupprefer
fixes flat-alias collision in resolvealias), #51 (1ce0f63, INTLIT
tsuffix stamp), #52 (747279c, typenameisunsigned collapse onto
typeisunsigned). Plus the A.6.2 type-AST stamp invariant at
check.ww L426-436.

Body collapses to two nil guards + ti.size + size cascade +
typeissigned(ti). cstage cmd/w6c/cgen.c:357-362 is the SSoT;
wwstage now reads tinfo.size directly the same way cstage reads
t->size, with TBANG / TENUM / TNAME-alias chains pre-folded by
tinfofornode (check.ww:1102-1153 TNAME, 1154-1161 TBANG,
1196-1208 TENUM).

Defensive nil branches mirror cstage's `(t && t->size > 0) ? sz : 8`
fall-through: when type info is missing, sz fails the != 1/2/4
discriminator and the helper returns MOVQ. Both nil paths are
reachable: cgenexpr.ww callers (4 sites: 643, 664, 5380, 5471)
populate the *node via a search loop that may exit with nil.

Signature unchanged — `c: *cgen` is retained unused for callsite
stability, mirroring A.6.3a fieldissignedc(c, t) which followed the
same precedent. 5 callsites in cgenexpr.ww untouched (body-only
collapse).

Net -33 LOC across cgenutil.ww + two .combined.ww bundler regens.
Byte-identity (994/995) is the behavior gate; full make test green
at 133/133 confirms.
2026-05-23 00:11:05 +09:00
747279c029 selfhost/cmd/wcc: collapse typenameisunsigned onto tinfo (#52, A.6.3c-cast)
A.6.3a (#45) deferred typenameisunsigned because its two callers —
typenodeprimresolved and exprprimresolved — consumed a raw str:
TNAME.str / INTLIT.tsuffix. #51 (1ce0f63) stamped tsuffix-typed
N_INTLIT.type_ via tinfofornode; together with check.ww L426-436
type-AST stamping, both call sites now read a stamped n.type_
instead of a raw name.

typenodeprimresolved L1583 swaps typenameisunsigned(nm) for
typeisunsigned(cur.type_: *tinfo). cur is the walked N_TNAME; its
type_ is stamped at check time.

exprprimresolved L1620 swaps typenameisunsigned(s) for typeisunsigned
(n.type_: *tinfo). n is the N_INTLIT whose tsuffix is s; type_ is
stamped by the #51 arm. primsize(s) > 0 IS the tsuffix-resolves-to-
builtin gate, so the stamp is guaranteed at the read site.

typenameisunsigned (cgenutil.ww L850-866) deleted: -17 LOC of body
+ WHY block. Net change is three files (cgenutil.ww + two
.combined.ww bundler regens, same -17 each).

Mirrors cstage cmd/wcc/type.c:178 type_isunsigned plus cmd/w6c/cgen.c
castsrcprim routing INTLIT.tsuffix through n->type, then
type_isunsigned. Aligned, not richer.

Byte-identity (994/995) is the behavior gate; full make test green
at 133/133 confirms.
2026-05-22 23:44:31 +09:00
3eef2828c6 selfhost/cmd/wcc: stamp typed-suffix N_FLOATLIT (#51b)
cstage cmd/wcc/check.c:702 cexpr N_FLOATLIT arm uses lookup_builtin
(n->tsuffix) with fall-through to ty_untyped_float. wwstage's
exprtype N_FLOATLIT arm at check.ww L1582 was unconditional
untyped_float — the symmetric-stage gap flagged at the tail of #51.

New arm: when e.tsuffix is non-empty, mktname+tinfofornode resolves
the builtin and stamps e.type_; on nil tinfo fall through to the
existing untyped_float path. Same shape as the #51 INTLIT arm one
block up.

Byte-identity (994/995) is the behavior gate; full make test green
at 133/133 confirms.
2026-05-22 23:12:07 +09:00
1ce0f638bf selfhost/cmd/wcc: stamp typed-suffix N_INTLIT (#51, #52 precursor)
cstage cmd/wcc/check.c:694 cexpr N_INTLIT arm uses lookup_builtin
(n->tsuffix) with fall-through to ty_untyped_int. wwstage's exprtype
N_INTLIT arm at check.ww L1565 was unconditional untyped_int — a
symmetric-stage gap that left the last raw-str-typed reads of
TNAME.str / INTLIT.tsuffix alive in typenodeprimresolved /
exprprimresolved (the deferrals named at the end of A.6.3a, #45).

New arm: when e.tsuffix is non-empty, mktname+tinfofornode resolves
the builtin and stamps e.type_; on nil tinfo fall through to the
existing untyped_int path. Mirrors harec ref/harec/src/check.c
check_expr_literal routing typed ICONST through builtin_type_for_storage.

N_FLOATLIT at check.ww:1582 carries the same gap (cstage check.c:702
does the same lookup_builtin/untyped_float fall-through); filed as
#51b for a separate bisect-clean follow-up.

This is the additive stamp half; #52 collapses the two remaining
typenameisunsigned callers onto tinfo reads of the stamped type_.

Byte-identity (994/995) is the behavior gate; full make test green
at 133/133 confirms.
2026-05-22 22:55:54 +09:00
e3237d1bcb selfhost/cmd/wcc/check: resolvealias prefer same-module (#53)
The bare-leaf TNAME lookup in resolvealias used flat scopelookup,
which bucket-walks all matching names and returns whichever entry
hashed in first. Two modules each declaring `type invalid = ...`
collided in the same flat scope: utf8.invalid (`!void`) and
strconv.invalid (`!i32`) resolved to whichever registered first.
That drove a localloadop divergence at the 994/995 byte-id gates —
MOVSXD vs MOVQ — depending on which alias the checker happened
to pick for a given site.

Switch to scopelookupprefer(c.cur, c.curmod, nm), mirroring cstage
cmd/wcc/check.c:66 (scope_lookup_prefer at sym.c:103): when the
current module matches the bucket entry's b.mod, prefer it; else
fall back to first-found. The SK_USE→scopelookuptype fallback for
the #61 A.5 bare-TNAME-vs-imported-module collision case is
unchanged.

Six remaining bare-leaf scopelookup sites in this file (exprtype
N_IDENT, N_DOT-callee leaf, varianterr, scruttype, exprtypeoftry
N_IDENT + N_CALL, walker N_IDENT) are punted to #55 — this commit
fixes the path the reproducer surfaced and leaves the rest behind
an explicit follow-up so the byte-id corpus stays the test for
each conversion.
2026-05-22 08:59:02 +09:00
b8e5a921f8 selfhost/cmd/wcc: collapse type-kind predicates onto n.type_ (A.6.3b, #46)
The node-keyed kind helpers (typeis8byteprimitive, isstrtype/raw,
isslicetype/raw, istaggedtype/raw, isfloattype, isf32type/raw,
isf64typeraw, isnullabletype) each re-walked TNAME aliases via
aliaslookup and peeled TBANG by hand — duplicating cstage's single-
peel kind predicates at the AST level. After A.6.2 every type-AST
kind these read is tinfo-stamped at check.ww L426-436, and
tinfofornode collapses N_TBANG (check.ww:1145-1152) and the TY_NAMED
chain, so each predicate folds to one tinfo read.

Six new tinfo helpers in lib/ww/typ.ww mirror their cstage SSoT
verbatim:

  typeisstr      — cstage cgen.c:159 `type_isstr`     (TY_STR / TY_UNTYPED_STR)
  typeisslice    — cstage cgen.c:174 `type_isslice`
  typeistagged   — cstage cgen.c:516 `type_istagged`
  typeisf32      — cstage cgen.c:188 `type_isf32`
  typeisnullable — cstage cgen.c:396 `type_isnullable` (reads tinfo.nullable
                                                       stamped at check.ww:1309-1318)
  typeis8byteprim — cstage cgen.c N_LET sz==8 ladder (slot-pad set)

Rule 9 carve-out per the A.6.3a precedent: each helper has a named
cstage counterpart; the wwstage shape mirrors it directly. The five
dead AST-walking variants (isstrtyperaw, isslicetyperaw,
istaggedtyperaw, isf32typeraw, isf64typeraw) are deleted; the five
remaining callsites (cgenstmt cglet / cgmlet str-routing, cgenexpr
cgdot tuple-field) graduate to the alias-aware isstrtype(c, t).

nullableptrtag stays AST-keyed for now — tinfofornode doesn't
populate TY_TAGGED.params (check.ww:1287-1337 sets size / align /
nullable but not the variant chain), so the tinfo equivalent of
cstage cgen.c:405 `nullable_ptr_tag` can't read params today. WHY
comment at the site cites #50 / A.6.3f as the graduation point,
alongside the variant-index work and the tparam-population glue.

Byte-identity (994/995) is the behavior gate; full `make test` green
at 133/133 confirms.
2026-05-22 05:53:34 +09:00
03e4718199 selfhost/cmd/wcc: collapse signedness predicates onto n.type_ (A.6.3a, #45)
The node-keyed signedness helpers (typenodeisunsigned,
typenodeisunsignedc, elemissigned, elemissignedc, fieldissignedc) each
re-walked TBANG / TENUM / TNAME chains and re-consulted alias / enum
registries — duplicating cstage's type_isunsigned (cmd/wcc/type.c:178)
and fld_issigned (cmd/w6c/cgen.c:240) at the AST level. After A.6.2
every type-AST kind we read here is tinfo-stamped at check.ww L426-436,
so the predicates collapse to a single tinfo read.

Two new arms close the wwstage divergence from cstage: typeisunsigned
gains TY_RUNE and TY_ENUM (recurse on .sub), matching type.c:178
verbatim. typeissigned is added as the cgen-facing predicate per
fld_issigned semantics (TY_BOOL excluded for sub-word storage —
0/1 → MOVZBQ — so it's not just !typeisunsigned). Rule 9 carve-out:
the helper exists in cstage; harec keeps the same pair.

elemissigned was fully dead (no callers); deleted. typenameissigned
was internal-only and dead post-collapse; deleted. typenameisunsigned
survives — two call sites (typenodeprimresolved, exprprimresolved)
hold only a raw `str` (TNAME.str / INTLIT.tsuffix). paramissigned in
cgenstmt.ww unchanged. Both deferrals close in A.6.3c (#47).

Byte-identity (994/995) is the behavior gate for the alias/enum
sites — full `make test` green at 133/133 confirms.
2026-05-22 05:24:49 +09:00
045c49e398 selfhost/cmd/wcc: enable asserttyped + close A.6.2 (#4, #15)
Final closer for the A.6.2 sequence. Mirror of harec's
`assert(expr->result)` at ref/harec/src/check.c:3810: every value-
producing nkind dispatched by resolvewalk (L475-488 + N_DOT at L391)
reaches a stamping arm in exprtype that sets e.type_ before
returning. asserttyped is the post-checker invariant gate; it walks
checkfile's decls in pass 3 (same curmod context exprtype saw in
pass 2) and writes a one-line stderr diagnostic for any dispatched
node whose type_ remained nil.

Three residual gates encode bails that aren't true gaps until #19
(Drew's δ: dedicated AST kinds for alloc/size/etc.) retires the
seeded-SK_FN-with-nil-decl + SK_USE-as-value shapes:
  1. N_IDENT resolving to SK_USE (module ref like `os` in `os.write`)
  2. N_IDENT whose sym.decl == nil (pseudo-builtin callee — len,
     append, free, alloc, size, align, offset seeded at L86-98)
  3. N_IDENT in LHS-of-N_DOT syntactic position (member-access
     lookup target, not value-producing) — tracked via `indot` param

ZERO fires across all 5 selfhost combined.ww corpora (wcc, w6c, w6a,
w6l, wwdump). asserttyped IS the regression catch — future commits
that drop a type_ stamp will fire it during the 990_selfhost probes;
no standalone table-driven test is bundled.

Accreted folds:
- 5-lite-a (#33): dispatcher-invariant docstring at exprtype L1535.
- 5-lite-b (#34): WHY comments at 9 helper bail sites
  (unifyarith/binoptype/unoptype/indexresult) classifying each as
  unreachable-for-valid-input, propagation-from-callee, or
  invalid-input (cstage errors at the matching cite). Cites
  ref/harec/src/types.c type_promote on the function-doc updates.
- A.6.2.1c (#24): three propagation pointers re-cite the
  inherent-IDENT bail at exprtype N_IDENT arm L1596-1599.
- unoptype TK_STAR dead `if (u == nil) { return nil; }` removed —
  resolvealias(unwrapbang(non-nil)) is non-nil by parser invariant
  (parsetype L148 always sets N_TBANG.lhs; resolvealias L514-569
  every exit returns non-nil for non-nil input).

lib/ww/ast.ww: nkname becomes export so asserttyped's diagnostic can
format the offending node's kind without duplicating the table.

Closes #4 (A.6.2 umbrella) and #15 (A.6.2.1e).
2026-05-22 04:10:24 +09:00
faba8b70dd selfhost/cmd/wcc: stamp inferred-let decl.lhs (#15 precursor, #43)
checkletassign previously early-returned on `n.lhs == nil`, so an
inferred binding (`let r = expr;`) left decl.lhs unset; exprtype's
N_IDENT branch at check.ww:1550 reads `s.decl.lhs` and so the use
sites lost the inferred type.

Mirrors cstage cmd/wcc/check.c:1477 clet `if (t == NULL && initt)
t = type_default(initt);` and ref/harec/src/check.c:1422
check_expr_binding. cstage carries the let type on Sym.type;
wwstage carries it on decl.lhs — same observable result, byte-id
(rule 10) intact. Defaulting (untyped_int → i32) stays at use
sites in exprtype, not the binding site. Mutation layer matches
#41's installparams parser-decl-mutation precedent at check.ww:2747.

Table-driven test deferred to #44 per the speed-first cadence;
existing 990–997 byte-id corpus implicitly exercises inferred lets.
Context for the capture sweep: #36.
2026-05-22 03:40:52 +09:00
45910ff966 selfhost/cmd/wcc: variadic param N_TSLICE wrap at installparams (cascade Commit 3, #25/#41)
installparams normalises `T...` p.lhs to []T so N_IDENT lookups
(s.decl.lhs) and cgen's variadic-slot synthesis see the effective
slice — mirrors cstage check.c:455 `tp->type = type_slice(c->a, pt)`
and harec check_func_type. cgendecl/cgenexpr drop the on-the-fly
slicewrap and consume p.lhs directly; cgenexpr cgcall peels the
N_TSLICE wrap when reading the element predicates / esz (Ken's
gate: cstage cgen.c:4352 `vsu->kind == TY_SLICE`), and passes
`velem` — not the wrap — into cgwidentaggedstore (cstage cgen.c
:4382). Closes the 22 N_DOT + 9 N_INDEX fires from #36 with the
cascade absorbed by e662156 (#39 arm-6 recursion). Class B "case:
not a variant of scrutinee" did NOT fire post-#39, so Commit 2
(#40 tagged_select_subtype) was not needed.
2026-05-22 03:09:22 +09:00
e662156574 selfhost/cmd/wcc: isassignable arm 6 → recursive (cascade Commit 1, #39)
The concrete→tagged arm walked variants with typeeqast-only, rejecting
widenings that aren't strict surface-eq: NAMED-aliased variants, nested
tagged inside a variant, and concrete → variant after the wrap-induced
exprtype reshape that Commit 3 (#41, variadic wrap re-land) introduces.

Replace the walk with a recursive isassignable call per variant, mirroring
harec tagged_select_subtype (ref/harec/src/types.c:702-739, recursive
type_is_assignable at :718; invoked from the TAGGED arm at :1110-1112)
and the byte-id cstage precedent at cmd/wcc/type.c:298-299. The recursive
call's leading typeeqast (check.ww:2257) preserves the #55 surface-nominal
fast path; the #57 bare-vs-qualified TNAME residual is unchanged.

No new test: the new widen path is dormant pre-Commit-3; existing
tagged-union tests cover the surface-eq fast path. Commit 3's fmttest
exercise will exercise the recursive widen for free.

Closes 39 cascade errors that fire once #41 lands.
2026-05-22 02:37:00 +09:00
edd27101bf selfhost/cmd/wcc: N_CALL intercepts for len/append/free (A.6.2.1b)
Three Hare pseudo-builtins (len/append/free) were resolving via the
generic N_CALL path and leaving e.type_ nil, blocking #15's post-
checker assertion. Add inline intercepts in exprtype that stamp e.type_
to mktname("i32")/mktname("void") and return the same tnode, matching
the cstage shape at cmd/wcc/check.c:896-1011 (rule 10 stage byte-id).

No shadow guard: cstage's len/append/free intercepts have none either,
and L85-88 seeds the names into c.top so a same-module decl dup-
silences. No arg-walk: resolvewalk descends children before dispatching
the parent N_CALL (check.ww:404-417), so args are stamped before the
intercept fires.

insert/delete deferred — not implemented in either stage. The cstage
divergence from harec (len → i32 not size; append → void not tagged)
pre-dates this task; #19 (dedicated AST kinds) is the Hare-faithful
path. Behavior is transitively covered by the 990-997 byte-id corpus
(append used in progs 16, 19, 20); the stamp side gates on #15.
2026-05-22 00:52:53 +09:00
f8aac547b9 selfhost/cmd/wcc: extend enum fold to constexpr set (A.6.2.1a)
check.ww's N_DOT enum-fold (L1724-1810) walks the enum body to
resolve each `EnumT.MEMBER` access; the pre-#22 walker only accepted
N_INTLIT for a member's lhs and bailed on every richer shape via
`return nil`. Wwstage compensated at codegen time through cgen.ww's
enumevalmember (cgen.ww:158-227), so program semantics held; the
gap was visible only in check.ww's e.type_ stamp coverage, which
A.6.2.1e's post-checker assertion will land on.

Lift the literal-only branch into an `enumvalfold(body, until, e,
*u64) bool` helper alongside foldtointlit. The accepted set mirrors
cstage cmd/wcc/check.c:185-208 (fold_int_literal) + :210-284
(eval_enum_value) and harec's enum-resolve constexpr eval at
ref/harec/src/check.c:4419-4434: literal leaves
(INTLIT/RUNELIT/TRUE/FALSE/NIL), unary +/-/~, binary +/-/*//%
& | ^ << >>, and N_IDENT sibling backref bounded by `until` per
harec's lnext forward-only-ref discipline
(ref/harec/src/check.c:4436-4438). Both N_DOT call sites (inner
`EnumT.MEMBER`, outer `pkg.EnumT.MEMBER` via base-resolve) delegate
non-literal lhs to enumvalfold instead of bailing.

Closes #7. Lands on the A.6.2.1a slot per PLAN.md / Drew's 5-lite
plan; subsequent A.6.2.1b-d retire the remaining bail paths before
A.6.2.1e enables the assertion.

Add test/wcc/759_check_enum_fold.c — table-driven, modelled on
631_def_neg_global.c. 17 rows cover each new shape (INTLIT,
RUNELIT, sibling backref, unary +/-/~, all ten binops, chained
backref). Exit-code rows pin per-shape fold correctness through
both stages (cgen reads the mutated N_INTLIT, so a wrong fold
leaks into the constant); asm-byte-id rows pin the symmetric-emit
contract between cstage's eval_enum_value and wwstage's
enumvalfold.

`make sizelint` clean. `make test` green 133/133 (132 pre +
new 759).
2026-05-22 00:14:36 +09:00
8e3752f5ea ref: vendor harec checker sources (#20)
ref/hare/ ships only ast/lex/parse/module/unparse — no checker. Every
bail-fix landing in A.6.2.1 (helper bail audit, N_IDENT bail audit,
enum fold) needs a `ref/harec/...` cite anchor so divergence rationale
isn't claimed against memory. PLAN.md L16, L35.

Snapshot of upstream commit ee640c6b2c17f57e8014d277a3028b262ffb7952
(`rt/+openbsd/start.ha: remove outdated comment about crt0`). 20 files:
5 src (check.c, eval.c, scope.c, types.c, type_store.c), 14 transitive
include/ headers (no parser/codegen surface), and COPYING.

License GPLv3 (COPYING included). Vendored as read-only reference per
CLAUDE.md rule 6 — no redistribution as binary, no edits.
2026-05-21 23:03:11 +09:00
6c70b46d5f selfhost/cmd/wcc: checkfile pass-2 walks d.attr (A.6.2.1-pre)
`@symbol("rt_abort")` and similar attr arg literals (N_STRLIT inside
N_ATTR.list) never reach the post-order exprtype dispatch because the
top-level dispatch in checkfile pass-2 only enters per-decl via d.lhs
and d.body — d.attr was an oversight. Add a one-line resolvewalk
descent before the kind dispatch, mirroring resolvewalk L405 which
already descends n.attr on inner nodes.

Discovered while landing the A.6.2.1 assertion: the unstamped
N_STRLIT inside `@symbol("...")` would trip the assertion on every
selfhost source (lib/os pulls these in transitively). Fix lands as
its own prep commit so the next session can start clean on the
A.6.2.1 main work (bail-discipline refactor per Drew's 5-lite, then
δ+γ stamp completion).

A.6.2 status: 0a-g landed; 0b-pre N_TPARAM landed; assertion enable
(A.6.2.1e) deferred behind 5-lite + per-bail closure work — see
PLAN.md and tasks #20-#25.

`make sizelint` clean. `make test-unit` green; full `make test`
batched per option B (next session).
2026-05-21 22:37:27 +09:00
009c4b35e2 selfhost/cmd/wcc: stamp e.type_ for N_MATCH + matchyieldtype port (A.6.2.0g)
Port cstage's match_yield_type walker (cmd/wcc/check.c:110-135)
as `matchyieldtype` (Plan-9-cased) — recursive arm-body walker
that finds the first reachable yield's operand type, descends
N_BLOCK / N_IF / N_FOR / N_FORRANGE, and stops at nested N_MATCH
(each match opens its own yield scope). Sole structural
divergence from cstage: where cstage reads `body->lhs->type`,
wwstage calls `exprtype(c, body.lhs, nil)` — wwstage's AST is
untyped at parse time and the type lives in the tinfocache;
exprtype is the canonical reader (tinfocache-idempotent per
L467).

Port cstage's N_MATCH match-as-expression stamp (check.c:1316-
1330) into a new exprtype arm. Walks the first non-nil arm yield
via matchyieldtype, defaults to void if no arm yields. Closes
the consumer half of the match-as-expression contract that
A.6.2.0f opened on the producer side (N_YIELD).

One documented divergence from cstage (lenient, intentional):
the arm-yield-unification check (cstage L1322-1327) is skipped.
That's a checker-correctness concern; this arm only stamps.
Cstage's `match_yield_type` IS a helper there too — porting it
is structural fidelity per rule 10, not a new helper invention
under rule 9.

β scope per Drew (2026-05-21): α (stamp void unconditionally)
would bury a latent miscompile that A.6.2.1 assertion can't
catch (it sees nil, not wrong). Hare's `match_expr` AST has no
type field (ref/hare/hare/ast/expr.ha:341-348); harec/cstage
unify arms at check time — same architecture wwstage mirrors.

A.6.2 step 7 of 8 (γ order). The assertion closer (#15) is
next, which lands the invariant on a green tree.

`make test-unit` green; full `make test` batched per option B.
2026-05-21 21:27:56 +09:00
f0a8a37077 selfhost/cmd/wcc: stamp e.type_ for N_YIELD (A.6.2.0f)
Documented richer-than-cstage divergence: cstage cmd/wcc/check.c
:1708 walks N_YIELD's lhs but does NOT stamp `n->type` — yield is
statement-shaped there. Wwstage's A.6.2 invariant requires every
post-dispatch kind have `type_` set, so this commit draws in the
leaner side. Yield's value type is the operand's type per Hare's
unified stmt/expr AST (ref/hare/hare/ast/expr.ha:449-461 —
`yield_expr` is on L459 inside the `expr` sum). Bare `yield;`
(no operand) stamps void.

Same nil-tolerant pass-through template as A.6.2.0e N_SPREAD,
plus the bare-yield void variant.

A.6.2 step 6 of 8 (γ order). N_MATCH-as-expression next, then
the assertion closer.

`make test-unit` green; full `make test` batched per option B.
2026-05-21 21:18:25 +09:00
afd62a9187 selfhost/cmd/wcc: stamp e.type_ for N_SPREAD (A.6.2.0e)
Port head-only of cstage cmd/wcc/check.c:1212-1213 to exprtype's
new N_SPREAD arm. The spread expression `xs...` carries the
operand's type — pass-through stamp, no structural synthesis.

A.6.2 step 5 of 8 (γ order). The smallest stamp arm in the
series; mirrors cstage's one-liner directly.

`make test-unit` green; full `make test` batched per option B.
2026-05-21 21:14:08 +09:00
48c758bbe7 selfhost/cmd/wcc: stamp e.type_ for N_RECV (A.6.2.0d)
Port head-only of cstage cmd/wcc/check.c:1230-1236 to exprtype's
new N_RECV arm. Peel alias on the channel base; `chan T` → T.
N_TCHAN element lives in .lhs (cstage ww.h:279, ww typeeqast
L585).

One documented divergence: cstage L1234 errors on a non-chan
base; wwstage returns nil under the lenient-on-miss policy
(scruttype L656 / A.6.1.5b N_DOT precedent).

A.6.2 step 4 of 8 (γ order). Same shape as A.6.2.0a N_SLICE
scaffold — precedent-consistent.

`make test-unit` green; full `make test` batched per option B.
2026-05-21 21:10:58 +09:00