Commit Graph

209 Commits

Author SHA1 Message Date
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
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
4e75285a0b selfhost/cmd/wcc: drop dead N_ALLOC from post-dispatch list (A.6.2.0c)
N_ALLOC is a vestigial nkind enum entry. Defined in cstage
cmd/wcc/ww.h:243 (comment: "lhs=expr, rhs=size-or-null") and
mirrored in lib/ww/ast.ww:47, but no parser produces it — the
alloc-call syntax routes via N_CALL with callee=alloc (check.ww
:1479). Cstage cexpr has no case N_ALLOC; wwstage's listing it
in the post-dispatch kind set at check.ww:482 was speculative.

Remove the disjunct. Enum entry stays — sync with ww.h is the
gate, not stamp-coverage. Broader dead-kind audit tracked as
task #18.

A.6.2 step 3 of 8 (γ order).

`make test-unit` green; full `make test` batched per option B.
2026-05-21 21:05:50 +09:00
1131e7b68d selfhost/cmd/wcc: stamp e.type_ for N_TUPLE (A.6.2.0b)
Port head-only of cstage cmd/wcc/check.c:1437-1451 to exprtype's
new N_TUPLE arm. The arm walks e.list, types each element via
recursive exprtype, and assembles an N_TTUPLE whose .list chains
N_TPARAM wrappers (one per element) so shared element-type ASTs
(sym.decl.lhs, struct field's .lhs, another tuple's element) keep
their own .next untouched.

Foundation: A.6.2.0b-pre (805c841) introduced N_TPARAM as the
chain wrapper for N_TTUPLE.list, mirroring cstage's Tparam at the
AST layer (cstage keeps it at the Type layer; wwstage has no
separate type layer). This commit is the first checker-side
synthesizer to use it.

One documented divergence: empty list returns nil under the
lenient policy (cstage would synthesize empty TY_TUPLE; ww grammar
requires >= 2 elements per parse/expr.ww:117, so empty is
unreachable either way). Same shape as scruttype L656 / A.6.1.5b
N_DOT lenient-on-miss precedent.

α scope per Drew (no hint plumbing, no field-level walks, no
unify check). Hint param stays unused.

A.6.2 step 2 of 8 (γ order). N_ALLOC next (most likely a
parser-vestigial kind — A.6.2.0c worker audits first).

`make test-unit` green; full `make test` deferred to the batched
gate after the A.6.2.1 assertion commit (option B per user).
2026-05-21 21:01:57 +09:00
805c841f34 selfhost+lib/ww: N_TPARAM wrapper for tuple chains (A.6.2.0b-pre)
A.6.2.0b worker hit a real shared-`.next`-aliasing bug and stopped
per rule 7. Wwstage's N_TTUPLE chained element type ASTs via the
nodes' own `.next` field. `exprtype` routinely returns shared
nodes (sym.decl.lhs, struct field's `.lhs`, another N_TTUPLE's
`.list` element). Naive chain construction in the checker
corrupts source ASTs.

Introduce N_TPARAM = 67 as a chain wrapper for N_TTUPLE.list:

  - `.lhs` holds the (possibly-shared) element type AST.
  - `.next` chains within the parent N_TTUPLE.
  - Other fields unused; never appears outside N_TTUPLE.list.

Mirrors cstage's Tparam at cmd/wcc/check.c:1437-1451. Cstage
keeps it at the Type layer; wwstage has no separate type layer
for tuple chains so the wrapper sits at the AST. Hare's design
intent at ref/hare/hare/ast/type.ha:117 uses `[]*_type` slice-of-
pointer — same principle, slice-flavored.

