Files
ww/lib/fmt/fmt.ww

272 lines
9.1 KiB
Plaintext

// fmt — formatting writers. Mirrors Hare's lib/fmt subset.
//
// Hare's `fmt::fprint` takes `io::handle = (io::file | int)`, which
// ww doesn't yet have. So we ship two sinks side-by-side, with the
// distinction baked into the name:
//
// fprint / fprintln write to a [[io.stream]] — Hare's
// primary surface. Errors via `io.closed`.
// fdprint / fdprintln write to a raw fd via [[os.write]] — ww-
// specific. Errors via the raw `-errno` i64
// convention. Used by the process-stdio
// wrappers below (print/println/errorln/
// fatal) until lib/io grows an fd-backed
// stream; at that point both halves
// graduate "in one go" (lib/CLAUDE.md) and
// the fd-suffixed names disappear.
//
// Call sites take Hare's variadic shape: `fmt.println(42, "hi", true)`
// gathers the args into a `[]formattable` slice; wrappers forward
// via `args...`.
use io;
// Direct rt_syscall / rt_exit bindings rather than `use os;` because
// os exports read/write/close, which collide with io.read/write/close
// under the driver's flat-scope concat — same workaround used by
// lib/memio. Both fmt's fd sink and io.stream sink need to coexist
// in this module, so the os surface has to come in à la carte.
@symbol("rt_syscall") fn rtsyscall3(num: i64, a: i64, b: i64, c: i64) i64;
@symbol("rt_syscall") fn rtsyscall1(num: i64, a: i64) i64;
// rawwrite — Linux write(2) syscall (nr=1). The fd sinks below call
// this directly instead of [[os.write]] to keep the collision off
// fmt's exported surface. Same signature, same negative-errno
// convention.
fn rawwrite(fd: i32, buf: *u8, n: u64) i64 = {
return rtsyscall3(1i64, fd: i64, buf: i64, n: i64);
};
// rawexit — Linux exit(2) syscall (nr=60). Used only by `fatal`.
fn rawexit(code: i32) void = {
rtsyscall1(60i64, code: i64);
};
// i64dec_buf — scratch buffer for [[i64dec]] below. Module-level
// because Hare's `strconv::i64tos` is a static-buffer view and we
// match that shape here. 21 bytes is enough for `-9223372036854775808`
// (20 digits + sign).
let i64dec_buf: [21]u8;
// i64dec — render `v` as a base-10 ASCII string into [[i64dec_buf]],
// returning a borrowed view. Inlined here rather than calling
// [[strconv.i64tos]] because `use strconv;` would transitively pull
// `use os;`, whose exported read/write/close clash with
// io.read/write/close under the driver's flat-scope concat. Same
// algorithmic shape as strconv's version, narrowed to base-10.
fn i64dec(v: i64) str = {
let neg: bool = false;
let n: i64 = v;
if (n < 0) { neg = true; n = -n; };
let tmp: [20]u8;
let i: i32 = 0;
if (n == 0) { tmp[0] = 48u8; i = 1; };
for (n > 0) {
let d: i64 = n % 10i64;
tmp[i] = (d + 48i64): u8;
n = n / 10i64;
i += 1;
};
let out: i32 = 0;
if (neg) { i64dec_buf[out] = 45u8; out += 1; }; // '-'
for (i > 0) {
i -= 1;
i64dec_buf[out] = tmp[i];
out += 1;
};
let r: str;
r.ptr = &i64dec_buf[0];
r.len = out;
return r;
};
// formattable — tagged union of types fmt can render. Mirrors Hare's
// `fmt::formattable = (...types::numeric | uintptr | str | rune |
// bool | nullable *opaque | void)`, narrowed to the set ww actually
// has codegen for. Slot size is 24B (8 tag + 16 str payload).
export type formattable = (i64 | str | bool | rune);
// ---- fd sinks --------------------------------------------------------
// fdprint — write the formatted form of each `args` element to `fd`,
// separated by spaces. Returns total bytes written or the first
// negative [[os.write]] result (Linux's `-errno`). Hare's separator-
// by-space matches.
//
// Renamed from `fprint` once lib/fmt grew an io.stream sink (`fprint`
// now points at that). This entry stays under `fd`-prefix until lib/io
// can express the full Hare `io::handle = (file | int)` union, at
// which point both halves graduate in one go.
export fn fdprint(fd: i32, args: formattable...) i64 = {
let total: i64 = 0;
let i: i32 = 0;
for (i < args.len) {
if (i > 0) {
let r: i64 = rawwrite(fd, " ".ptr, 1u64);
if (r < 0) { return r; };
total += r;
};
match (args[i]) {
case let n: i64 => {
let s: str = i64dec(n);
let r: i64 = rawwrite(fd, s.ptr, s.len: u64);
if (r < 0) { return r; };
total += r;
};
case let s: str => {
let r: i64 = rawwrite(fd, s.ptr, s.len: u64);
if (r < 0) { return r; };
total += r;
};
case let b: bool => {
let s: str = "false";
if (b) { s = "true"; };
let r: i64 = rawwrite(fd, s.ptr, s.len: u64);
if (r < 0) { return r; };
total += r;
};
case let r: rune => {
let buf: [4]u8;
buf[0] = r: u8;
let n: i64 = rawwrite(fd, &buf[0], 1u64);
if (n < 0) { return n; };
total += n;
};
};
i += 1;
};
return total;
};
// fdprintln — fdprint plus a trailing newline.
export fn fdprintln(fd: i32, args: formattable...) i64 = {
let n: i64 = fdprint(fd, args...);
if (n < 0) { return n; };
let m: i64 = rawwrite(fd, "\n".ptr, 1u64);
if (m < 0) { return m; };
return n + m;
};
// ---- stream sinks ----------------------------------------------------
// putbytes — internal helper that wraps (`*u8`, `i32`) into a `[]u8`
// slice and feeds it to [[io.write]]. Not exported: callers compose
// the same `(ptr, len)` triple as their underlying source (str view,
// strconv buffer, stack rune buffer), and the slice is invariant
// in shape across the formattable arms.
fn putbytes(s: *io.stream, p: *u8, n: i32) (i32 | io.closed) = {
let v: []u8;
v.ptr = p;
v.len = n;
return io.write(s, v);
};
// fprint — write the formatted form of each `args` element to `s`,
// separated by spaces. Returns total bytes written, or `io.closed`
// if the sink rejects mid-write. Mirrors Hare's `fmt::fprint` shape
// for an `io::handle` sink, modulo ww's i32-sized byte counters and
// the narrower `io.closed`-only error set on lib/io's stream vtable.
//
// A short write (sink accepts fewer bytes than asked) is reported by
// the returned count, not as an error — matches [[io.write]]'s contract
// per [[memio.fixedwrite]]. Callers that need write-all semantics layer
// it on top, the same way they do over raw [[io.write]].
export fn fprint(s: *io.stream, args: formattable...) (i32 | io.closed) = {
let total: i32 = 0;
let i: i32 = 0;
for (i < args.len) {
if (i > 0) {
let r: (i32 | io.closed) = putbytes(s, " ".ptr, 1);
match (r) {
case let n: i32 => { total += n; };
case io.closed => { let c: io.closed; return c; };
};
};
match (args[i]) {
case let n: i64 => {
let view: str = i64dec(n);
let r: (i32 | io.closed) = putbytes(s, view.ptr, view.len);
match (r) {
case let m: i32 => { total += m; };
case io.closed => { let c: io.closed; return c; };
};
};
case let v: str => {
let r: (i32 | io.closed) = putbytes(s, v.ptr, v.len);
match (r) {
case let m: i32 => { total += m; };
case io.closed => { let c: io.closed; return c; };
};
};
case let b: bool => {
let v: str = "false";
if (b) { v = "true"; };
let r: (i32 | io.closed) = putbytes(s, v.ptr, v.len);
match (r) {
case let m: i32 => { total += m; };
case io.closed => { let c: io.closed; return c; };
};
};
case let r: rune => {
let buf: [4]u8;
buf[0] = r: u8;
let rs: (i32 | io.closed) = io.write(s, buf[0:1]);
match (rs) {
case let m: i32 => { total += m; };
case io.closed => { let c: io.closed; return c; };
};
};
};
i += 1;
};
return total;
};
// fprintln — fprint plus a trailing newline. Mirrors Hare's
// `fmt::fprintln(io::handle, args...)`.
export fn fprintln(s: *io.stream, args: formattable...) (i32 | io.closed) = {
let total: i32 = 0;
let r1: (i32 | io.closed) = fprint(s, args...);
match (r1) {
case let n: i32 => { total = n; };
case io.closed => { let c: io.closed; return c; };
};
let r2: (i32 | io.closed) = putbytes(s, "\n".ptr, 1);
match (r2) {
case let m: i32 => { total += m; };
case io.closed => { let c: io.closed; return c; };
};
return total;
};
// ---- process-stdio wrappers -----------------------------------------
// print / println — fdprint / fdprintln on stdout. Direct counterparts
// of Hare's fmt::print / fmt::println.
export fn print(args: formattable...) i64 = {
return fdprint(1, args...);
};
export fn println(args: formattable...) i64 = {
return fdprintln(1, args...);
};
// errorln — fdprintln on stderr. Hare's `fmt::error` (without -ln) is
// skipped here: the bare `error` name collides with strconv's
// `type error = !(invalid | overflow)` under the driver's flat
// concatenation namespace. Callers wanting the no-newline form use
// `fdprint(2, args...)` directly.
export fn errorln(args: formattable...) i64 = {
return fdprintln(2, args...);
};
// fatal — errorln then exit(255). `never` return marks the bottom
// type so flow-control checks treat callers as terminated. The
// fdprintln result is dropped as an expression statement (Hare's
// `_ = fprintln(...)` wouldn't add safety here — process exit
// follows immediately).
export fn fatal(args: formattable...) never = {
fdprintln(2, args...);
rawexit(255);
};