Commit Graph

12 Commits

Author SHA1 Message Date
7f320d3e75 lib/fmt+test: add f64 dispatch arm (#17)
#30 (82be8b9) unblocked tagged-union widen for runtime f64. Add the
f64 arm to fmt's formattable union and dispatch.

`formattable` gains an f64 case (appended last to preserve existing
tag indices). fdprint / fprint mirror their i64-arm shape. formatraw
peels strconv's natural '-' so signof folds neg/+/space uniformly
with i64. formatfield uses the inline widen-per-arm #18 sidestep.
rawlenf64 renders via strconv.f64tos to count bytes for width
alignment (Hare's print.ha:53 uses an io::empty sink for this; ww
has none yet, so we render twice — acceptable v1 trade).

Width / alignment / pad / sign mods honored. prec / base ignored
with inline rationale (no ffmt/fflags in mods yet; Hare aborts on
non-DEC base, ww silently falls through). NaN/Inf deferred — Inf
renders deterministically as "huge"/"-huge" via strconv's `f >= cap`
path; NaN is garbage. Detection waits on f64↔u64 bit-reinterpret in
cgen.

13 test rows at signalled 31-43 cover basic/int-valued/neg/zero/
small-frac/huge/sign±/space/width-right/width-left + fprint
variadic + bsprintf + asprintf sinks. Each pins exact byte output.

Three rows bind negative literal via intermediate `let nv: f64 =
-2.5;` to route around #40 (cstage drops payload on N_UNARY-of-
N_FLOATLIT in tagged-union widen). Comments cite #40 at each row.
Probe at .ai/probe_f64_unary_neg.ww.

Strconv f64tos is fixed-point today; graduate to Ryū (ref/hare/
strconv/ftos.ha:432) when needed.
2026-05-16 14:36:45 +09:00
f906081c8c lib/fmt+test: add asprintf (heap-allocated formatter)
Now that os.alloc/free ship (db2b05b), the heap-shape printf wrapper
that bb10ee7 deferred is implementable.

`asprintf(fmt: str, args: field...) str` — Hare wrappers.ha:29 shape.
Body wires memio.dynamic, runs fprintf into it, takes a stringview,
and shrink-to-fit-copies into a fresh os.alloc(view.len) before
io.closing the dynamic stream (which frees the cap-sized internal
buffer). The shrink-to-fit copy is forced by os.free's (p, n) shape:
n must match the mmap length, so the caller can't free a
cap-allocated body if cap > len.

Caller contract documented inline: free with `os.free(r.ptr, r.len)`
when r.len > 0; skip when r.len == 0 (no allocation happens).

Mirrors strings.dup's shape; not a workaround.

The fprintf io.closed arm is matched-and-ignored — memio.dynamicwrite
only returns size, never io.closed (verified at memio.ww:163-175).
Same shape as Hare's `case size => void;` in print.ha.

Hare's nomem variant intentionally dropped; ww's os.alloc returns a
poisonous pointer on OOM (per #14 contract) which faults on deref —
no in-band error to model.

Tests (signalled 27-30): basic (str + i64), growth (34B output
through 8→16→32→64 grow), empty (no-alloc / skip-free), indexed_mods
({1:_05} through heap sink).

errorf / error / errorln family deferred — drew's call to ship the
whole error story in one commit when the error type lands.
2026-05-16 10:06:09 +09:00
bb10ee73a4 lib/fmt+test: add {n}-placeholder printf family
Hare-shaped {} / {0} / {n:mods} parser + printf wrappers. APIs:
fprintf, fprintfln, fdprintf, fdprintfln, printf, printfln, errorfln,
fatalf, bsprintf. Parser handles indexed/positional placeholders,
alignment (- / default / =), pad-width, zero-pad (_05), radix (x X o
b), precision (.N for int pad / str trunc), sign markers (+, space),
and {{ / }} escape.

Internals: scandigits + scanmods drive a field-by-field dispatch into
formatfield, which inlines the field→formattable widen per-arm to
sidestep task #18 (24B return-by-value miscompile in for-loop
context). Render through formatraw + formatone over io.stream sinks.

formatone tail-pad uses a separate counter rather than mirroring
Hare's `?`-propagating loop: ww's memio.fixed returns partial-write
0 instead of errors::overflow, so the Hare shape would spin forever
on a full fixed buffer.