Migrations:
  - lib/ww/ast.ww: kind + nkname + pr() unwrap (transparent for
    the 990 -a astprint byte-diff).
  - lib/ww/parse/parse.ww: parsetype N_TTUPLE construction wraps
    each element in N_TPARAM (sole construction site).
  - selfhost/cmd/wcc/check.ww: 4 readers (astalign, astsize,
    tinfofornode TY_TUPLE, exprtype N_DOT-tuple-positional). The
    last change retires the latent A.6.1.5b shared-`p` return.
  - selfhost/cmd/wcc/cgenutil.ww: slotsize TY_TUPLE arm.
  - selfhost/cmd/wcc/cgenexpr.ww: cgdot tuple-positional
    (size/load op + str-check).
  - selfhost/cmd/wcc/cgenstmt.ww: cglet TTUPLE init, cgmlet
    call-return walk, cgforrange elem-size + bind-walk.

Out of scope: N_TFN params, N_TTAGGED variants, N_TSTRUCT fields.
N_TFIELD already wraps struct fields; N_TFN/N_TTAGGED aren't
currently chain-mutated by checker synthesis. If they ever are,
the same pattern applies.

Unblocks A.6.2.0b stamp on a clean foundation. Retires task #16.

Verified 132/132 incl. 990 AST byte-diff (astprint unwrap) + 995
self-rebuild byte-identity.
2026-05-21 20:55:40 +09:00
c564d7d0fd selfhost/cmd/wcc: stamp e.type_ for N_SLICE (A.6.2.0a)
Port head-only of cstage cmd/wcc/check.c:1214-1228 to exprtype's
new N_SLICE arm. Four base shapes:

  - N_TARRAY → synthesize N_TSLICE{lhs=elem} (cstage L1219).
  - N_TSLICE → return basetn (pre-peel, matches cstage `base`
    not `u`; L1221).
  - N_TNAME("str") → mktname("str") (matches cstage's `ty_str`
    canonical singleton, L1223).
  - N_TPTR with non-nil sub → synthesize N_TSLICE{lhs=sub}
    (L1225, Hare-faithful slice-of-elem from pointer-to-elem).

Slice bounds (e.rhs start, e.cond end) are already walked by
resolvewalk L406-408 + post-order dispatch L460-489 — typical
N_INTLIT/N_IDENT/N_BIN are in the dispatch list; this arm does
not double-walk.

One documented divergence from cstage: lenient on non-sliceable
base (cstage L1227 errs; wwstage returns nil under the established
scruttype L656 / A.6.1.5b N_DOT struct-miss precedent).

A.6.2 step 1 of 8 (γ scope per Drew, 2026-05-21) — gap-sweep
per-kind first, post-checker assertion last. Order by triviality:
N_SLICE → N_TUPLE → N_ALLOC → N_RECV → N_SPREAD → N_YIELD →
N_MATCH → assertion. Each commit holds invariant; cgen readers
migrate in A.6.3.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 20:16:24 +09:00
0e1ab38586 selfhost/cmd/wcc: stamp e.type_ for N_ARRLIT (A.6.1.7)
Port head-only of cstage cmd/wcc/check.c:1198-1211 to exprtype's
new N_ARRLIT arm:

  - Walk e.list, skip the N_FIELD repeat marker (lib/ww/parse/
    expr.ww:100-107).
  - First non-skipped element via recursive exprtype → elt.
  - Count non-skipped elements.
  - Empty list → mktname("i32") per cstage L1209.
  - Synthesize N_TARRAY{lhs=elt, rhs=INTLIT{uval=count}}, stamp
    tinfofornode, return.

One documented divergence from cstage: the inline type_default
lift (cstage L1206 — untyped_int → i32 etc) is skipped. Wwstage
uniformly returns the AST-level untyped name and defers defaulting
to the assignability sink; the N_INTLIT arm (check.ww:1388-1392)
and alloc-value-form (check.ww:1509) follow the same shape, so
defaulting here would be the outlier. No cgen consumer reads
e.type_ on N_ARRLIT today (verified via grep of cgen*.ww); A.6.3
will move the default to the read site or hoist a typedefault
helper — out of α scope.

α scope per Drew (ref/hare/hare/ast/expr.ha:215-218 — Hare's
array_literal is the uniform `{expand, values}` shape, no
named/anonymous split, so head-only is the natural cadence). No
hint plumbing, no unify check on mixed-type elements (cstage uses
first-element-wins).

