diff --git a/Makefile b/Makefile index 44331d72..c163dabd 100644 --- a/Makefile +++ b/Makefile @@ -404,6 +404,7 @@ TESTS = $(BIN)/test_smoke $(BIN)/test_lex $(BIN)/test_parse $(BIN)/test_check \ $(BIN)/test_dotbase_arr_run \ $(BIN)/test_dotbase_addr_slice_run \ $(BIN)/test_structlit_arrfield_run \ + $(BIN)/test_arraytoslice_run \ $(BIN)/test_continue_run \ $(BIN)/test_callret_unsigned_arith_run \ $(BIN)/test_sar_shr_run \ @@ -1605,6 +1606,11 @@ $(BIN)/test_structlit_arrfield_run: test/wcc/949_structlit_arrfield_run.c \ $(LIB)/libwwrt.a | $(BIN) $(CC) $(CFLAGS) -o $@ $< +$(BIN)/test_arraytoslice_run: test/wcc/953_arraytoslice_run.c \ + $(BIN)/ww $(BIN)/w6c $(BIN)/w6c_ww $(BIN)/w6a $(BIN)/w6l \ + $(LIB)/libwwrt.a | $(BIN) + $(CC) $(CFLAGS) -o $@ $< + $(BIN)/test_continue_run: test/wcc/911_continue_run.c $(BIN)/ww \ $(BIN)/w6c $(BIN)/w6c_ww $(BIN)/w6a $(BIN)/w6l \ $(LIB)/libwwrt.a | $(BIN) diff --git a/cmd/wcc/check.c b/cmd/wcc/check.c index ccdf8563..0260c0d6 100644 --- a/cmd/wcc/check.c +++ b/cmd/wcc/check.c @@ -924,6 +924,46 @@ coerce_floatlit(Node *n, Type *target) n->type = ty_f32; } +/* desugar_arrayslice — #258. The single shared injection point for the + * implicit [N]T → []T borrow. type_assignable already admits an array + * with a defined length into a matching []T slot (see type.c:#258); here + * we lower it to the explicit full slice `arr[0:len(arr)]` (an N_SLICE + * over the array base), reusing the existing slice cgen — #252/#257/#135 + * made array bases (incl struct-field arrays) correct. No new array→slice + * store cgen, and the borrow header is byte-identical across stages. + * + * Mutates `expr` IN PLACE: the original array expr moves into a fresh base + * node (keeping its stamped array type for cgen's esz/alen), and `expr` + * becomes the N_SLICE — preserving the sibling link so a desugared + * call-arg keeps its place in the argument list. Self-guards on shape, so + * the four acceptance sites can call it unconditionally; it no-ops unless + * the dst is a slice and the src an array with an exactly-matching + * element. */ +static void +desugar_arrayslice(Checker *c, Type *dst, Node *expr) +{ + if (dst == NULL || expr == NULL || expr->type == NULL) + return; + Type *du = (dst->kind == TY_NAMED) ? dst->under : dst; + Type *su = (expr->type->kind == TY_NAMED) ? expr->type->under + : expr->type; + if (du == NULL || su == NULL || + du->kind != TY_SLICE || su->kind != TY_ARRAY) + return; + if (su->alen == SIZE_UNDEFINED || !type_eq(du->sub, su->sub)) + return; + Node *base = newnode(c->a, expr->kind, expr->pos); + Node *next = expr->next; + *base = *expr; + base->next = NULL; + memset(expr, 0, sizeof *expr); + expr->kind = N_SLICE; + expr->pos = base->pos; + expr->next = next; + expr->lhs = base; /* sliced base; lo/hi NULL → 0 : len(arr) */ + expr->type = type_slice(c->a, su->sub); +} + static Type * cbinop(Checker *c, Node *n) { @@ -1483,6 +1523,8 @@ cexpr(Checker *c, Node *n) && !assignable_addrfn(c, p->type, a)) err(c, a->pos, "argument type %s not assignable to %s", type_name(c->a, at), type_name(c->a, p->type)); + /* #258: `f(arr)` borrows the array as a full slice. */ + desugar_arrayslice(c, p->type, a); p = p->next; } if (p != NULL && !p->variadic) @@ -1510,6 +1552,8 @@ cexpr(Checker *c, Node *n) !assignable_addrfn(c, l, n->rhs)) err(c, n->pos, "cannot assign %s to %s", type_name(c->a, r), type_name(c->a, l)); + /* #258: `s = arr` borrows the array as a full slice. */ + desugar_arrayslice(c, l, n->rhs); return n->type = l; } case N_STRUCTLIT: { @@ -1904,6 +1948,8 @@ clet(Checker *c, Node *n) type_name(c->a, initt), type_name(c->a, declared)); /* #104 fold-2: `let x: f32 = 1.0` — narrow the init literal to f32. */ coerce_floatlit(n->rhs, declared); + /* #258: `let s: []T = arr` borrows the array as a full slice. */ + desugar_arrayslice(c, declared, n->rhs); n->type = t; if (n->str && n->str[0]) { check_module_shadow(c, n->str, n->pos, "let"); @@ -1945,6 +1991,8 @@ cstmt(Checker *c, Node *n) type_name(c->a, rt), type_name(c->a, c->ret)); /* #104 fold-2: `fn g() f32 = { return 1.0; }` — narrow to f32. */ coerce_floatlit(n->lhs, c->ret); + /* #258: `return arr` borrows the array as a full slice. */ + desugar_arrayslice(c, c->ret, n->lhs); break; } case N_IF: { diff --git a/cmd/wcc/type.c b/cmd/wcc/type.c index 72c8597b..3a449bae 100644 --- a/cmd/wcc/type.c +++ b/cmd/wcc/type.c @@ -386,6 +386,24 @@ type_assignable(Type *dst, Type *src) return pa == NULL && pb == NULL; } + /* #258: implicit [N]T → []T array-to-slice borrow. Hare admits an + * array with a DEFINED length wherever its element slice is expected + * — assign / return / call-arg / init alike (ref/harec/src/types.c: + * 1080-1097, the SLICE-dst arm). The checker accepts it here; the + * acceptance sites (clet / N_ASSIGN / call-arg gather / N_RETURN) + * then DESUGAR the array expr to an explicit full slice `arr[0:len + * (arr)]` via desugar_arrayslice, reusing the existing slice cgen so + * there is ZERO new array→slice store and the borrow header + * {.ptr=&arr[0], .len=N, .cap=N} is byte-identical across stages. + * Element types must match exactly — no element decay. */ + { + Type *du = (dst->kind == TY_NAMED) ? dst->under : dst; + Type *su = (src->kind == TY_NAMED) ? src->under : src; + if (du && su && du->kind == TY_SLICE && su->kind == TY_ARRAY && + su->alen != SIZE_UNDEFINED && type_eq(du->sub, su->sub)) + return 1; + } + /* #108(c): opaque is a type-erasure sink. Any pointer is assignable * to *opaque, and any slice to []opaque — the universal void-pointer * and erased slice. harec type_is_assignable: ptr→*opaque at ref/harec/src/ @@ -394,13 +412,11 @@ type_assignable(Type *dst, Type *src) * (to_secondary->storage == STORAGE_OPAQUE) return true;`). * * Array→[]opaque (harec's STORAGE_POINTER-to-array and array→slice - * decay, types.c:1080-1099) is deliberately EXCLUDED: ww has no - * implicit array→slice conversion for any element type (`let s: - * []i32 = a` is rejected too — a slice is built only via an explicit - * `a[0:n]` op), so there is no array→slice-header cgen. Accepting - * array→[]opaque alone would assign a fat array local into a 24-byte - * slot with no decay — a silent miscompile (rule 7). sort's caller - * passes a slice, so slice→[]opaque is the only shape it needs. + * decay, types.c:1080-1099) stays EXCLUDED here: the #258 arm above + * desugars a concrete-element borrow only on an EXACT element match, + * and this arm fires only when dst and src share a kind (ptr→ptr, + * slice→slice), so an array reaches []opaque only after an explicit + * `a[0:n]` slice. ww-stricter than Hare; documented divergence. * * Both rules fire only when the destination element is opaque, so * they are inert on the opaque-free selfhost corpus. */ diff --git a/selfhost/cmd/w6c/main.combined.ww b/selfhost/cmd/w6c/main.combined.ww index 5c18434a..3a437d7c 100644 --- a/selfhost/cmd/w6c/main.combined.ww +++ b/selfhost/cmd/w6c/main.combined.ww @@ -11020,6 +11020,16 @@ fn resolvewalk(c: *checker, n: *node) void = { // are not value-typed nodes; their expression children get stamped on // the recursive descent into them. Type-expression kinds (N_T*) are // covered separately by the tinfofornode block above. + // #258: desugar an array arg/rhs into an implicit full slice at the + // call-arg and assignment contexts (let / return drive their own + // desugar in checkletassign / checkretassign). Placed post-child-walk + // so arg/operand types are stamped, and before the end-dispatch + // exprtype below so a regular N_CALL is still an N_CALL (not folded to + // an N_INTLIT by the size/align intercept). Mirrors cstage's post- + // order cexpr desugar at the call-arg / N_ASSIGN sites. + if (k == nkind.N_CALL) { desugarcallargs(c, n); }; + if (k == nkind.N_ASSIGN) { checkassign(c, n); }; + if (k == nkind.N_INTLIT || k == nkind.N_FLOATLIT || k == nkind.N_STRLIT || k == nkind.N_RUNELIT || k == nkind.N_TRUE || k == nkind.N_FALSE || @@ -13618,6 +13628,19 @@ fn isassignable(c: *checker, dst: *node, src: *node, confident: *bool) bool = { if (du == nil) { *confident = false; return true; }; if (su == nil) { *confident = false; return true; }; if (typeeqast(du, su)) { return true; }; + // #258: implicit [N]T -> []T array-to-slice borrow. Hare admits an + // array with a defined length wherever its element slice is expected + // (ref/harec/src/types.c:1080-1097, the SLICE-dst arm). Element types + // must match exactly — no element decay; a mismatch is a CONFIDENT + // reject (mirror cstage type.c type_assignable's #258 arm + fallthrough + // to 0). The acceptance sites then desugar the array expr to an + // explicit full slice via desugararrayslice; cgen is untouched. + if (du.kind == nkind.N_TSLICE) { + if (su.kind == nkind.N_TARRAY) { + if (typeeqast(du.lhs, su.lhs)) { return true; }; + return false; + }; + }; // untyped numeric → any numeric named type. if (isuntypedint(su)) { if (isnumerictname(du)) { return true; }; @@ -14114,6 +14137,139 @@ fn checkarrlitfits(c: *checker, arrtn: *node, rhs: *node) void = { }; }; +// desugararrayslice — #258. The single shared lowering for the implicit +// [N]T -> []T borrow. isassignable already admits an array with a defined +// length into a matching []T slot (see isassignable's #258 arm); here we +// rewrite the array expr to the explicit full slice `arr[0:len(arr)]` (an +// N_SLICE over the array base), reusing the existing slice cgen — #252/ +// #257/#135 made array bases (incl struct-field arrays) correct. No new +// array->slice store cgen; pushargsrev / cgslice / cglet already lower an +// N_SLICE identically to cstage, so the borrow header is byte-id across +// stages. Twin of cstage cmd/wcc/check.c desugar_arrayslice. +// +// Returns the (possibly new) node for the caller's tree slot: `val` +// unchanged when the shape doesn't match, else a fresh N_SLICE whose base +// is `val` (which keeps its stamped array type_). The original sibling +// link transfers to the N_SLICE so a desugared call-arg keeps its place. +fn desugararrayslice(c: *checker, dsttn: *node, srctn: *node, val: *node) *node = { + if (dsttn == nil) { return val; }; + if (srctn == nil) { return val; }; + if (val == nil) { return val; }; + let du: *node = resolvealias(c, unwrapbang(dsttn)); + let su: *node = resolvealias(c, unwrapbang(srctn)); + if (du == nil) { return val; }; + if (su == nil) { return val; }; + if (du.kind != nkind.N_TSLICE) { return val; }; + if (su.kind != nkind.N_TARRAY) { return val; }; + if (!typeeqast(du.lhs, su.lhs)) { return val; }; + let sl: *node = newnode(nkind.N_SLICE, val.file, val.line, val.col); + sl.lhs = val; // sliced base; lo (.rhs) / hi (.cond) nil → 0 : len(arr) + let slt: *node = newnode(nkind.N_TSLICE, "", 0, 0); + slt.lhs = su.lhs; + sl.type_ = tinfofornode(c, slt): *void; + sl.next = val.next; + val.next = nil; + return sl; +}; + +// calleefndecl — resolve a call's callee to its fn-decl node so the +// arg/param lockstep (desugarcallargs) can read declared param types. +// Mirrors exprtype's N_CALL resolution (bare-leaf via scopelookupprefer, +// module-qualified via the SK_USE receiver). nil for builtins / fn-value +// callees — they have no declared param list to drive the #258 desugar, +// and the selfhost corpus has no array→slice arg there anyway. +fn calleefndecl(c: *checker, callee: *node) *node = { + if (callee == nil) { return nil; }; + if (callee.kind == nkind.N_IDENT) { + let s: *sym = scopelookupprefer(c.cur, c.curmod, callee.str); + if (s != nil) { + if (s.skind == skind.SK_FN) { return s.decl; }; + }; + return nil; + }; + if (callee.kind == nkind.N_DOT) { + if (callee.lhs != nil) { + if (callee.lhs.kind == nkind.N_IDENT) { + let ms: *sym = scopelookupprefer(c.cur, c.curmod, callee.lhs.str); + if (ms != nil && ms.skind != skind.SK_USE) { + let mu: *sym = scopelookupuselocal(ms.scope, callee.lhs.str); + if (mu != nil) { ms = mu; }; + }; + if (ms != nil) { + if (ms.skind == skind.SK_USE) { + let fs: *sym = scopelookupinmodule(c.cur, callee.lhs.str, callee.str); + if (fs != nil) { + if (fs.skind == skind.SK_FN) { return fs.decl; }; + }; + }; + }; + }; + }; + }; + return nil; +}; + +// desugarcallargs — #258 at the call-arg context. Lockstep the call's +// args against the callee's declared params and desugar an array arg +// passed where a []T param is expected. Mirrors cstage cmd/wcc/check.c's +// non-variadic call-arg arm. Variadic (`T...`) slots are skipped (the +// arg flows into the gather as an element, not the slice itself). +fn desugarcallargs(c: *checker, n: *node) void = { + if (n == nil) { return; }; + let decl: *node = calleefndecl(c, n.lhs); + if (decl == nil) { return; }; + let param: *node = decl.list; + let prev: *node = nil; + let a: *node = n.list; + for (a != nil) { + let nexta: *node = a.next; + if (param != nil) { + if (param.kind == nkind.N_PARAM) { + if (param.op != tkind.TK_ELLIPSIS) { + let atype: *node = exprtype(c, a, nil); + // #258: an array arg into a []T param with a + // MISMATCHED element is not a borrow — loud reject, + // mirror cstage's call-arg type_assignable failure. + // Gated to the array→slice-param shape so wwstage's + // broader call-arg leniency (it runs no general + // param typecheck) is untouched. + let pu: *node = resolvealias(c, unwrapbang(param.lhs)); + let au: *node = resolvealias(c, unwrapbang(atype)); + if (pu != nil) { if (au != nil) { + if (pu.kind == nkind.N_TSLICE) { if (au.kind == nkind.N_TARRAY) { + if (!typeeqast(pu.lhs, au.lhs)) { + errnotassign(c, param.lhs, atype, "argument"); + }; + }; }; + }; }; + let rep: *node = desugararrayslice(c, param.lhs, atype, a); + if (rep != a) { + if (prev == nil) { n.list = rep; } else { prev.next = rep; }; + a = rep; + }; + }; + if (param.op != tkind.TK_ELLIPSIS) { param = param.next; }; + }; + }; + prev = a; + a = nexta; + }; +}; + +// checkassign — #258 at the assignment context. wwstage runs no other +// N_ASSIGN typecheck (cstage's lives in cexpr); this exists solely to +// route an array→slice rhs through the shared desugar so w6c_ww emits +// the same borrow as w6c (rule-10). No error diagnostics — cstage gates +// the shape. +fn checkassign(c: *checker, n: *node) void = { + if (n == nil) { return; }; + if (n.lhs == nil) { return; }; + if (n.rhs == nil) { return; }; + let ltn: *node = exprtype(c, n.lhs, nil); + let rtn: *node = exprtype(c, n.rhs, nil); + n.rhs = desugararrayslice(c, ltn, rtn, n.rhs); +}; + fn checkletassign(c: *checker, n: *node) void = { if (n == nil) { return; }; if (n.rhs == nil) { return; }; // no init @@ -14205,6 +14361,8 @@ fn checkletassign(c: *checker, n: *node) void = { if (!ok) { if (assignableaddrfn(c, n.lhs, n.rhs)) { ok = true; }; }; if (!conf) { return; }; if (!ok) { errnotassign(c, n.lhs, src, "let"); }; + // #258: `let s: []T = arr` borrows the array as a full slice. + n.rhs = desugararrayslice(c, n.lhs, src, n.rhs); }; fn checkretassign(c: *checker, n: *node) void = { @@ -14224,6 +14382,8 @@ fn checkretassign(c: *checker, n: *node) void = { if (!ok) { if (assignableaddrfn(c, c.fnret, n.lhs)) { ok = true; }; }; if (!conf) { return; }; if (!ok) { errnotassign(c, c.fnret, src, "return"); }; + // #258: `return arr` borrows the array as a full slice. + n.lhs = desugararrayslice(c, c.fnret, src, n.lhs); }; // ---- is / as validity ------------------------------------------------ diff --git a/selfhost/cmd/wcc/check.ww b/selfhost/cmd/wcc/check.ww index 3b1df141..bcb7f218 100644 --- a/selfhost/cmd/wcc/check.ww +++ b/selfhost/cmd/wcc/check.ww @@ -615,6 +615,16 @@ fn resolvewalk(c: *checker, n: *node) void = { // are not value-typed nodes; their expression children get stamped on // the recursive descent into them. Type-expression kinds (N_T*) are // covered separately by the tinfofornode block above. + // #258: desugar an array arg/rhs into an implicit full slice at the + // call-arg and assignment contexts (let / return drive their own + // desugar in checkletassign / checkretassign). Placed post-child-walk + // so arg/operand types are stamped, and before the end-dispatch + // exprtype below so a regular N_CALL is still an N_CALL (not folded to + // an N_INTLIT by the size/align intercept). Mirrors cstage's post- + // order cexpr desugar at the call-arg / N_ASSIGN sites. + if (k == nkind.N_CALL) { desugarcallargs(c, n); }; + if (k == nkind.N_ASSIGN) { checkassign(c, n); }; + if (k == nkind.N_INTLIT || k == nkind.N_FLOATLIT || k == nkind.N_STRLIT || k == nkind.N_RUNELIT || k == nkind.N_TRUE || k == nkind.N_FALSE || @@ -3213,6 +3223,19 @@ fn isassignable(c: *checker, dst: *node, src: *node, confident: *bool) bool = { if (du == nil) { *confident = false; return true; }; if (su == nil) { *confident = false; return true; }; if (typeeqast(du, su)) { return true; }; + // #258: implicit [N]T -> []T array-to-slice borrow. Hare admits an + // array with a defined length wherever its element slice is expected + // (ref/harec/src/types.c:1080-1097, the SLICE-dst arm). Element types + // must match exactly — no element decay; a mismatch is a CONFIDENT + // reject (mirror cstage type.c type_assignable's #258 arm + fallthrough + // to 0). The acceptance sites then desugar the array expr to an + // explicit full slice via desugararrayslice; cgen is untouched. + if (du.kind == nkind.N_TSLICE) { + if (su.kind == nkind.N_TARRAY) { + if (typeeqast(du.lhs, su.lhs)) { return true; }; + return false; + }; + }; // untyped numeric → any numeric named type. if (isuntypedint(su)) { if (isnumerictname(du)) { return true; }; @@ -3709,6 +3732,139 @@ fn checkarrlitfits(c: *checker, arrtn: *node, rhs: *node) void = { }; }; +// desugararrayslice — #258. The single shared lowering for the implicit +// [N]T -> []T borrow. isassignable already admits an array with a defined +// length into a matching []T slot (see isassignable's #258 arm); here we +// rewrite the array expr to the explicit full slice `arr[0:len(arr)]` (an +// N_SLICE over the array base), reusing the existing slice cgen — #252/ +// #257/#135 made array bases (incl struct-field arrays) correct. No new +// array->slice store cgen; pushargsrev / cgslice / cglet already lower an +// N_SLICE identically to cstage, so the borrow header is byte-id across +// stages. Twin of cstage cmd/wcc/check.c desugar_arrayslice. +// +// Returns the (possibly new) node for the caller's tree slot: `val` +// unchanged when the shape doesn't match, else a fresh N_SLICE whose base +// is `val` (which keeps its stamped array type_). The original sibling +// link transfers to the N_SLICE so a desugared call-arg keeps its place. +fn desugararrayslice(c: *checker, dsttn: *node, srctn: *node, val: *node) *node = { + if (dsttn == nil) { return val; }; + if (srctn == nil) { return val; }; + if (val == nil) { return val; }; + let du: *node = resolvealias(c, unwrapbang(dsttn)); + let su: *node = resolvealias(c, unwrapbang(srctn)); + if (du == nil) { return val; }; + if (su == nil) { return val; }; + if (du.kind != nkind.N_TSLICE) { return val; }; + if (su.kind != nkind.N_TARRAY) { return val; }; + if (!typeeqast(du.lhs, su.lhs)) { return val; }; + let sl: *node = newnode(nkind.N_SLICE, val.file, val.line, val.col); + sl.lhs = val; // sliced base; lo (.rhs) / hi (.cond) nil → 0 : len(arr) + let slt: *node = newnode(nkind.N_TSLICE, "", 0, 0); + slt.lhs = su.lhs; + sl.type_ = tinfofornode(c, slt): *void; + sl.next = val.next; + val.next = nil; + return sl; +}; + +// calleefndecl — resolve a call's callee to its fn-decl node so the +// arg/param lockstep (desugarcallargs) can read declared param types. +// Mirrors exprtype's N_CALL resolution (bare-leaf via scopelookupprefer, +// module-qualified via the SK_USE receiver). nil for builtins / fn-value +// callees — they have no declared param list to drive the #258 desugar, +// and the selfhost corpus has no array→slice arg there anyway. +fn calleefndecl(c: *checker, callee: *node) *node = { + if (callee == nil) { return nil; }; + if (callee.kind == nkind.N_IDENT) { + let s: *sym = scopelookupprefer(c.cur, c.curmod, callee.str); + if (s != nil) { + if (s.skind == skind.SK_FN) { return s.decl; }; + }; + return nil; + }; + if (callee.kind == nkind.N_DOT) { + if (callee.lhs != nil) { + if (callee.lhs.kind == nkind.N_IDENT) { + let ms: *sym = scopelookupprefer(c.cur, c.curmod, callee.lhs.str); + if (ms != nil && ms.skind != skind.SK_USE) { + let mu: *sym = scopelookupuselocal(ms.scope, callee.lhs.str); + if (mu != nil) { ms = mu; }; + }; + if (ms != nil) { + if (ms.skind == skind.SK_USE) { + let fs: *sym = scopelookupinmodule(c.cur, callee.lhs.str, callee.str); + if (fs != nil) { + if (fs.skind == skind.SK_FN) { return fs.decl; }; + }; + }; + }; + }; + }; + }; + return nil; +}; + +// desugarcallargs — #258 at the call-arg context. Lockstep the call's +// args against the callee's declared params and desugar an array arg +// passed where a []T param is expected. Mirrors cstage cmd/wcc/check.c's +// non-variadic call-arg arm. Variadic (`T...`) slots are skipped (the +// arg flows into the gather as an element, not the slice itself). +fn desugarcallargs(c: *checker, n: *node) void = { + if (n == nil) { return; }; + let decl: *node = calleefndecl(c, n.lhs); + if (decl == nil) { return; }; + let param: *node = decl.list; + let prev: *node = nil; + let a: *node = n.list; + for (a != nil) { + let nexta: *node = a.next; + if (param != nil) { + if (param.kind == nkind.N_PARAM) { + if (param.op != tkind.TK_ELLIPSIS) { + let atype: *node = exprtype(c, a, nil); + // #258: an array arg into a []T param with a + // MISMATCHED element is not a borrow — loud reject, + // mirror cstage's call-arg type_assignable failure. + // Gated to the array→slice-param shape so wwstage's + // broader call-arg leniency (it runs no general + // param typecheck) is untouched. + let pu: *node = resolvealias(c, unwrapbang(param.lhs)); + let au: *node = resolvealias(c, unwrapbang(atype)); + if (pu != nil) { if (au != nil) { + if (pu.kind == nkind.N_TSLICE) { if (au.kind == nkind.N_TARRAY) { + if (!typeeqast(pu.lhs, au.lhs)) { + errnotassign(c, param.lhs, atype, "argument"); + }; + }; }; + }; }; + let rep: *node = desugararrayslice(c, param.lhs, atype, a); + if (rep != a) { + if (prev == nil) { n.list = rep; } else { prev.next = rep; }; + a = rep; + }; + }; + if (param.op != tkind.TK_ELLIPSIS) { param = param.next; }; + }; + }; + prev = a; + a = nexta; + }; +}; + +// checkassign — #258 at the assignment context. wwstage runs no other +// N_ASSIGN typecheck (cstage's lives in cexpr); this exists solely to +// route an array→slice rhs through the shared desugar so w6c_ww emits +// the same borrow as w6c (rule-10). No error diagnostics — cstage gates +// the shape. +fn checkassign(c: *checker, n: *node) void = { + if (n == nil) { return; }; + if (n.lhs == nil) { return; }; + if (n.rhs == nil) { return; }; + let ltn: *node = exprtype(c, n.lhs, nil); + let rtn: *node = exprtype(c, n.rhs, nil); + n.rhs = desugararrayslice(c, ltn, rtn, n.rhs); +}; + fn checkletassign(c: *checker, n: *node) void = { if (n == nil) { return; }; if (n.rhs == nil) { return; }; // no init @@ -3800,6 +3956,8 @@ fn checkletassign(c: *checker, n: *node) void = { if (!ok) { if (assignableaddrfn(c, n.lhs, n.rhs)) { ok = true; }; }; if (!conf) { return; }; if (!ok) { errnotassign(c, n.lhs, src, "let"); }; + // #258: `let s: []T = arr` borrows the array as a full slice. + n.rhs = desugararrayslice(c, n.lhs, src, n.rhs); }; fn checkretassign(c: *checker, n: *node) void = { @@ -3819,6 +3977,8 @@ fn checkretassign(c: *checker, n: *node) void = { if (!ok) { if (assignableaddrfn(c, c.fnret, n.lhs)) { ok = true; }; }; if (!conf) { return; }; if (!ok) { errnotassign(c, c.fnret, src, "return"); }; + // #258: `return arr` borrows the array as a full slice. + n.lhs = desugararrayslice(c, c.fnret, src, n.lhs); }; // ---- is / as validity ------------------------------------------------ diff --git a/selfhost/cmd/wwdump/main.combined.ww b/selfhost/cmd/wwdump/main.combined.ww index b3491b1b..263cddae 100644 --- a/selfhost/cmd/wwdump/main.combined.ww +++ b/selfhost/cmd/wwdump/main.combined.ww @@ -11020,6 +11020,16 @@ fn resolvewalk(c: *checker, n: *node) void = { // are not value-typed nodes; their expression children get stamped on // the recursive descent into them. Type-expression kinds (N_T*) are // covered separately by the tinfofornode block above. + // #258: desugar an array arg/rhs into an implicit full slice at the + // call-arg and assignment contexts (let / return drive their own + // desugar in checkletassign / checkretassign). Placed post-child-walk + // so arg/operand types are stamped, and before the end-dispatch + // exprtype below so a regular N_CALL is still an N_CALL (not folded to + // an N_INTLIT by the size/align intercept). Mirrors cstage's post- + // order cexpr desugar at the call-arg / N_ASSIGN sites. + if (k == nkind.N_CALL) { desugarcallargs(c, n); }; + if (k == nkind.N_ASSIGN) { checkassign(c, n); }; + if (k == nkind.N_INTLIT || k == nkind.N_FLOATLIT || k == nkind.N_STRLIT || k == nkind.N_RUNELIT || k == nkind.N_TRUE || k == nkind.N_FALSE || @@ -13618,6 +13628,19 @@ fn isassignable(c: *checker, dst: *node, src: *node, confident: *bool) bool = { if (du == nil) { *confident = false; return true; }; if (su == nil) { *confident = false; return true; }; if (typeeqast(du, su)) { return true; }; + // #258: implicit [N]T -> []T array-to-slice borrow. Hare admits an + // array with a defined length wherever its element slice is expected + // (ref/harec/src/types.c:1080-1097, the SLICE-dst arm). Element types + // must match exactly — no element decay; a mismatch is a CONFIDENT + // reject (mirror cstage type.c type_assignable's #258 arm + fallthrough + // to 0). The acceptance sites then desugar the array expr to an + // explicit full slice via desugararrayslice; cgen is untouched. + if (du.kind == nkind.N_TSLICE) { + if (su.kind == nkind.N_TARRAY) { + if (typeeqast(du.lhs, su.lhs)) { return true; }; + return false; + }; + }; // untyped numeric → any numeric named type. if (isuntypedint(su)) { if (isnumerictname(du)) { return true; }; @@ -14114,6 +14137,139 @@ fn checkarrlitfits(c: *checker, arrtn: *node, rhs: *node) void = { }; }; +// desugararrayslice — #258. The single shared lowering for the implicit +// [N]T -> []T borrow. isassignable already admits an array with a defined +// length into a matching []T slot (see isassignable's #258 arm); here we +// rewrite the array expr to the explicit full slice `arr[0:len(arr)]` (an +// N_SLICE over the array base), reusing the existing slice cgen — #252/ +// #257/#135 made array bases (incl struct-field arrays) correct. No new +// array->slice store cgen; pushargsrev / cgslice / cglet already lower an +// N_SLICE identically to cstage, so the borrow header is byte-id across +// stages. Twin of cstage cmd/wcc/check.c desugar_arrayslice. +// +// Returns the (possibly new) node for the caller's tree slot: `val` +// unchanged when the shape doesn't match, else a fresh N_SLICE whose base +// is `val` (which keeps its stamped array type_). The original sibling +// link transfers to the N_SLICE so a desugared call-arg keeps its place. +fn desugararrayslice(c: *checker, dsttn: *node, srctn: *node, val: *node) *node = { + if (dsttn == nil) { return val; }; + if (srctn == nil) { return val; }; + if (val == nil) { return val; }; + let du: *node = resolvealias(c, unwrapbang(dsttn)); + let su: *node = resolvealias(c, unwrapbang(srctn)); + if (du == nil) { return val; }; + if (su == nil) { return val; }; + if (du.kind != nkind.N_TSLICE) { return val; }; + if (su.kind != nkind.N_TARRAY) { return val; }; + if (!typeeqast(du.lhs, su.lhs)) { return val; }; + let sl: *node = newnode(nkind.N_SLICE, val.file, val.line, val.col); + sl.lhs = val; // sliced base; lo (.rhs) / hi (.cond) nil → 0 : len(arr) + let slt: *node = newnode(nkind.N_TSLICE, "", 0, 0); + slt.lhs = su.lhs; + sl.type_ = tinfofornode(c, slt): *void; + sl.next = val.next; + val.next = nil; + return sl; +}; + +// calleefndecl — resolve a call's callee to its fn-decl node so the +// arg/param lockstep (desugarcallargs) can read declared param types. +// Mirrors exprtype's N_CALL resolution (bare-leaf via scopelookupprefer, +// module-qualified via the SK_USE receiver). nil for builtins / fn-value +// callees — they have no declared param list to drive the #258 desugar, +// and the selfhost corpus has no array→slice arg there anyway. +fn calleefndecl(c: *checker, callee: *node) *node = { + if (callee == nil) { return nil; }; + if (callee.kind == nkind.N_IDENT) { + let s: *sym = scopelookupprefer(c.cur, c.curmod, callee.str); + if (s != nil) { + if (s.skind == skind.SK_FN) { return s.decl; }; + }; + return nil; + }; + if (callee.kind == nkind.N_DOT) { + if (callee.lhs != nil) { + if (callee.lhs.kind == nkind.N_IDENT) { + let ms: *sym = scopelookupprefer(c.cur, c.curmod, callee.lhs.str); + if (ms != nil && ms.skind != skind.SK_USE) { + let mu: *sym = scopelookupuselocal(ms.scope, callee.lhs.str); + if (mu != nil) { ms = mu; }; + }; + if (ms != nil) { + if (ms.skind == skind.SK_USE) { + let fs: *sym = scopelookupinmodule(c.cur, callee.lhs.str, callee.str); + if (fs != nil) { + if (fs.skind == skind.SK_FN) { return fs.decl; }; + }; + }; + }; + }; + }; + }; + return nil; +}; + +// desugarcallargs — #258 at the call-arg context. Lockstep the call's +// args against the callee's declared params and desugar an array arg +// passed where a []T param is expected. Mirrors cstage cmd/wcc/check.c's +// non-variadic call-arg arm. Variadic (`T...`) slots are skipped (the +// arg flows into the gather as an element, not the slice itself). +fn desugarcallargs(c: *checker, n: *node) void = { + if (n == nil) { return; }; + let decl: *node = calleefndecl(c, n.lhs); + if (decl == nil) { return; }; + let param: *node = decl.list; + let prev: *node = nil; + let a: *node = n.list; + for (a != nil) { + let nexta: *node = a.next; + if (param != nil) { + if (param.kind == nkind.N_PARAM) { + if (param.op != tkind.TK_ELLIPSIS) { + let atype: *node = exprtype(c, a, nil); + // #258: an array arg into a []T param with a + // MISMATCHED element is not a borrow — loud reject, + // mirror cstage's call-arg type_assignable failure. + // Gated to the array→slice-param shape so wwstage's + // broader call-arg leniency (it runs no general + // param typecheck) is untouched. + let pu: *node = resolvealias(c, unwrapbang(param.lhs)); + let au: *node = resolvealias(c, unwrapbang(atype)); + if (pu != nil) { if (au != nil) { + if (pu.kind == nkind.N_TSLICE) { if (au.kind == nkind.N_TARRAY) { + if (!typeeqast(pu.lhs, au.lhs)) { + errnotassign(c, param.lhs, atype, "argument"); + }; + }; }; + }; }; + let rep: *node = desugararrayslice(c, param.lhs, atype, a); + if (rep != a) { + if (prev == nil) { n.list = rep; } else { prev.next = rep; }; + a = rep; + }; + }; + if (param.op != tkind.TK_ELLIPSIS) { param = param.next; }; + }; + }; + prev = a; + a = nexta; + }; +}; + +// checkassign — #258 at the assignment context. wwstage runs no other +// N_ASSIGN typecheck (cstage's lives in cexpr); this exists solely to +// route an array→slice rhs through the shared desugar so w6c_ww emits +// the same borrow as w6c (rule-10). No error diagnostics — cstage gates +// the shape. +fn checkassign(c: *checker, n: *node) void = { + if (n == nil) { return; }; + if (n.lhs == nil) { return; }; + if (n.rhs == nil) { return; }; + let ltn: *node = exprtype(c, n.lhs, nil); + let rtn: *node = exprtype(c, n.rhs, nil); + n.rhs = desugararrayslice(c, ltn, rtn, n.rhs); +}; + fn checkletassign(c: *checker, n: *node) void = { if (n == nil) { return; }; if (n.rhs == nil) { return; }; // no init @@ -14205,6 +14361,8 @@ fn checkletassign(c: *checker, n: *node) void = { if (!ok) { if (assignableaddrfn(c, n.lhs, n.rhs)) { ok = true; }; }; if (!conf) { return; }; if (!ok) { errnotassign(c, n.lhs, src, "let"); }; + // #258: `let s: []T = arr` borrows the array as a full slice. + n.rhs = desugararrayslice(c, n.lhs, src, n.rhs); }; fn checkretassign(c: *checker, n: *node) void = { @@ -14224,6 +14382,8 @@ fn checkretassign(c: *checker, n: *node) void = { if (!ok) { if (assignableaddrfn(c, c.fnret, n.lhs)) { ok = true; }; }; if (!conf) { return; }; if (!ok) { errnotassign(c, c.fnret, src, "return"); }; + // #258: `return arr` borrows the array as a full slice. + n.lhs = desugararrayslice(c, c.fnret, src, n.lhs); }; // ---- is / as validity ------------------------------------------------ diff --git a/test/wcc/953_arraytoslice_run.c b/test/wcc/953_arraytoslice_run.c new file mode 100644 index 00000000..50f7a2c6 --- /dev/null +++ b/test/wcc/953_arraytoslice_run.c @@ -0,0 +1,272 @@ +/* + * 953_arraytoslice_run — runtime + byte-id + reject net for #258: the + * implicit [N]T -> []T array-to-slice BORROW. Hare admits an array with a + * defined length wherever its element slice is expected (assign / return / + * call-arg / init), as a borrow — `.ptr = &arr[0], .len = N, .cap = N` + * (ref/harec/src/types.c:1080-1097, the SLICE-dst arm). ww previously + * REJECTED it everywhere (cmd/wcc/type.c:#108(c) exclusion); base64 + * worked around the gap with explicit `a[0:n]` slices. + * + * Fix (DESUGAR, checker-only, ZERO new cgen): type_assignable / + * isassignable admit array→slice on an exact element match; the four + * acceptance sites (clet / N_ASSIGN / call-arg gather / N_RETURN) then + * rewrite the array expr to the explicit full slice `arr[0:len(arr)]` (an + * N_SLICE over the array base) via the shared desugar_arrayslice / + * desugararrayslice helper. cgen is untouched — the existing slice + * lowering (#252/#257/#135 made array bases, incl struct-field arrays, + * correct) materialises the borrow header, identically in both stages. + * + * Positive rows: cstage `ww build` + run for exit code (the four contexts + * + a BORROW proof — mutate through the slice, observe the change in the + * backing array, i.e. alias not copy), then w6c vs w6c_ww `.s` cmp for the + * rule-10 byte-id gate (all four contexts emit byte-identical asm). + * - let_i32 let-init borrow `let s: []i32 = a`, s[2] → 33 + * - let_u8 let-init borrow, u8 element, s[3] → 66 + * - assign_i32 assignment borrow `s = a` (s was a[0:1]), s[3] → 4 + * - callarg_i32 call-arg borrow `sum(a)` (sums all elements) → 65 + * - callarg_u8 call-arg borrow, u8 element → 70 + * - return_i32 return borrow `return g` (g a global array) → 17 + * - borrow_i32 mutate s[2]=55 through the slice, read a[2] → 55 + * + * Reject rows (cs==ww symmetric loud-reject): an element-type MISMATCH + * ([4]i32 -> []u8) is NOT a borrow — both stages must refuse it. w6c and + * w6c_ww are each run directly and must exit non-zero (the desugar's + * element-exact gate; type_assignable / isassignable fall through to a + * confident reject). + * - mismatch_let let s: []u8 = a where a:[4]i32 → both reject + * - mismatch_callarg f(a) where f wants []u8, a:[4]i32 → both reject + */ +#include +#include +#include +#include +#include +#include + +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"), *fb = fopen(b, "rb"); + if (fa == NULL || fb == NULL) { + if (fa) fclose(fa); + if (fb) fclose(fb); + return -1; + } + int ca, cb, eq = 0; + do { + ca = fgetc(fa); + cb = fgetc(fb); + if (ca != cb) { eq = -1; break; } + } while (ca != EOF); + fclose(fa); + fclose(fb); + return eq; +} + +struct row { const char *label; const char *src; int want_exit; int reject; }; + +static const struct row rows[] = { + { "let_i32", + "package main;\n" + "export fn main() i32 = {\n" + " let a: [4]i32 = [11, 22, 33, 44];\n" + " let s: []i32 = a;\n" + " return s[2];\n" + "};\n", 33, 0 }, + { "let_u8", + "package main;\n" + "export fn main() i32 = {\n" + " let a: [4]u8 = [11u8, 22u8, 33u8, 66u8];\n" + " let s: []u8 = a;\n" + " return s[3]: i32;\n" + "};\n", 66, 0 }, + { "assign_i32", + "package main;\n" + "export fn main() i32 = {\n" + " let a: [4]i32 = [1, 2, 3, 4];\n" + " let s: []i32 = a[0:1];\n" + " s = a;\n" + " return s[3];\n" + "};\n", 4, 0 }, + { "callarg_i32", + "package main;\n" + "fn sum(s: []i32) i32 = {\n" + " let t: i32 = 0; let i: i32 = 0;\n" + " for (i < s.len) { t += s[i]; i += 1; };\n" + " return t;\n" + "};\n" + "export fn main() i32 = {\n" + " let a: [4]i32 = [10, 20, 30, 5];\n" + " return sum(a);\n" + "};\n", 65, 0 }, + { "callarg_u8", + "package main;\n" + "fn sum(s: []u8) i32 = {\n" + " let t: i32 = 0; let i: i32 = 0;\n" + " for (i < s.len) { t += s[i]: i32; i += 1; };\n" + " return t;\n" + "};\n" + "export fn main() i32 = {\n" + " let a: [3]u8 = [10u8, 20u8, 40u8];\n" + " return sum(a);\n" + "};\n", 70, 0 }, + { "return_i32", + "package main;\n" + "let g: [3]i32 = [7, 8, 9];\n" + "fn mk() []i32 = { return g; };\n" + "export fn main() i32 = {\n" + " let s: []i32 = mk();\n" + " return s[1] + s[2];\n" + "};\n", 17, 0 }, + { "borrow_i32", + "package main;\n" + "export fn main() i32 = {\n" + " let a: [4]i32 = [1, 2, 3, 4];\n" + " let s: []i32 = a;\n" + " s[2] = 55;\n" + " return a[2];\n" + "};\n", 55, 0 }, + /* Reject rows: element-type mismatch — both stages refuse. */ + { "mismatch_let", + "package main;\n" + "export fn main() i32 = {\n" + " let a: [4]i32 = [1, 2, 3, 4];\n" + " let s: []u8 = a;\n" + " return 0;\n" + "};\n", 0, 1 }, + { "mismatch_callarg", + "package main;\n" + "fn f(s: []u8) i32 = { return 0; };\n" + "export fn main() i32 = {\n" + " let a: [4]i32 = [1, 2, 3, 4];\n" + " return f(a);\n" + "};\n", 0, 1 }, + { NULL, NULL, 0, 0 }, +}; + +int +main(void) +{ + const char *bin = getenv("BIN"); + if (!bin) bin = "out/bin"; + char absbin[1024]; + if (bin[0] != '/') { + char cwd[1024]; + if (getcwd(cwd, sizeof cwd) == NULL) return 1; + snprintf(absbin, sizeof absbin, "%s/%s", cwd, bin); + bin = absbin; + } + + char w6c[1100], w6c_ww[1100]; + snprintf(w6c, sizeof w6c, "%s/w6c", bin); + snprintf(w6c_ww, sizeof w6c_ww, "%s/w6c_ww", bin); + if (access(w6c_ww, X_OK) != 0) { + fprintf(stderr, "arraytoslice: w6c_ww missing — cannot run the " + "cs==ww byte-id gate (the whole point of this test)\n"); + return 1; + } + + int n = 0, fail = 0; + for (int i = 0; rows[i].src; i++, n++) { + char src[64]; + snprintf(src, sizeof src, "/tmp/wwa2s_%d_%d.ww", getpid(), i); + FILE *f = fopen(src, "wb"); + if (f == NULL) { fail++; continue; } + fputs(rows[i].src, f); + fclose(f); + + char cs_s[64], ws_s[64]; + snprintf(cs_s, sizeof cs_s, "/tmp/wwa2s_%d_%d_cs.s", getpid(), i); + snprintf(ws_s, sizeof ws_s, "/tmp/wwa2s_%d_%d_ww.s", getpid(), i); + char cmd[2048]; + + if (rows[i].reject) { + /* Element mismatch — both stages must refuse (non-zero). */ + snprintf(cmd, sizeof cmd, "%s -o %s %s 2>/dev/null", + w6c, cs_s, src); + if (runwait(cmd) == 0) { + fprintf(stderr, "row[%s]: w6c ACCEPTED a " + "type-mismatch array→slice (must reject)\n", + rows[i].label); + fail++; + } + 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 ACCEPTED a " + "type-mismatch array→slice (must reject)\n", + rows[i].label); + fail++; + } + unlink(src); unlink(cs_s); unlink(ws_s); + continue; + } + + /* Positive row: cstage build + run for exit code. */ + char tmpdir[64]; + snprintf(tmpdir, sizeof tmpdir, "/tmp/wwa2s_%d_d_%d", + getpid(), i); + mkdir(tmpdir, 0755); + snprintf(cmd, sizeof cmd, "cd %s && %s/ww build %s", + tmpdir, bin, src); + if (runwait(cmd) != 0) { + fprintf(stderr, "row[%s]: cstage build failed\n", + rows[i].label); + fail++; + unlink(src); rmdir(tmpdir); + continue; + } + char outbin[128]; + const char *base = strrchr(src, '/'); + base = base ? base + 1 : src; + snprintf(outbin, sizeof outbin, "%s/%s", tmpdir, base); + char *dot = strrchr(outbin, '.'); + if (dot && strcmp(dot, ".ww") == 0) *dot = '\0'; + int got = runwait(outbin); + if (got != rows[i].want_exit) { + fprintf(stderr, "row[%s]: cstage exit %d, want %d\n", + rows[i].label, got, rows[i].want_exit); + fail++; + } + unlink(outbin); rmdir(tmpdir); + + /* rule-10 byte-id: w6c vs w6c_ww .s. */ + 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", rows[i].label); + fail++; unlink(src); continue; + } + 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", + rows[i].label); + fail++; unlink(src); unlink(cs_s); continue; + } + if (slurp_eq(cs_s, ws_s) != 0) { + fprintf(stderr, + "row[%s]: cstage/wwstage .s DIFFER (rule-10 " + "byte-id violation)\n", rows[i].label); + fail++; + } + unlink(src); unlink(cs_s); unlink(ws_s); + } + + if (fail) { + fprintf(stderr, "%d/%d array-to-slice tests failed\n", fail, n); + return 1; + } + printf("arraytoslice: %d/%d ok (cstage run + cs==ww byte-id + reject)\n", + n, n); + return 0; +}