lib/fmt: add Option C parallel vstream API (#94 fold-e3)

Adds lib/fmt/vstream.ww with four new wrappers — fdprint_v /
fdprintln_v / fdprintf_v / fdprintfln_v — that take a raw fd, stack-
allocate an fd_ctx whose first field is `vt: io.vtable`, and
dispatch through io.st_write on a vstream pointing at &c.vt
(intrusive offset-0 cast — same shape as lib/memio/vstream.ww's
fixed_ctx / dynamic_ctx in fold-e2). Coexists with the pre-vtable
fdprint / fdprintln / fdprintf / fdprintfln in fmt.ww.

ken's escape-risk discipline: every wrapper owns the fd_ctx slot
for its frame only; the &c.vt vstream pointer is consumed inside
the same function (passed through internal vfprint / vfprintf
helpers) and never returned. Single tagged field (vt) lets the
local default-zero plus chained `c.vt.X = …` assigns sidestep the
multi-tagged-field copy drop (sibling #207) — no struct-lit init
needed and c is a stack value, not an aliased pointer, so #195's
chained-store carve-out doesn't bite either.

Drew defer cited at the file head: io.handle (= file | int) is
out-of-scope for this fold per fold-d/fold-e3 precedent; Hare's
ref/hare/fmt/wrappers.ha:9-25 routes through the handle sum, and
fdNNN_v collapses into bare fNNN_v once io fold-2 lands the port
(filed inline as "io fold-2 handle port" backlog).

Internal vfprint / vfprintf duplicate the per-arg and {n}-
placeholder loops from fmt.ww (fprint:177, fprintf:676) because
the OLD versions take *io.stream (the legacy struct) and fmt.ww
stays UNCHANGED this fold. Shared bits — i64dec, modsinit,
scandigits, scanmods, formattable, field, mods, fmtabort — are
reused directly from fmt.ww. vformatfield mirrors the inline-per-
arm dispatch shape OLD formatfield (fmt.ww:648) uses to dodge #18
silent miscompile of 24B return-by-value in for-loop context.

Cast workaround per #206 at each vtable-fn-ptr-slot init (2 sites
per wrapper, 8 total): bare `&fn_name` does not type-check as
`(*<alias> | void)`. Same `(&fn): *io.<role>` cast shape that
lib/memio/vstream.ww uses. Drops out wholesale when #206 closes.

#173 workaround at fdsinkwrite_v: constructs nomem and widens to
io.error explicitly rather than `os.trywrite(...)?` — same shape
memio.vstream.ww line 71-74 note adopted.

OLD fmt surface is UNCHANGED. fold-eFinal (task #50) atomically
flips the package shape: deletes OLD wrappers + callbacks, renames
_v suffix off, and migrates the few callers (with io fold-2's
handle sum landing in the same flip).

Probe test/wcc/777_fmt_vstream_run.c: 4 rows
(fdprintf_v_int / fdprintln_v_multi / fdprint_v_raw /
branched_fdprintf_v) open per-row /tmp output files, dispatch one
V wrapper per row, reopen the file, read the bytes back, and
assert both the exact byte content and a unique row-tagged exit
constant. 4/4 fixtures total, all green via cstage.

Cstage-only per row (no STAGE_WW, no byte_id) — pre-existing
wwstage match-arm bug (sibling of #190, filed inline as #209): the
wwstage checker bails `case: not a variant of scrutinee (X)` /
`match: variant not handled (formattable)` on the OLD
fmt.fdprint's match arms whenever any probe `import fmt;`s the
package. The bug bites the OLD surface identically — even
`fmt.errorln("hi")` from a probe trips the same trace. 970
fmttest dodges via cstage-only ww run; 995 self-rebuild dodges
because no selfhost cmd transitively pulls fmt (err.ww imports
fmt but no main.ww in cmd/{ww,w6c,w6a,w6l,wwdump} pulls err.ww in).
Byte-id graduates when #209 closes — out-of-scope for the additive
fold-e3.

Combined.ww regen NO-OP: none of the five tracked combined.ww
files (cmd/{ww,w6c,w6a,w6l,wwdump}/main.combined.ww) embed
`package fmt;` — fmt is not in the dep graph of any selfhost
binary. combined_ww_fresh stays green untouched.

210/210 tests passing (was 209; +1 for 777_fmt_vstream_run).
This commit is contained in:
2026-05-29 09:41:46 +09:00
parent b842f9337b
commit 2a405a4ad6
3 changed files with 732 additions and 0 deletions

View File

@@ -0,0 +1,397 @@
/*
* 777_fmt_vstream_run — project #94 fold-e3 sentinel. Pins the
* additive lib/fmt/vstream.ww Option C parallel API: stack-resident
* fd_ctx with `vt: io.vtable` as the first field for the intrusive
* vstream cast, four wrappers (fdprint_v / fdprintln_v / fdprintf_v /
* fdprintfln_v) that take a raw fd, allocate fd_ctx on their own
* frame (never escapes — ken's dispatcher-CONTAINED discipline), and
* dispatch through io.st_write via the wired fdsinkwrite_v callback.
* Coexists with the pre-vtable fdprint / fdprintln / fdprintf /
* fdprintfln surface in fmt.ww (fold-eFinal, task #50, retires the
* latter once io fold-2 ports `handle = (file | int)`).
*
* Each row imports fmt + os + io, opens a per-process /tmp output
* file, calls one V wrapper to write through the fd, closes, re-
* opens for read, reads the bytes back, and asserts both (a) the
* exact byte content and (b) a unique row-tagged exit constant.
*
* Cstage-only per row (no STAGE_WW, no byte_id) — pre-existing
* wwstage bug #209 (sibling of #190): the wwstage checker bails
* `case: not a variant of scrutinee (X)` + `match: variant not
* handled (formattable)` on the OLD fmt.fdprint / fdprintf's
* match-on-formattable arms whenever a downstream probe `import
* fmt;`s the package. The bug bites the OLD surface identically
* — `fmt.errorln("hi")` from a probe trips the same trace. The
* pre-existing surface (fmt.ww) is fine via cstage because every
* other test that uses fmt is cstage-only (970 fmttest runs the
* @test fixture under cstage `ww run` only). 995 self-rebuild
* dodges it because no selfhost cmd imports fmt transitively —
* fmt is consumed by selfhost/cmd/wcc/err.ww but no main.ww in
* cmd/{ww,w6c,w6a,w6l,wwdump} pulls err.ww in. Fix-of-the-bug =
* one-class checker repair, out-of-scope for the additive
* fold-e3; closes the wwstage half here when it lands. Byte-id
* graduates with #209 close.
*
* row | what it pins
* --------------------------+--------------------------------------
* fdprintf_v_int | fdprintf_v with `"v={}\n"`-style
* | format + one i64 arg. Asserts the
* | full intrusive shape (stack fd_ctx →
* | &c.vt → io.st_write → fdsinkwrite_v
* | → os.write) plus the {n}-placeholder
* | parser routed through vformatfield.
* fdprintln_v_multi | fdprintln_v with three positional
* | args (i64 + str + bool). Asserts the
* | space-separator + trailing newline
* | shape mirrors OLD fdprintln (fmt.ww:
* | 145), routed through io.st_write.
* fdprint_v_raw | fdprint_v with one str arg, no
* | format mods (zero-format raw). Pins
* | the per-arg loop without the
* | placeholder parser (vfprint code
* | path, fmt/vstream.ww).
* branched_fdprintf_v | branched callee per #105: two
* | distinct format strings runtime-
* | selected from a single fdprintf_v
* | call site. Catches a constant-fold
* | mistake in the format-string
* | dispatch (mirror of 776's
* | branched_fixed for the format-side).
*
* IMPORT-ORDER WORKAROUND (sibling task #208, pre-existing): every
* row places `import os;` FIRST for the same reason 776 documents
* (wwstage checker ordering-sensitivity on os.tryread/trywrite/
* tryopen's bare `return r;` over a tagged return type).
*
* SIBLINGS (filed inline, NOT fixed here — fold-e3 is purely
* additive over fold-e1/e2's frozen io.* + memio.* surface):
*
* - io fold-2 (handle port): drew-deferred per fold-d/fold-e3
* precedent. Hare's ref/hare/fmt/wrappers.ha:9-25 routes through
* io::handle; fdNNN_v collapses into bare fNNN_v once handle =
* (file | int) lands. eFinal (#50) graduates.
*
* - #206 (bare &fn → (*alias|void)): 2 cast sites per wrapper
* vtable wire-up; drop out wholesale on close.
*
* - #173 (TRY-on-tagged-return both-stages broken): fdsinkwrite_v
* constructs nomem and widens to io.error explicitly rather
* than using `os.trywrite(...)?`; same memio.vstream.ww shape.
*
* GATE POLARITY: must stay GREEN. A red here means vstream.ww
* regressed, the stack fd_ctx → vstream cast miscomputed offsets,
* the {n}-placeholder dispatch through vformatfield regressed, or
* io.vtable's first-field embed lost its offset-0 invariant.
*/
#include <stdio.h>
#include <stdlib.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;
}
#define STAGE_CS 1
#define STAGE_WW 2
struct row {
const char *label;
const char *src;
int want_exit;
int stage_mask;
int byte_id;
};
static const struct row rows[] = {
{ "fdprintf_v_int",
"package main;\n"
"import os;\n"
"import fmt;\n"
"import io;\n"
"export fn main() i32 = {\n"
" let path: str = \"/tmp/wwfmtv_777_a\";\n"
" let fd: i32 = os.open(path, os.flag.RDWR | os.flag.CREATE | os.flag.TRUNC, 0o644: i32);\n"
" if (fd < 0) { return 90; };\n"
" let wr = fmt.fdprintf_v(fd, \"v={}\\n\", 42i64);\n"
" let nw: size = 0;\n"
" match (wr) {\n"
" case let n: size => { nw = n; };\n"
" case io.error => { return 91; };\n"
" };\n"
" os.close(fd);\n"
" let rd: i32 = os.open(path, os.flag.RDONLY, 0i32);\n"
" if (rd < 0) { return 92; };\n"
" let buf: [16]u8;\n"
" let n: i64 = os.read(rd, &buf[0], 16u64);\n"
" os.close(rd);\n"
" if (n != 5i64) { return 93; };\n"
" if (nw != 5: size) { return 94; };\n"
" if (buf[0] != 118u8 || buf[1] != 61u8 || buf[2] != 52u8 || buf[3] != 50u8 || buf[4] != 10u8) { return 95; };\n"
" return 42;\n"
"};\n",
42,
STAGE_CS, 0 },
{ "fdprintln_v_multi",
"package main;\n"
"import os;\n"
"import fmt;\n"
"import io;\n"
"export fn main() i32 = {\n"
" let path: str = \"/tmp/wwfmtv_777_b\";\n"
" let fd: i32 = os.open(path, os.flag.RDWR | os.flag.CREATE | os.flag.TRUNC, 0o644: i32);\n"
" if (fd < 0) { return 90; };\n"
" let wr = fmt.fdprintln_v(fd, 7i64, \"hi\", true);\n"
" let nw: size = 0;\n"
" match (wr) {\n"
" case let n: size => { nw = n; };\n"
" case io.error => { return 91; };\n"
" };\n"
" os.close(fd);\n"
" let rd: i32 = os.open(path, os.flag.RDONLY, 0i32);\n"
" if (rd < 0) { return 92; };\n"
" let buf: [16]u8;\n"
" let n: i64 = os.read(rd, &buf[0], 16u64);\n"
" os.close(rd);\n"
" if (n != 10i64) { return 93; };\n"
" if (nw != 10: size) { return 94; };\n"
" if (buf[0] != 55u8 || buf[1] != 32u8 || buf[2] != 104u8 || buf[3] != 105u8 || buf[4] != 32u8 || buf[5] != 116u8 || buf[6] != 114u8 || buf[7] != 117u8 || buf[8] != 101u8 || buf[9] != 10u8) { return 95; };\n"
" return 43;\n"
"};\n",
43,
STAGE_CS, 0 },
{ "fdprint_v_raw",
"package main;\n"
"import os;\n"
"import fmt;\n"
"import io;\n"
"export fn main() i32 = {\n"
" let path: str = \"/tmp/wwfmtv_777_c\";\n"
" let fd: i32 = os.open(path, os.flag.RDWR | os.flag.CREATE | os.flag.TRUNC, 0o644: i32);\n"
" if (fd < 0) { return 90; };\n"
" let wr = fmt.fdprint_v(fd, \"raw\");\n"
" let nw: size = 0;\n"
" match (wr) {\n"
" case let n: size => { nw = n; };\n"
" case io.error => { return 91; };\n"
" };\n"
" os.close(fd);\n"
" let rd: i32 = os.open(path, os.flag.RDONLY, 0i32);\n"
" if (rd < 0) { return 92; };\n"
" let buf: [8]u8;\n"
" let n: i64 = os.read(rd, &buf[0], 8u64);\n"
" os.close(rd);\n"
" if (n != 3i64) { return 93; };\n"
" if (nw != 3: size) { return 94; };\n"
" if (buf[0] != 114u8 || buf[1] != 97u8 || buf[2] != 119u8) { return 95; };\n"
" return 44;\n"
"};\n",
44,
STAGE_CS, 0 },
{ "branched_fdprintf_v",
"package main;\n"
"import os;\n"
"import fmt;\n"
"import io;\n"
"export fn main() i32 = {\n"
" let path: str = \"/tmp/wwfmtv_777_d\";\n"
" let fd: i32 = os.open(path, os.flag.RDWR | os.flag.CREATE | os.flag.TRUNC, 0o644: i32);\n"
" if (fd < 0) { return 90; };\n"
" let sel: i32 = 1;\n"
" let f1: str = \"A{}\";\n"
" let f2: str = \"B{}\";\n"
" let fmtstr: str = f1;\n"
" if (sel == 0) { fmtstr = f2; };\n"
" let wr = fmt.fdprintf_v(fd, fmtstr, 9i64);\n"
" let nw: size = 0;\n"
" match (wr) {\n"
" case let n: size => { nw = n; };\n"
" case io.error => { return 91; };\n"
" };\n"
" os.close(fd);\n"
" let rd: i32 = os.open(path, os.flag.RDONLY, 0i32);\n"
" if (rd < 0) { return 92; };\n"
" let buf: [8]u8;\n"
" let n: i64 = os.read(rd, &buf[0], 8u64);\n"
" os.close(rd);\n"
" if (n != 2i64) { return 93; };\n"
" if (nw != 2: size) { return 94; };\n"
" if (buf[0] != 65u8 || buf[1] != 57u8) { return 95; };\n"
" return 45;\n"
"};\n",
45,
STAGE_CS, 0 },
};
static int
write_source(const char *path, const char *src)
{
FILE *f = fopen(path, "wb");
if (!f) return -1;
fputs(src, f);
fclose(f);
return 0;
}
/* Per-row tmpdir cleanup. ww_ww writes intermediates next to the
* source (filed task #15), so each row's build leaves
* <src>.{combined.ww,s,o} + bare exe alongside. Sweep all then
* rmdir. Mirror of 776's cleanup_tmp. */
static void
cleanup_tmp(const char *tmpdir, const char *base)
{
char p[640];
snprintf(p, sizeof p, "%s/%s.ww", tmpdir, base); unlink(p);
snprintf(p, sizeof p, "%s/%s.s", tmpdir, base); unlink(p);
snprintf(p, sizeof p, "%s/%s.o", tmpdir, base); unlink(p);
snprintf(p, sizeof p, "%s/%s.combined.ww", tmpdir, base); unlink(p);
snprintf(p, sizeof p, "%s/%s", tmpdir, base); unlink(p);
rmdir(tmpdir);
}
static int
build_via_driver(const char *driver, const char *tmpdir, const char *cwd,
const char *src)
{
char cmd[2048];
snprintf(cmd, sizeof cmd,
"cd %s && timeout 180 %s build -I %s/lib %s 2>/dev/null",
tmpdir, driver, cwd, src);
return runwait(cmd);
}
static int
run_row(const char *driver, const char *cwd, const struct row *r, int seq)
{
char tmpdir[256], src[512], base[64], outbin[768];
snprintf(tmpdir, sizeof tmpdir, "/tmp/fvs_%d_d_%d", getpid(), seq);
snprintf(base, sizeof base, "main777");
snprintf(src, sizeof src, "%s/%s.ww", tmpdir, base);
mkdir(tmpdir, 0755);
if (write_source(src, r->src) != 0) { cleanup_tmp(tmpdir, base); return -1; }
int rc;
int br = build_via_driver(driver, tmpdir, cwd, src);
if (br == 0) {
snprintf(outbin, sizeof outbin, "%s/%s", tmpdir, base);
rc = runwait(outbin);
} else {
rc = -1;
}
cleanup_tmp(tmpdir, base);
return rc;
}
/* asm_byte_identical — diff cstage vs wwstage .s. Parallel trees so
* ww_ww writing intermediates next to the source doesn't clobber the
* cstage .s (CLAUDE.md rule 14 phase split). Mirror of 776's. */
static int
asm_byte_identical(const char *cdrv, const char *wdrv, const char *cwd,
const struct row *r, int seq)
{
char src[512], tdc[256], tdw[256], base[64], cs[512], ws[512];
snprintf(tdc, sizeof tdc, "/tmp/fvs_%d_c_%d", getpid(), seq);
snprintf(tdw, sizeof tdw, "/tmp/fvs_%d_w_%d", getpid(), seq);
snprintf(base, sizeof base, "main777");
mkdir(tdc, 0755);
mkdir(tdw, 0755);
snprintf(src, sizeof src, "%s/%s.ww", tdc, base);
if (write_source(src, r->src) != 0) { cleanup_tmp(tdc, base); cleanup_tmp(tdw, base); return -1; }
int rc = -1;
if (build_via_driver(cdrv, tdc, cwd, src) != 0) goto out;
snprintf(cs, sizeof cs, "%s/%s.s", tdc, base);
snprintf(src, sizeof src, "%s/%s.ww", tdw, base);
if (write_source(src, r->src) != 0) goto out;
if (build_via_driver(wdrv, tdw, cwd, src) != 0) goto out;
snprintf(ws, sizeof ws, "%s/%s.s", tdw, base);
FILE *fc = fopen(cs, "rb");
FILE *fw = fopen(ws, "rb");
if (fc && fw) {
rc = 0;
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);
out:
cleanup_tmp(tdc, base);
cleanup_tmp(tdw, base);
return rc;
}
int
main(void)
{
const char *bin = getenv("BIN");
if (!bin) bin = "out/bin";
char cwd[256];
if (getcwd(cwd, sizeof cwd) == NULL) return 1;
char absbin[512];
if (bin[0] != '/') {
snprintf(absbin, sizeof absbin, "%s/%s", cwd, bin);
bin = absbin;
}
char cdrv[640], wdrv[640];
snprintf(cdrv, sizeof cdrv, "%s/ww", bin);
snprintf(wdrv, sizeof wdrv, "%s/ww_ww", bin);
int n = (int)(sizeof rows / sizeof rows[0]);
int total = 0, fail = 0;
int wwpresent = (access(wdrv, X_OK) == 0);
int seq = 0;
for (int i = 0; i < n; i++) {
if (rows[i].stage_mask & STAGE_CS) {
total++;
int got = run_row(cdrv, cwd, &rows[i], seq++);
if (got != rows[i].want_exit) {
fprintf(stderr,
"fmt_vstream_run[cs][%s]: exit=%d want=%d\n",
rows[i].label, got, rows[i].want_exit);
fail++;
}
}
if (wwpresent && (rows[i].stage_mask & STAGE_WW)) {
total++;
int got = run_row(wdrv, cwd, &rows[i], seq++);
if (got != rows[i].want_exit) {
fprintf(stderr,
"fmt_vstream_run[ww][%s]: exit=%d want=%d\n",
rows[i].label, got, rows[i].want_exit);
fail++;
}
if (rows[i].byte_id) {
total++;
if (asm_byte_identical(cdrv, wdrv, cwd, &rows[i], seq++) != 0) {
fprintf(stderr,
"fmt_vstream_run[byte-id][%s]: cstage vs wwstage asm differs\n",
rows[i].label);
fail++;
}
}
}
}
if (!wwpresent)
fprintf(stderr, "fmt_vstream_run: skip wwstage (no %s)\n", wdrv);
if (fail) {
fprintf(stderr, "fmt_vstream_run: %d/%d fixtures failed\n",
fail, total);
return 1;
}
printf("fmt_vstream_run: %d/%d ok\n", total, total);
return 0;
}