Phase 1 A.6 step 7 of ~8 — closes the A.6.1 per-kind stamp series.
A.6.2 next: post-checker assertion that every expression node has
type_ set + fail-suite gap sweep.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 19:53:31 +09:00
5f19015e16 selfhost/cmd/wcc: stamp e.type_ for N_STRUCTLIT (A.6.1.6)
Port head-only of cstage cmd/wcc/check.c:1161-1197 to exprtype's
new N_STRUCTLIT arm:

  - N_IDENT lhs: scopelookupprefer → SK_TYPE sym; stamp
    tinfofornode(sym.decl.lhs), return that body. Mirrors cstage
    L1166-1173.
  - Synthetic type-expr lhs (e.g. `(*T){...}`): stamp
    tinfofornode(e.lhs), return e.lhs directly. Mirrors cstage
    L1174-1176.
  - e.lhs == nil: bail (future Hare anonymous-lit shape ww
    doesn't parse yet — lib/ww/parse/expr.ww:147-148 always
    plants the TYPE_IDENT).

Field-level walk (cstage L1178-1194) stays parked behind #23 /
Phase 2; field-value exprs still get their own n.type_ via the
post-order dispatch at L460-489 (N_STRUCTLIT is in the kind
list since A.6.0).

One documented divergence from cstage: lenient on missing-
struct-type / non-SK_TYPE sym (cstage L1170 errors; wwstage
falls through to nil under the established scruttype L656 /
A.6.1.5b N_DOT struct-miss policy).

α scope per Drew (ref/hare/hare/ast/expr.ha:229-237 — Hare's
struct_literal AST distinguishes named/anonymous alias; ww
only parses the named form, so the hint param plumbed in A.6.0
stays unused for this arm). β/γ (hint plumbing into clet/
cassign; A.6.1.7 preempt) deferred per rule 11.

Phase 1 A.6 step 6 of ~8 — Hare struct_literal surface closed;
N_ARRLIT (A.6.1.7) is the genuine hint-consumer next.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 19:28:45 +09:00
aa73e73013 selfhost/cmd/wcc: stamp N_DOT struct/pseudo/tuple in exprtype (A.6.1.5b)
Port cstage cmd/wcc/check.c:833-866 stamp cases to exprtype's
N_DOT arm. Three sub-cases append to the A.6.1.5a basetn-walk
block, all pure type_ annotations — none mutate e.kind:

  - Pseudo-fields .len / .cap / .ptr on slice / str / array
    (cstage L833-842). `len` and `cap` stamp i32; `ptr` synthesises
    an N_TPTR over the element (u8 for str, bu.lhs else).
  - Struct field walk on N_TSTRUCT (cstage L843-849) — match
    N_TFIELD by name, return f.lhs and stamp.
  - Tuple positional access `t.0`, `t.1`, … on N_TTUPLE
    (cstage L850-866). fldnumidx (cgenutil SSoT for decimal-only
    parsing) yields the index; walk bu.list .next idx times.

Two divergences from cstage, documented inline:
  - Wwstage carries str as N_TNAME("str") (no dedicated N_TSTR);
    the pseudo-field guard tests the trio shape directly.
  - Wwstage falls through to nil on struct/tuple miss instead
    of erroring (lenient policy per scruttype L656).

Cumulative N_DOT arm now ~162 LOC, under Rob's 250-LOC tripwire.
No new helpers; fldnumidx reused. #56 mod.fn() parser-rep stays
parked.

Phase 1 A.6 step 5b of ~8 — closes Hare's access_field surface
(ref/hare/hare/ast/expr.ha:7-38). Cgenutil's paired walker still
derives the same shapes; A.6.3 collapses those onto these stamps.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 19:08:02 +09:00
894d966707 selfhost/cmd/wcc: fold N_DOT module/enum in exprtype (A.6.1.5a)
Port cstage cmd/wcc/check.c:740-832 fold cases to exprtype's new
N_DOT arm. Two paths land:

  - Module-qualified ref (`pkg.x`): SK_USE leaf via
    scopelookupinmodule, type returned from the resolved sym's
    decl.lhs. Mirrors cstage L749-775.
  - Enum member fold to N_INTLIT: bare `EnumT.MEMBER` (cstage
    L780-803) and outer `pkg.EnumT.MEMBER` where the inner N_DOT
    folded via case 1 (cstage L805-832, including TPTR peel at L808).
    foldtointlit rewrites kind/uval/str/lhs/rhs; type_ stamps from
    the enum body.

