Files
ww/test/wcc/821_def_str_index_reject.c
Hojun-Cho ce3a25a0b4 test: contain sepwork scratch per-driver tmpdir, fix /tmp+in-repo leak (#8)
The wcc test drivers ran `ww build <bare-/tmp src>` with no -o, so the
compiler's <stem>.sepwork scratch landed beside the source and was never
cleaned: unbounded /tmp growth (2195 stale dirs observed) that fills tmpfs
and fabricates phantom test failures + silent harness aborts, and for
in-repo fixture builds leaked .sepwork into the tracked tree.

Each leaking build now writes its source + output inside a per-invocation
tmpdir, passes -o <tmpdir>/<stem> so the .sepwork lands inside it, and
rm -rf's the tmpdir on every exit path -- including fopen-fail and the
expected-fail reject builds (scratch is mkdir'd before the build can fail).
`ww run` and explicit-`-o`/byte-id helpers are left as-is; the 990/993
byte-id comparison logic is byte-for-byte unchanged.

Two items filed separately (this commit holds the no-Makefile / no-main.c
rail):
- #13: a stale <src>.s byte-id readback (749) silently no-ops since
  separate-compile emits .s to <ostem>.sepwork/__root.s; documented inline.
- #14: build-system Makefile recipes build selfhost/cmd/*/main.ww with no
  -o and leak main.sepwork in-tree (bounded, gitignored; own commit).

One concern -- sepwork leak hygiene -- across 228 drivers; uniform
transform applied per-file and two-round reviewed. make test: all 402
passed, zero net-new /tmp scratch, zero test-driven in-repo .sepwork.
2026-06-22 23:29:39 +09:00

353 lines
11 KiB
C

/*
* 821_def_str_index_reject — indexing a bare DEF-GLOBAL scalar str is INVALID
* ww and BOTH stages must LOUDLY REJECT at check time (#14, the #8 sibling;
* drew ruling .ai/drew-14-ruling.md, rob spec .ai/rob-14-spec.md).
*
* `str[i] -> u8` itself is VALID ww — a sanctioned Go-like direct byte-index,
* a deliberate divergence from Hare's `strings::toutf8(s)[i]` (the Hare
* reference checker rejects str-index, harec check.c:362). lib/strings is
* load-bearing on it (compare/dup/join). The reject is SCOPED to ONE operand
* shape: a bare def-global SCALAR str.
*
* The bug (both-stage, but each side misbehaved DIFFERENTLY):
* - cstage: `def S:str="hi"; S[0]` BUILT and emitted an unbacked `main.S(SB)`
* base load — at runtime a frame-garbage base → SILENT SEGFAULT.
* - wwstage: the same source referenced an unbacked symbol → w6l LINK-FAIL.
* A `def` is an inline compile-time CONSTANT (def-as-constant; not storage-
* backed like a `let`), so it has no address to index. The fix REJECTS that
* one operand at the checker (N_IDENT operand + SK_DEF sym + scalar TY_STR
* base), surfacing a source error before cgen — segfault gone by construction.
*
* Mutation-sanity: the genuinely-silent pre-fix case is cstage's def-scalar
* index, which BUILT (then segfaulted) — neg rows assert BUILD-FAIL, so they
* FAIL pre-fix on cstage (built-ok) and pass post-fix. wwstage already
* link-failed pre-fix.
*
* neg row | shape | gate
* --------------------+----------------------------------------+----------
* def_scalar_index | def S:str="hi", return S[0]:i32 | build FAIL
* def_scalar_varbind | def S:str="hi", let c=S[1] | build FAIL
*
* pos row | shape | want
* --------------------+----------------------------------------+------
* let_scalar_index | module let S:str="hi", S[0]:i32 | 104 ('h')
* param_index | fn f(s:str) i32 = s[0]:i32; f("hi") | 104 ('h')
* local_index | local let s:str="hi", s[0]:i32 | 104 ('h')
* def_strarray_elem | def C:[2]str=["ab","cd"], C[1][0]:i32 | 99 ('c')
*
* The def_strarray_elem row pins the #8 materialised array-element str stays
* VALID: the outer operand `C[1]` is N_INDEX (not N_IDENT), so the scalar-str
* gate excludes it; and a bare def str-ARRAY operand's base is TY_ARRAY (not
* scalar str), also excluded. let/param/local + string-literal operands stay
* valid (the lib/strings compare/dup pattern).
*/
#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[] = {
/* module-level `let` str is storage-backed (DATA) → indexable. */
{ "let_scalar_index",
"package main;\n"
"let S: str = \"hi\";\n"
"export fn main() i32 = {\n"
"\treturn S[0]: i32;\n"
"};\n",
104 },
{ "param_index",
"package main;\n"
"fn f(s: str) i32 = {\n"
"\treturn s[0]: i32;\n"
"};\n"
"export fn main() i32 = {\n"
"\treturn f(\"hi\");\n"
"};\n",
104 },
{ "local_index",
"package main;\n"
"export fn main() i32 = {\n"
"\tlet s: str = \"hi\";\n"
"\treturn s[0]: i32;\n"
"};\n",
104 },
/* #8 materialised array-element str — `C[1]` is N_INDEX, not N_IDENT,
* so the def-scalar-str gate excludes it; must STAY valid. */
{ "def_strarray_elem",
"package main;\n"
"def C: [2]str = [\"ab\", \"cd\"];\n"
"export fn main() i32 = {\n"
"\treturn C[1][0]: i32;\n"
"};\n",
99 },
/* CRITICAL PRESERVE — INTERP-style def-global scalar str `.len`/`.ptr`
* N_DOT FIELD read (lib w6l/dynout.ww INTERP, load-bearing in the ELF
* emit; bootstrap dies if this breaks). The #14 reject is on N_INDEX,
* NOT N_DOT — this field read must STAY valid. 3 + *"abc".ptr(='a'=97)
* = 100. */
{ "def_scalar_field",
"package main;\n"
"def S: str = \"abc\";\n"
"export fn main() i32 = {\n"
"\tlet n: i32 = S.len: i32;\n"
"\tlet p: *u8 = S.ptr;\n"
"\treturn n + (*p): i32;\n"
"};\n",
100 },
/* def-global NON-str array index — the scalar-str gate (TY_STR only)
* must NOT over-catch a legit def-array index (the #8 array path). */
{ "def_arr_index",
"package main;\n"
"def A: [3]int = [10, 20, 30];\n"
"export fn main() i32 = {\n"
"\treturn A[1]: i32;\n"
"};\n",
20 },
};
/* Indexing a bare def-global scalar str — both stages must FAIL the build
* (loud checker diagnostic, not silent segfault / link-error). */
static const char *neg[] = {
/* def_scalar_index */
"package main;\n"
"def S: str = \"hi\";\n"
"export fn main() i32 = {\n"
"\treturn S[0]: i32;\n"
"};\n",
/* def_scalar_varbind */
"package main;\n"
"def S: str = \"hi\";\n"
"export fn main() i32 = {\n"
"\tlet c = S[1];\n"
"\treturn c: i32;\n"
"};\n",
};
/* Per-neg expected diagnostic body (parallel to neg[]); both rows hit the
* same "cannot index a def-constant str" path on both stages. */
static const char *neg_diag[] = {
"cannot index a def-constant str",
"cannot index a def-constant str",
};
static int
run_driver(const char *driver, const struct row *r, int i)
{
char tmpdir[64], src[128], outbin[128], cmd[1024], rmcmd[160];
snprintf(tmpdir, sizeof tmpdir, "/tmp/dsi_%d_d_%d", getpid(), i);
mkdir(tmpdir, 0755);
snprintf(src, sizeof src, "%s/dsi_%d_%d.ww", tmpdir, getpid(), i);
snprintf(outbin, sizeof outbin, "%s/dsi_%d_%d", tmpdir, getpid(), i);
snprintf(rmcmd, sizeof rmcmd, "rm -rf %s", tmpdir);
FILE *f = fopen(src, "wb");
if (!f) { runwait(rmcmd); return -1; }
fputs(r->src, f);
fclose(f);
/* #8: -o pins binary + .sepwork scratch under tmpdir; rm -rf on
* every exit path removes the now-non-empty dir. */
snprintf(cmd, sizeof cmd, "%s build -o %s %s 2>/dev/null",
driver, outbin, src);
if (runwait(cmd) != 0) {
fprintf(stderr, "row[%s]: build via %s failed\n",
r->label, driver);
runwait(rmcmd);
return -1;
}
int got = runwait(outbin);
runwait(rmcmd);
return got;
}
static int
filehas(const char *path, const char *needle)
{
char buf[8192];
FILE *f = fopen(path, "rb");
if (!f) return 0;
size_t n = fread(buf, 1, sizeof buf - 1, f);
fclose(f);
buf[n] = '\0';
return strstr(buf, needle) != NULL;
}
/* build_should_fail — indexing a def-global scalar str must error on
* `driver`; returns 0 when the build FAILS *and* emits `diag`. A crash
* (segfault) wraps as a nonzero "w6c failed" with no diagnostic, so the
* substring distinguishes it from a clean reject (#20). */
static int
build_should_fail(const char *driver, const char *src, const char *diag,
int i)
{
char tmpdir[64], s[128], outbin[128], cmd[1024], errf[128], rmcmd[160];
snprintf(tmpdir, sizeof tmpdir, "/tmp/dsin_%d_d_%d", getpid(), i);
mkdir(tmpdir, 0755);
snprintf(s, sizeof s, "%s/dsin_%d_%d.ww", tmpdir, getpid(), i);
snprintf(outbin, sizeof outbin, "%s/dsin_%d_%d", tmpdir, getpid(), i);
snprintf(errf, sizeof errf, "%s/err", tmpdir);
snprintf(rmcmd, sizeof rmcmd, "rm -rf %s", tmpdir);
FILE *f = fopen(s, "wb");
if (!f) { runwait(rmcmd); return -1; }
fputs(src, f);
fclose(f);
/* #8: -o pins binary + any .sepwork scratch under tmpdir; rm -rf
* removes the now-non-empty dir. */
snprintf(cmd, sizeof cmd, "%s build -o %s %s >/dev/null 2>%s",
driver, outbin, s, errf);
int rc = runwait(cmd);
int hasmsg = filehas(errf, diag);
runwait(rmcmd);
/* build must NOT succeed AND must emit its diagnostic. */
return (rc != 0 && hasmsg) ? 0 : -1;
}
/* 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/dsi_asm_%d_%d.ww", getpid(), i);
snprintf(cs, sizeof cs, "/tmp/dsi_asm_%d_%d_c.s", getpid(), i);
snprintf(ws, sizeof ws, "/tmp/dsi_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, "def_str_index_reject: 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,
"def_str_index_reject[%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],
neg_diag[i], 100 + i) != 0) {
fprintf(stderr,
"def_str_index_reject[%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,
"def_str_index_reject: %d/%d fixtures failed\n", fail, total);
return 1;
}
printf("def_str_index_reject: %d/%d ok\n", total, total);
return 0;
}