Deferred per drew's vet: asprintf/errorf (needs os.alloc, #16),
parametric width/precision dispatch (#16-family), float arm (#17),
log.printfln family wiring (#15).

Tests: 26 scenarios covering every placeholder shape, both arms of
fprintf's variadic dispatch (incl. bool/rune to pin #18 regression),
bsprintf overflow + width-against-full-buffer, closed-stream.
2026-05-16 00:45:30 +09:00
c3f994822d lib/fmt+lib/log+lib/memio: drop rt_syscall stubs in tests; use os
After 12436dd, lib/fmt and lib/log production code routed through
os.write / os.exit. The test files (fmttest, logtest, memiotest)
still carried the same @symbol("rt_syscall") syscall1ww / doexit
stub block with the (now stale) os↔io collision rationale. Same
mechanical drop as 12436dd: add use os;, route fail() through
os.exit, remove the stubs.

Also reword the stale workaround comment in lib/memio/memio.ww
covering rt_alloc/rt_free. The decls themselves stay until lib/os
exports alloc/free as a follow-up.

No combined.ww regen (these files aren't bootstrap-folded).
2026-05-16 00:03:19 +09:00
12436ddaca lib/fmt+lib/log: drop rt_syscall stubs; use os
After #9 (f1440bf) fn labels mangle by module, so lib/fmt and lib/log
can use os; without colliding with lib/io on the read/write/close
leaves at link.

Drop the @symbol("rt_syscall") rtsyscall3/rtsyscall1 + rawwrite/
rawexit wrappers in both files; route the 7 fmt + 3 log call sites
through os.write / os.exit. Trim the workaround-rationale comments.

Mechanical rename; underlying syscall numbers and args unchanged.
2026-05-15 23:53:02 +09:00
0ef94eef04 lib+test: fmt rename fprint→fdprint; add io.stream fprint sink 2026-05-15 11:34:47 +09:00
b6cf68f2b8 w6c+selfhost+lib: Hare-style variadic call sites
Param-decl `name: T...` (Tparam.variadic=1, type []T), call-site
gather of N args into a fresh `[N]T`, forward via `xs...`, full
selfhost mirror, and lib/fmt graduated to the Hare shape.

Frontend:
  - parse: `T...` after a param's type stamps Node.op=TK_ELLIPSIS
    and breaks out (variadic must be last).
  - check: resolve_type N_TFN / build_fn_type wrap the param type
    as []T and set tp->variadic. N_CALL accepts either a tail of
    args assignable to T (gather) or a single `xs...` spread of
    []T (forward); both bypass the "too many args" check on the
    variadic slot.
  - type: type_eq compares Tparam.variadic.

Cgen (cstage):
  - call site: when the callee has a variadic last param,
    materialise the tail args into a frame-resident `[N]T` via
    localoff, write a 24B slice descriptor (ptr,len,cap), and
    splice a synthesised N_IDENT into args[] so the downstream
    widen/eval/pop loops see one slice slot. Tagged-element types
    route each store through cg_widen_tagged_store. Forwarding
    skips gather: the N_SPREAD wrapper is replaced with its inner
    slice expression. Empty form writes {nil,0,0}. args[] / widen[]
    bump from 16 to 64 to accommodate Hare's mixed-arg printers.

Selfhost mirror:
  - lib/ww/parse: `T...` mark on N_PARAM.op.
  - cgen: varargseq counter on Cg; scanlocals reserves
    @vararg_d_N + @vararg_sl_N per variadic call (seq recorded on
    N_CALL.uval so cgcall picks the same names). cgcall does the
    same gather/forward and N_IDENT splice. cgfnparams treats
    variadic params as 24B slice slots via a synthesised TSLICE
    tnode. pushargsrev skips the tagged-widen detection for
    variadic params (effective type is []T, not tagged).
  - rhstargetname now recognises N_TRUE/N_FALSE/N_RUNELIT and
    typed N_INTLIT so the variant-tag lookup finds bool/rune/iN
    variants instead of falling through to "first non-str" (which
    misassigned tag 0 to bool in tagged unions like formattable).

lib/fmt graduated: print/println/fprint/fprintln/errorln/fatal
take `args: formattable...`. Bare `error` (no -ln) is skipped —
the leaf name collides with strconv's `type error = !(invalid |
overflow)` under the driver's flat namespace.

Tests: 5 new e2e rows (plain gather, zero-arg, tagged element,
forwarding, fmt.println end-to-end). lib/CLAUDE.md workaround
paragraph replaced with the Hare-shape description.
2026-05-13 08:56:01 +09:00
46edb8db4a w6c+selfhost+lib: cgen quality batch + lib Hare-shape graduation
Six fixes across the toolchain, surfaced by lib/lisp porting work.

  1. f64 compound assigns (`acc += d`, `-=`, `*=`, `/=`). Both stages
     load slot → X1, OP X0 into X1, store back (ADDSD/SUBSD/MULSD/
     DIVSD are reg-reg only). Previous MOVSD-overwrite dropped the
     OP. Locals and top-level lets.

  2. Top-level `[N]u8` arrays + `&arr[i]`. let_emit_size grows a
     TY_ARRAY branch so zero-init DATAW lands; cgindex / N_INDEX
     store / `&base[i]` all detect a global array base and use
     LEAQ name(SB) instead of LEAQ (BP). TK_AMP no longer pre-
     evaluates the operand as a value-load — `&base[i]` computes
     base + i*esz directly. Unblocks Hare's static-buffer pattern:
     strconv.{u64,i64,f64}tos graduate to module-level `*_buf`
     arrays and return owned views.

  3. Cross-module `pkg.Enum.MEMBER`. Nested N_DOT chains that
     don't fold to a known shape now emit `MOVQ <leaf>(SB), AX`
     (mirrors the bare-IDENT unresolved fallback), so isolation
     probes — and the test 990 cgen-match floor — stay consistent
     across stages. strconv exposes `base` as a real `enum i32`;
     callers updated. The `main` exemption (linker entry-point
     keeps bare name even when not exported) mirrors C-side
     collectmods into selfhost cgendecl.

  4. Sum-typed parameter ABI. lib/bytes.{index,rindex} take
     `(u8 | []u8)` needle; lib/strings.byteindex / rbyteindex take
     `(str | rune)` needle (Hare-shaped; the byte-wise misnomer
     `index` is dropped). tagged_arg_size cap bumps to 48 (6 int
     regs), with a new partial-fit branch on the callee: when an
     N-word tagged arg overflows remaining regs, fill what fits and
     stitch the rest from positive BP offsets. scanlocals MCASE
     handles slice binds (24B) and walks each arm with a saved /
     restored seenmark set so two arms naming the same local each
     get their own slot — matches cstage's per-arm scope reset.

  5. 4-reg tagged-return ABI (AX=tag, DX=word0, CX=word1, R8=word2),
     up from 3 regs. Slice-payload variants (`([]T | E)`, slot 32B)
     round-trip ptr/len/cap end-to-end. Every receive site updates:
     let-init via cgwidentaggedstore, match scrutinee spill, cgindex
     tagged-element load (both N_IDENT and fallback bases),
     pushargsrev tagged-ident arg (reads word count from slot size),
     cgreturn slice variant in the shuffle path.

  6. `expr: TaggedAlias` is a widening, not a re-interpret. C cgen +
     selfhost cgwidentaggedstore peel an N_CAST whose destination IS
     the union — so cgexpr's natural shape (str: AX=ptr, BX=len;
     slice: AX=ptr, BX=len, CX=cap) is consumed by the matching
     concrete-variant branch instead of being misread as a tagged
     AX/DX/CX triple. Inner casts to a concrete variant (`7: i32`)
     keep their type for proper tag lookup. `[N]Alias` arrays
     resolve element size via slotsize + aliaslookup, and aliaslookup
     strips a `pkg.` prefix so cross-module references work.

lib/fmt grows `formattable = (i64 | str | bool | rune)` plus
`printv` / `printlnv` taking an explicit `[]formattable` slice (the
receive side of Hare's `args: formattable...`). Call-site variadic
gather isn't wired — callers either hand-build the slice or compose
strconv.i64tos + strings.concat.

700_e2e: 114 → 123 rows (f64 compound, top-level u8 arrays + `&buf[i]`,
pkg.Enum.MEMBER, sum-typed (str|rune) and (u8|[]u8) params, 4-reg
slice-return ABI, formattable array). 26/26 tests, bootstrap stable
through ww4.
2026-05-13 08:05:01 +09:00
be8a662f15 lib/strconv: graduate to owned-str returns with Hare-shape base param
i64tos / u64tos / f64tos return a fresh owned str (caller frees via
os.free) instead of writing into a caller-supplied [N]u8. Adds typed
variants (i32tos / i16tos / i8tos and u32 / u16 / u8) and the missing
base parameter on stoi64 / stou64 + typed parse wrappers.

Base values are exported as plain-i32 `def`s (strconv.DEC,
strconv.HEX_UPPER, ...) rather than a `base` enum: cross-module
`strconv.base.DEC` chains miscompile in the cstage cgen — it emits a
memory load through `base(SB)` rather than inlining the constant.
The Sdef path resolves correctly, so callers say `strconv.DEC` and
both cgens lower to an immediate.

Also renames strings.byteindex / rbyteindex to strings.indexbyte /
rindexbyte, matching bytes.indexbyte and reserving the Hare name
`byteindex` for the future `(str | rune)`-needle shape.

fmt drops printint / printlnint / fprintint — those were stand-ins
for variadic `fmt::println(42)`; with the owned-str graduation the
substitute is one call: `fmt.println(strconv.i64tos(42, strconv.DEC))`.

strerror is sketched in a comment but not shipped — match arms over
the wider `error = !(invalid | overflow)` union still expose a
cstage-vs-wwstage spill divergence.
2026-05-13 03:55:16 +09:00
9bc973dc96 lib: drop non-Hare extras (ascii.digitval, bytes.copy, fmt.errpos)
ascii.digitval/isidstart/isidpart are lexer-private, not Hare-stdlib.
Moved into lib/ww/lex/lex.ww as fn (renamed digitval to hexval since
its sole job is the \\xHH escape decoder).

bytes.copy and fmt.errpos have no Hare counterpart and no external
callers; gone.
2026-05-13 03:24:33 +09:00
1ac1d985f6 lib: rename stdlib surface to Hare names; add endian/math
Sweeping rename so the lib/ surface mirrors Hare's stdlib spellings.
- ascii: rune-taking predicates; ishex -> isxdigit
- bufio: rinit -> init; take1/takeline -> readbyte/readline
- bytes: indexsub -> index
- encoding/utf8: runelen -> runesz
- errors: eEOF/eShortRead/... -> eof/underread/...
- fmt: errln -> errorln; println/fprintln return i64
- os: readfull/writefull -> readall/writeall; unlink -> remove
- path: isabs -> abs; drop lastindex (now strings.rbyteindex)
- strconv: u64toa/i64toa -> u64tos/i64tos; parse64/parseu64 -> stoi64/stou64
- strings: drop len/isempty; equal -> compare; indexbyte -> byteindex; +rbyteindex
- types: drop numeric helpers (moved to math)
- new lib/endian (htonu16/ntohu16), lib/math (absi32/absi64)
- net: drop htons (use endian.htonu16)

Callers in selfhost/, lib/ww/, cmd/w6c/cgen.c, and test/wcc/700_e2e.c
updated to match.
2026-05-12 00:45:18 +09:00
1657bdeda3 ww: import toolchain — C bootstrap + ww-side self-host (phases 0-10)
C bootstrap (phases 0-9):
  cmd/wwc, cmd/6c, cmd/6a, cmd/6l, cmd/ww, rt, lib/*.

ww-side self-host (phase 10):
  selfhost/cmd/wwc — ww-cgen frontend; bootstrap fixed point.
  selfhost/cmd/6a  — assembler; byte-identical to C 6a (test 991).
  selfhost/cmd/6l  — linker w/ archive (.a) support; byte-identical
                     to C 6l (test 992).
  selfhost/cmd/ww  — driver (build/run/version); byte-identical to
                     C ww (test 993).

make test: 15/15. make bootstrap: ww2.s == ww3.s, ww2.o == ww3.o,
ww2 == ww3 byte-identical, with the full ww-tooled chain.
2026-05-11 02:17:47 +09:00