Stamp surface (struct field + pseudo-field .len/.cap/.ptr) lands
in A.6.1.5b. #56 mod.fn() parser-rep stays parked.

Two documented divergences from cstage:
  - No use_alias gate — wwstage uses sym.mod disambiguation per
    installdecl L195-207; SK_USE alone suffices.
  - Cstage errors on unknown enum member; wwstage falls through
    to nil under the lenient-check policy at scruttype L656.

Check-side enum eval is literal-only (N_INTLIT + nil-auto-
increment); cgen.ww's enumevalmember has the full const-folder
for cgen-side. Every selfhost+lib enum uses explicit literals
today (audited 2026-05-21). Tracked as task #7.

Phase 1 A.6 step 5a of ~8 — bisect-clean split per Hare's AST
access_identifier vs access_field axis
(ref/hare/hare/ast/expr.ha:7-38).

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 18:46:34 +09:00
0715ec9662 selfhost/cmd/wcc: stamp e.type_ for N_INDEX (A.6.1.4)
Port cstage cmd/wcc/check.c:870-894 to exprtype. indexresult yields
the resolved element tnode for slice/array, u8 for str, T for *[N]T
(decay) and *T (generic), and []T for *[]T (no decay, mirrors the
Hare-faithful rule at check.c:883-885). The arm stamps e.type_ via
tinfofornode same shape as the A.6.1.3 BIN/UN pattern.

Phase 1 A.6 step 4 of 6 — slot the indexing result type into the
mandatory post-checker invariant. Cgenutil still derives index
stride from AST shape (indexbaseesz, elemsizeofc, indexvaluetnode);
A.6.3 will collapse those onto the now-stamped N_INDEX type_.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 16:08:48 +09:00
ada99973ee selfhost/cmd/wcc: stamp e.type_ for N_BIN + N_UN (A.6.1.3)
Adds unifyarith / binoptype / unoptype mirroring cstage
cmd/wcc/check.c:580-596, 598-640, 642-687. Two new exprtype
arms stamp e.type_ for N_BIN and N_UN via the same
tinfofornode pattern as A.6.1.1/.2.

unifyarith: untyped+untyped (prefer float), untyped+typed
(typed via isassignable), typed+typed (typeeqast), fallback ltn.
binoptype: ptr arith (ptr±int → ptr, ptr-ptr → i64), bitwise/
arith → unifyarith, comparison + logical → bool.
unoptype: deref (resolvealias+unwrapbang then N_TPTR.lhs),
addrof → *T with slice/str pseudo-field .len/.cap widening
to *i64 (mirrors check.c:672-682), unary +/-/^/!.

