Files
ww/lib/fmt/vstream.ww
Hojun-Cho 2a405a4ad6 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).
2026-05-29 09:41:46 +09:00

328 lines
11 KiB
Plaintext

// vstream — Hare-shaped vtable wrappers over an fd sink. Project #94
// fold-e3 (Option C, parallel API for lib/fmt).
//
// Adds four wrappers that take a raw fd and dispatch through an
// [[io.vstream]] (= `*io.vtable`, the Hare-shape from
// lib/io/stream.ww) alongside the pre-vtable fdprint / fdprintln /
// fdprintf / fdprintfln in fmt.ww. The OLD surface stays untouched
// here — fold-eFinal (task #50) atomically flips the package shape:
// deletes the OLD wrappers + callbacks, renames `_v` suffix off, and
// migrates the few callers.
//
// Hare routes fmt's fd sinks through `io::handle = (io::file | int)`
// (ref/hare/fmt/wrappers.ha:9-25); ww doesn't have the handle sum yet
// so the pure-vstream sink — drew-deferred per fold-d/fold-e3 —
// stands in until io fold-2 lands the handle port. fd_ctx is the
// minimum carrier: one tagged field (vt) + one i32 (fd). Single-
// tagged-field shape lets direct struct-lit init through (sibling
// task #207 only bites multi-tagged-field copies); ken's escape-risk
// discipline holds — every wrapper stack-allocates fd_ctx inside its
// own frame, gets `vs = &c.vt` from the same frame, and dispatches
// without returning &c outside it.
//
// Cast workaround per #206: bare `&fn_name` does not type-check as a
// `(*<alias> | void)` field-init / let-binding. Explicit
// `(&fn_name): *io.<role>` cast at each store site is the Hare-
// faithful minimum-touch route — same workaround memio/vstream.ww
// uses (2 cast tokens here at the vtable wire-up site; both drop out
// wholesale once #206 closes).
//
// Dispatch chain (per wrapper):
// fd{print,println,printf,printfln}_v
// → vfprint / vfprintf (internal vstream-side formatter)
// → io.st_write(vs, buf)
// → vs.writer (= fdsinkwrite_v after the cast)
// → os.write(c.fd, ...)
//
// The internal vfprint/vfprintf duplicate the per-arg and {n}-
// placeholder loops from fmt.ww (fprint at line 177, fprintf at 676)
// because the OLD versions take `*io.stream` (the legacy struct) and
// fmt.ww must stay UNCHANGED this fold. Shared bits — `i64dec`,
// `modsinit`, `scandigits`, `scanmods`, `formattable`, `field`,
// `mods`, `fmtabort` — are reused directly from fmt.ww (same package).
//
// Sibling tasks parked here (filed, NOT fixed):
//
// - io fold-2 (handle port): drew-deferred. 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 and the V API graduates over the OLD per-fd surface.
// - #206 (bare &fn → (*alias|void)): 2 cast sites here; drops
// 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 shape memio.vstream.ww
// adopted at line 71-74.
package fmt;
import io;
import os;
import strconv;
// fd_ctx — vt at offset 0 for the intrusive vstream→*fd_ctx cast.
// Mirrors lib/memio.fixed_ctx (memio/vstream.ww:48); single tagged
// field (vt) means the multi-tagged-field drop in #207 doesn't bite.
export type fd_ctx = struct {
vt: io.vtable,
fd: i32,
};
// fdsinkread_v — eof-only sink; the fd half of fmt is write-only.
// Mirrors OLD fdsinkread (fmt.ww:765). The unused-`buf` parameter
// matches io.reader's signature.
fn fdsinkread_v(s: io.vstream, buf: []u8) (size | io.eof | io.error) = {
let e: io.eof;
return e;
};
// fdsinkwrite_v — recover fd via intrusive cast, dispatch one
// os.write. -errno collapses to a nomem-widened io.error: the OLD
// fdsinkwrite (fmt.ww:768) flattens this to io.closed; we keep the
// Hare-shape error here because the V surface returns io.error
// directly. Construction-then-widen (vs `os.trywrite(...)?`)
// sidesteps #173 same as memio.vstream.ww (line 71-74 note).
fn fdsinkwrite_v(s: io.vstream, buf: []u8) (size | io.error) = {
let c: *fd_ctx = s: *fd_ctx;
let r: i64 = os.write(c.fd, buf.ptr, buf.len: u64);
if (r < 0) {
let nm: nomem;
let e: io.error = nm;
return e;
};
return r: size;
};
// ---- internal vstream-side formatters -------------------------------
// vputbytes — io.st_write(vs, [ptr..ptr+n)). Internal helper; the
// inline `let v` slice synthesis mirrors fmt.putbytes (fmt.ww:160)
// for the legacy *io.stream sink.
fn vputbytes(vs: io.vstream, p: *u8, n: i32) (size | io.error) = {
let v: []u8;
v.ptr = p;
v.len = n;
return io.st_write(vs, v);
};
// vwriteone — emit one formattable through io.st_write. Mirror of
// the per-arm dispatch in fmt.fdprint (fmt.ww:103-138) and fmt.fprint
// (fmt.ww:188-234); shape matches OLD modulo the (size | io.error)
// return instead of i64 / (i32 | io.closed).
fn vwriteone(vs: io.vstream, a: formattable) (size | io.error) = {
match (a) {
case let n: i64 => {
let s: str = i64dec(n);
return vputbytes(vs, s.ptr, s.len);
};
case let s: str => return vputbytes(vs, s.ptr, s.len);
case let b: bool => {
let s: str = "false";
if (b) { s = "true"; };
return vputbytes(vs, s.ptr, s.len);
};
case let r: rune => {
let buf: [4]u8;
buf[0] = r: u8;
return vputbytes(vs, &buf[0], 1);
};
case let v: f64 => {
// strconv.f64tos static-buffer view consumed before next
// strconv call — same shape as fmt.fdprint (fmt.ww:130).
let s: str = strconv.f64tos(v);
return vputbytes(vs, s.ptr, s.len);
};
};
return 0: size;
};
// vformatfield — field→formattable inline-per-arm dispatch. The
// for-loop call site in vfprintf would trip task #18 (silent
// miscompile of 24B return-by-value in for-loop context) if widened
// via a helper; inline-per-arm sidesteps it — same shape OLD
// formatfield uses at fmt.ww:648. `*mods` arm aborts (parametric '%'
// form not implemented; OLD fprintf aborts identically).
fn vformatfield(vs: io.vstream, f: field) (size | io.error) = {
match (f) {
case let v: i64 => {
let a: formattable = v;
return vwriteone(vs, a);
};
case let v: str => {
let a: formattable = v;
return vwriteone(vs, a);
};
case let b: bool => {
let a: formattable = b;
return vwriteone(vs, a);
};
case let r: rune => {
let a: formattable = r;
return vwriteone(vs, a);
};
case let v: f64 => {
let a: formattable = v;
return vwriteone(vs, a);
};
case let p: *mods => { fmtabort(); let z: size = 0; return z; };
};
};
// vfprint — vstream-side fprint. Mirror of fmt.fprint (fmt.ww:177).
// Per-arg loop with a space separator; returns total bytes written
// or the first io.error.
fn vfprint(vs: io.vstream, args: formattable...) (size | io.error) = {
let total: size = 0;
let i: i32 = 0;
for (i < args.len) {
if (i > 0) {
let r: (size | io.error) = vputbytes(vs, " ".ptr, 1);
match (r) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
};
let r: (size | io.error) = vwriteone(vs, args[i]);
match (r) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
i += 1;
};
return total;
};
// vfprintf — vstream-side fprintf. Mirror of fmt.fprintf (fmt.ww:676).
// {n}-placeholder parser routed through vformatfield + vputbytes
// instead of fmt.formatfield + fmt.putbytes; the placeholder language
// (incl. `{N:mods}` modifier subset) is identical — scandigits /
// scanmods / modsinit reused directly from fmt.ww.
fn vfprintf(vs: io.vstream, fmt: str, args: field...) (size | io.error) = {
let total: size = 0;
let i: i32 = 0;
let nextimpl: i32 = 0;
let checkunused: bool = true;
for (i < fmt.len) {
let c: u8 = fmt[i];
if (c == 123u8) { // '{'
i += 1;
if (i >= fmt.len) { fmtabort(); };
if (fmt[i] == 123u8) { // '{{' literal
let r: (size | io.error) = vputbytes(vs, fmt.ptr + i: u64, 1);
match (r) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
i += 1;
} else {
let idx: i32 = 0;
let d: u8 = fmt[i];
if (d >= 48u8 && d <= 57u8) {
checkunused = false;
idx = scandigits(fmt, &i);
} else {
idx = nextimpl;
nextimpl += 1;
};
let m: mods;
modsinit(&m);
if (i < fmt.len && fmt[i] == 58u8) { // ':'
i += 1;
scanmods(fmt, &i, &m);
};
if (i >= fmt.len || fmt[i] != 125u8) { fmtabort(); };
i += 1;
if (idx >= args.len) { fmtabort(); };
let r: (size | io.error) = vformatfield(vs, args[idx]);
match (r) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
};
} else if (c == 125u8) { // '}'
i += 1;
if (i >= fmt.len || fmt[i] != 125u8) { fmtabort(); };
let r: (size | io.error) = vputbytes(vs, fmt.ptr + i: u64, 1);
match (r) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
i += 1;
} else {
let r: (size | io.error) = vputbytes(vs, fmt.ptr + i: u64, 1);
match (r) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
i += 1;
};
};
if (checkunused && nextimpl != args.len) { fmtabort(); };
return total;
};
// ---- public fd-sink wrappers (V API) ---------------------------------
// fdprint_v — fdprint over io.vstream. Stack-allocates fd_ctx; the
// &c.vt vstream pointer never escapes this frame (ken's escape-risk
// discipline). Mirrors fmt.fdprint (fmt.ww:94).
export fn fdprint_v(fd: i32, args: formattable...) (size | io.error) = {
let c: fd_ctx;
c.fd = fd;
c.vt.reader = (&fdsinkread_v): *io.reader;
c.vt.writer = (&fdsinkwrite_v): *io.writer;
let vs: io.vstream = &c.vt;
return vfprint(vs, args...);
};
// fdprintln_v — fdprint_v + trailing newline. Mirrors fmt.fdprintln
// (fmt.ww:145).
export fn fdprintln_v(fd: i32, args: formattable...) (size | io.error) = {
let c: fd_ctx;
c.fd = fd;
c.vt.reader = (&fdsinkread_v): *io.reader;
c.vt.writer = (&fdsinkwrite_v): *io.writer;
let vs: io.vstream = &c.vt;
let total: size = 0;
match (vfprint(vs, args...)) {
case let n: size => { total = n; };
case let e: io.error => return e;
};
match (vputbytes(vs, "\n".ptr, 1)) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
return total;
};
// fdprintf_v — fdprintf over io.vstream. Mirrors fmt.fdprintf
// (fmt.ww:786).
export fn fdprintf_v(fd: i32, fmt: str, args: field...) (size | io.error) = {
let c: fd_ctx;
c.fd = fd;
c.vt.reader = (&fdsinkread_v): *io.reader;
c.vt.writer = (&fdsinkwrite_v): *io.writer;
let vs: io.vstream = &c.vt;
return vfprintf(vs, fmt, args...);
};
// fdprintfln_v — fdprintf_v + trailing newline. Mirrors
// fmt.fdprintfln (fmt.ww:797) and Hare's wrappers.ha:69.
export fn fdprintfln_v(fd: i32, fmt: str, args: field...) (size | io.error) = {
let c: fd_ctx;
c.fd = fd;
c.vt.reader = (&fdsinkread_v): *io.reader;
c.vt.writer = (&fdsinkwrite_v): *io.writer;
let vs: io.vstream = &c.vt;
let total: size = 0;
match (vfprintf(vs, fmt, args...)) {
case let n: size => { total = n; };
case let e: io.error => return e;
};
match (vputbytes(vs, "\n".ptr, 1)) {
case let n: size => { total += n; };
case let e: io.error => return e;
};
return total;
};