w6c+wwstage: construct + bind tuple-in-union payload (#242)

A mixed-scalar tuple WRAPPED IN A TAGGED UNION (the (neg, n) shape Hare's
strconv parseint returns, ((bool,u64)|invalid|overflow)) miscompiled three
ways, all gate-blind (no bootstrap tuple-in-union):

(a) cstage CONSTRUCTION: a tuple variant fell through the N_RETURN scalar
    shuffle, which ZEROED tag + payload — the operands were never packed.
    Route the tuple variant through the scratch-slot widen path; add a
    TY_TUPLE arm to cg_widen_tagged_store that packs each element into the
    union payload at the register-ABI 8B stride + sets the variant tag.

(b) wwstage CHECKER: `let (a,b)=t` over a plain tuple ident (the match-
    bound union payload) left the un-annotated binders UNTYPED, so the bin
    node reading them was untyped -> asserttyped abort. The element-type
    distribution only fired for an N_CALL rhs. Consume the rhs tuple type
    for ANY rhs (mirror cstage check.c:2017).

(c) BOTH stages DESTRUCTURE: the register-cursor receive assumes the rhs
    left every element in AX/DX/CX (a call's tuple-return ABI). For a tuple
    IDENT cgexpr loads only word0->AX, so the 2nd binder read a STALE DX.
    Copy each element from the ident's slot at the 8B stride.

Construction is correct at ANY variant position (the resolved tag, not a
default 0); wwstage resolves it via the typeeq core (flatvariantidxt), not
taggedvariantindext whose str/slice shape-fallback would mask a mismatch.

Two rule-7 loud-stops cover shapes this slotted packing can't yet handle,
on BOTH stages, so neither silently miscompiles:

  - a tuple with a SysV-eightbyte-sharing narrow pair (e.g. (i32,i32,u64)),
    caught by the 8+payload > slot-size guard (the eightbyte tuple
    classification is #243);

  - a tuple built from a BARE LITERAL element (`true`/`false`, suffix-less
    `7`). cstage's cg_tag_for_variant can't type the literal (#241), returns
    -1, and loud-stops. wwstage types `true` as bool and `7` as untyped_int,
    so flatvariantidxt WOULD resolve the variant — a program cstage rejects
    but wwstage accepts is the cs!=ww divergence rule 10 forbids. wwstage
    mirrors cstage's CONDITION (a bare-literal element), not its -1
    mechanism, with an explicit guard that aligns the richer side DOWN. Lift
    BOTH guards together when #241 lands cstage literal typing -> symmetric
    accept.

Test 940_tuple_in_union: 4 K_RUN rows (variant 0, void arm, tuple at
variant 1 two ways) x cstage-run + wwstage-run + cs==ww byte-id, plus 2
K_BUILDERR rows (eightbyte-share, bare-literal) asserting a loud stop with
the #242 diagnostic on BOTH drivers = 16 ok.
This commit is contained in:
2026-06-01 19:56:52 +09:00
parent b79f005489
commit 6fc85f9aaf
8 changed files with 1114 additions and 16 deletions

View File

@@ -291,6 +291,7 @@ TESTS = $(BIN)/test_smoke $(BIN)/test_lex $(BIN)/test_parse $(BIN)/test_check \
$(BIN)/test_tuple_nary_destructure_run \
$(BIN)/test_overcap_tuple_field_store_run \
$(BIN)/test_mixed_scalar_tuple_sret_run \
$(BIN)/test_tuple_in_union_run \
$(BIN)/test_tuple_elem_slice_len_run \
$(BIN)/test_str_forrange_loopvar_run \
$(BIN)/test_composite_call_arg \
@@ -1187,6 +1188,12 @@ $(BIN)/test_mixed_scalar_tuple_sret_run: test/wcc/940_mixed_scalar_tuple_sret_ru
$(LIB)/libwwrt.a | $(BIN)
$(CC) $(CFLAGS) -o $@ $<
$(BIN)/test_tuple_in_union_run: test/wcc/940_tuple_in_union_run.c \
$(BIN)/ww $(BIN)/w6c $(BIN)/w6a $(BIN)/w6l \
$(BIN)/ww_ww $(BIN)/w6c_ww $(BIN)/w6a_ww $(BIN)/w6l_ww \
$(LIB)/libwwrt.a | $(BIN)
$(CC) $(CFLAGS) -o $@ $<
$(BIN)/test_composite_call_arg: test/wcc/723_composite_call_arg.c \
$(BIN)/w6c $(BIN)/w6c_ww | $(BIN)
$(CC) $(CFLAGS) -o $@ $<

View File

@@ -2034,6 +2034,74 @@ cg_widen_tagged_store(Cg *c, Local **locals_p, Type *dst, Node *src,
if (via_outer) goto copy_out;
return;
}
/* #242: tuple payload. Each element rides ONE register-ABI
* eightbyte — scalar/float a single 8B word, a slice/str its 3-word
* {ptr,len,cap} header (24B) — matching the tagged-return load
* (AX=tag, DX=word0, CX=word1, R8=word2) and the cgmlet receive
* cursor. NOT the packed-by-size t.N field layout (#238). Mirror of
* the struct-literal field-flow below, but 8B-slotted, not field-
* offset. */
if (su && su->kind == TY_TUPLE && src->kind == N_TUPLE) {
int tag = cg_tag_for_variant(du, st);
/* #242: a tuple built from UNTYPED/literal elements (`(true,7)`)
* leaves the src tuple type un-matchable by type_eq, so the
* variant tag can't resolve — the supported shape is a tuple of
* TYPED expressions (the strconv parseint `(neg, n)` shape).
* Loud-stop rather than silently mis-tag (tag 0) — rule 7.
* Untyped tuple-element coercion is the #241 literal-init
* family. */
if (tag < 0)
fatal("cg_widen_tagged_store: tuple-in-union variant tag "
"unresolved (untyped/literal tuple element; "
"see #242 / #241)");
/* #242: this 8B-per-eightbyte packing is correct only when no
* two scalar elements share a SysV eightbyte — e.g. (bool,u64),
* where the sub-8 bool is padded out by u64's 8-alignment. A
* tuple whose natural aligned layout packs two narrows into one
* eightbyte (e.g. (i32,i32,u64)) would overflow the union
* payload the slotted write assumes. Loud-stop (rule 7); the
* SysV eightbyte tuple classification is a deferred follow-up. */
int total = 0;
for (Node *e = src->list; e; e = e->next)
total += (node_isstr(e) || node_isslice(e)) ? 24 : 8;
if (8 + total > sz)
fatal("cg_widen_tagged_store: tuple-in-union payload needs "
"SysV eightbyte packing (narrow elements share an "
"eightbyte; see #242 follow-up)");
ins2(c, A_XORQ, areg(D_AX), areg(D_AX));
for (int k = 0; k < sz; k += 8)
ins2(c, A_MOVQ, areg(D_AX),
amem(D_BP, write_off + k));
int foff = 0;
for (Node *e = src->list; e; e = e->next) {
int e_isf32 = 0;
int isflt = fld_isfloat(e->type, &e_isf32);
int wide = node_isstr(e) || node_isslice(e);
int esz = e->type ? (int)e->type->size : 8;
cgexpr(c, e, *locals_p);
if (isflt) {
ins2(c, e_isf32 ? A_MOVSS : A_MOVSD,
areg(D_X0),
amem(D_BP, write_off + 8 + foff));
} else if (wide) {
ins2(c, A_MOVQ, areg(D_AX),
amem(D_BP, write_off + 8 + foff + 0));
ins2(c, A_MOVQ, areg(D_BX),
amem(D_BP, write_off + 8 + foff + 8));
ins2(c, A_MOVQ, areg(D_CX),
amem(D_BP, write_off + 8 + foff + 16));
} else {
ins2(c, fldstoreop(e->type, esz),
areg(D_AX),
amem(D_BP, write_off + 8 + foff));
}
foff += wide ? 24 : 8;
}
ins2(c, A_MOVQ, aimm(tag < 0 ? 0 : tag),
amem(D_BP, write_off + 0));
if (via_outer) goto copy_out;
return;
}
/* Struct payload: zero the whole slot, then write fields/words
* at slot+8+ — keeping the tag word at slot+0 from the zero-fill,
* then patch it with the variant tag. */
@@ -8399,12 +8467,19 @@ cgstmt(Cg *c, Node *n, Local **locals, int *frame)
int passthrough = istagged && (vu == rt ||
type_eq(vt, cg_ret_type));
int isstruct = vu && vu->kind == TY_STRUCT;
/* #242: a tuple variant must be PACKED into the union
* payload (tag + per-element words), not shuffled like a
* bare scalar — route it through the scratch-slot widen
* path (cg_widen_tagged_store TY_TUPLE arm). The scalar
* arm below zeroed the whole value (never packed the
* operands). */
int istuple = vu && vu->kind == TY_TUPLE;
if (rt->nullable) {
cgexpr(c, n->lhs, *locals);
} else if (passthrough) {
/* same tagged type: forward AX/DX/CX. */
cgexpr(c, n->lhs, *locals);
} else if (!istagged && !isstruct) {
} else if (!istagged && !isstruct && !istuple) {
/* str / slice / scalar variant: synthesise
* the tag in AX and shuffle the value into
* DX[/CX[/R8]]. Direct register path keeps
@@ -9123,6 +9198,55 @@ cgstmt(Cg *c, Node *n, Local **locals, int *frame)
* at its NATURAL width (#169). The receive has no single lvalue
* dest, so it reuses the same per-fn @sretscr slot a discarded
* sret call would; the in-reg path below is unchanged. */
/* #242: rhs is a tuple already materialised in a local slot (a
* match-bound union payload, `let (a,b)=t`), NOT a register-
* returning call. cgexpr(tuple ident) loads only word0->AX, so
* the register-cursor path below reads DX/CX stale. Copy each
* element from the ident's slot at the register-ABI 8B stride
* (24B for a slice/str header) — the SAME layout the tagged
* construct + match payload-bind write. */
if (n->rhs && n->rhs->kind == N_IDENT) {
Type *rty = type_chase_named(n->rhs->type);
if (rty && rty->kind == TY_TUPLE) {
int srcoff = localfind(*locals, n->rhs->str);
int lf32b;
int foff = 0;
for (Node *l = n->list; l; l = l->next) {
Type *t = l->type;
Type *u = type_chase_named(t);
int wide = u && (u->kind == TY_SLICE
|| u->kind == TY_STR);
int isflt = fld_isfloat(t, &lf32b);
int esz = t ? (int)t->size : 8;
int bsz = wide ? esz : 8;
int off = localoff(c, locals, l->str,
bsz, frame);
if (isflt) {
ins2(c, lf32b ? A_MOVSS : A_MOVSD,
amem(D_BP, srcoff + foff),
areg(D_X0));
ins2(c, lf32b ? A_MOVSS : A_MOVSD,
areg(D_X0), amem(D_BP, off));
} else if (wide) {
for (int k = 0; k < esz; k += 8) {
ins2(c, A_MOVQ,
amem(D_BP, srcoff + foff + k),
areg(D_AX));
ins2(c, A_MOVQ, areg(D_AX),
amem(D_BP, off + k));
}
} else {
ins2(c, fldloadop(t, esz),
amem(D_BP, srcoff + foff),
areg(D_AX));
ins2(c, fldstoreop(t, esz),
areg(D_AX), amem(D_BP, off));
}
foff += wide ? 24 : 8;
}
break;
}
}
int sret_recv = (n->rhs && n->rhs->kind == N_CALL)
? cg_sret_retsize(n->rhs->type) : 0;
cgexpr(c, n->rhs, *locals);

View File

@@ -10721,14 +10721,19 @@ fn resolvewalk(c: *checker, n: *node) void = {
if (k == nkind.N_MLET) {
if (n.rhs != nil) { resolvewalk(c, n.rhs); };
let pt: *node = nil;
if (n.rhs != nil) { if (n.rhs.kind == nkind.N_CALL) {
// #242: consume the rhs's tuple type for ANY rhs, not just an
// N_CALL — `let (a,b) = t` over a plain tuple ident (e.g. a
// match-bound union payload) must stamp its bindings too, or
// the un-annotated binder stays untyped and asserttyped aborts.
// Mirrors cstage check.c:2017 (cexpr(rhs), unconditional).
if (n.rhs != nil) {
// `rt` would shadow the imported lib/rt module
// (checkmoduleshadow errors); `rty` avoids it.
let rty: *node = exprtype(c, n.rhs, nil);
if (rty != nil) { if (rty.kind == nkind.N_TTUPLE) {
pt = rty.list;
}; };
}; };
};
stamptuplebinds(c, n.list, pt, true, "let");
return;
};
@@ -10743,12 +10748,13 @@ fn resolvewalk(c: *checker, n: *node) void = {
if (k == nkind.N_MASSIGN) {
if (n.rhs != nil) { resolvewalk(c, n.rhs); };
let pt: *node = nil;
if (n.rhs != nil) { if (n.rhs.kind == nkind.N_CALL) {
// #242: consume the rhs tuple type for ANY rhs (see N_MLET).
if (n.rhs != nil) {
let rty: *node = exprtype(c, n.rhs, nil);
if (rty != nil) { if (rty.kind == nkind.N_TTUPLE) {
pt = rty.list;
}; };
}; };
};
let l: *node = n.list;
for (l != nil) { resolvewalk(c, l); l = l.next; };
stamptuplebinds(c, n.list, pt, false, "");
@@ -17993,6 +17999,134 @@ fn cgwidentaggedstorebp(c: *cgen, dst: *tinfo, src: *node, slot_off: i32, slot_s
};
return;
};
// #242: tuple payload. Each element rides ONE register-ABI
// eightbyte — scalar/float a single 8B word, a slice/str its 3-word
// {ptr,len,cap} header (24B) — matching the tagged-return load
// (AX=tag, DX=word0, CX=word1, R8=word2) and the cgmlet receive
// cursor. NOT the packed-by-size t.N field layout (#238). Mirror of
// cstage cg_widen_tagged_store's TY_TUPLE arm.
if (src != nil) { if (src.kind == nkind.N_TUPLE) {
let stu: *tinfo = src.type_: *tinfo;
for (stu != nil && stu.kind == tykind.TY_NAMED) { stu = stu.under; };
if (stu != nil) { if (stu.kind == tykind.TY_TUPLE) {
// #242/#241: mirror cstage's loud-stop CONDITION, not its
// -1 mechanism (rule 10, align the RICHER side DOWN).
// wwstage types `true`/`false` as bool and a suffix-less `7`
// as untyped_int, so flatvariantidxt below DOES resolve the
// variant — but cstage's cg_tag_for_variant can't type a bare
// literal element (#241), returns -1, and loud-stops. A
// program cstage rejects, wwstage must also reject. The shape
// cstage can't type: a bool literal (N_TRUE/N_FALSE) or a
// suffix-less numeric literal (untyped_int/untyped_float).
// LIFT BOTH stage guards together when #241 fixes cstage
// literal typing -> symmetric accept.
let bl: *node = src.list;
for (bl != nil) {
let bare: bool = false;
if (bl.kind == nkind.N_TRUE) { bare = true; };
if (bl.kind == nkind.N_FALSE) { bare = true; };
if (bl.kind == nkind.N_INTLIT && bl.tsuffix.len == 0) {
bare = true;
};
if (bl.kind == nkind.N_FLOATLIT && bl.tsuffix.len == 0) {
bare = true;
};
if (bare) {
let ml: str = "cgwidentaggedstore: tuple-in-union variant tag unresolved (untyped/literal tuple element; see #242 / #241)\n";
os.write(2, ml.ptr, ml.len: u64);
os.exit(1);
};
bl = bl.next;
};
// #242: resolve the variant tag via the typeeq core
// (flatvariantidxt) — NOT taggedvariantindext, whose
// str/slice shape fallback would silently pick tag 0 for an
// unmatched tuple, diverging from cstage cg_tag_for_variant
// (which returns -1) and masking the loud-stop below.
let ttag: i32 = flatvariantidxt(dt, src.type_: *tinfo);
// #242: an untyped/literal tuple element (`(true,7)`) leaves
// the src tuple un-matchable, so the variant tag can't
// resolve — the supported shape is a tuple of TYPED exprs
// (strconv parseint `(neg, n)`). Loud-stop rather than
// silently mis-tag (rule 7); #241 literal-init family.
if (ttag < 0) {
let m1: str = "cgwidentaggedstore: tuple-in-union variant tag unresolved (untyped/literal tuple element; see #242 / #241)\n";
os.write(2, m1.ptr, m1.len: u64);
os.exit(1);
};
// #242: this 8B-per-eightbyte packing is correct only when
// no two scalar elements share a SysV eightbyte — e.g.
// (bool,u64). A (i32,i32,u64) would overflow the union
// payload the slotted write assumes. Loud-stop (rule 7);
// SysV eightbyte tuple classification is a deferred
// follow-up. Symmetric with cstage cg_widen_tagged_store.
let ttotal: i32 = 0;
let ce: *node = src.list;
for (ce != nil) {
if (nodeisstr(c, ce) || nodeisslice(c, ce)) {
ttotal += 24;
} else { ttotal += 8; };
ce = ce.next;
};
if (8 + ttotal > slot_sz) {
let m2: str = "cgwidentaggedstore: tuple-in-union payload needs SysV eightbyte packing (narrow elements share an eightbyte; see #242 follow-up)\n";
os.write(2, m2.ptr, m2.len: u64);
os.exit(1);
};
emitline("\tXORQ\tAX, AX\n");
let tzk: i32 = 0;
for (tzk < slot_sz) {
emitline("\tMOVQ\tAX, ");
emitoff((slot_off + tzk): i64);
emitline("(BP)\n");
tzk += 8;
};
let tfoff: i32 = 0;
let te: *node = src.list;
for (te != nil) {
let isflt: bool = isfloattype(c, te);
let wide: bool = nodeisstr(c, te) || nodeisslice(c, te);
let esz: i32 = 8;
let eti: *tinfo = te.type_: *tinfo;
if (eti != nil) { esz = eti.size: i32; };
cgexpr(c, te);
if (isflt) {
let mov: str = "MOVSD";
if (isf32type(c, te)) { mov = "MOVSS"; };
emitline("\t");
emitline(mov);
emitline("\tX0, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
} else { if (wide) {
emitline("\tMOVQ\tAX, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
emitline("\tMOVQ\tBX, ");
emitoff((slot_off + 8 + tfoff + 8): i64);
emitline("(BP)\n");
emitline("\tMOVQ\tCX, ");
emitoff((slot_off + 8 + tfoff + 16): i64);
emitline("(BP)\n");
} else {
let sop: str = tnodestoreop(c, te, esz);
emitline("\t");
emitline(sop);
emitline("\tAX, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
}; };
if (wide) { tfoff += 24; } else { tfoff += 8; };
te = te.next;
};
emitline("\tMOVQ\t$");
emitint(ttag: i64);
emitline(", ");
emitoff(slot_off: i64);
emitline("(BP)\n");
return;
}; };
}; };
// Struct payload (literal or ident).
let sname: str = rhsstructpayload(c, src);
if (sname.len > 0) {
@@ -26477,7 +26611,13 @@ fn cgreturn(c: *cgen, n: *node) void = {
// INTEGER cursor (ref/qbe/amd64/sysv.c retr L95-108). Both rows
// loud-stop at their cap (rule-7): INTEGER 4, SSE 2. The SAME
// class split drives the receive sites.
if (rhs.kind == nkind.N_TUPLE) {
// #242: a bare tuple return packs into the register cursor; a
// tuple WRAPPED IN A TAGGED UNION must instead pack into the
// union payload (tag + words) — fall through to the tagged path
// below, which routes it via cgwidentaggedstore. Without this
// guard the bare-tuple arm fired first and dropped the tag,
// returning (AX=word0, DX=word1) with no tag word.
if (rhs.kind == nkind.N_TUPLE && !istaggedtype(c, c.fnret)) {
let ssecap: i32 = TUPLE_SSECAP; // X0,X1 per SysV
let gptotal: i32 = 0;
let ssecount: i32 = 0;
@@ -26681,6 +26821,11 @@ fn cgreturn(c: *cgen, n: *node) void = {
if (rhstaggedident(c, rhs) != nil) {
needswiden = true;
};
// #242: a tuple variant packs into the union
// payload via cgwidentaggedstore's TY_TUPLE arm.
if (rhs.kind == nkind.N_TUPLE) {
needswiden = true;
};
};
};
if (needswiden) {
@@ -28095,6 +28240,71 @@ fn cgmlet(c: *cgen, n: *node) void = {
let sretrecv: i32 = 0;
if (rhs.kind == nkind.N_CALL) { sretrecv = callsretsize(c, rhs); };
// #242: rhs is a tuple already materialised in a local slot (a match-
// bound union payload, `let (a,b)=t`), NOT a register-returning call.
// cgexpr(tuple ident) loads only word0->AX, so the register cursor
// path below reads DX/CX stale. Copy each element from the ident's
// slot at the register-ABI 8B stride (24B for a slice/str header) —
// the SAME layout the tagged construct + match payload-bind write.
// Mirror of cstage cgen.c N_MLET tuple-ident arm. The binding element
// types ride l.lhs (stamped by the checker's stamptuplebinds).
if (rhs.kind == nkind.N_IDENT) {
let rl: *local = localfindnode(c, rhs.str);
if (rl != nil) {
let rti: *tinfo = rl.tnode.type_: *tinfo;
for (rti != nil && rti.kind == tykind.TY_NAMED) { rti = rti.under; };
if (rti != nil) { if (rti.kind == tykind.TY_TUPLE) {
let srcoff: i32 = rl.off;
let foff: i32 = 0;
let lb: *node = n.list;
for (lb != nil) {
let tn: *node = lb.lhs;
let isflt: bool = isfloattype(c, tn);
let wide: bool = isstrtype(c, tn) || isslicetype(c, tn);
let esz: i32 = 8;
let eti: *tinfo = nil;
if (tn != nil) { eti = tn.type_: *tinfo; };
if (eti != nil) { esz = eti.size: i32; };
let bsz: i32 = 8;
if (wide) { bsz = tyslicesize(): i32; };
let off: i32 = localadd(c, lb.str, bsz, tn);
if (isflt) {
let mov: str = "MOVSD";
if (isf32type(c, tn)) { mov = "MOVSS"; };
emitline("\t"); emitline(mov); emitline("\t");
emitoff((srcoff + foff): i64);
emitline("(BP), X0\n");
emitline("\t"); emitline(mov); emitline("\tX0, ");
emitoff(off: i64); emitline("(BP)\n");
} else { if (wide) {
let k: i32 = 0;
for (k < esz) {
emitline("\tMOVQ\t");
emitoff((srcoff + foff + k): i64);
emitline("(BP), AX\n");
emitline("\tMOVQ\tAX, ");
emitoff((off + k): i64);
emitline("(BP)\n");
k += 8;
};
} else {
let lop: str = tnodeloadop(c, tn, esz);
let sop: str = tnodestoreop(c, tn, esz);
emitline("\t"); emitline(lop); emitline("\t");
emitoff((srcoff + foff): i64);
emitline("(BP), AX\n");
emitline("\t"); emitline(sop); emitline("\tAX, ");
emitoff(off: i64); emitline("(BP)\n");
}; };
if (wide) { foff += 24; } else { foff += 8; };
lb = lb.next;
};
c.lastwasreturn = 0;
return;
}; };
};
};
cgexpr(c, rhs);
if (sretrecv > 0) {

View File

@@ -265,7 +265,13 @@ fn cgreturn(c: *cgen, n: *node) void = {
// INTEGER cursor (ref/qbe/amd64/sysv.c retr L95-108). Both rows
// loud-stop at their cap (rule-7): INTEGER 4, SSE 2. The SAME
// class split drives the receive sites.
if (rhs.kind == nkind.N_TUPLE) {
// #242: a bare tuple return packs into the register cursor; a
// tuple WRAPPED IN A TAGGED UNION must instead pack into the
// union payload (tag + words) — fall through to the tagged path
// below, which routes it via cgwidentaggedstore. Without this
// guard the bare-tuple arm fired first and dropped the tag,
// returning (AX=word0, DX=word1) with no tag word.
if (rhs.kind == nkind.N_TUPLE && !istaggedtype(c, c.fnret)) {
let ssecap: i32 = TUPLE_SSECAP; // X0,X1 per SysV
let gptotal: i32 = 0;
let ssecount: i32 = 0;
@@ -469,6 +475,11 @@ fn cgreturn(c: *cgen, n: *node) void = {
if (rhstaggedident(c, rhs) != nil) {
needswiden = true;
};
// #242: a tuple variant packs into the union
// payload via cgwidentaggedstore's TY_TUPLE arm.
if (rhs.kind == nkind.N_TUPLE) {
needswiden = true;
};
};
};
if (needswiden) {
@@ -1883,6 +1894,71 @@ fn cgmlet(c: *cgen, n: *node) void = {
let sretrecv: i32 = 0;
if (rhs.kind == nkind.N_CALL) { sretrecv = callsretsize(c, rhs); };
// #242: rhs is a tuple already materialised in a local slot (a match-
// bound union payload, `let (a,b)=t`), NOT a register-returning call.
// cgexpr(tuple ident) loads only word0->AX, so the register cursor
// path below reads DX/CX stale. Copy each element from the ident's
// slot at the register-ABI 8B stride (24B for a slice/str header) —
// the SAME layout the tagged construct + match payload-bind write.
// Mirror of cstage cgen.c N_MLET tuple-ident arm. The binding element
// types ride l.lhs (stamped by the checker's stamptuplebinds).
if (rhs.kind == nkind.N_IDENT) {
let rl: *local = localfindnode(c, rhs.str);
if (rl != nil) {
let rti: *tinfo = rl.tnode.type_: *tinfo;
for (rti != nil && rti.kind == tykind.TY_NAMED) { rti = rti.under; };
if (rti != nil) { if (rti.kind == tykind.TY_TUPLE) {
let srcoff: i32 = rl.off;
let foff: i32 = 0;
let lb: *node = n.list;
for (lb != nil) {
let tn: *node = lb.lhs;
let isflt: bool = isfloattype(c, tn);
let wide: bool = isstrtype(c, tn) || isslicetype(c, tn);
let esz: i32 = 8;
let eti: *tinfo = nil;
if (tn != nil) { eti = tn.type_: *tinfo; };
if (eti != nil) { esz = eti.size: i32; };
let bsz: i32 = 8;
if (wide) { bsz = tyslicesize(): i32; };
let off: i32 = localadd(c, lb.str, bsz, tn);
if (isflt) {
let mov: str = "MOVSD";
if (isf32type(c, tn)) { mov = "MOVSS"; };
emitline("\t"); emitline(mov); emitline("\t");
emitoff((srcoff + foff): i64);
emitline("(BP), X0\n");
emitline("\t"); emitline(mov); emitline("\tX0, ");
emitoff(off: i64); emitline("(BP)\n");
} else { if (wide) {
let k: i32 = 0;
for (k < esz) {
emitline("\tMOVQ\t");
emitoff((srcoff + foff + k): i64);
emitline("(BP), AX\n");
emitline("\tMOVQ\tAX, ");
emitoff((off + k): i64);
emitline("(BP)\n");
k += 8;
};
} else {
let lop: str = tnodeloadop(c, tn, esz);
let sop: str = tnodestoreop(c, tn, esz);
emitline("\t"); emitline(lop); emitline("\t");
emitoff((srcoff + foff): i64);
emitline("(BP), AX\n");
emitline("\t"); emitline(sop); emitline("\tAX, ");
emitoff(off: i64); emitline("(BP)\n");
}; };
if (wide) { foff += 24; } else { foff += 8; };
lb = lb.next;
};
c.lastwasreturn = 0;
return;
}; };
};
};
cgexpr(c, rhs);
if (sretrecv > 0) {

View File

@@ -2895,6 +2895,134 @@ fn cgwidentaggedstorebp(c: *cgen, dst: *tinfo, src: *node, slot_off: i32, slot_s
};
return;
};
// #242: tuple payload. Each element rides ONE register-ABI
// eightbyte — scalar/float a single 8B word, a slice/str its 3-word
// {ptr,len,cap} header (24B) — matching the tagged-return load
// (AX=tag, DX=word0, CX=word1, R8=word2) and the cgmlet receive
// cursor. NOT the packed-by-size t.N field layout (#238). Mirror of
// cstage cg_widen_tagged_store's TY_TUPLE arm.
if (src != nil) { if (src.kind == nkind.N_TUPLE) {
let stu: *tinfo = src.type_: *tinfo;
for (stu != nil && stu.kind == tykind.TY_NAMED) { stu = stu.under; };
if (stu != nil) { if (stu.kind == tykind.TY_TUPLE) {
// #242/#241: mirror cstage's loud-stop CONDITION, not its
// -1 mechanism (rule 10, align the RICHER side DOWN).
// wwstage types `true`/`false` as bool and a suffix-less `7`
// as untyped_int, so flatvariantidxt below DOES resolve the
// variant — but cstage's cg_tag_for_variant can't type a bare
// literal element (#241), returns -1, and loud-stops. A
// program cstage rejects, wwstage must also reject. The shape
// cstage can't type: a bool literal (N_TRUE/N_FALSE) or a
// suffix-less numeric literal (untyped_int/untyped_float).
// LIFT BOTH stage guards together when #241 fixes cstage
// literal typing -> symmetric accept.
let bl: *node = src.list;
for (bl != nil) {
let bare: bool = false;
if (bl.kind == nkind.N_TRUE) { bare = true; };
if (bl.kind == nkind.N_FALSE) { bare = true; };
if (bl.kind == nkind.N_INTLIT && bl.tsuffix.len == 0) {
bare = true;
};
if (bl.kind == nkind.N_FLOATLIT && bl.tsuffix.len == 0) {
bare = true;
};
if (bare) {
let ml: str = "cgwidentaggedstore: tuple-in-union variant tag unresolved (untyped/literal tuple element; see #242 / #241)\n";
os.write(2, ml.ptr, ml.len: u64);
os.exit(1);
};
bl = bl.next;
};
// #242: resolve the variant tag via the typeeq core
// (flatvariantidxt) — NOT taggedvariantindext, whose
// str/slice shape fallback would silently pick tag 0 for an
// unmatched tuple, diverging from cstage cg_tag_for_variant
// (which returns -1) and masking the loud-stop below.
let ttag: i32 = flatvariantidxt(dt, src.type_: *tinfo);
// #242: an untyped/literal tuple element (`(true,7)`) leaves
// the src tuple un-matchable, so the variant tag can't
// resolve — the supported shape is a tuple of TYPED exprs
// (strconv parseint `(neg, n)`). Loud-stop rather than
// silently mis-tag (rule 7); #241 literal-init family.
if (ttag < 0) {
let m1: str = "cgwidentaggedstore: tuple-in-union variant tag unresolved (untyped/literal tuple element; see #242 / #241)\n";
os.write(2, m1.ptr, m1.len: u64);
os.exit(1);
};
// #242: this 8B-per-eightbyte packing is correct only when
// no two scalar elements share a SysV eightbyte — e.g.
// (bool,u64). A (i32,i32,u64) would overflow the union
// payload the slotted write assumes. Loud-stop (rule 7);
// SysV eightbyte tuple classification is a deferred
// follow-up. Symmetric with cstage cg_widen_tagged_store.
let ttotal: i32 = 0;
let ce: *node = src.list;
for (ce != nil) {
if (nodeisstr(c, ce) || nodeisslice(c, ce)) {
ttotal += 24;
} else { ttotal += 8; };
ce = ce.next;
};
if (8 + ttotal > slot_sz) {
let m2: str = "cgwidentaggedstore: tuple-in-union payload needs SysV eightbyte packing (narrow elements share an eightbyte; see #242 follow-up)\n";
os.write(2, m2.ptr, m2.len: u64);
os.exit(1);
};
emitline("\tXORQ\tAX, AX\n");
let tzk: i32 = 0;
for (tzk < slot_sz) {
emitline("\tMOVQ\tAX, ");
emitoff((slot_off + tzk): i64);
emitline("(BP)\n");
tzk += 8;
};
let tfoff: i32 = 0;
let te: *node = src.list;
for (te != nil) {
let isflt: bool = isfloattype(c, te);
let wide: bool = nodeisstr(c, te) || nodeisslice(c, te);
let esz: i32 = 8;
let eti: *tinfo = te.type_: *tinfo;
if (eti != nil) { esz = eti.size: i32; };
cgexpr(c, te);
if (isflt) {
let mov: str = "MOVSD";
if (isf32type(c, te)) { mov = "MOVSS"; };
emitline("\t");
emitline(mov);
emitline("\tX0, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
} else { if (wide) {
emitline("\tMOVQ\tAX, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
emitline("\tMOVQ\tBX, ");
emitoff((slot_off + 8 + tfoff + 8): i64);
emitline("(BP)\n");
emitline("\tMOVQ\tCX, ");
emitoff((slot_off + 8 + tfoff + 16): i64);
emitline("(BP)\n");
} else {
let sop: str = tnodestoreop(c, te, esz);
emitline("\t");
emitline(sop);
emitline("\tAX, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
}; };
if (wide) { tfoff += 24; } else { tfoff += 8; };
te = te.next;
};
emitline("\tMOVQ\t$");
emitint(ttag: i64);
emitline(", ");
emitoff(slot_off: i64);
emitline("(BP)\n");
return;
}; };
}; };
// Struct payload (literal or ident).
let sname: str = rhsstructpayload(c, src);
if (sname.len > 0) {

View File

@@ -471,14 +471,19 @@ fn resolvewalk(c: *checker, n: *node) void = {
if (k == nkind.N_MLET) {
if (n.rhs != nil) { resolvewalk(c, n.rhs); };
let pt: *node = nil;
if (n.rhs != nil) { if (n.rhs.kind == nkind.N_CALL) {
// #242: consume the rhs's tuple type for ANY rhs, not just an
// N_CALL — `let (a,b) = t` over a plain tuple ident (e.g. a
// match-bound union payload) must stamp its bindings too, or
// the un-annotated binder stays untyped and asserttyped aborts.
// Mirrors cstage check.c:2017 (cexpr(rhs), unconditional).
if (n.rhs != nil) {
// `rt` would shadow the imported lib/rt module
// (checkmoduleshadow errors); `rty` avoids it.
let rty: *node = exprtype(c, n.rhs, nil);
if (rty != nil) { if (rty.kind == nkind.N_TTUPLE) {
pt = rty.list;
}; };
}; };
};
stamptuplebinds(c, n.list, pt, true, "let");
return;
};
@@ -493,12 +498,13 @@ fn resolvewalk(c: *checker, n: *node) void = {
if (k == nkind.N_MASSIGN) {
if (n.rhs != nil) { resolvewalk(c, n.rhs); };
let pt: *node = nil;
if (n.rhs != nil) { if (n.rhs.kind == nkind.N_CALL) {
// #242: consume the rhs tuple type for ANY rhs (see N_MLET).
if (n.rhs != nil) {
let rty: *node = exprtype(c, n.rhs, nil);
if (rty != nil) { if (rty.kind == nkind.N_TTUPLE) {
pt = rty.list;
}; };
}; };
};
let l: *node = n.list;
for (l != nil) { resolvewalk(c, l); l = l.next; };
stamptuplebinds(c, n.list, pt, false, "");

View File

@@ -10721,14 +10721,19 @@ fn resolvewalk(c: *checker, n: *node) void = {
if (k == nkind.N_MLET) {
if (n.rhs != nil) { resolvewalk(c, n.rhs); };
let pt: *node = nil;
if (n.rhs != nil) { if (n.rhs.kind == nkind.N_CALL) {
// #242: consume the rhs's tuple type for ANY rhs, not just an
// N_CALL — `let (a,b) = t` over a plain tuple ident (e.g. a
// match-bound union payload) must stamp its bindings too, or
// the un-annotated binder stays untyped and asserttyped aborts.
// Mirrors cstage check.c:2017 (cexpr(rhs), unconditional).
if (n.rhs != nil) {
// `rt` would shadow the imported lib/rt module
// (checkmoduleshadow errors); `rty` avoids it.
let rty: *node = exprtype(c, n.rhs, nil);
if (rty != nil) { if (rty.kind == nkind.N_TTUPLE) {
pt = rty.list;
}; };
}; };
};
stamptuplebinds(c, n.list, pt, true, "let");
return;
};
@@ -10743,12 +10748,13 @@ fn resolvewalk(c: *checker, n: *node) void = {
if (k == nkind.N_MASSIGN) {
if (n.rhs != nil) { resolvewalk(c, n.rhs); };
let pt: *node = nil;
if (n.rhs != nil) { if (n.rhs.kind == nkind.N_CALL) {
// #242: consume the rhs tuple type for ANY rhs (see N_MLET).
if (n.rhs != nil) {
let rty: *node = exprtype(c, n.rhs, nil);
if (rty != nil) { if (rty.kind == nkind.N_TTUPLE) {
pt = rty.list;
}; };
}; };
};
let l: *node = n.list;
for (l != nil) { resolvewalk(c, l); l = l.next; };
stamptuplebinds(c, n.list, pt, false, "");
@@ -17993,6 +17999,134 @@ fn cgwidentaggedstorebp(c: *cgen, dst: *tinfo, src: *node, slot_off: i32, slot_s
};
return;
};
// #242: tuple payload. Each element rides ONE register-ABI
// eightbyte — scalar/float a single 8B word, a slice/str its 3-word
// {ptr,len,cap} header (24B) — matching the tagged-return load
// (AX=tag, DX=word0, CX=word1, R8=word2) and the cgmlet receive
// cursor. NOT the packed-by-size t.N field layout (#238). Mirror of
// cstage cg_widen_tagged_store's TY_TUPLE arm.
if (src != nil) { if (src.kind == nkind.N_TUPLE) {
let stu: *tinfo = src.type_: *tinfo;
for (stu != nil && stu.kind == tykind.TY_NAMED) { stu = stu.under; };
if (stu != nil) { if (stu.kind == tykind.TY_TUPLE) {
// #242/#241: mirror cstage's loud-stop CONDITION, not its
// -1 mechanism (rule 10, align the RICHER side DOWN).
// wwstage types `true`/`false` as bool and a suffix-less `7`
// as untyped_int, so flatvariantidxt below DOES resolve the
// variant — but cstage's cg_tag_for_variant can't type a bare
// literal element (#241), returns -1, and loud-stops. A
// program cstage rejects, wwstage must also reject. The shape
// cstage can't type: a bool literal (N_TRUE/N_FALSE) or a
// suffix-less numeric literal (untyped_int/untyped_float).
// LIFT BOTH stage guards together when #241 fixes cstage
// literal typing -> symmetric accept.
let bl: *node = src.list;
for (bl != nil) {
let bare: bool = false;
if (bl.kind == nkind.N_TRUE) { bare = true; };
if (bl.kind == nkind.N_FALSE) { bare = true; };
if (bl.kind == nkind.N_INTLIT && bl.tsuffix.len == 0) {
bare = true;
};
if (bl.kind == nkind.N_FLOATLIT && bl.tsuffix.len == 0) {
bare = true;
};
if (bare) {
let ml: str = "cgwidentaggedstore: tuple-in-union variant tag unresolved (untyped/literal tuple element; see #242 / #241)\n";
os.write(2, ml.ptr, ml.len: u64);
os.exit(1);
};
bl = bl.next;
};
// #242: resolve the variant tag via the typeeq core
// (flatvariantidxt) — NOT taggedvariantindext, whose
// str/slice shape fallback would silently pick tag 0 for an
// unmatched tuple, diverging from cstage cg_tag_for_variant
// (which returns -1) and masking the loud-stop below.
let ttag: i32 = flatvariantidxt(dt, src.type_: *tinfo);
// #242: an untyped/literal tuple element (`(true,7)`) leaves
// the src tuple un-matchable, so the variant tag can't
// resolve — the supported shape is a tuple of TYPED exprs
// (strconv parseint `(neg, n)`). Loud-stop rather than
// silently mis-tag (rule 7); #241 literal-init family.
if (ttag < 0) {
let m1: str = "cgwidentaggedstore: tuple-in-union variant tag unresolved (untyped/literal tuple element; see #242 / #241)\n";
os.write(2, m1.ptr, m1.len: u64);
os.exit(1);
};
// #242: this 8B-per-eightbyte packing is correct only when
// no two scalar elements share a SysV eightbyte — e.g.
// (bool,u64). A (i32,i32,u64) would overflow the union
// payload the slotted write assumes. Loud-stop (rule 7);
// SysV eightbyte tuple classification is a deferred
// follow-up. Symmetric with cstage cg_widen_tagged_store.
let ttotal: i32 = 0;
let ce: *node = src.list;
for (ce != nil) {
if (nodeisstr(c, ce) || nodeisslice(c, ce)) {
ttotal += 24;
} else { ttotal += 8; };
ce = ce.next;
};
if (8 + ttotal > slot_sz) {
let m2: str = "cgwidentaggedstore: tuple-in-union payload needs SysV eightbyte packing (narrow elements share an eightbyte; see #242 follow-up)\n";
os.write(2, m2.ptr, m2.len: u64);
os.exit(1);
};
emitline("\tXORQ\tAX, AX\n");
let tzk: i32 = 0;
for (tzk < slot_sz) {
emitline("\tMOVQ\tAX, ");
emitoff((slot_off + tzk): i64);
emitline("(BP)\n");
tzk += 8;
};
let tfoff: i32 = 0;
let te: *node = src.list;
for (te != nil) {
let isflt: bool = isfloattype(c, te);
let wide: bool = nodeisstr(c, te) || nodeisslice(c, te);
let esz: i32 = 8;
let eti: *tinfo = te.type_: *tinfo;
if (eti != nil) { esz = eti.size: i32; };
cgexpr(c, te);
if (isflt) {
let mov: str = "MOVSD";
if (isf32type(c, te)) { mov = "MOVSS"; };
emitline("\t");
emitline(mov);
emitline("\tX0, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
} else { if (wide) {
emitline("\tMOVQ\tAX, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
emitline("\tMOVQ\tBX, ");
emitoff((slot_off + 8 + tfoff + 8): i64);
emitline("(BP)\n");
emitline("\tMOVQ\tCX, ");
emitoff((slot_off + 8 + tfoff + 16): i64);
emitline("(BP)\n");
} else {
let sop: str = tnodestoreop(c, te, esz);
emitline("\t");
emitline(sop);
emitline("\tAX, ");
emitoff((slot_off + 8 + tfoff): i64);
emitline("(BP)\n");
}; };
if (wide) { tfoff += 24; } else { tfoff += 8; };
te = te.next;
};
emitline("\tMOVQ\t$");
emitint(ttag: i64);
emitline(", ");
emitoff(slot_off: i64);
emitline("(BP)\n");
return;
}; };
}; };
// Struct payload (literal or ident).
let sname: str = rhsstructpayload(c, src);
if (sname.len > 0) {
@@ -26477,7 +26611,13 @@ fn cgreturn(c: *cgen, n: *node) void = {
// INTEGER cursor (ref/qbe/amd64/sysv.c retr L95-108). Both rows
// loud-stop at their cap (rule-7): INTEGER 4, SSE 2. The SAME
// class split drives the receive sites.
if (rhs.kind == nkind.N_TUPLE) {
// #242: a bare tuple return packs into the register cursor; a
// tuple WRAPPED IN A TAGGED UNION must instead pack into the
// union payload (tag + words) — fall through to the tagged path
// below, which routes it via cgwidentaggedstore. Without this
// guard the bare-tuple arm fired first and dropped the tag,
// returning (AX=word0, DX=word1) with no tag word.
if (rhs.kind == nkind.N_TUPLE && !istaggedtype(c, c.fnret)) {
let ssecap: i32 = TUPLE_SSECAP; // X0,X1 per SysV
let gptotal: i32 = 0;
let ssecount: i32 = 0;
@@ -26681,6 +26821,11 @@ fn cgreturn(c: *cgen, n: *node) void = {
if (rhstaggedident(c, rhs) != nil) {
needswiden = true;
};
// #242: a tuple variant packs into the union
// payload via cgwidentaggedstore's TY_TUPLE arm.
if (rhs.kind == nkind.N_TUPLE) {
needswiden = true;
};
};
};
if (needswiden) {
@@ -28095,6 +28240,71 @@ fn cgmlet(c: *cgen, n: *node) void = {
let sretrecv: i32 = 0;
if (rhs.kind == nkind.N_CALL) { sretrecv = callsretsize(c, rhs); };
// #242: rhs is a tuple already materialised in a local slot (a match-
// bound union payload, `let (a,b)=t`), NOT a register-returning call.
// cgexpr(tuple ident) loads only word0->AX, so the register cursor
// path below reads DX/CX stale. Copy each element from the ident's
// slot at the register-ABI 8B stride (24B for a slice/str header) —
// the SAME layout the tagged construct + match payload-bind write.
// Mirror of cstage cgen.c N_MLET tuple-ident arm. The binding element
// types ride l.lhs (stamped by the checker's stamptuplebinds).
if (rhs.kind == nkind.N_IDENT) {
let rl: *local = localfindnode(c, rhs.str);
if (rl != nil) {
let rti: *tinfo = rl.tnode.type_: *tinfo;
for (rti != nil && rti.kind == tykind.TY_NAMED) { rti = rti.under; };
if (rti != nil) { if (rti.kind == tykind.TY_TUPLE) {
let srcoff: i32 = rl.off;
let foff: i32 = 0;
let lb: *node = n.list;
for (lb != nil) {
let tn: *node = lb.lhs;
let isflt: bool = isfloattype(c, tn);
let wide: bool = isstrtype(c, tn) || isslicetype(c, tn);
let esz: i32 = 8;
let eti: *tinfo = nil;
if (tn != nil) { eti = tn.type_: *tinfo; };
if (eti != nil) { esz = eti.size: i32; };
let bsz: i32 = 8;
if (wide) { bsz = tyslicesize(): i32; };
let off: i32 = localadd(c, lb.str, bsz, tn);
if (isflt) {
let mov: str = "MOVSD";
if (isf32type(c, tn)) { mov = "MOVSS"; };
emitline("\t"); emitline(mov); emitline("\t");
emitoff((srcoff + foff): i64);
emitline("(BP), X0\n");
emitline("\t"); emitline(mov); emitline("\tX0, ");
emitoff(off: i64); emitline("(BP)\n");
} else { if (wide) {
let k: i32 = 0;
for (k < esz) {
emitline("\tMOVQ\t");
emitoff((srcoff + foff + k): i64);
emitline("(BP), AX\n");
emitline("\tMOVQ\tAX, ");
emitoff((off + k): i64);
emitline("(BP)\n");
k += 8;
};
} else {
let lop: str = tnodeloadop(c, tn, esz);
let sop: str = tnodestoreop(c, tn, esz);
emitline("\t"); emitline(lop); emitline("\t");
emitoff((srcoff + foff): i64);
emitline("(BP), AX\n");
emitline("\t"); emitline(sop); emitline("\tAX, ");
emitoff(off: i64); emitline("(BP)\n");
}; };
if (wide) { foff += 24; } else { foff += 8; };
lb = lb.next;
};
c.lastwasreturn = 0;
return;
}; };
};
};
cgexpr(c, rhs);
if (sretrecv > 0) {

View File

@@ -0,0 +1,337 @@
/*
* 940_tuple_in_union_run — project #242: a mixed-scalar tuple WRAPPED IN A
* TAGGED UNION must construct, match-bind, and destructure IDENTICALLY in
* both stages and round-trip every element. BARE tuples already worked
* (#240/#83); only the union-wrapped variant was broken.
*
* Three SILENT, gate-blind (no bootstrap tuple-in-union) cs!=ww divergences
* met here, all on the `(neg, n)`-shape tuple Hare's strconv parseint returns
* (`((bool, u64) | invalid | overflow)`, stou.ha):
*
* (a) cstage CONSTRUCTION (cgen.c N_RETURN tagged arm): a tuple variant fell
* through the scalar shuffle, which ZEROED the whole value (MOVQ $0 to
* tag + payload) — the operands were never packed. Fix: route the tuple
* variant through the scratch-slot widen path (cg_widen_tagged_store's
* new TY_TUPLE arm), packing each element into the union payload + tag.
*
* (b) wwstage CHECKER (check.ww N_MLET): `let (a,b)=t` over a plain tuple
* ident (the match-bound union payload) left the un-annotated binders
* UNTYPED — the bin node reading them was untyped → asserttyped abort.
* The element-type distribution only fired for an N_CALL rhs. Fix:
* consume the rhs tuple type for ANY rhs (mirror cstage check.c:2017).
*
* (c) BOTH stages DESTRUCTURE (N_MLET / cgmlet): the register-cursor receive
* assumes the rhs left every element in AX/DX/CX (a call's tuple-return
* ABI). For a tuple IDENT cgexpr loads only word0->AX, so the 2nd binder
* read a STALE DX. Fix: copy each element from the ident's slot at the
* register-ABI 8B stride.
*
* Construction is correct at ANY variant position (the variant tag, not a
* default-0) — `tuple_tag1` and `tuple_after_int` place the tuple at index 1.
*
* SCOPE (rule 7 loud-stops, PINNED by the K_BUILDERR rows): a tuple built
* from a BARE LITERAL element (cstage mis-types `true`/`false`/untyped `7` →
* tag unresolved, #241 literal-init family; wwstage types them but mirrors
* cstage's CONDITION down per rule 10) and a tuple whose narrow elements
* SHARE a SysV eightbyte (e.g. (i32,i32,u64), needs eightbyte classification,
* #243) both loud-stop in cgen on BOTH stages rather than silently
* miscompile. The K_RUN rows build their tuple from TYPED expressions — the
* supported, byte-identical shape.
*
* K_RUN rows: build+run exit 0 on BOTH drivers AND cs==ww byte-identical.
* K_BUILDERR rows: build FAILS with the #242 diagnostic on BOTH drivers.
* NNN<950, self-contained (/tmp, no imports), so rule-14's selfhost-sibling
* race does not apply (903/940/945 precedent).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
static int
runwait(const char *cmd)
{
int rc = system(cmd);
if (rc == -1) return -1;
if (WIFEXITED(rc)) return WEXITSTATUS(rc);
return -1;
}
static int
slurp_eq(const char *a, const char *b)
{
FILE *fa = fopen(a, "rb");
FILE *fb = fopen(b, "rb");
if (!fa || !fb) { if (fa) fclose(fa); if (fb) fclose(fb); return -1; }
int rc = 0;
for (;;) {
int ca = fgetc(fa), cb = fgetc(fb);
if (ca != cb) { rc = -1; break; }
if (ca == EOF) break;
}
fclose(fa); fclose(fb);
return rc;
}
static int
file_contains(const char *path, const char *needle)
{
FILE *f = fopen(path, "rb");
if (!f) return 0;
char buf[8192];
size_t n = fread(buf, 1, sizeof buf - 1, f);
fclose(f);
buf[n] = '\0';
return strstr(buf, needle) != NULL;
}
#define K_RUN 0 /* build+run both drivers, exit==want, + cs==ww byte-id */
#define K_BUILDERR 1 /* build must FAIL with experr on BOTH drivers (rule 7) */
struct row { const char *label; const char *src; int kind; int want;
const char *experr; };
static const struct row rows[] = {
/* canonical #242 case: (bool,u64) at variant 0, match-bind +
* destructure, both elements checked. */
{ "bool_u64",
"package main;\n"
"fn mku(x: u64, s: bool) ((bool, u64) | void) = { return (s, x); };\n"
"export fn main() i32 = {\n"
" match (mku(7u64, true)) {\n"
" case let t: (bool, u64) => {\n"
" let (sg, u) = t;\n"
" if (u != 7u64) { return 1; };\n"
" if (!sg) { return 2; };\n"
" return 0;\n"
" };\n"
" case void => { return 3; };\n"
" };\n"
" return 4;\n"
"};\n", K_RUN, 0, NULL },
/* the void variant: bare `return;` packs the void tag, the match
* takes the void arm. The tuple branch still compiles (typed vars). */
{ "void_arm",
"package main;\n"
"fn mku(ok: bool, x: u64, s: bool) ((bool, u64) | void) = {\n"
" if (ok) { return (s, x); };\n"
" return;\n"
"};\n"
"export fn main() i32 = {\n"
" match (mku(false, 1u64, true)) {\n"
" case let t: (bool, u64) => { return 1; };\n"
" case void => { return 0; };\n"
" };\n"
" return 2;\n"
"};\n", K_RUN, 0, NULL },
/* tuple at variant 1 (`(void | (bool,u64))`): the construct must emit
* tag 1, not a default 0 — and the match must dispatch to it. */
{ "tuple_tag1",
"package main;\n"
"fn mku(x: u64, s: bool) (void | (bool, u64)) = { return (s, x); };\n"
"export fn main() i32 = {\n"
" match (mku(9u64, true)) {\n"
" case void => { return 50; };\n"
" case let t: (bool, u64) => {\n"
" let (sg, u) = t;\n"
" if (u != 9u64) { return 1; };\n"
" if (!sg) { return 2; };\n"
" return 0;\n"
" };\n"
" };\n"
" return 4;\n"
"};\n", K_RUN, 0, NULL },
/* tuple variant 1 of `(int | (bool,u64))`, selected at runtime, built
* from typed locals (the parseint shape: an int-or-tuple result). */
{ "tuple_after_int",
"package main;\n"
"fn mk(which: bool) (int | (bool, u64)) = {\n"
" let s: bool = true;\n"
" let v: u64 = 88u64;\n"
" if (which) { return (s, v); };\n"
" return 5;\n"
"};\n"
"export fn main() i32 = {\n"
" match (mk(true)) {\n"
" case let n: int => { return 1; };\n"
" case let t: (bool, u64) => {\n"
" let (sg, u) = t;\n"
" if (u != 88u64) { return 2; };\n"
" if (!sg) { return 3; };\n"
" return 0;\n"
" };\n"
" };\n"
" return 4;\n"
"};\n", K_RUN, 0, NULL },
/* rule-7 loud-stop (i): a tuple whose narrow elements SHARE a SysV
* eightbyte ((i32,i32,u64) — i32@0,i32@4,u64@8 packs to 16B, but the
* 8B-slotted write needs 24B) overflows the union payload. Both stages
* MUST loud-stop (eightbyte classification is the #243 follow-up), not
* silently miscompile. Typed params -> the tag resolves; the SIZE guard
* fires. */
{ "eightbyte_share",
"package main;\n"
"fn f(a: i32, b: i32, c: u64) ((i32, i32, u64) | void) = {\n"
" return (a, b, c);\n"
"};\n"
"export fn main() i32 = { return 0; };\n",
K_BUILDERR, 0, "needs SysV eightbyte packing" },
/* rule-7 loud-stop (ii): a tuple built from a BARE LITERAL element
* (`true`). cstage's cg_tag_for_variant can't type the literal (#241)
* so it returns -1 and loud-stops; wwstage types `true` as bool and
* WOULD resolve the tag, so it mirrors cstage's CONDITION with an
* explicit bare-literal guard (rule 10 — align the richer side DOWN).
* Both stages MUST loud-stop with the SAME diagnostic. Lift both guards
* together when #241 lands cstage literal typing. */
{ "bool_literal",
"package main;\n"
"fn f(x: u64) ((bool, u64) | void) = { return (true, x); };\n"
"export fn main() i32 = { return 0; };\n",
K_BUILDERR, 0, "variant tag unresolved (untyped/literal tuple element" },
};
/* build+run via a driver (ww / ww_ww); returns 0 pass, nonzero fail. */
static int
run_driver(const char *driver, const struct row *r, int i)
{
char src[96], tmpdir[96], errf[96], cmd[1024];
snprintf(src, sizeof src, "/tmp/tiu_%d_%d.ww", getpid(), i);
snprintf(tmpdir, sizeof tmpdir, "/tmp/tiu_%d_d_%d", getpid(), i);
snprintf(errf, sizeof errf, "/tmp/tiu_%d_e_%d", getpid(), i);
FILE *f = fopen(src, "wb");
if (!f) return -1;
fputs(r->src, f);
fclose(f);
mkdir(tmpdir, 0755);
snprintf(cmd, sizeof cmd, "cd %s && %s build %s >/dev/null 2>%s",
tmpdir, driver, src, errf);
int brc = runwait(cmd);
if (r->kind == K_BUILDERR) {
int ok = (brc != 0)
&& (r->experr == NULL || file_contains(errf, r->experr));
if (!ok)
fprintf(stderr, "row[%s]: %s expected loud #242 builderr "
"(brc=%d)\n", r->label, driver, brc);
unlink(src); unlink(errf); rmdir(tmpdir);
return ok ? 0 : 1;
}
if (brc != 0) {
fprintf(stderr, "row[%s]: build via %s failed\n",
r->label, driver);
unlink(src); unlink(errf); rmdir(tmpdir);
return -1;
}
const char *base = strrchr(src, '/');
base = base ? base + 1 : src;
char outbin[256];
snprintf(outbin, sizeof outbin, "%s/%s", tmpdir, base);
char *dot = strrchr(outbin, '.');
if (dot && strcmp(dot, ".ww") == 0) *dot = '\0';
int got = runwait(outbin);
unlink(src); unlink(outbin); unlink(errf); rmdir(tmpdir);
if (got != r->want) {
fprintf(stderr, "row[%s]: %s exit %d, want %d\n",
r->label, driver, got, r->want);
return 1;
}
return 0;
}
/* cs==ww .s byte-id (rule 10). */
static int
byteid(const char *w6c, const char *w6c_ww, const struct row *r, int i)
{
char src[96], cs_s[96], ws_s[96], cmd[1024];
snprintf(src, sizeof src, "/tmp/tiu_bi_%d_%d.ww", getpid(), i);
snprintf(cs_s, sizeof cs_s, "/tmp/tiu_bi_%d_%d_cs.s", getpid(), i);
snprintf(ws_s, sizeof ws_s, "/tmp/tiu_bi_%d_%d_ww.s", getpid(), i);
FILE *f = fopen(src, "wb");
if (!f) return -1;
fputs(r->src, f);
fclose(f);
int rc = 0;
snprintf(cmd, sizeof cmd, "%s -o %s %s 2>/dev/null", w6c, cs_s, src);
if (runwait(cmd) != 0) { fprintf(stderr, "row[%s]: w6c failed\n", r->label); rc = 1; }
else {
snprintf(cmd, sizeof cmd, "%s -o %s %s 2>/dev/null", w6c_ww, ws_s, src);
if (runwait(cmd) != 0) { fprintf(stderr, "row[%s]: w6c_ww failed\n", r->label); rc = 1; }
else if (slurp_eq(cs_s, ws_s) != 0) {
fprintf(stderr, "row[%s]: cstage/wwstage .s DIFFER "
"(#242 tuple-in-union construct/destructure regression)\n",
r->label);
rc = 1;
}
}
unlink(src); unlink(cs_s); unlink(ws_s);
return rc;
}
int
main(void)
{
const char *bin = getenv("BIN");
if (!bin) bin = "out/bin";
char absbin[512];
if (bin[0] != '/') {
char cwd[256];
if (getcwd(cwd, sizeof cwd) == NULL) return 1;
snprintf(absbin, sizeof absbin, "%s/%s", cwd, bin);
bin = absbin;
}
char cdrv[640], wdrv[640], w6c[640], w6c_ww[640];
snprintf(cdrv, sizeof cdrv, "%s/ww", bin);
snprintf(wdrv, sizeof wdrv, "%s/ww_ww", bin);
snprintf(w6c, sizeof w6c, "%s/w6c", bin);
snprintf(w6c_ww, sizeof w6c_ww, "%s/w6c_ww", bin);
struct { const char *name; const char *path; int gated; }
drivers[] = {
{ "cstage", cdrv, 0 },
{ "wwstage", wdrv, 1 },
{ NULL, NULL, 0 },
};
int n = (int)(sizeof rows / sizeof rows[0]);
int total = 0, fail = 0;
for (int d = 0; drivers[d].name; d++) {
if (drivers[d].gated && access(drivers[d].path, X_OK) != 0) {
fprintf(stderr, "tuple_in_union: skip %s (no %s)\n",
drivers[d].name, drivers[d].path);
continue;
}
for (int i = 0; i < n; i++) {
total++;
if (run_driver(drivers[d].path, &rows[i], i) != 0) fail++;
}
}
/* cs==ww byte-id for the K_RUN rows only; a K_BUILDERR row emits no
* .s on either stage (both loud-stop), so byte-id does not apply. */
if (access(w6c_ww, X_OK) == 0) {
for (int i = 0; i < n; i++) {
if (rows[i].kind != K_RUN) continue;
total++;
if (byteid(w6c, w6c_ww, &rows[i], i) != 0) fail++;
}
}
if (fail) {
fprintf(stderr, "tuple_in_union: %d/%d checks failed\n",
fail, total);
return 1;
}
printf("tuple_in_union: %d/%d ok\n", total, total);
return 0;
}