Wwstage stays silent on operator-type errors per existing
checker discipline; cstage flags the same shapes.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 15:31:03 +09:00
19095e4b50 selfhost/cmd/wcc: stamp e.type_ for N_CALL + drop fold hook (A.6.1.2)
Six N_CALL stamp sites in exprtype:
- alloc slice form: tt = ([]u8 | nomem)
- alloc value form: tt = (*T | nomem)
- size/align/offset fold sites: untyped_int (mirrors cstage
  cmd/wcc/check.c:926/958 which sets n->type = ty_untyped_int
  after the fold; the returned mktname("i32") is the assignability
  target for callers, not the constant's own type)
- regular call: s.decl.lhs (mirrors cstage's build_fn_type ret)

Five error-path nil returns deliberately don't stamp.

Drop the size/align/offset trigger hook in resolvewalk: the A.6.0
end-of-fn general N_CALL dispatch already fires exprtype on every
N_CALL, making the targeted hook redundant. Pre-edit relied on
double-dispatch (hook → fold → re-dispatch → N_INTLIT stamp);
post-edit folds and stamps in one pass. Final n.type_ identical.

Hook removal + stamps bundled per CLAUDE.md rule 11: same-concern
(N_CALL handling) and the removal is what justifies the inline
fold-site stamps replacing the double-dispatch path.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 14:54:29 +09:00
c0fe38c101 selfhost/cmd/wcc: stamp e.type_ for CAST/TRY/TYPEASSERT/TYPETEST (A.6.1.1)
Phase 1 A.6.1 commit 1. Extends A.6.0's literal+ident type_
population to the CAST + TRY family + TYPEASSERT/TYPETEST arms in
exprtype. Mirrors cstage cmd/wcc/check.c:737 (N_CAST) and
1332-1435 (TYPETEST/TYPEASSERT/TRYPROP/TRYUNW) where n->type is
stamped on each value-returning path.

N_TRYPROP / N_TRYUNW only stamp the value-returning paths
(success-variant match inside the for-loop, no-error tail at
ou.list); the three nil-returning early-outs are intentionally
left unstamped.

Verified 132/132 incl. 995_self_rebuild byte-identity.
2026-05-21 14:27:09 +09:00
321e7ca615 selfhost/cmd/wcc: plumb exprtype hint + resolvewalk dispatch (A.6.0)
A.6.0: extend `exprtype(c, e)` → `exprtype(c, e, hint)` and dispatch
post-order on every expression-yielding node kind in resolvewalk.

hint is threaded but unused by every arm; A.6.1's STRUCTLIT/ARRLIT
arms consume it (harec's check_expression result_type shape per
feedback_hare_frontend_reference.md). Dispatch fires existing literal
+ ident stamps universally; per-kind stamp coverage lands in A.6.1+.
Cgen reads tnode.type_ (not expression-node type_), so byte-identity
holds.

Verified 132/132 incl. 995_self_rebuild.
2026-05-21 13:58:25 +09:00
17765942f9 selfhost/cmd/wcc: delete mem.ww (γ-7, Phase 0 close)
mem.ww has 0 callers post-γ-6 — newarena/amalloc/grow/freearena/
roundup all unreferenced after the *arena cascade strip. Drop the
91-line module.

Makefile: remove mem.ww from 5 dep lists (wwdump_ww, w6c_ww,
w6a_ww, w6l_ww, ww_ww); drop `-I selfhost/cmd/wcc` from w6a_ww/
w6l_ww/ww_ww build invocations (wwdump_ww + w6c_ww still need it
for check.ww/cgen*.ww).

test/wcc/990_selfhost.c: drop 6 mem.ww entries from probe_codegen,
probe_dump_diff (×2), probe_resolve, probe_dump_stable, and
probe_cgen_match file lists.

lib/memio/memio.ww: dynamicgrow doc comment reframed as historical
context (collision source is gone, but task #9 keeps the
module-prefixed name conservative against future collisions).

Two dead `import mem;` lines remain in selfhost/cmd/w6a/asm.ww and
selfhost/test/uses.ww; tolerated silently by ww build, swept in
task #8.

main.combined.ww auto-regenerated for w6a/w6c/wwdump.

Verified 132/132 incl. 994_w6c_ww + 995_self_rebuild byte-identity.
Phase 0 closes.
2026-05-21 13:24:27 +09:00
353dffb5e8 lib/ww + wcc + w6c + wwdump: strip *arena cascade (γ-6)
amalloc has 0 callers post-γ-2; the *arena threaded through
newnode/newscope/newtype/prim/typesinit/type{ptr,slice,array,chan,
named}/lexinit/parserinit/joindotted/checkinit/arenau64tos/cgeninit
and the scope.a / tctx.a / lex.a / parser.a / checker.a / cgen.a
fields are vestigial.

Drop `import mem;` from 15 files, remove six struct fields, strip
*arena from 14 signatures, update ~120 call sites across lib/ww +
wcc + w6c + wwdump. selfhost/test/sym_link.ww fixture drops the
newarena/freearena probe; still exits 42 on scopedefine/scopelookup.
Both main.combined.ww auto-regenerated.

Comments retidied: typ.ww "once per arena" → "once per program";
parse.ww drops "arena-build" qualifier on joindotted; sym.ww drops
mem-sibling-imports rationale.

Verified 132/132 incl. 994_w6c_ww + 995_self_rebuild byte-identity
(the primary symmetric-stages gate).
2026-05-21 13:01:57 +09:00
3dae4d9e9a selfhost/cmd: astrndup → strings.dup view (γ-2); drop wcc.astrndup
The final 2 astrndup callers in w6a (main.ww fname capture and the
dupstr wrapper in parse.ww) now use the uniform γ-1 shape:

    let view: str;
    view.ptr = src;
    view.len = n: i32;
    out = strings.dup(view);

With both call sites converted, wcc.astrndup is dead and removed
from selfhost/cmd/wcc/mem.ww. amalloc + arena bootstrap stay
(other callers; #7 Phase B/C territory).

The two `// astrndup until #11 (w6a types shadow) is fixed.`
WHY-pointers are obsolete (#11 landed in 6696e95) and dropped per
CLAUDE.md rule 8.

dupstr in parse.ww keeps its (*arena, *u8, u64) signature; the
vestigial *arena param is tracked by task #10.

Verified 132/132 incl. 991_w6a_ww + 995_self_rebuild byte-identity.
2026-05-21 11:21:07 +09:00
fd7dee985e cgen + memio: cgoutarena → memio.dynamic, grow → dynamicgrow (β-3)
Phase 0 last β-shape site. Two concerns in one commit because the
refactor surfaced the rename:

 - selfhost/cmd/wcc/cgen.ww  cgout buffer (cgoutbuf/cap/len + arena +
   cgout_grow + CGOUT_INIT_CAP) → memio.state + io.stream behind a
   one-shot lazy-init guard. cgout_enable drops its *arena param;
   memio.reset in cgout_flush keeps the buffer sticky across fns so
   the arena's amortisation survives — re-init per fn would abandon
   the buffer and re-grow from 0 via the 8→…→65536 ladder for every
   function (no io.close path → no os.free).

 - lib/memio/memio.ww  private fn grow → dynamicgrow. Symmetric with
   dynamicwrite / dynamicclose; required because cstage bundles all
   imported modules into a flat TU and resolves private fns by
   unqualified name, so the new `import memio;` in wcc's bundle
   collided with selfhost/cmd/wcc/mem.ww's arena `grow`. Module-aware
   private-fn scoping in cstage is task #9.

@test fn dynamicgrow in memiotest.ww (same package as memio.ww)
renamed to dynamicgrowcases to free the name; new suffix mirrors the
file's existing fixedwritecases / borrowedreadcases convention.

Lazy-init guard cgoutinit. memio.dynamic runs once on first
cgout_enable; subsequent enables just set cgoutmode. Mirrors
lib/log/log.ww:124 ensureinit. Without it, ~14 mmap syscalls per fn
and ~100 MiB+ cumulative leak on a typical bootstrap.

io.write bare discard in emitbytes mirrors lib/log/log.ww:169 —
memio.dynamicwrite never returns io.closed (memio.ww:166).

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

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

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

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

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

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

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

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

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

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

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

Verified: make test 132/132, 995_self_rebuild byte-identity holds.
Closes #42; advances #41.
2026-05-21 00:35:14 +09:00
a376ec89eb lib/rt: rename rt_alloc → rt_malloc; rt.alloc → rt.malloc
Hare's canonical runtime allocator is rt::malloc with linker symbol
rt.malloc (ref/hare/rt/malloc.ha:27,78). ww kept the dot→underscore
Plan 9 convention (CLAUDE.md rule 4) so the linker symbol becomes
rt_malloc; the lib/rt exported function name becomes malloc; ww
callers say rt.malloc(...).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

131/131 + 994 + 995 byte-identity green; smoke.combined.ww (lib-only
consumer) emits the same asm pre vs post, confirming the change is
SSoT routing only (no behaviour shift).
2026-05-20 09:06:50 +09:00