Files
ww/test/wcc/684_arr_infer_len.c
Hojun-Cho 7ca32432b1 w6c+wcc/check: infer [_]T array length from initializer element count (fix #7)
`[_]T = [...]` (canonical Hare array-length inference) silently
miscompiled to a zero-length array: the parser already left the array
type's length child nil as the infer sentinel — distinct from an
explicit [N] — but neither checker stamped the real count, so `len(x)`
returned 0 with no diagnostic (rule-7 silent miscompile). Module-level
was worse on wwstage, where `x.len` on ANY global array (even an
explicit [N]) fell to the SB fallback and mis-emitted `MOVQ len(SB), AX`
(linker: undefined reference to len).

The length lives in the stamped TYPE and cgen already keys stride /
length / data-emission off it, so stamping the inferred count at the one
checker inference point closes it permanently (rob's #7 ruling):

  - check.c clet + module-level N_LET pass-2: count the initializer's
    elements and patch the array type's length (the Sym too, so a later
    x.len reads the inferred alen). No-init / non-array init can't infer
    -> loud error, never a silent zero-length array.
  - check.ww inferarraylen: the wwstage twin — stamp a synthesized
    N_INTLIT length child before resolvewalk caches the array tinfo;
    same loud-error rule. Idempotent for the module-level double-call.
  - cgenexpr.ww cgdot: the missing wwstage arm for a top-level [N]T
    global's .len / .ptr (cstage cgen.c:8011 already had it).
  - cgenutil.ww letslotsize: drop the now-redundant [_] slot-size
    intercept — a workaround for this very bug; the stamped length flows
    through the general slotsize path (rule 7).

Both stages converge byte-identical; new table-driven test 684 covers
[_]int/[_]str/[_]u8 local + module-level, len + element read-back,
dual-stage runtime + asm byte-id, plus three negative no-infer rows.
2026-06-03 18:44:39 +09:00

350 lines
9.6 KiB
C

/*
* 684_arr_infer_len — cstage and wwstage agree, byte-for-byte and at
* runtime, that a `[_]T = [...]` array infers its length from the
* initialiser's element count (task #7, a canonical Hare form).
*
* The bug: `[_]T` silently miscompiled to a zero-length array. The
* parser already left the array type's length child nil as the infer
* sentinel (distinct from an explicit `[N]`), but neither checker
* stamped the real count — so `len(x)` / `x.len` returned 0 with no
* diagnostic (rule-7 silent miscompile). Module-level was worse on
* wwstage: `x.len` on ANY global array (even explicit `[N]`) fell to
* the SB fallback and mis-emitted `MOVQ len(SB), AX` (linker:
* undefined reference to len).
*
* The fix (BOTH stages, converged byte-identical):
* - checker (cmd/wcc/check.c clet + module-level N_LET;
* selfhost/cmd/wcc/check.ww inferarraylen): count the array-literal
* elements and stamp the length onto the array TYPE. cgen already
* keys stride/length/data off the stamped length, so it "just
* works" (rob's #7 ruling). A `[_]T` with no array-literal init
* can't infer → LOUD error, never a silent zero-length array.
* - cgen (selfhost/cmd/wcc/cgenexpr.ww cgdot): a top-level `[N]T`
* global's `.len` / `.ptr` pseudo-fields, the wwstage arm that was
* missing (cstage cgen.c:8011 already handled it).
*
* Coverage: `[_]int` / `[_]str` / `[_]u8`, both local and module-level,
* `len` read-back and element read-back, dual-stage runtime + asm
* byte-id. Mutation-sanity: the old collapse-to-0 fails every `*_len`
* row (len would be 0, not the count). Plus three negative rows where
* `[_]T` can't infer (no init / non-array init) — both stages must
* FAIL the build.
*
* row | shape | want
* ----------------+--------------------------------------+------
* local_int_len | local [_]int=[10,20,30,40], x.len | 4
* local_int_elem | local, x[2] | 30
* mod_int_len | global [_]int=[..], x.len | 4
* mod_int_elem | global, x[2] | 30
* local_str_len | local [_]str=["a","b","c"], x.len | 3
* local_str_elem | local [_]str=["ab","cde"], x[0].len | 2
* mod_str_len | global [_]str=["a","b","c"], x.len | 3
* local_u8_len | local [_]u8=[1..5], x.len | 5
* local_u8_elem | local, x[4] | 5
*/
#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;
}
struct row { const char *label; const char *src; int want; };
static const struct row rows[] = {
{ "local_int_len",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]int = [10, 20, 30, 40];\n"
"\treturn x.len: i32;\n"
"};\n",
4 },
{ "local_int_elem",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]int = [10, 20, 30, 40];\n"
"\treturn x[2]: i32;\n"
"};\n",
30 },
{ "mod_int_len",
"package main;\n"
"let x: [_]int = [10, 20, 30, 40];\n"
"export fn main() i32 = {\n"
"\treturn x.len: i32;\n"
"};\n",
4 },
{ "mod_int_elem",
"package main;\n"
"let x: [_]int = [10, 20, 30, 40];\n"
"export fn main() i32 = {\n"
"\treturn x[2]: i32;\n"
"};\n",
30 },
{ "local_str_len",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]str = [\"a\", \"b\", \"c\"];\n"
"\treturn x.len: i32;\n"
"};\n",
3 },
{ "local_str_elem",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]str = [\"ab\", \"cde\"];\n"
"\treturn x[0].len: i32;\n"
"};\n",
2 },
{ "mod_str_len",
"package main;\n"
"let x: [_]str = [\"a\", \"b\", \"c\"];\n"
"export fn main() i32 = {\n"
"\treturn x.len: i32;\n"
"};\n",
3 },
{ "local_u8_len",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]u8 = [1u8, 2u8, 3u8, 4u8, 5u8];\n"
"\treturn x.len: i32;\n"
"};\n",
5 },
{ "local_u8_elem",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]u8 = [1u8, 2u8, 3u8, 4u8, 5u8];\n"
"\treturn x[4]: i32;\n"
"};\n",
5 },
};
/* `[_]T` that can't infer its length — both stages must FAIL the build
* (loud diagnostic, not a silent zero-length array). */
static const char *neg[] = {
/* no init, local */
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]str;\n"
"\treturn 0;\n"
"};\n",
/* no init, module-level */
"package main;\n"
"let x: [_]int;\n"
"export fn main() i32 = { return 0; };\n",
/* non-array initialiser */
"package main;\n"
"export fn main() i32 = {\n"
"\tlet x: [_]int = 5;\n"
"\treturn 0;\n"
"};\n",
};
static int
run_driver(const char *driver, const struct row *r, int i)
{
char src[64], tmpdir[64], cmd[1024];
snprintf(src, sizeof src, "/tmp/ail_%d_%d.ww", getpid(), i);
snprintf(tmpdir, sizeof tmpdir, "/tmp/ail_%d_d_%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 2>/dev/null",
tmpdir, driver, src);
if (runwait(cmd) != 0) {
fprintf(stderr, "row[%s]: build via %s failed\n",
r->label, driver);
unlink(src); rmdir(tmpdir);
return -1;
}
const char *base = strrchr(src, '/');
base = base ? base + 1 : src;
char outbin[128];
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); rmdir(tmpdir);
return got;
}
/* build_should_fail — a `[_]T` that can't infer must error on `driver`;
* returns 0 when the build correctly FAILS, non-zero when it wrongly
* succeeded. */
static int
build_should_fail(const char *driver, const char *src, int i)
{
char s[64], tmpdir[64], cmd[1024];
snprintf(s, sizeof s, "/tmp/ailn_%d_%d.ww", getpid(), i);
snprintf(tmpdir, sizeof tmpdir, "/tmp/ailn_%d_d_%d", getpid(), i);
FILE *f = fopen(s, "wb");
if (!f) return -1;
fputs(src, f);
fclose(f);
mkdir(tmpdir, 0755);
snprintf(cmd, sizeof cmd, "cd %s && %s build %s 2>/dev/null",
tmpdir, driver, s);
int rc = runwait(cmd);
unlink(s);
/* clean any emitted binary */
const char *base = strrchr(s, '/');
base = base ? base + 1 : s;
char outbin[128];
snprintf(outbin, sizeof outbin, "%s/%s", tmpdir, base);
char *dot = strrchr(outbin, '.');
if (dot && strcmp(dot, ".ww") == 0) *dot = '\0';
unlink(outbin);
rmdir(tmpdir);
return rc == 0 ? -1 : 0; /* build must NOT succeed */
}
/* asm_byte_identical — w6c vs w6c_ww .s for the same source must match. */
static int
asm_byte_identical(const char *bin, const struct row *r, int i)
{
char src[64], cs[64], ws[64], cmd[1024];
snprintf(src, sizeof src, "/tmp/ail_asm_%d_%d.ww", getpid(), i);
snprintf(cs, sizeof cs, "/tmp/ail_asm_%d_%d_c.s", getpid(), i);
snprintf(ws, sizeof ws, "/tmp/ail_asm_%d_%d_w.s", getpid(), i);
FILE *f = fopen(src, "wb");
if (!f) return -1;
fputs(r->src, f);
fclose(f);
snprintf(cmd, sizeof cmd, "%s/w6c -o %s %s 2>/dev/null", bin, cs, src);
if (runwait(cmd) != 0) {
fprintf(stderr, "row[%s]: w6c errored\n", r->label);
unlink(src);
return -1;
}
snprintf(cmd, sizeof cmd, "%s/w6c_ww -o %s %s 2>/dev/null",
bin, ws, src);
if (runwait(cmd) != 0) {
fprintf(stderr, "row[%s]: w6c_ww errored\n", r->label);
unlink(src); unlink(cs);
return -1;
}
FILE *fc = fopen(cs, "rb");
FILE *fw = fopen(ws, "rb");
int rc = 0;
if (!fc || !fw) {
rc = -1;
} else {
for (;;) {
int a = fgetc(fc);
int b = fgetc(fw);
if (a != b) { rc = -1; break; }
if (a == EOF) break;
}
}
if (fc) fclose(fc);
if (fw) fclose(fw);
if (rc != 0)
fprintf(stderr, "row[%s]: cstage vs wwstage asm differs\n",
r->label);
unlink(src); unlink(cs); unlink(ws);
return rc;
}
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 cdrv[1024];
snprintf(cdrv, sizeof cdrv, "%s/ww", bin);
char wdrv[1024];
snprintf(wdrv, sizeof wdrv, "%s/ww_ww", bin);
struct { const char *name; const char *path; int gated_on_existence; }
drivers[] = {
{ "cstage", cdrv, 0 },
{ "wwstage", wdrv, 1 },
{ NULL, NULL, 0 },
};
int n = (int)(sizeof rows / sizeof rows[0]);
int nn = (int)(sizeof neg / sizeof neg[0]);
int total = 0, fail = 0;
for (int d = 0; drivers[d].name; d++) {
if (drivers[d].gated_on_existence
&& access(drivers[d].path, X_OK) != 0) {
fprintf(stderr, "arr_infer_len: skip %s (no %s)\n",
drivers[d].name, drivers[d].path);
continue;
}
for (int i = 0; i < n; i++) {
int got = run_driver(drivers[d].path, &rows[i], i);
total++;
if (got != rows[i].want) {
fprintf(stderr,
"arr_infer_len[%s][%s]: exit=%d want=%d\n",
drivers[d].name, rows[i].label,
got, rows[i].want);
fail++;
}
}
for (int i = 0; i < nn; i++) {
total++;
if (build_should_fail(drivers[d].path, neg[i],
100 + i) != 0) {
fprintf(stderr,
"arr_infer_len[%s][neg%d]: built ok, "
"expected a loud error\n",
drivers[d].name, i);
fail++;
}
}
}
if (access(wdrv, X_OK) == 0) {
for (int i = 0; i < n; i++) {
total++;
if (asm_byte_identical(bin, &rows[i], i) != 0)
fail++;
}
}
if (fail) {
fprintf(stderr,
"arr_infer_len: %d/%d fixtures failed\n", fail, total);
return 1;
}
printf("arr_infer_len: %d/%d ok\n", total, total);
return 0;
}