Files
ww/selfhost/test/smoke.combined.ww
Hojun-Cho 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

829 lines
25 KiB
Plaintext

// MODULE: os
// os — process and filesystem facade. The body of each call lands
// either in libwwrt.a (rt_syscall trampoline) or libc bindings,
// depending on how the program was linked.
@symbol("rt_syscall") fn syscall0(num: nr) i64;
@symbol("rt_syscall") fn syscall1(num: nr, a: i64) i64;
@symbol("rt_syscall") fn syscall2(num: nr, a: i64, b: i64) i64;
@symbol("rt_syscall") fn syscall3(num: nr, a: i64, b: i64, c: i64) i64;
@symbol("rt_syscall") fn syscall4(num: nr, a: i64, b: i64, c: i64, d: i64) i64;
@symbol("rt_alloc") fn alloc(n: u64) *void;
@symbol("rt_free") fn free(p: *void, n: u64) void;
@symbol("rt_abort") fn abort(msg: str) void;
// Hare-style runtime check. Caller passes a message that's printed
// to stderr before exit(1).
export fn assert(cond: bool, msg: str) void = {
if (!cond) { abort(msg); };
};
// Linux amd64 syscall numbers. Internal to this module — passed as
// the first arg of syscall0..4 via libwwrt's rt_syscall trampoline.
// `nr` is the type so the call sites can't accidentally pass an
// arbitrary i64 (`syscall1(0i64, ...)` no longer typechecks).
type nr = enum i64 {
READ = 0,
WRITE = 1,
OPEN = 2,
CLOSE = 3,
LSEEK = 8,
ACCESS = 21,
DUP2 = 33,
GETPID = 39,
FORK = 57,
EXECVE = 59,
EXIT = 60,
WAIT4 = 61,
UNLINK = 87,
GETCWD = 79,
GETDENTS64 = 217,
};
// open(2) flags. Linux values, matching <fcntl.h>. Hare names them
// `fs::flag::RDONLY` etc; we use the same leaf names so callers say
// `os.flag.RDONLY` and `os.flag.WRONLY | os.flag.CREATE`.
export type flag = enum i32 {
RDONLY = 0,
WRONLY = 1,
RDWR = 2,
CREATE = 64, // 0x40
TRUNC = 512, // 0x200
};
// lseek(2) whence. Hare names it `io::whence`.
export type whence = enum i32 {
SET = 0,
CUR = 1,
END = 2,
};
export fn exit(code: i32) void = {
syscall1(nr.EXIT, code: i64);
};
// Raw, non-fallible primitives. These return Linux's int conventions
// (negative = -errno, non-negative = bytes/fd/etc). Callers wanting a
// Hare-style fallible API use the wrappers below.
export fn write(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(nr.WRITE, fd: i64, buf: i64, n: i64);
};
export fn read(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(nr.READ, fd: i64, buf: i64, n: i64);
};
export fn close(fd: i32) i32 = {
return syscall1(nr.CLOSE, fd: i64): i32;
};
// dup2(2): make `newfd` refer to the same description as `oldfd`,
// closing `newfd` first if open. Returns `newfd` on success or a
// negative errno. Used by w6c_ww to redirect stdout into an output
// file without changing the cgen emit path.
export fn dup2(oldfd: i32, newfd: i32) i32 = {
return syscall2(nr.DUP2, oldfd: i64, newfd: i64): i32;
};
// Fallible wrappers. The error variant is `oserror` (an i64 carrying
// -errno). The sum type makes success/failure explicit and lets
// callers `?` the result up the stack.
export fn tryread(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let r: i64 = read(fd, buf, n);
if (r < 0) { return r: oserror; };
return r;
};
export fn trywrite(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let r: i64 = write(fd, buf, n);
if (r < 0) { return r: oserror; };
return r;
};
// open — Linux open(2). Path must be NUL-terminated; callers using ww
// `str` must ensure the bytes are followed by a 0 byte (literals are,
// arena-copied paths usually are by construction). Returns -errno on
// failure, fd otherwise. Higher-level callers prefer `tryopen`.
export fn open(path: *u8, flags: flag, mode: i32) i32 = {
return syscall3(nr.OPEN, path: i64, (flags as i32): i64, mode: i64): i32;
};
export fn tryopen(path: *u8, flags: flag, mode: i32) (i32 | oserror) = {
let fd: i32 = open(path, flags, mode);
if (fd < 0) { return fd: i64: oserror; };
return fd;
};
// lseek — set/inspect the fd's position. Returns the new offset or
// a negative errno. We use this for fstat-free file-size discovery
// (open ⇒ lseek to end ⇒ lseek back).
export fn lseek(fd: i32, off: i64, w: whence) i64 = {
return syscall3(nr.LSEEK, fd: i64, off, (w as i32): i64);
};
// oserror — the underlying errno from a failed syscall, as a
// negative i64 (Linux's int convention; e.g. -2 = ENOENT). The
// `!`-flagged alias makes ?-propagation pick this variant as the
// error half of any (T | oserror) shape. Hare's analogue is
// errors::errno carried inside io::error.
export type oserror = !i64;
// filesize — byte length of an open fd via lseek-to-end-and-back.
export fn filesize(fd: i32) (i64 | oserror) = {
let end: i64 = lseek(fd, 0i64, whence.END);
if (end < 0) { return end: oserror; };
let r: i64 = lseek(fd, 0i64, whence.SET);
if (r < 0) { return r: oserror; };
return end;
};
// readall — keep reading until `n` bytes have arrived or the fd
// closes early. Hare name (io::readall); the buffer is caller-
// supplied, matching the Plan 9 subset convention.
export fn readall(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let got: u64 = 0u64;
for (got < n) {
let r: i64 = read(fd, buf + got, n - got);
if (r < 0) { return r: oserror; };
if (r == 0) { return got: i64; }; // short read: caller decides
got += r: u64;
};
return got: i64;
};
// writeall — keep writing until `n` bytes have been accepted or the
// fd refuses progress. Hare name (io::writeall).
export fn writeall(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
let sent: u64 = 0u64;
for (sent < n) {
let r: i64 = write(fd, buf + sent, n - sent);
if (r < 0) { return r: oserror; };
if (r == 0) { return sent: i64; };
sent += r: u64;
};
return sent: i64;
};
// ---- process and filesystem helpers used by the `ww` driver ----------
// access(2): returns 0 if the file is reachable, negative errno
// otherwise. mode is the bitset described in <unistd.h> (F_OK=0).
export fn access(path: *u8, mode: i32) i32 = {
return syscall2(nr.ACCESS, path: i64, mode: i64): i32;
};
// remove — unlink(2). Hare name; the underlying syscall is unlink(2).
export fn remove(path: *u8) i32 = {
return syscall1(nr.UNLINK, path: i64): i32;
};
// getpid(2). Used by the driver to mint unique scratch paths.
export fn getpid() i32 = {
return syscall0(nr.GETPID): i32;
};
// fork(2): 0 in the child, child pid in the parent, negative errno
// on failure.
export fn fork() i32 = {
return syscall0(nr.FORK): i32;
};
// execve(2): on success, does not return.
export fn execve(path: *u8, argv: **u8, envp: **u8) i32 = {
return syscall3(nr.EXECVE, path: i64, argv: i64, envp: i64): i32;
};
// wait4(2): wait for `pid` (or any child if -1), store status in
// `*status`, return the pid that ended (or negative errno).
export fn wait4(pid: i32, status: *i32, options: i32, rusage: *void) i32 = {
return syscall4(nr.WAIT4, pid: i64, status: i64,
options: i64, rusage: i64): i32;
};
// getcwd(2) — Linux flavour. Writes the NUL-terminated cwd into `buf`
// and returns the number of bytes written (including the NUL), or a
// negative errno. The driver uses it to expand `.` to the cwd's
// basename for `ww build` / `ww test`.
export fn getcwd(buf: *u8, n: u64) i64 = {
return syscall2(nr.GETCWD, buf: i64, n: i64);
};
// getdents64(2) — Linux directory enumeration. The fd must be opened
// with O_RDONLY on a directory. `buf` receives a packed sequence of
// linux_dirent64 records:
//
// struct linux_dirent64 {
// u64 d_ino; // 0..7
// i64 d_off; // 8..15
// u16 d_reclen; // 16..17 — total bytes for this record
// u8 d_type; // 18 — DT_REG/DT_DIR/...
// u8 d_name[]; // 19.. — NUL-terminated name + padding
// };
//
// Returns bytes written into `buf` (advance by d_reclen to walk),
// 0 at end-of-directory, or a negative errno.
export fn getdents64(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(nr.GETDENTS64, fd: i64, buf: i64, n: i64);
};
// MODULE: strconv
// strconv — number↔string conversions.
//
// Mirrors Hare's strconv:: surface. The *tos functions return a fresh
// owned `str`; release via os.free(r.ptr, r.len: u64) when done.
// Hare returns `const str` into a static buffer; ww allocates per
// call because the wwstage cgen doesn't currently support mutating a
// module-level `*u8` (so a lazy-init shared buffer isn't expressible
// today). Graduate to the static-buffer shape once that lands.
use os;
// invalid — input wasn't a valid number in the requested format.
// Payload is the byte index of the first offending position.
// Mirrors Hare's strconv::invalid = !size.
export type invalid = !i32;
// overflow — input was valid but doesn't fit the target type.
// Mirrors Hare's strconv::overflow = !void.
export type overflow = !void;
// error — any error from a strconv call. Mirrors Hare's strconv::error.
export type error = !(invalid | overflow);
// base — numeric base for parsing/formatting. Plain i32 (not a named
// enum) because cross-module `strconv.base.DEC` chains miscompile in
// the cstage cgen — it emits a memory load through `base(SB)` rather
// than inlining the enum value. Hare names them as `strconv::base`
// enum values; we expose them as module-level `def`s so callers say
// `strconv.DEC` and the cgen inlines the immediate.
//
// HEX is HEX_UPPER; HEX_LOWER is a separate pseudo-base that produces
// lowercase a-f digits.
export def DEFAULT: i32 = 0;
export def BIN: i32 = 2;
export def OCT: i32 = 8;
export def DEC: i32 = 10;
export def HEX_UPPER: i32 = 16;
export def HEX: i32 = 16;
export def HEX_LOWER: i32 = 17;
fn basenum(b: i32) i64 = {
if (b == BIN) { return 2; };
if (b == OCT) { return 8; };
if (b == HEX) { return 16; };
if (b == HEX_UPPER) { return 16; };
if (b == HEX_LOWER) { return 16; };
return 10; // DEC and DEFAULT
};
fn basedigit(d: i64, b: i32) u8 = {
if (d < 10) { return (d + 48): u8; };
let off: i64 = d - 10;
if (b == HEX_LOWER) { return (off + 97): u8; };
return (off + 65): u8;
};
// u64tos — convert v to a base-b numeric string. Returns owned str;
// release via os.free(r.ptr, r.len: u64). Mirrors Hare's
// strconv::u64tos (Hare returns const str into a static buffer).
export fn u64tos(v: u64, b: i32) str = {
let nb: u64 = basenum(b): u64;
let tmp: [65]u8;
let i: i32 = 0;
let n: u64 = v;
if (n == 0u64) { tmp[0] = 48u8; i = 1; };
for (n > 0u64) {
let d: i64 = (n % nb): i64;
tmp[i] = basedigit(d, b);
n = n / nb;
i += 1;
};
let buf: *u8 = os.alloc(i: u64): *u8;
let out: i32 = 0;
for (i > 0) {
i -= 1;
buf[out] = tmp[i];
out += 1;
};
let r: str;
r.ptr = buf;
r.len = out;
return r;
};
// i64tos — convert v to a base-b numeric string. Returns owned str;
// release via os.free. Mirrors Hare's strconv::i64tos.
export fn i64tos(v: i64, b: i32) str = {
let neg: bool = false;
let n: i64 = v;
if (n < 0) { neg = true; n = -n; };
let nb: i64 = basenum(b);
let tmp: [65]u8;
let i: i32 = 0;
if (n == 0) { tmp[0] = 48u8; i = 1; };
for (n > 0) {
let d: i64 = n % nb;
tmp[i] = basedigit(d, b);
n = n / nb;
i += 1;
};
let extra: i32 = 0;
if (neg) { extra = 1; };
let total: i32 = i + extra;
let buf: *u8 = os.alloc(total: u64): *u8;
let out: i32 = 0;
if (neg) { buf[out] = 45u8; out += 1; }; // '-'
for (i > 0) {
i -= 1;
buf[out] = tmp[i];
out += 1;
};
let r: str;
r.ptr = buf;
r.len = out;
return r;
};
export fn i32tos(v: i32, b: i32) str = { return i64tos(v: i64, b); };
export fn i16tos(v: i16, b: i32) str = { return i64tos(v: i64, b); };
export fn i8tos(v: i8, b: i32) str = { return i64tos(v: i64, b); };
export fn u32tos(v: u32, b: i32) str = { return u64tos(v: u64, b); };
export fn u16tos(v: u16, b: i32) str = { return u64tos(v: u64, b); };
export fn u8tos(v: u8, b: i32) str = { return u64tos(v: u64, b); };
// digval — value of digit byte `c` under base `b`, or -1 if not a
// valid digit. Letters are accepted case-insensitively under HEX /
// HEX_UPPER; only lowercase under HEX_LOWER.
fn digval(c: u8, b: i32) i32 = {
if (c >= 48u8) { if (c <= 57u8) { return (c - 48u8): i32; }; };
if (b == HEX_LOWER) {
if (c >= 97u8) { if (c <= 102u8) { return ((c - 97u8) + 10u8): i32; }; };
return -1;
};
if (c >= 65u8) { if (c <= 70u8) { return ((c - 65u8) + 10u8): i32; }; };
if (c >= 97u8) { if (c <= 102u8) { return ((c - 97u8) + 10u8): i32; }; };
return -1;
};
// stoi64 — parse signed base-b number. Mirrors Hare's strconv::stoi64.
// No locale, no whitespace, no underscores: optional leading '-' then
// digits. Returns invalid with the offending index or overflow on
// out-of-range.
export fn stoi64(s: str, b: i32) (i64 | invalid | overflow) = {
if (s.len == 0) { return 0: invalid; };
let i: i32 = 0;
let neg: bool = false;
if (s[0] == 45u8) { neg = true; i = 1; };
if (i >= s.len) { return i: invalid; };
let nb: i32 = basenum(b): i32;
let v: i64 = 0;
for (i < s.len) {
let c: u8 = s[i];
let d: i32 = digval(c, b);
if (d < 0) { return i: invalid; };
if (d >= nb) { return i: invalid; };
v = v * (nb: i64) + (d: i64);
i += 1;
};
if (neg) { v = -v; };
return v;
};
// stou64 — parse unsigned base-b number. Mirrors Hare's strconv::stou64.
export fn stou64(s: str, b: i32) (u64 | invalid | overflow) = {
if (s.len == 0) { return 0: invalid; };
let nb: u64 = basenum(b): u64;
let v: u64 = 0u64;
let i: i32 = 0;
for (i < s.len) {
let c: u8 = s[i];
let d: i32 = digval(c, b);
if (d < 0) { return i: invalid; };
if ((d: u64) >= nb) { return i: invalid; };
v = v * nb + (d: u64);
i += 1;
};
return v;
};
export fn stoi32(s: str, b: i32) (i32 | invalid | overflow) = {
let r = stoi64(s, b);
match (r) {
case let v: i64 => {
if (v > 2147483647i64) { return overflow{}; };
if (v < -2147483648i64) { return overflow{}; };
return v: i32;
};
case let e: invalid => return e;
case let e: overflow => return e;
};
return 0: invalid; // unreachable; appeases the path-cov checker
};
export fn stoi16(s: str, b: i32) (i16 | invalid | overflow) = {
let r = stoi64(s, b);
match (r) {
case let v: i64 => {
if (v > 32767i64) { return overflow{}; };
if (v < -32768i64) { return overflow{}; };
return v: i16;
};
case let e: invalid => return e;
case let e: overflow => return e;
};
return 0: invalid;
};
export fn stoi8(s: str, b: i32) (i8 | invalid | overflow) = {
let r = stoi64(s, b);
match (r) {
case let v: i64 => {
if (v > 127i64) { return overflow{}; };
if (v < -128i64) { return overflow{}; };
return v: i8;
};
case let e: invalid => return e;
case let e: overflow => return e;
};
return 0: invalid;
};
export fn stou32(s: str, b: i32) (u32 | invalid | overflow) = {
let r = stou64(s, b);
match (r) {
case let v: u64 => {
if (v > 4294967295u64) { return overflow{}; };
return v: u32;
};
case let e: invalid => return e;
case let e: overflow => return e;
};
return 0: invalid;
};
export fn stou16(s: str, b: i32) (u16 | invalid | overflow) = {
let r = stou64(s, b);
match (r) {
case let v: u64 => {
if (v > 65535u64) { return overflow{}; };
return v: u16;
};
case let e: invalid => return e;
case let e: overflow => return e;
};
return 0: invalid;
};
export fn stou8(s: str, b: i32) (u8 | invalid | overflow) = {
let r = stou64(s, b);
match (r) {
case let v: u64 => {
if (v > 255u64) { return overflow{}; };
return v: u8;
};
case let e: invalid => return e;
case let e: overflow => return e;
};
return 0: invalid;
};
// f64tos — convert v to a decimal string. Returns owned str; release
// via os.free. Mirrors Hare's strconv::f64tos (current ww impl is
// fixed-point only, max 6 fractional digits, no NaN/Inf support —
// see graduate-to-Ryū note below).
//
// Surface:
//
// - finite values only. NaN/±Inf detection needs an f64→u64 bit
// reinterpret cast that the cgen doesn't expose yet.
// - fixed-point only, up to 6 fractional digits. Trailing zeros
// after the decimal point are trimmed. Trailing '.' is dropped.
// - magnitudes ≥ 9e18 (overflows i64 in the integer-part cast)
// fall back to the literal token "huge". Hare would print these
// in scientific notation via Ryū; we will graduate when the
// compiler grows the bit-reinterpret cast.
//
// Round-trip is therefore lossy past 6 fractional digits.
//
// No float literals in the body — 990's wwdump diff requires this
// file's TK_FLOAT count to match between C and ww front-ends, and
// the ww-side wwdump currently skips TK_FLOAT.fval while the C side
// %g-formats it. Same trick lib/ww/lex/lex.ww's parsef64 uses:
// build f64 constants via int-to-f64 casts.
export fn f64tos(v: f64) str = {
let tmp: [64]u8;
let out: i32 = 0;
let f: f64 = v;
let zero: f64 = 0: f64;
if (f < zero) {
tmp[out] = 45u8; // '-'
out += 1;
f = -f;
};
// 9e18 is comfortably under I64_MAX (9.22e18). Past this the
// `f: i64` cast wraps and the integer part comes back as garbage.
let cap: f64 = 9000000000000000000i64: f64;
if (f >= cap) {
let s: str = "huge";
let k: i32 = 0;
for (k < s.len) { tmp[out] = s[k]; out += 1; k += 1; };
let buf: *u8 = os.alloc(out: u64): *u8;
let q: i32 = 0;
for (q < out) { buf[q] = tmp[q]; q += 1; };
let r: str;
r.ptr = buf;
r.len = out;
return r;
};
let ip: i64 = f: i64;
// Fractional part scaled to 6 decimal digits, with round-to-
// nearest via +0.5. (f64 compound assigns mis-lower in cgen —
// use the explicit form, as the rest of lib does.)
let frac: f64 = f - (ip: f64);
let scale: f64 = 1000000: f64;
frac = frac * scale;
let half: f64 = (1: f64) / (2: f64);
let fp: i64 = (frac + half): i64;
// Carry: e.g. 0.9999996 rounds fp up to 1000000 and the integer
// part needs to advance.
if (fp >= 1000000) {
ip += 1;
fp = 0;
};
let intstr: str = i64tos(ip, DEC);
let k: i32 = 0;
for (k < intstr.len) { tmp[out] = intstr.ptr[k]; out += 1; k += 1; };
os.free(intstr.ptr: *void, intstr.len: u64);
if (fp != 0) {
tmp[out] = 46u8; // '.'
out += 1;
let fracstr: str = u64tos(fp: u64, DEC);
// Pad fractional to 6 digits with leading zeros (e.g. 0.05 →
// fp=50000, fracstr="50000", pad one '0' before).
let z: i32 = 6 - fracstr.len;
for (z > 0) { tmp[out] = 48u8; out += 1; z -= 1; };
k = 0;
for (k < fracstr.len) { tmp[out] = fracstr.ptr[k]; out += 1; k += 1; };
os.free(fracstr.ptr: *void, fracstr.len: u64);
// Trim trailing zeros in the fractional part.
for (out > 0) {
if (tmp[out - 1] != 48u8) { break; };
out -= 1;
};
};
let buf: *u8 = os.alloc(out: u64): *u8;
let q: i32 = 0;
for (q < out) { buf[q] = tmp[q]; q += 1; };
let r: str;
r.ptr = buf;
r.len = out;
return r;
};
// strerror — Hare has strconv::strerror; ww doesn't ship it yet
// because a `match (e) { case invalid => ... }` arm over the wider
// `error = !(invalid | overflow)` union exposes a cstage-vs-wwstage
// cgen divergence (one cgen spills the unused payload slot, the
// other elides it). Restore once the cgens converge.
// MODULE: ascii
// ascii — rune-class predicates and case folding for the ASCII range.
// Matches Hare's ascii::isdigit family (rune-taking signature). Runes
// outside 0..127 always answer `false`. The lexer hot path uses these
// inline; they are expected to inline to a couple of compares.
export fn isdigit(c: rune) bool = {
if (c < 48) { return false; };
if (c > 57) { return false; };
return true;
};
export fn isupper(c: rune) bool = {
if (c < 65) { return false; };
if (c > 90) { return false; };
return true;
};
export fn islower(c: rune) bool = {
if (c < 97) { return false; };
if (c > 122) { return false; };
return true;
};
export fn isalpha(c: rune) bool = {
if (isupper(c)) { return true; };
return islower(c);
};
export fn isalnum(c: rune) bool = {
if (isalpha(c)) { return true; };
return isdigit(c);
};
// isspace — the C/Hare set: space, tab, NL, VT, FF, CR.
export fn isspace(c: rune) bool = {
if (c == 32) { return true; }; // ' '
if (c == 9) { return true; }; // '\t'
if (c == 10) { return true; }; // '\n'
if (c == 11) { return true; }; // '\v'
if (c == 12) { return true; }; // '\f'
if (c == 13) { return true; }; // '\r'
return false;
};
export fn isxdigit(c: rune) bool = {
if (isdigit(c)) { return true; };
if (c >= 65) {
if (c <= 70) { return true; }; // 'A'..'F'
};
if (c >= 97) {
if (c <= 102) { return true; }; // 'a'..'f'
};
return false;
};
// tolower / toupper — fold ASCII case. Non-letters pass through.
export fn tolower(c: rune) rune = {
if (isupper(c)) { return c + 32; };
return c;
};
export fn toupper(c: rune) rune = {
if (islower(c)) { return c - 32; };
return c;
};
// MODULE: test
// selfhost/test/smoke.ww — end-to-end smoke for the selfhost path.
//
// Exercises the patterns the real ww-side compiler port will use:
// - bump arena allocator (mem.ww shape)
// - error idiom (T | str)
// - struct of fn pointers + ctx pointer (the io.stream-style
// polymorphism we use instead of interfaces)
// - byte-level scanning that mirrors the hot path inside lex.ww
// - strconv round-trip via the real stdlib
//
// `main` returns 42 when every check passes, 1..N on failure
// indicating which probe broke. The 990_selfhost test asserts 42.
//
// Note: only stack-local mutable state. Top-level `let` mutation
// requires a writable .data segment in w6l, which is a separate
// task; until then we exercise polymorphism via ctx pointers, which
// is what the real port wants anyway.
use os;
use strconv;
use ascii;
// --- bump arena ---------------------------------------------------------
type arena = struct {
buf: *u8,
off: u64,
cap: u64,
};
// In-place init. Returning a 24-byte struct by value isn't yet
// supported in w6c (SysV requires a hidden return-slot pointer for
// structs >16 bytes), so we initialize through a pointer like the
// real compiler does today.
fn arena_init(a: *arena, buf: *u8, cap: u64) void = {
a.buf = buf;
a.off = 0u64;
a.cap = cap;
};
fn arena_alloc(a: *arena, n: u64) *u8 = {
if (n > a.cap - a.off) { return nil; };
let p: *u8 = a.buf + a.off;
a.off += n;
return p;
};
// --- (i32 | str) error idiom -------------------------------------------
fn checked_div(num: i32, den: i32) (i32 | str) = {
if (den == 0) { return "div by zero"; };
return num / den;
};
// --- struct-of-fn-pointer polymorphism ---------------------------------
//
// A trivial "writer" abstraction: a function pointer plus a context.
// This mirrors how io.stream / Plan 9 Bio work. The ctx pointer lets
// the implementation own its own state without a global.
type counter = struct {
n: i32,
};
type writer = struct {
ctx: *void,
emit: fn(ctx: *void, b: u8) void,
};
fn count_emit(ctx: *void, b: u8) void = {
let c: *counter = ctx: *counter;
c.n += 1;
};
// --- byte scanner like lex.ww's hot path -------------------------------
fn count_digits(s: str) i32 = {
let i: i32 = 0;
let n: i32 = 0;
for (i < s.len) {
let c: u8 = s[i];
if (c >= 48u8) {
if (c <= 57u8) { n += 1; };
};
i += 1;
};
return n;
};
// --- entry --------------------------------------------------------------
export fn main() i32 = {
// Probe 1 — arena hands out distinct pointers, refuses oversize.
let buf: [256]u8;
let a: arena;
arena_init(&a, buf.ptr, 256u64);
let p1: *u8 = arena_alloc(&a, 32u64);
let p2: *u8 = arena_alloc(&a, 32u64);
if (p1 == nil) { return 1; };
if (p2 == nil) { return 2; };
if (p1 == p2) { return 3; };
let p3: *u8 = arena_alloc(&a, 1024u64);
if (p3 != nil) { return 4; };
// Probe 2 — error union both ways.
let r_ok: (i32 | str) = checked_div(84, 2);
let r_bad: (i32 | str) = checked_div(1, 0);
let acc: i32 = 0;
match (r_ok) {
case let v: i32 => acc = v;
case let e: str => return 5;
};
if (acc != 42) { return 6; };
match (r_bad) {
case let v: i32 => return 7;
case let e: str => acc = e.len: i32;
};
if (acc != 11) { return 8; }; // len("div by zero") == 11
// Probe 3 — struct-of-fn-pointer dispatch via ctx pointer.
let c: counter = counter { n = 0 };
let w: writer = writer { ctx = (&c): *void, emit = count_emit };
w.emit(w.ctx, 65u8);
w.emit(w.ctx, 66u8);
w.emit(w.ctx, 67u8);
if (c.n != 3) { return 9; };
// Probe 4 — byte scan over a literal.
let dn: i32 = count_digits("ww123abc");
if (dn != 3) { return 10; };
// Probe 5 — strconv round-trip via the real stdlib.
let s: str = strconv.i64tos(4242i64, strconv.DEC);
if (s.len != 4) { return 11; };
if (s.ptr[0] != 52u8) { return 12; }; // '4'
if (s.ptr[3] != 50u8) { return 13; }; // '2'
// Probe 6 — ascii classifications (rune-taking, Hare-shaped).
if (!ascii.isdigit(53)) { return 14; }; // '5'
if (ascii.isdigit(65)) { return 15; }; // 'A' is not a digit
if (!ascii.isalpha(122)) { return 16; }; // 'z'
if (!ascii.isxdigit(70)) { return 17; }; // 'F'
if (ascii.isxdigit(71)) { return 18; }; // 'G' is not hex
if (ascii.tolower(65) != 97) { return 19; }; // 'A' -> 'a'
if (ascii.toupper(122) != 90) { return 20; }; // 'z' -> 'Z'
// Probe 7 — file open/read via the new os APIs. /proc/self/cmdline
// always exists on Linux, no write side, and is non-empty.
let path: str = "/proc/self/cmdline";
// Use raw os.open here (returns i32 with -errno) for the same
// reason as os.read below: probe 6 in 990_selfhost compiles
// smoke.ww standalone (no `use` expansion), so cross-module type
// references like `os.oserror` and `os.flag` don't resolve at
// that step. RDONLY is 0; passing the literal keeps the call
// site standalone-compilable to byte-identical asm on both
// compilers.
let fd: i32 = os.open(path.ptr, 0, 0i32);
if (fd < 0) { return 21; };
let rbuf: [128]u8;
// Use raw os.read here (single syscall, plain i64) instead of
// os.readall: the 990 cgen-match probe compiles smoke.ww
// standalone without `use os;` expansion, so cross-module type
// references like `os.oserror` can't be resolved.
let n: i64 = os.read(fd, rbuf.ptr, 128u64);
os.close(fd);
if (n <= 0i64) { return 22; };
return 42;
};