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

1125 lines
33 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: strings
// strings — operations over the immutable str type ({ *u8, len }).
// Mirrors Hare's strings::; `len` and `is-empty` aren't functions
// (callers use `s.len` and `s.len == 0` directly).
use os;
// compare — bytewise three-way comparison: negative if a<b, 0 if equal,
// positive if a>b. Matches Hare's strings::compare. ASCII-order, not
// locale-aware. Callers that just need equality use `compare(a, b) == 0`.
export fn compare(a: str, b: str) i32 = {
let n: i32 = a.len;
if (b.len < n) { n = b.len; };
let i: i32 = 0;
for (i < n) {
if (a[i] != b[i]) { return (a[i]: i32) - (b[i]: i32); };
i += 1;
};
return a.len - b.len;
};
export fn hasprefix(s: str, p: str) bool = {
if (p.len > s.len) { return false; };
let i: i32 = 0;
for (i < p.len) {
if (s[i] != p[i]) { return false; };
i += 1;
};
return true;
};
export fn hassuffix(s: str, suf: str) bool = {
if (suf.len > s.len) { return false; };
let off: i32 = s.len - suf.len;
let i: i32 = 0;
for (i < suf.len) {
if (s[off + i] != suf[i]) { return false; };
i += 1;
};
return true;
};
// byteindex — first byte position of `needle` in `s`. Mirrors Hare's
// strings::byteindex: a single-codepoint rune scans for the byte that
// encodes it (ASCII only here — multi-byte UTF-8 awaits utf8 encode),
// a str needle scans for the substring. Returns void if absent.
export fn byteindex(s: str, needle: (str | rune)) (i32 | void) = {
match (needle) {
case let r: rune => {
let c: u8 = r: u8;
let i: i32 = 0;
for (i < s.len) {
if (s[i] == c) { return i; };
i += 1;
};
return;
};
case let sub: str => {
if (sub.len == 0) { return 0; };
if (sub.len > s.len) { return; };
let last: i32 = s.len - sub.len;
let i: i32 = 0;
for (i <= last) {
let j: i32 = 0;
let ok: bool = true;
for (j < sub.len) {
if (s[i + j] != sub[j]) { ok = false; j = sub.len; }
else { j += 1; };
};
if (ok) { return i; };
i += 1;
};
return;
};
};
return;
};
// contains — true iff `sub` appears in `s`. Mirrors Hare's
// strings::contains shape (byte-wise on the str-needle case).
export fn contains(s: str, sub: str) bool = {
let r: (i32 | void) = byteindex(s, sub);
match (r) {
case let i: i32 => return true;
case void => return false;
};
return false;
};
// concat — joins two strings into a fresh str. Caller owns the
// returned str's storage; release via `os.free(r.ptr, r.len)`. Mirrors
// Hare's strings::concat shape.
export fn concat(a: str, b: str) str = {
let total: i32 = a.len + b.len;
let buf: *u8 = os.alloc(total: u64): *u8;
let i: i32 = 0;
for (i < a.len) { buf[i] = a[i]; i += 1; };
let j: i32 = 0;
for (j < b.len) { buf[a.len + j] = b[j]; j += 1; };
let r: str;
r.ptr = buf;
r.len = total;
return r;
};
// dup — duplicate a string into a fresh allocation. Caller owns the
// returned str's storage; release via `os.free(r.ptr, r.len)`. Mirrors
// Hare's strings::dup shape — Hare returns `(str | nomem)`, ww doesn't
// have nomem (os.alloc aborts on OOM), so we return plain `str`.
//
// Empty input yields a `{nil, 0}` str — Hare returns the static empty
// string; same observable result.
export fn dup(s: str) str = {
let r: str;
r.ptr = nil;
r.len = 0;
if (s.len == 0) { return r; };
let buf: *u8 = os.alloc(s.len: u64): *u8;
let i: i32 = 0;
for (i < s.len) { buf[i] = s[i]; i += 1; };
r.ptr = buf;
r.len = s.len;
return r;
};
// rbyteindex — last byte position of `needle` in `s`. Mirrors Hare's
// strings::rbyteindex. Rune needle scans for the byte that encodes it
// (ASCII only); str needle scans for the substring. Empty str needle
// matches at s.len.
export fn rbyteindex(s: str, needle: (str | rune)) (i32 | void) = {
match (needle) {
case let r: rune => {
let c: u8 = r: u8;
let i: i32 = s.len - 1;
for (i >= 0) {
if (s[i] == c) { return i; };
i -= 1;
};
return;
};
case let sub: str => {
if (sub.len == 0) { return s.len; };
if (sub.len > s.len) { return; };
let i: i32 = s.len - sub.len;
for (i >= 0) {
let j: i32 = 0;
let ok: bool = true;
for (j < sub.len) {
if (s[i + j] != sub[j]) { ok = false; j = sub.len; }
else { j += 1; };
};
if (ok) { return i; };
i -= 1;
};
return;
};
};
return;
};
// sub — borrowed substring `s[start..end]`. Mirrors Hare's
// strings::sub. Caller must ensure 0 <= start <= end <= s.len; out-of-
// range indices are clamped silently here, where Hare aborts.
export fn sub(s: str, start: i32, end: i32) str = {
let lo: i32 = start;
let hi: i32 = end;
if (lo < 0) { lo = 0; };
if (hi > s.len) { hi = s.len; };
if (hi < lo) { hi = lo; };
let r: str;
r.ptr = s.ptr + (lo: u64);
r.len = hi - lo;
return r;
};
// trimprefix — `s` with `pre` stripped from the front, or `s`
// unchanged if it doesn't start with `pre`. Returns a borrowed view.
// Mirrors Hare's strings::trimprefix.
export fn trimprefix(s: str, pre: str) str = {
if (!hasprefix(s, pre)) { return s; };
let r: str;
r.ptr = s.ptr + (pre.len: u64);
r.len = s.len - pre.len;
return r;
};
// trimsuffix — `s` with `suf` stripped from the end, or `s` unchanged
// if it doesn't end with `suf`. Returns a borrowed view. Mirrors
// Hare's strings::trimsuffix.
export fn trimsuffix(s: str, suf: str) str = {
if (!hassuffix(s, suf)) { return s; };
let r: str;
r.ptr = s.ptr;
r.len = s.len - suf.len;
return r;
};
// ltrimbyte / rtrimbyte / trimbyte — strip occurrences of a single
// byte from the left, right, or both ends. Returns a borrowed view.
// Hare's strings::ltrim / rtrim / trim take a rune varargs set; ww's
// subset takes a single byte (the common ASCII case).
export fn ltrimbyte(s: str, c: u8) str = {
let i: i32 = 0;
for (i < s.len) {
if (s[i] != c) { break; };
i += 1;
};
let r: str;
r.ptr = s.ptr + (i: u64);
r.len = s.len - i;
return r;
};
export fn rtrimbyte(s: str, c: u8) str = {
let n: i32 = s.len;
for (n > 0) {
if (s[n - 1] != c) { break; };
n -= 1;
};
let r: str;
r.ptr = s.ptr;
r.len = n;
return r;
};
export fn trimbyte(s: str, c: u8) str = {
return rtrimbyte(ltrimbyte(s, c), c);
};
// MODULE: strconv
// strconv — number↔string conversions.
//
// Mirrors Hare's strconv:: surface. The *tos functions return a
// `const str` view into a module-level buffer that is overwritten on
// the next call to the same function; callers must copy the bytes if
// they need to outlive the next invocation. See [[strings.dup]] to
// duplicate. Matches Hare's strconv::*tos semantics.
use os;
use strings;
// 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. Mirrors Hare's
// `strconv::base` (Hare uses `enum uint`; we pick `enum i32` since
// the underlying parse/format loops index with i32).
//
// HEX is an alias for HEX_UPPER; HEX_LOWER is a pseudo-base that
// produces lowercase a-f digits.
export type base = enum i32 {
DEFAULT = 0,
BIN = 2,
OCT = 8,
DEC = 10,
HEX_UPPER = 16,
HEX = 16,
HEX_LOWER = 17,
};
fn basenum(b: base) i64 = {
if (b == base.BIN) { return 2; };
if (b == base.OCT) { return 8; };
if (b == base.HEX) { return 16; };
if (b == base.HEX_UPPER) { return 16; };
if (b == base.HEX_LOWER) { return 16; };
return 10; // DEC and DEFAULT
};
fn basedigit(d: i64, b: base) u8 = {
if (d < 10) { return (d + 48): u8; };
let off: i64 = d - 10;
if (b == base.HEX_LOWER) { return (off + 97): u8; };
return (off + 65): u8;
};
// u64tos — convert v to a base-b numeric string. Returns a view into
// `u64tos_buf` which is overwritten on the next call. Matches Hare's
// strconv::u64tos.
let u64tos_buf: [65]u8;
export fn u64tos(v: u64, b: base) 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 out: i32 = 0;
for (i > 0) {
i -= 1;
u64tos_buf[out] = tmp[i];
out += 1;
};
let r: str;
r.ptr = &u64tos_buf[0];
r.len = out;
return r;
};
// i64tos — convert v to a base-b numeric string. Returns a view into
// `i64tos_buf` which is overwritten on the next call. Independent
// buffer from u64tos so i64tos's own call to u64tos doesn't clobber
// the in-flight result. Matches Hare's strconv::i64tos.
let i64tos_buf: [66]u8;
export fn i64tos(v: i64, b: base) 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 out: i32 = 0;
if (neg) { i64tos_buf[out] = 45u8; out += 1; }; // '-'
for (i > 0) {
i -= 1;
i64tos_buf[out] = tmp[i];
out += 1;
};
let r: str;
r.ptr = &i64tos_buf[0];
r.len = out;
return r;
};
export fn i32tos(v: i32, b: base) str = { return i64tos(v: i64, b); };
export fn i16tos(v: i16, b: base) str = { return i64tos(v: i64, b); };
export fn i8tos(v: i8, b: base) str = { return i64tos(v: i64, b); };
export fn u32tos(v: u32, b: base) str = { return u64tos(v: u64, b); };
export fn u16tos(v: u16, b: base) str = { return u64tos(v: u64, b); };
export fn u8tos(v: u8, b: base) 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: base) i32 = {
if (c >= 48u8) { if (c <= 57u8) { return (c - 48u8): i32; }; };
if (b == base.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: base) (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: base) (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: base) (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: base) (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: base) (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: base) (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: base) (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: base) (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.
let f64tos_buf: [64]u8;
export fn f64tos(v: f64) str = {
let out: i32 = 0;
let f: f64 = v;
let zero: f64 = 0: f64;
if (f < zero) {
f64tos_buf[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) { f64tos_buf[out] = s[k]; out += 1; k += 1; };
let r: str;
r.ptr = &f64tos_buf[0];
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, base.DEC);
let k: i32 = 0;
for (k < intstr.len) { f64tos_buf[out] = intstr.ptr[k]; out += 1; k += 1; };
if (fp != 0) {
f64tos_buf[out] = 46u8; // '.'
out += 1;
let fracstr: str = u64tos(fp: u64, base.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) { f64tos_buf[out] = 48u8; out += 1; z -= 1; };
k = 0;
for (k < fracstr.len) { f64tos_buf[out] = fracstr.ptr[k]; out += 1; k += 1; };
// Trim trailing zeros in the fractional part.
for (out > 0) {
if (f64tos_buf[out - 1] != 48u8) { break; };
out -= 1;
};
};
let r: str;
r.ptr = &f64tos_buf[0];
r.len = out;
return r;
};
// strerror — convert an strconv error to a user-readable string.
// Returns owned str; release via os.free. Mirrors Hare's
// strconv::strerror.
export fn strerror(e: error) str = {
match (e) {
case let v: invalid => return strings.dup("input is not a valid number");
case let v: overflow => return strings.dup("input number doesn't fit target type");
};
return strings.dup("");
};
// 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;
};
// valid — `c` is in the 0..127 ASCII range.
export fn valid(c: rune) bool = {
if (c < 0) { return false; };
if (c > 127) { return false; };
return true;
};
// validstr — every byte in `s` is ASCII (0..127).
export fn validstr(s: str) bool = {
let i: i32 = 0;
for (i < s.len) {
// High-bit test rather than `> 127u8`; both cgens lower
// the bitwise form identically. The `> u8` form picks
// JA vs JG depending on signed/unsigned dispatch.
if ((s[i] & 128u8) != 0u8) { return false; };
i += 1;
};
return true;
};
// iscntrl — control chars: 0..31 and 127.
export fn iscntrl(c: rune) bool = {
if (c >= 0) { if (c <= 31) { return true; }; };
if (c == 127) { return true; };
return false;
};
// isblank — space and tab.
export fn isblank(c: rune) bool = {
if (c == 32) { return true; }; // ' '
if (c == 9) { return true; }; // '\t'
return false;
};
// isprint — printable: space through '~'.
export fn isprint(c: rune) bool = {
if (c < 32) { return false; };
if (c > 126) { return false; };
return true;
};
// isgraph — printable, non-space.
export fn isgraph(c: rune) bool = {
if (c < 33) { return false; };
if (c > 126) { return false; };
return true;
};
// ispunct — printable, non-alnum, non-space.
export fn ispunct(c: rune) bool = {
if (!isgraph(c)) { return false; };
if (isalnum(c)) { return false; };
return true;
};
// 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;
};
// strcasecmp — three-way ASCII case-insensitive compare.
export fn strcasecmp(a: str, b: str) i32 = {
let n: i32 = a.len;
if (b.len < n) { n = b.len; };
let i: i32 = 0;
for (i < n) {
let ca: rune = tolower(a[i]: rune);
let cb: rune = tolower(b[i]: rune);
if (ca != cb) { return (ca - cb): i32; };
i += 1;
};
return a.len - b.len;
};
// 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.base.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;
};