Files
ww/selfhost/cmd/ww/main.combined.ww

4382 lines
141 KiB
Plaintext

// time — clocks, instants, durations. Mirrors Hare's lib/time
// (ref/hare/time/duration.ha, instant.ha, arithm.ha,
// +linux/functions.ha). Calendar / date / strftime / timezone /
// sleep live in separate Hare modules and graduate when callers /
// supporting stdlib arrive.
//
// `duration` is a NAMED alias of i64 (lib/math/random precedent
// at lib/math/random/random.ww:8); ww treats NAMED as a newtype,
// so cross-i64 arithmetic inside this module needs explicit casts.
// Hare's structural alias semantics let those casts vanish, but
// our type checker is strict.
package time;
@symbol("rt_syscall") fn syscall2(num: i64, a: i64, b: i64) i64;
@symbol("rt_abort") fn abort(msg: str) void;
def SYS_CLOCK_GETTIME: i64 = 228;
// ref/hare/time/duration.ha:6. 290y representable range.
export type duration = i64;
// ref/hare/time/duration.ha:9-18. Plan-9 naming (lowercase)
// diverges from Hare's uppercase per project rule 4.
export def nanosecond: duration = 1i64;
export def microsecond: duration = 1000i64;
export def millisecond: duration = 1000000i64;
export def second: duration = 1000000000i64;
// ref/hare/time/instant.ha:9. (sec, nsec) pair — NOT POSIX struct
// timespec (which uses u32 nsec). Layout matches Linux's struct
// timespec on 64-bit (i64+i64) so we can pass &instant directly
// to clock_gettime.
export type instant = struct {
sec: i64,
nsec: i64,
};
// ref/hare/time/+linux/functions.ha:84. First cut exposes only
// realtime and monotonic; Hare's process_cpu / thread_cpu / boot /
// realtime_alarm / boot_alarm / tai graduate when a caller needs
// them (CLAUDE.md rule 9 — Hare-fidelity, no premature surface).
export type clock = enum i32 {
realtime = 0,
monotonic = 1,
};
// ref/hare/time/+linux/functions.ha:138. Hare's now() also aborts
// on impossible errnos. (instant | oserror) is deliberately not
// the return shape — EINVAL / EFAULT are programmer errors (bad
// clock id, bad ptr), and a 1-word-payload sum return walks into
// task #9's cgen-divergence trap.
export fn now(c: clock) instant = {
let i: instant;
let rc = syscall2(SYS_CLOCK_GETTIME, (c as i32): i64, (&i): i64);
if (rc != 0i64) { abort("time.now: clock_gettime failed"); };
return i;
};
// ref/hare/time/arithm.ha:9. Adds duration to instant. The
// negative-duration branch normalises nsec into [0, second).
export fn add(i: instant, x: duration) instant = {
let r: instant;
let xi: i64 = x: i64;
let sec: i64 = second: i64;
let nsec: i64 = nanosecond: i64;
if (xi == 0i64) {
r.sec = i.sec;
r.nsec = i.nsec;
return r;
};
if (xi > 0i64) {
r.sec = i.sec + (i.nsec + xi) / sec;
r.nsec = (i.nsec + xi) % sec;
return r;
};
r.sec = i.sec + (i.nsec + xi - sec + nsec) / sec;
r.nsec = (i.nsec + (xi % sec) + sec) % sec;
return r;
};
// ref/hare/time/arithm.ha:26. Returns duration from a to b.
// Sign convention: b - a.
export fn diff(a: instant, b: instant) duration = {
let sec: i64 = second: i64;
let v: i64 = ((b.sec - a.sec) * sec) + (b.nsec - a.nsec);
return v: duration;
};
// ref/hare/time/arithm.ha:32. -1 if a < b, 0 if equal, +1 if a > b.
export fn compare(a: instant, b: instant) i8 = {
if (a.sec < b.sec) { return -1i8; };
if (a.sec > b.sec) { return 1i8; };
if (a.nsec < b.nsec) { return -1i8; };
if (a.nsec > b.nsec) { return 1i8; };
return 0i8;
};
// 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.
package os;
import time;
@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_free") export 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,
MKDIR = 83,
RMDIR = 84,
UNLINK = 87,
GETCWD = 79,
GETDENTS64 = 217,
NEWFSTATAT = 262,
};
// 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
EXCL = 128, // 0x80 — pair with CREATE to fail on existing path
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);
};
// PATH_MAX / pathbuf / kpath — port of Hare's ref/hare/sys/+linux/
// syscalls.ha:25,27,29-55. Hare's `path` accepts a sum `(str |
// []u8 | *const u8)`; ww's lib/os public surface narrows to `str`
// (the Hare-faithful surface at ref/hare/os/os.ha:37,47,50 etc).
// Internally, [[kpath]] copies the `str` bytes into a single
// module-level [[pathbuf]] scratch slot and NUL-terminates so the
// raw Linux syscalls (which require C strings) see a valid
// terminator. Same precedent as Hare's static `pathbuf`.
//
// Non-reentrant: one buffer, every [[stat]] / [[open]] / etc.
// rewrites it. Same caveat as strconv's `*tos` family (overwritten
// on next call). Caller must NOT hold a kpath-returned pointer
// across another lib/os path call. Graduates when ww grows a
// thread story.
//
// `nil`-as-overflow over `(*u8 | oserror)`: wwstage over-allocates
// 1-word-payload tagged returns to 24B (cstage emits 16B).
// Task #9; revert at task #10 when fixed. Repro at
// .ai/probe_tagged_return_pointer_payload.ww.
export def PATH_MAX: i32 = 4096;
let pathbuf: [4096]u8;
// ref/hare/sys/+linux/types.ha:886-888. ww folds `sys` into `os`, so the
// std fd NUMBERS live here (the sys role). Typed i32, NOT io.file as in
// Hare's os::stdout_file (ref/hare/os/+linux/stdfd.ha:28): Hare's `os`
// imports `io`, but ww's `os` is the import floor and must never import
// io (lib/CLAUDE.md) — so the io.file/io.handle binding can't live here.
// Consumers (lib/fmt's stdio wrappers) cast i32→io.file at the use site,
// where the handle layer is already in scope.
export def STDIN_FILENO: i32 = 0;
export def STDOUT_FILENO: i32 = 1;
export def STDERR_FILENO: i32 = 2;
fn kpath(p: str) *u8 = {
if (p.len + 1 >= PATH_MAX) { return nil: *u8; }; // ENAMETOOLONG
let i: i32 = 0;
for (i < p.len) { pathbuf[i] = p[i]; i += 1; };
pathbuf[p.len] = 0u8;
return &pathbuf[0];
};
// 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). Returns -errno on failure, fd otherwise.
// Higher-level callers prefer `tryopen`. Mirrors Hare's os::open
// (ref/hare/os/os.ha:117); kpath lands the bytes in pathbuf.
// Returns -ENAMETOOLONG (-36) if the path overflows PATH_MAX.
export fn open(path: str, flags: flag, mode: i32) i32 = {
let p: *u8 = kpath(path);
if (p == nil: *u8) { return -36i32; }; // ENAMETOOLONG
return syscall3(nr.OPEN, p: i64, (flags as i32): i64, mode: i64): i32;
};
export fn tryopen(path: str, 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;
// errno — the raw Linux errno as a positive code (ref/hare/sys/+linux/
// errno.ha:5, `errno = !int`). ww folds Hare's `sys` role into os
// (lib/CLAUDE.md), so the sys::errno machinery lands here. Spelled i32
// rather than int: Linux errnos are kernel ints (32-bit), keeping os's
// kernel-facing surface uniformly i32. Distinct from [[oserror]] (!i64,
// the syscall's *negative* raw return) — the two model different
// things, so they are not unified; the negative→positive normalization
// lives at the oserror→errors.error boundary in those callers.
export type errno = !i32;
// Mapped errno values, ref/hare/sys/+linux/errno.ha:559-682. Positive,
// matching Hare's defs (the kernel returns -N; the wrap-to-positive is
// the caller's concern). Subset: exactly the errnos [[errors.errno]]
// maps to a named condition; grow as callers surface more.
export def ENOENT: errno = 2;
export def EINTR: errno = 4;
export def EAGAIN: errno = 11;
export def EACCES: errno = 13;
export def EBUSY: errno = 16;
export def EEXIST: errno = 17;
export def EINVAL: errno = 22;
export def EOVERFLOW: errno = 75;
export def ENETUNREACH: errno = 101;
export def ETIMEDOUT: errno = 110;
export def ECONNREFUSED: errno = 111;
export def ECANCELED: errno = 125;
// strerror — human-readable text for an [[errno]] (Hare's
// sys::strerror, ref/hare/sys/+linux/errno.ha:18). FAITHFUL MINIMAL
// SUBSET: the mapped errnos above plus a generic fallback; grow the
// switch as callers surface more (lib/CLAUDE.md documented-subset, not
// a workaround). Messages verbatim from the reference. Hare's
// unknown_errno formats the numeric value; that is deferred.
export fn strerror(err: errno) str = {
switch (err) {
case ENOENT: return "No such file or directory";
case EINTR: return "Interrupted system call";
case EAGAIN: return "Resource temporarily unavailable";
case EACCES: return "Permission denied";
case EBUSY: return "Device or resource busy";
case EEXIST: return "File exists";
case EINVAL: return "Invalid argument";
case EOVERFLOW: return "Value too large for defined data type";
case ENETUNREACH: return "Network is unreachable";
case ETIMEDOUT: return "Connection timed out";
case ECONNREFUSED: return "Connection refused";
case ECANCELED: return "Operation canceled";
};
return "Unknown error";
};
// 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).
// Mirrors Hare's os::access (ref/hare/os/+linux/fs.ha:access).
// Returns -ENAMETOOLONG (-36) if the path overflows PATH_MAX.
export fn access(path: str, mode: i32) i32 = {
let p: *u8 = kpath(path);
if (p == nil: *u8) { return -36i32; };
return syscall2(nr.ACCESS, p: i64, mode: i64): i32;
};
// remove — unlink(2). Mirrors Hare's os::remove
// (ref/hare/os/os.ha:12).
export fn remove(path: str) i32 = {
let p: *u8 = kpath(path);
if (p == nil: *u8) { return -36i32; };
return syscall1(nr.UNLINK, p: i64): i32;
};
// mkdir — mkdir(2). Mode is the unix permission bitset (e.g. 0o700).
// Returns 0 on success, negative errno otherwise. Mirrors Hare's
// os::mkdir (ref/hare/os/os.ha:50).
export fn mkdir(path: str, mode: i32) i32 = {
let p: *u8 = kpath(path);
if (p == nil: *u8) { return -36i32; };
return syscall2(nr.MKDIR, p: i64, mode: i64): i32;
};
// rmdir — rmdir(2). Mirrors Hare's os::rmdir
// (ref/hare/os/os.ha:58).
export fn rmdir(path: str) i32 = {
let p: *u8 = kpath(path);
if (p == nil: *u8) { return -36i32; };
return syscall1(nr.RMDIR, p: i64): i32;
};
// mkdirs — recursive mkdir. Creates `path` and any non-existent
// parent directories with the given mode. EEXIST is silently
// accepted (matches Hare's `errors::exists` skip in os::mkdirs);
// any other syscall failure surfaces as `oserror`.
//
// Mirrors Hare's os::mkdirs (ref/hare/os/os.ha:54). The in-place
// '/' → NUL splice walks the kpath-loaded [[pathbuf]] directly
// instead of recursing through [[mkdir]] — re-entering kpath would
// clobber the buffer mid-walk (single static slot, see kpath's
// non-reentrancy note above).
export fn mkdirs(path: str, mode: i32) (void | oserror) = {
let cp: *u8 = kpath(path);
if (cp == nil: *u8) { return -36i64: oserror; };
let n: i32 = path.len;
if (n == 0) { return; };
// Walk forward; at each '/' boundary, NUL-terminate the prefix,
// raw MKDIR syscall on pathbuf, restore the slash, continue.
// Skip index 0 so a leading '/' on absolute paths doesn't
// trigger an empty mkdir.
let i: i32 = 1;
for (i < n) {
if (pathbuf[i] == '/') {
pathbuf[i] = 0u8;
let r: i32 = syscall2(nr.MKDIR,
(&pathbuf[0]): i64, mode: i64): i32;
pathbuf[i] = 47u8;
if (r < 0) {
if (r != -17) { return r: i64: oserror; };
};
};
i += 1;
};
let r: i32 = syscall2(nr.MKDIR,
(&pathbuf[0]): i64, mode: i64): i32;
if (r < 0) {
if (r != -17) { return r: i64: oserror; };
};
return;
};
// 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. Mirrors Hare's
// os::exec::exec path arg (str). argv/envp stay `**u8` — the
// kernel takes a NUL-pointer-terminated table of NUL-terminated
// C strings, a different shape from a path.
export fn execve(path: str, argv: **u8, envp: **u8) i32 = {
let p: *u8 = kpath(path);
if (p == nil: *u8) { return -36i32; };
return syscall3(nr.EXECVE, p: 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);
};
// ---- environment ------------------------------------------------------
// rt_envp — runtime-side getter. rt/start.s captures envp into a DATAW
// slot before calling main; this binding lifts the captured pointer
// into ww. Same FFI shape as rt_syscall / rt_malloc / rt_abort: a TEXT
// symbol the linker resolves. The returned `**u8` is a NUL-terminated
// table of `*u8` entries, each pointing at a NUL-terminated
// "NAME=VALUE" byte sequence.
//
// We don't expose `rtenvp` directly; [[getenv]] is the only consumer.
@symbol("rt_envp") fn rtenvp() **u8;
// getenv — POSIX getenv. Returns a borrowed `str` view over the value
// bytes of the named environment variable, or void if the name is not
// present. The view is valid for the process lifetime — the bytes
// live in the kernel-supplied envp table at process entry. A future
// `setenv` (separate task) that grows the table behind the scenes
// would invalidate prior views; v1 has no setenv, so callers can
// hold the view indefinitely.
//
// Mirrors Hare's os::tryenv shape (returns void rather than panicking
// on missing). Hare also ships os::getenv (`(str | void)`) and
// os::mustenv (panic-on-missing); ww collapses to the single
// `(str | void)` form for now — consumers wanting "must" semantics
// abort at the call site.
//
// Algorithm: walk the NUL-pointer-terminated `environ` table doing a
// "name=" prefix match against each entry, byte-wise. NUL inside
// `name` would never match a real env var (env var names cannot
// contain '\0'), so we don't filter — POSIX puts that responsibility
// on the caller.
export fn getenv(name: str) (str | void) = {
let envp: **u8 = rtenvp();
let i: i32 = 0;
for (true) {
let entry: *u8 = envp[i];
if (entry == nil: *u8) { return; };
let j: i32 = 0;
let matched: bool = true;
for (j < name.len) {
if (entry[j] == 0u8) { matched = false; break; };
if (entry[j] != name[j]) { matched = false; break; };
j += 1;
};
if (matched) {
if (entry[name.len] == '=') {
let val: *u8 = entry + ((name.len + 1): u64);
let n: i32 = 0;
for (val[n] != 0u8) { n += 1; };
let r: str;
r.ptr = val;
r.len = n;
return r;
};
};
i += 1;
};
return;
};
// ---- stat / lstat / fstat / exists -----------------------------------
//
// Ports of Hare's stat family (ref/hare/fs/fs.ha:172,196 +
// ref/hare/sys/+linux/stat.ha:24-58). The Hare surface returns
// `filestat` by value; ww's cgreturn ABI tops out at 24B today (see
// STATUS task #21) and filestat is 80B, so [[stat]] / [[lstat]] /
// [[fstat]] take an out-parameter and return `(void | oserror)`.
// Re-evaluate the by-value shape when full sret lands.
//
// `filestat`, `mode`, and `stat_mask` live in lib/os because ww has
// no lib/fs yet; Hare puts them in `fs::`. These types graduate to
// lib/fs when that module ships — callers should expect a future
// re-export.
//
// Underlying syscall is SYS_newfstatat (262), which unifies
// stat/lstat/fstat through the `dirfd + flags` triple:
// stat = newfstatat(AT_FDCWD, path, 0)
// lstat = newfstatat(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW)
// fstat = newfstatat(fd, "", AT_EMPTY_PATH)
// Avoiding SYS_statx — its 256B variable layout would buy btime,
// but Hare's filestat doesn't expose btime either, so we stay on
// the simpler 144B kernel struct.
// fstatat(2) flag values. Linux constants from <linux/fcntl.h>.
// Names mirror Hare's ref/hare/sys/+linux/types.ha:45-51 (capital-
// AT_ prefix, top-level `def`s).
export def AT_FDCWD: i32 = -100;
export def AT_SYMLINK_NOFOLLOW: i32 = 256; // 0x100
export def AT_EMPTY_PATH: i32 = 4096; // 0x1000
// mode — file-mode bits. Mirrors Hare's fs::mode (ref/hare/fs/
// types.ha:63). Permission bits are the standard Unix octal subset;
// type bits live in the S_IFMT = 0o170000 region. Type-bit test:
//
// let t: u32 = (fi.mode as u32) & 61440u32; // 0o170000 mask
// if (t == os.mode.DIR as u32) { /* directory */ };
//
// Numeric values are octal in Hare's source; ww has no octal
// literals so they're written as decimal with the octal in a
// trailing comment.
export type mode = enum u32 {
// permission bits
USER_RWX = 448u32, // 0o700
USER_RW = 384u32, // 0o600
USER_RX = 320u32, // 0o500
USER_R = 256u32, // 0o400
USER_W = 128u32, // 0o200
USER_X = 64u32, // 0o100
GROUP_RWX = 56u32, // 0o070
GROUP_RW = 48u32, // 0o060
GROUP_RX = 40u32, // 0o050
GROUP_R = 32u32, // 0o040
GROUP_W = 16u32, // 0o020
GROUP_X = 8u32, // 0o010
OTHER_RWX = 7u32, // 0o007
OTHER_RW = 6u32, // 0o006
OTHER_RX = 5u32, // 0o005
OTHER_R = 4u32, // 0o004
OTHER_W = 2u32, // 0o002
OTHER_X = 1u32, // 0o001
SETUID = 2048u32, // 0o4000
SETGID = 1024u32, // 0o2000
STICKY = 512u32, // 0o1000
// file-type bits (S_IFMT mask = 0o170000 = 61440)
UNKNOWN = 0u32,
FIFO = 4096u32, // 0o010000
CHR = 8192u32, // 0o020000
DIR = 16384u32, // 0o040000
BLK = 24576u32, // 0o060000
REG = 32768u32, // 0o100000
LINK = 40960u32, // 0o120000
SOCK = 49152u32, // 0o140000
};
// stat_mask — which filestat fields the call populated. Mirrors
// Hare's fs::stat_mask (ref/hare/fs/types.ha:129). newfstatat fills
// every field, so [[stat]] / [[lstat]] / [[fstat]] always set all
// seven bits OR-folded (see [[fillfilestat]]); per-bit testing is
// the documented sparse-backend pattern (cf. Hare's fs::fs network
// backends that only populate mtime+size).
export type stat_mask = enum u32 {
UID = 1u32,
GID = 2u32,
SIZE = 4u32,
INODE = 8u32,
ATIME = 16u32,
MTIME = 32u32,
CTIME = 64u32,
};
// filestat — Hare's fs::filestat (ref/hare/fs/types.ha:141). 80
// bytes. Times are time.instant (ref/hare/time/instant.ha:9) — the
// canonical Hare shape. See module-header note re: graduation to
// lib/fs.
export type filestat = struct {
mask: stat_mask, // 0 (4)
mode: mode, // 4 (4)
uid: u32, // 8 (4)
gid: u32, // 12 (4)
sz: u64, // 16 (8)
inode: u64, // 24 (8)
atime: time.instant, // 32 (16)
mtime: time.instant, // 48 (16)
ctime: time.instant, // 64 (16) — ends at 80
};
// kstat — x86_64 kernel `struct stat` layout. Mirrors
// arch/x86/include/uapi/asm/stat.h (`__kernel_ulong_t`-keyed
// fields). 144 bytes. Module-internal; SYS_newfstatat writes into
// this buffer and the public stat fns then copy the bits into the
// Hare-shaped [[filestat]].
type kstat = struct {
dev: u64, // 0
ino: u64, // 8
nlink: u64, // 16
mode: u32, // 24
uid: u32, // 28
gid: u32, // 32
pad0: u32, // 36
rdev: u64, // 40
sz: i64, // 48
blksize: i64, // 56
blocks: i64, // 64
atime_sec: i64, // 72
atime_nsec: i64, // 80
mtime_sec: i64, // 88
mtime_nsec: i64, // 96
ctime_sec: i64, // 104
ctime_nsec: i64, // 112
unused0: i64, // 120
unused1: i64, // 128
unused2: i64, // 136 — ends at 144
};
// emptypath — single-NUL byte used as the `pathname` arg to
// newfstatat with AT_EMPTY_PATH. The kernel requires a non-NULL
// pointer to a zero-length C string, NOT a null pointer. Bytes are
// read-only from the kernel's view; ww has no module-level const so
// this is a writable `let`.
let emptypath: [1]u8 = [0u8];
// fillfilestat — copy a 144B kstat into the 80B Hare-shaped
// filestat. Internal helper used by all three public entry points.
// Mirrors Hare's st_to_filestat (ref/hare/os/+linux/dirfdfs.ha:259):
// newfstatat populates every field, so the mask is the OR-fold of
// all seven Hare stat_mask bits.
fn fillfilestat(out: *filestat, k: *kstat) void = {
out.mask = stat_mask.UID | stat_mask.GID | stat_mask.SIZE
| stat_mask.INODE | stat_mask.ATIME | stat_mask.MTIME
| stat_mask.CTIME;
out.mode = k.mode: mode;
out.uid = k.uid;
out.gid = k.gid;
out.sz = k.sz: u64;
out.inode = k.ino;
out.atime.sec = k.atime_sec;
out.atime.nsec = k.atime_nsec;
out.mtime.sec = k.mtime_sec;
out.mtime.nsec = k.mtime_nsec;
out.ctime.sec = k.ctime_sec;
out.ctime.nsec = k.ctime_nsec;
};
// stat — fill *out with metadata for `path`. Follows symlinks.
// Returns ENAMETOOLONG (-36) as `oserror` if the path overflows
// PATH_MAX.
//
// Mirrors Hare's sys::stat (ref/hare/sys/+linux/stat.ha:51) modulo
// the out-param shape forced by the cgreturn 24B cap. Note: Hare's
// higher-level fs::stat (ref/hare/fs/fs.ha:172) instead has lstat
// semantics — we follow sys::stat's POSIX-stat behavior here.
export fn stat(out: *filestat, path: str) (void | oserror) = {
let cp: *u8 = kpath(path);
if (cp == nil: *u8) { return -36i64: oserror; };
let k: kstat;
let r: i64 = syscall4(nr.NEWFSTATAT,
AT_FDCWD: i64, cp: i64, (&k): i64, 0i64);
if (r < 0) { return r: oserror; };
fillfilestat(out, &k);
};
// lstat — like [[stat]] but does NOT follow a terminal symlink.
// Mirrors Hare's sys::lstat (ref/hare/sys/+linux/stat.ha:57).
export fn lstat(out: *filestat, path: str) (void | oserror) = {
let cp: *u8 = kpath(path);
if (cp == nil: *u8) { return -36i64: oserror; };
let k: kstat;
let r: i64 = syscall4(nr.NEWFSTATAT,
AT_FDCWD: i64, cp: i64, (&k): i64,
AT_SYMLINK_NOFOLLOW: i64);
if (r < 0) { return r: oserror; };
fillfilestat(out, &k);
};
// fstat — like [[stat]] but addresses the file by fd. Uses
// newfstatat(fd, "", AT_EMPTY_PATH); the kernel resolves the fd
// directly. Mirrors Hare's sys::fstat (ref/hare/sys/+linux/stat.ha:54).
export fn fstat(out: *filestat, fd: i32) (void | oserror) = {
let k: kstat;
let r: i64 = syscall4(nr.NEWFSTATAT,
fd: i64, (&emptypath[0]): i64, (&k): i64,
AT_EMPTY_PATH: i64);
if (r < 0) { return r: oserror; };
fillfilestat(out, &k);
};
// exists — true if `path` resolves to anything (regular file,
// directory, symlink, ...). Stat-shaped (Hare's `fs::exists`,
// ref/hare/fs/fs.ha:196) — no separate syscall. Symlinks are
// followed; a dangling symlink is `false`. ENAMETOOLONG is
// swallowed as `false` — Hare's os::exists doc says "true if a
// node exists at the given path, or false if not."
//
// Race warning: prefer "open and handle the error" over "exists
// then open" in real code (Hare's docstring carries the same
// note). The race is unavoidable in this shape.
//
// Goes through SYS_newfstatat directly rather than match'ing on
// [[stat]]'s `(void | oserror)` return. Functionally identical;
// the direct shape sidesteps a cstage/wwstage cgen disagreement
// on the slot size of `(void | oserror)` (cstage 16B, wwstage 24B
// — same class as STATUS #22, surfaced first time a match on this
// shape combined with an 80B local-struct local frame). Use the
// match shape once #22 lands.
export fn exists(path: str) bool = {
let cp: *u8 = kpath(path);
if (cp == nil: *u8) { return false; };
let k: kstat;
let r: i64 = syscall4(nr.NEWFSTATAT,
AT_FDCWD: i64, cp: i64, (&k): i64, 0i64);
return r >= 0i64;
};
// rt — runtime primitives exposed to ww programs.
// Mirrors Hare's rt:: module placement (ref/hare/rt/).
package rt;
// malloc — mmap-backed page allocator. Untyped: `malloc(n)` returns a
// `*void`; callers cast to the target type. Diverges from Hare: Hare
// exposes `alloc` / `free` as typed language builtins that the
// compiler lowers to rt::malloc/rt::free; ww has no such builtins,
// so the rt-symbol surface is exposed directly. Stdlib callers that
// need a typed allocation pattern wrap this with a cast plus a stored
// capacity (see [[strings.dup]], [[memio.dynamic]]).
//
// OOM: rt_malloc is a bare mmap(MAP_ANON|MAP_PRIVATE) wrapper with no
// error path. The raw Linux mmap syscall returns a negative errno cast
// to `*void` on failure (e.g. `(void*)-12` for ENOMEM); the
// `MAP_FAILED` (`(void*)-1`) value is a libc-wrapper convention that
// rt_malloc doesn't apply. Neither `== nil` nor `== (void*)-1` catches
// it; any deref of such a return faults. Today the stdlib does not
// check; OOM faults on first dereference. A typed fallible variant is
// a future task (task #39). ref/hare/rt/malloc.ha:27.
@symbol("rt_malloc") export fn malloc(n: u64) *void;
// types — integer limits. Mirrors Hare's types::limits (I8_MAX, …)
// platform-fixed for amd64. Numeric helpers live in lib/math, matching
// Hare's split between types::limits and math::.
package types;
def I8_MAX: i8 = 127;
def I16_MAX: i16 = 32767;
def I32_MAX: i32 = 2147483647;
def I64_MAX: i64 = 9223372036854775807;
def I8_MIN: i8 = -128;
def I16_MIN: i16 = -32768;
def I32_MIN: i32 = -2147483648;
def I64_MIN: i64 = -9223372036854775808;
def U8_MAX: u8 = 255;
def U16_MAX: u16 = 65535;
def U32_MAX: u32 = 4294967295;
def U64_MAX: u64 = 18446744073709551615;
def U8_MIN: u8 = 0;
def U16_MIN: u16 = 0;
def U32_MIN: u32 = 0;
def U64_MIN: u64 = 0;
// int/uint are machine-word (Go-style, type.c:58); limits derived from
// size(int) per #114 + user ruling; cf Go math.MaxInt; diverges from
// Hare's per-arch literal (arch+x86_64.ha) because ww's int is 64-bit.
def INT_MAX: int = (1 << (size(int)*8 - 1)) - 1;
def INT_MIN: int = -1 << (size(int)*8 - 1);
def UINT_MIN: uint = 0;
def UINT_MAX: uint = ~(0: uint);
// size is 8B on amd64; no cast needed (size ∈ unsigned class per #113).
def SIZE_MIN: size = U64_MIN;
def SIZE_MAX: size = U64_MAX;
// uintptr not in the unsigned class, so the cast is required (Hare's form).
def UINTPTR_MIN: uintptr = U64_MIN: uintptr;
def UINTPTR_MAX: uintptr = U64_MAX: uintptr;
def RUNE_MIN: rune = '\0';
// bytes — slice operations over []u8. Mirrors Hare's bytes module
// (ref/hare/bytes/) for the in-tree subset: search/equality/prefix
// helpers used by lib/encoding, lib/bufio, lib/memio.
//
// Documented divergences from Hare:
// - index_slice / rindex_slice use naive O(n·m); Hare specialises
// 2/3/4-byte needles and falls back to two_way (Crochemore-Perrin)
// for longer (ref/hare/bytes/index.ha:61, ref/hare/bytes/two_way.ha).
// Correctness equivalent.
// - peek_token dispatches index/rindex by branching on `reverse`
// rather than a function-pointer `ifunc` (ref/hare/bytes/tokenize.ha:97).
// ww has no fn pointers in scope yet — same pattern as lib/strings
// `move`. Outwardly identical.
// - tokenize / rtokenize zero the `delim` field on the constructed
// tokenizer when `in` is empty, rather than mutating the variadic
// param before the struct write (ref/hare/bytes/tokenize.ha:26-28).
// Semantically identical; the variadic param is borrowed and
// captured-by-value into the struct, so mutating either side
// yields the same observable state.
package bytes;
import os;
import types;
// done — iteration sentinel returned by next_token / peek_token at
// end-of-input. ref/hare/bytes/tokenize.ha uses the built-in `done`
// token; ww spells it per-package the same way lib/encoding/utf8 does
// (utf8.ww:36). Plain `void` (not `!void`): continuation signal.
export type done = void;
// tokenizer — cursor over an input slice. Layout mirrors
// ref/hare/bytes/tokenize.ha:6-10. `p` is the cached peek-position;
// I64_MAX (forward) / I64_MIN (reverse) are the unprimed sentinels.
// p < 0 also identifies a reverse-direction iterator.
export type tokenizer = struct {
in: []u8,
delim: []u8,
p: i64,
};
// equal — true iff `a` and `b` have the same length and contents.
// ref/hare/bytes/equal.ha:9.
export fn equal(a: []u8, b: []u8) bool = {
if (a.len != b.len) { return false; };
let i: i32 = 0;
for (i < a.len) {
if (a[i] != b[i]) { return false; };
i += 1;
};
return true;
};
// index — first offset of `needle` in `s`. u8 needle scans for the
// byte; []u8 needle scans for the substring. void if absent.
// ref/hare/bytes/index.ha:6.
export fn index(s: []u8, needle: (u8 | []u8)) (i32 | void) = {
match (needle) {
case let c: u8 => {
let i: i32 = 0;
for (i < s.len) {
if (s[i] == c) { return i; };
i += 1;
};
return;
};
case let sub: []u8 => {
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;
};
// rindex — last offset of `needle` in `s`. Empty []u8 needle returns
// s.len (ref/hare/bytes/index.ha:103 — Hare's loop yields r-0 at i=0).
// ref/hare/bytes/index.ha:86.
export fn rindex(s: []u8, needle: (u8 | []u8)) (i32 | void) = {
match (needle) {
case let c: u8 => {
let i: i32 = s.len - 1;
for (i >= 0) {
if (s[i] == c) { return i; };
i -= 1;
};
return;
};
case let sub: []u8 => {
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;
};
// contains — true iff any of `needles` (byte or sub-slice) appears in `s`.
// ref/hare/bytes/contains.ha:6.
export fn contains(s: []u8, needles: (u8 | []u8)...) bool = {
let i: i32 = 0;
for (i < needles.len) {
match (needles[i]) {
case let b: u8 => {
match (index(s, b)) {
case let bo: i32 => return true;
case void => void;
};
};
case let n: []u8 => {
match (index(s, n)) {
case let bo: i32 => return true;
case void => void;
};
};
};
i += 1;
};
return false;
};
// ltrim — borrowed view of `in` with leading bytes in `trim` stripped.
// `trim` must be non-empty. ref/hare/bytes/trim.ha:7.
export fn ltrim(in: []u8, trim: u8...) []u8 = {
os.assert(trim.len > 0, "bytes.ltrim called with empty trim set");
let i: i32 = 0;
for (i < in.len && contains(trim, in[i])) { i += 1; };
let r: []u8;
r.ptr = in.ptr + (i: u64);
r.len = in.len - i;
r.cap = r.len;
return r;
};
// rtrim — borrowed view of `in` with trailing bytes in `trim` stripped.
// `trim` must be non-empty. ref/hare/bytes/trim.ha:17. Hare's loop uses
// `size` underflow at i==0 to terminate; ww indices are signed i32, so
// the equivalent termination is spelled `i >= 0` explicitly.
export fn rtrim(in: []u8, trim: u8...) []u8 = {
os.assert(trim.len > 0, "bytes.rtrim called with empty trim set");
let i: i32 = in.len - 1;
for (i >= 0 && contains(trim, in[i])) { i -= 1; };
let r: []u8;
r.ptr = in.ptr;
r.len = i + 1;
r.cap = r.len;
return r;
};
// trim — borrowed view of `in` with both ends in `trim` stripped.
// ref/hare/bytes/trim.ha:27.
export fn trim(in: []u8, trim: u8...) []u8 = {
return ltrim(rtrim(in, trim...), trim...);
};
// hasprefix — true iff `s` starts with `pre`.
// ref/hare/bytes/contains.ha:21.
export fn hasprefix(s: []u8, pre: []u8) bool = {
if (pre.len > s.len) { return false; };
let i: i32 = 0;
for (i < pre.len) {
if (s[i] != pre[i]) { return false; };
i += 1;
};
return true;
};
// hassuffix — true iff `s` ends with `suf`.
// ref/hare/bytes/contains.ha:35.
export fn hassuffix(s: []u8, suf: []u8) 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;
};
// reverse — in-place reverse of `s`. ref/hare/bytes/reverse.ha:5.
export fn reverse(s: []u8) void = {
let i: i32 = 0;
let j: i32 = s.len - 1;
for (i < j) {
let t: u8 = s[i];
s[i] = s[j];
s[j] = t;
i += 1;
j -= 1;
};
};
// zero — set every byte of `s` to 0. ref/hare/bytes/zero.ha:5.
export fn zero(s: []u8) void = {
let i: i32 = 0;
for (i < s.len) {
s[i] = 0u8;
i += 1;
};
};
// tokenize — iterator yielding tokens from `in` separated by any byte
// in `delim`. Leading / trailing / adjacent delims yield empty tokens.
// `delim` is borrowed; caller keeps it valid for the tokenizer's
// lifetime. ref/hare/bytes/tokenize.ha:22.
export fn tokenize(in: []u8, delim: u8...) tokenizer = {
os.assert(delim.len > 0, "bytes.tokenize called with empty slice");
os.assert((in.len: i64) < types.I64_MAX,
"bytes.tokenize: input length exceeds I64_MAX");
let t: tokenizer;
t.in = in;
t.delim = delim;
if (in.len == 0) {
t.delim.len = 0;
t.delim.cap = 0;
};
t.p = types.I64_MAX;
return t;
};
// rtokenize — reverse-direction tokenize. First next_token yields the
// last token, last next_token yields the first. ref/hare/bytes/tokenize.ha:40.
export fn rtokenize(in: []u8, delim: u8...) tokenizer = {
os.assert(delim.len > 0, "bytes.rtokenize called with empty slice");
os.assert((in.len: i64) < types.I64_MAX,
"bytes.rtokenize: input length exceeds I64_MAX");
let t: tokenizer;
t.in = in;
t.delim = delim;
if (in.len == 0) {
t.delim.len = 0;
t.delim.cap = 0;
};
t.p = types.I64_MIN;
return t;
};
// peek_token — next token without advancing the cursor. Returns done
// once `s.delim` has been zeroed by a prior past-end next_token.
// ref/hare/bytes/tokenize.ha:91.
export fn peek_token(s: *tokenizer) ([]u8 | done) = {
if (s.delim.len == 0) {
let d: done; return d;
};
let reverse: bool = s.p < 0i64;
let known: bool = false;
if (reverse) {
if (s.p != types.I64_MIN) { known = true; };
} else {
if (s.p != types.I64_MAX) { known = true; };
};
if (!known) {
let i: i64 = types.I64_MAX;
if (reverse) { i = types.I64_MIN; };
let dlen: i64 = 0i64;
let slen: i64 = s.in.len: i64;
let k: i32 = 0;
for (k < s.delim.len) {
let d: u8 = s.delim[k];
let ix_found: bool = false;
let ix_val: i32 = 0;
if (reverse) {
match (rindex(s.in, d)) {
case let v: i32 => { ix_found = true; ix_val = v; };
case void => void;
};
} else {
match (index(s.in, d)) {
case let v: i32 => { ix_found = true; ix_val = v; };
case void => void;
};
};
if (ix_found) {
if (!reverse) {
if ((ix_val: i64) < i) { i = ix_val: i64; dlen = 1i64; };
} else {
if ((ix_val: i64) > i) { i = ix_val: i64; dlen = 1i64; };
};
} else {
if (!reverse) {
if (slen < i) { i = slen; };
} else {
if (0i64 > i) { i = 0i64; };
};
};
k += 1;
};
if (reverse) {
if (i == slen) {
s.p = -(slen + 1i64);
} else {
s.p = i + dlen - slen - 1i64;
};
} else {
s.p = i;
};
};
let r: []u8;
if (reverse) {
let start: i32 = (s.in.len: i64 + s.p + 1i64): i32;
r.ptr = s.in.ptr + (start: u64);
r.len = s.in.len - start;
r.cap = r.len;
} else {
let end: i32 = s.p: i32;
r.ptr = s.in.ptr;
r.len = end;
r.cap = end;
};
return r;
};
// next_token — current token, then advance past it and the delim.
// Once the input is exhausted, returns done and zeros `s.delim` so
// subsequent peeks short-circuit. ref/hare/bytes/tokenize.ha:59.
export fn next_token(s: *tokenizer) ([]u8 | done) = {
let b: []u8;
match (peek_token(s)) {
case let v: []u8 => { b = v; };
case done => { let d: done; return d; };
};
let slen: i64 = s.in.len: i64;
let reverse: bool = s.p < 0i64;
if (reverse) {
if (slen + s.p + 1i64 == 0i64) {
s.delim.len = 0;
s.delim.cap = 0;
s.in.len = 0;
s.in.cap = 0;
} else {
let end: i32 = (slen + s.p + 1i64 - 1i64): i32;
s.in.len = end;
s.in.cap = end;
};
s.p = types.I64_MIN;
} else {
if (s.p == slen) {
s.delim.len = 0;
s.delim.cap = 0;
s.in.len = 0;
s.in.cap = 0;
} else {
let adv: u64 = (s.p: u64) + 1u64;
let adv_i32: i32 = (s.p: i32) + 1;
s.in.ptr = s.in.ptr + adv;
s.in.len = s.in.len - adv_i32;
s.in.cap = s.in.cap - adv_i32;
};
s.p = types.I64_MAX;
};
return b;
};
// remaining_tokens — the unconsumed portion of `s.in`. Read-only view.
// ref/hare/bytes/tokenize.ha:145.
export fn remaining_tokens(s: *tokenizer) []u8 = {
return s.in;
};
// rt_ensure is the runtime slice-growth helper invoked by the
// `append(s, v)` builtin. We bind it directly because the builtin's
// expansion stores only 8 bytes of the new element (cgen emits a
// single MOVQ), losing the .len/.cap fields of a []u8 element (24B).
// Mirrors the same workaround in lib/shlex.shlex (appendstr, 16B) and
// lib/getopt.getopt (appendoption, 24B); collapses in one go when the
// append builtin learns to store the full element width.
@symbol("rt_ensure") fn rtensure(s: *void, membsz: u64) void;
// appendslice — grow `*slice` by one and store `item` (24B). Mirror
// of [[shlex.appendstr]] / [[getopt.appendoption]]. Bypasses the
// `append` builtin's first-8B-only-store gap for a slice-element.
fn appendslice(slice: *[][]u8, item: []u8) void = {
let newlen: i32 = slice.len + 1;
slice.len = newlen;
rtensure(slice: *void, 24u64);
let dst: *[]u8 = &slice.ptr[newlen - 1];
dst.ptr = item.ptr;
dst.len = item.len;
dst.cap = item.cap;
};
// splitn — split `in` on any byte in `delim`, returning up to `n`
// tokens via forward iteration. The trailing slot (when more than
// `n - 1` tokens exist) holds the unconsumed remainder.
//
// The caller frees the returned slice via
// `os.free(r.ptr: *void, (r.cap: u64) * 24u64)`. Element bytes are
// borrowed from `in`.
//
// Hare's `([][]u8 | nomem)` collapses to `[][]u8` here: ww os.alloc
// has no recoverable failure path. Same precedent as
// shlex.split / getopt.tryparse.
//
// ref/hare/bytes/tokenize.ha:156.
export fn splitn(in: []u8, delim: []u8, n: i32) [][]u8 = {
os.assert(delim.len > 0,
"bytes.splitn must not be called with an empty delimiter");
let toks: [][]u8;
toks.ptr = nil: *[]u8;
toks.len = 0;
toks.cap = 0;
let tok: tokenizer = tokenize(in, delim...);
let i: i32 = 0;
for (i < n - 1) {
match (next_token(&tok)) {
case let s: []u8 => { appendslice(&toks, s); };
case done => { return toks; };
};
i += 1;
};
match (peek_token(&tok)) {
case done => void;
case let pk: []u8 => {
let r: []u8 = remaining_tokens(&tok);
appendslice(&toks, r);
};
};
return toks;
};
// rsplitn — reverse-direction counterpart to [[splitn]]: tokens are
// collected from the end of `in`. The trailing slot holds the
// unconsumed prefix (everything before the n-th-from-last delim hit).
//
// When the input has fewer than n tokens, the `done` short-circuit
// returns toks UN-reversed (in last-token-first order). Mirrors Hare
// at ref/hare/bytes/tokenize.ha:196-199 where the in-place reverse
// step is gated behind the n-1 loop running to completion. Only the
// "loop ran to completion AND peek saw a remainder" path applies the
// reverse; both early-exit paths skip it.
//
// ref/hare/bytes/tokenize.ha:186.
export fn rsplitn(in: []u8, delim: []u8, n: i32) [][]u8 = {
os.assert(delim.len > 0,
"bytes.rsplitn called with empty delimiter");
let toks: [][]u8;
toks.ptr = nil: *[]u8;
toks.len = 0;
toks.cap = 0;
let tok: tokenizer = rtokenize(in, delim...);
let i: i32 = 0;
for (i < n - 1) {
match (next_token(&tok)) {
case let s: []u8 => { appendslice(&toks, s); };
case done => { return toks; };
};
i += 1;
};
match (peek_token(&tok)) {
case done => void;
case let pk: []u8 => {
let r: []u8 = remaining_tokens(&tok);
appendslice(&toks, r);
};
};
// In-place reverse so callers see argv-order, matching Hare
// (ref/hare/bytes/tokenize.ha:207). Element copy is field-wise
// through `*[]u8` because `toks[i] = toks[j]` (full 24B slice
// store) lands in the multi-word-store gap noted at
// cmd/w6c/cgen.c:6515-6523.
let a: i32 = 0;
let b: i32 = toks.len - 1;
for (a < b) {
let pa: *[]u8 = &toks.ptr[a];
let pb: *[]u8 = &toks.ptr[b];
let tp: *u8 = pa.ptr;
let tl: i32 = pa.len;
let tc: i32 = pa.cap;
pa.ptr = pb.ptr;
pa.len = pb.len;
pa.cap = pb.cap;
pb.ptr = tp;
pb.len = tl;
pb.cap = tc;
a += 1;
b -= 1;
};
return toks;
};
// split — full split of `in` on `delim` (no token cap). Mirrors
// `splitn(in, delim, types::SIZE_MAX)`. ww uses `types.I32_MAX`
// because the index type is i32 (lib/CLAUDE.md).
//
// ref/hare/bytes/tokenize.ha:225.
export fn split(in: []u8, delim: []u8) [][]u8 = {
return splitn(in, delim, types.I32_MAX);
};
// cut — split `in` along the first instance of `delim`, returning the
// portion before and the portion after the delimiter as a borrowed
// tuple. When `delim` is absent, the whole input is the first half and
// the second is empty. ref/hare/bytes/tokenize.ha:392.
//
// Delim is spelled (u8 | []u8) to match index/rindex (bytes.ww:57/91);
// the tagged union is an unordered set, so this is the same type as
// Hare's ([]u8 | u8), not a divergence.
export fn cut(in: []u8, delim: (u8 | []u8)) ([]u8, []u8) = {
let ln: i32 = match (delim) {
case let c: u8 => yield 1i32;
case let sub: []u8 => {
os.assert(sub.len > 0,
"bytes.cut called with empty delimiter");
yield sub.len;
};
};
match (index(in, delim)) {
case let i: i32 => {
let lo: i32 = i + ln;
return (in[0:i], in[lo:in.len]);
};
case void => {
let empty: []u8;
empty.ptr = nil; empty.len = 0; empty.cap = 0;
return (in, empty);
};
};
};
// rcut — like [[cut]] but splits along the last instance of `delim`.
// ref/hare/bytes/tokenize.ha:413.
export fn rcut(in: []u8, delim: (u8 | []u8)) ([]u8, []u8) = {
let ln: i32 = match (delim) {
case let c: u8 => yield 1i32;
case let sub: []u8 => {
os.assert(sub.len > 0,
"bytes.rcut called with empty delimiter");
yield sub.len;
};
};
match (rindex(in, delim)) {
case let i: i32 => {
let lo: i32 = i + ln;
return (in[0:i], in[lo:in.len]);
};
case void => {
let empty: []u8;
empty.ptr = nil; empty.len = 0; empty.cap = 0;
return (in, empty);
};
};
};
// encoding/utf8 — UTF-8 encode/decode. Hare port; see
// ref/hare/encoding/utf8/{types,rune,encode,decode,decodetable}.ha.
//
// The decoder is Hoehrmann's branchless DFA, originally published
// at <https://bjoern.hoehrmann.de/utf-8/decoder/dfa/>. Hare's
// ref/hare/encoding/utf8/decodetable.ha:4 restructures Hoehrmann's
// flat table to 2D `[8][256]i8`; we flatten back to 1D `[2048]i8`
// because ww cgen does not yet ship 2D arrays (task #20).
//
// Surface deviation from ref/hare/encoding/utf8:
//
// - `encoderune` takes a caller-supplied `out: []u8` and returns
// the byte count. Hare returns a slice into a `static let buf`;
// the caller-buffer form skips the static-buffer/slice-return pair.
//
// Deferred (no in-tree caller, follow-up tasks): `appendrune`,
// `strencode`, `strdecode`. Hare's string-iteration surface
// (`strings::iterator`/`strings::next` — ref/hare/strings/iter.ha)
// lives under lib/strings, not here.
// ref/hare/encoding/utf8/types.ha:6 — incomplete trailing sequence.
// Plain `void` (not `!void`): a truncated tail is a control-flow
// signal, not an error caller can ignore.
package utf8;
export type more = void;
// ref/hare/encoding/utf8/types.ha:9 — invalid UTF-8 sequence.
export type invalid = !void;
// ref/hare/encoding/utf8/types.ha:12 — fixed message; `invalid` carries
// no payload, so the rendering is constant.
export fn strerror(err: invalid) str = {
return "Invalid UTF-8";
};
// `done` is not a built-in singleton in ww (Hare ships it as part of
// the type system). Plain `void` (not `!void`): end-of-input is a
// continuation signal, not an error. lib/io spells its EOF the same
// way (lib/io/io.ww:8-11).
export type done = void;
// ref/hare/encoding/utf8/decodetable.ha:4 — Hoehrmann's UTF-8 DFA,
// flat 1D `[2048]i8`. Layout: dfa[state*256 + byte] gives the next
// state (>0), the accept transition (0 — emit rune), or invalid (-1).
// Values match ref/hare/encoding/utf8/decodetable.ha verbatim.
let dfa: [2048]i8 = [
// state 0 — initial byte: ASCII accepts (0), continuation/illegal
// byte rejects (-1), legal multibyte start emits a state.
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
3i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 4i8, 2i8, 2i8,
5i8, 6i8, 6i8, 6i8, 7i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 1 — expecting one continuation byte (0x80..0xBF).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8, 0i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 2 — expecting one continuation byte (full 0x80..0xBF range).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 3 — first byte was 0xE0; continuation byte must be 0xA0..0xBF
// (rejects overlong 3-byte encodings).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 4 — first byte was 0xED; continuation byte must be 0x80..0x9F
// (rejects UTF-16 surrogate codepoints U+D800..U+DFFF).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8, 1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 5 — first byte was 0xF0; continuation byte must be 0x90..0xBF
// (rejects overlong 4-byte encodings).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 6 — middle continuation byte of a 4-byte sequence (0x80..0xBF).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
// state 7 — first byte was 0xF4; continuation byte must be 0x80..0x8F
// (rejects codepoints above U+10FFFF).
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8, 2i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
-1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8, -1i8,
];
// ref/hare/encoding/utf8/decode.ha:17 — payload-bit masks. Hare's
// [2][8]u8 flattened to 1D [16]u8; row 0 (offsets 0..7) is the
// continuation-byte mask (always 0x3F), row 1 (offsets 8..15) is the
// initial-byte payload mask indexed by the transition class.
let masks: [16]u8 = [
0x3fu8, 0x3fu8, 0x3fu8, 0x3fu8, 0x3fu8, 0x3fu8, 0x3fu8, 0x3fu8,
0x7fu8, 0x1fu8, 0x0fu8, 0x0fu8, 0x0fu8, 0x07u8, 0x07u8, 0x07u8,
];
// ref/hare/encoding/utf8/decode.ha:6 — incremental decoder state.
export type decoder = struct {
offs: i32,
src: []u8,
};
// ref/hare/encoding/utf8/decode.ha:12.
export fn decode(src: []u8) decoder = {
let d: decoder;
d.src = src;
d.offs = 0;
return d;
};
// ref/hare/encoding/utf8/decode.ha:27. Returns the next rune from a
// decoder, `done` at end-of-input, `more` on truncated trailing
// sequence, `invalid` on malformed input (overlong, surrogate,
// out-of-range, bad continuation).
//
// Algorithm is verbatim Hoehrmann (see file header). One structural
// rewrite: Hare encodes the "initial vs continuation byte" decision
// as the branchless `(state - 1): uint >> 31`, which assumes a 32-bit
// uint. ww's uint is 64-bit (cmd/wcc/type.c:58), so the shift answer
// would be 0x1_ffff_ffff rather than 1. We spell the same predicate
// with an explicit conditional.
export fn next(d: *decoder) (rune | done | more | invalid) = {
if (d.offs == d.src.len) {
let dn: done; return dn;
};
let nx: i32 = 0;
let state: i32 = 0;
let r: u32 = 0u32;
for (d.offs < d.src.len) {
let b: u8 = d.src[d.offs];
let bi: i32 = b: i32;
let row: i32 = state * 256 + bi;
let cell: i8 = dfa[row];
nx = cell: i32;
let mi: i32 = 0;
if (state == 0) { mi = 1; };
let m: u8 = masks[mi * 8 + (nx & 7)];
r = (r << 6u32) | ((b & m): u32);
if (nx <= 0) {
d.offs += 1;
if (nx == 0) { return r: rune; };
let e: invalid; return e;
};
state = nx;
d.offs += 1;
};
let mr: more; return mr;
};
// ref/hare/encoding/utf8/decode.ha:207. Strict whole-input check.
// The hot path: tight DFA loop, no rune assembly. Bails the moment
// the table returns -1 so malformed inputs don't pay for the rest
// of the buffer.
export fn validate(src: []u8) (void | invalid) = {
let state: i32 = 0;
let i: i32 = 0;
for (i < src.len) {
if (state < 0) { break; };
let bi: i32 = src[i]: i32;
let cell: i8 = dfa[state * 256 + bi];
state = cell: i32;
i += 1;
};
if (state == 0) { return; };
let e: invalid; return e;
};
// ref/hare/encoding/utf8/rune.ha:5. Encoded byte length of `r` as
// UTF-8. Callers in ww use this to size the buffer they hand to
// [[encoderune]]; values >0x10FFFF or negative are not legal Unicode
// codepoints and Hare aborts on them in `encoderune` itself, so we
// keep `runesz` infallible (matches Hare).
export fn runesz(r: rune) i32 = {
let ch: u32 = r: u32;
if (ch < 128u32) { return 1; };
if (ch < 2048u32) { return 2; };
if (ch < 65536u32) { return 3; };
return 4;
};
// ref/hare/encoding/utf8/rune.ha:15. Expected byte length of the
// codepoint that starts with `c`, or `invalid` if `c` cannot start
// a legal UTF-8 sequence. Constants written in decimal because ww
// doesn't accept Hare's `0b1000_0000` binary syntax: 0x80=128,
// 0xC2=194, 0xE0=224, 0xF0=240, 0xF8=248.
export fn utf8sz(c: u8) (i32 | invalid) = {
if (c < 128u8) { return 1; };
if (c < 194u8) { let e: invalid; return e; };
if (c >= 248u8) { let e: invalid; return e; };
if (c < 224u8) { return 2; };
if (c < 240u8) { return 3; };
return 4;
};
// ref/hare/encoding/utf8/encode.ha:7. Encode `r` into `out` (caller-
// supplied; must hold at least [[runesz]](r) bytes) and return the
// byte count. ABORT if `r` is a UTF-16 surrogate or above U+10FFFF —
// same precondition Hare asserts at ref/hare/encoding/utf8/encode.ha:9.
//
// Surface deviation: Hare returns `[]u8` (slice into a static buf).
// ww uses the caller-buffer form; caller can reuse a [4]u8 stack
// scratch across encodes.
export fn encoderune(out: []u8, r: rune) i32 = {
let ch: u32 = r: u32;
if (ch >= 0xD800u32) {
if (ch <= 0xDFFFu32) {
abort("utf8.encoderune: surrogate codepoint");
};
};
if (ch > 0x10FFFFu32) {
abort("utf8.encoderune: codepoint > U+10FFFF");
};
let n: i32 = 0;
let first: u8 = 0u8;
if (ch < 0x80u32) {
first = 0u8; n = 1;
} else if (ch < 0x800u32) {
first = 0xC0u8; n = 2;
} else if (ch < 0x10000u32) {
first = 0xE0u8; n = 3;
} else {
first = 0xF0u8; n = 4;
};
let v: u32 = ch;
let i: i32 = n - 1;
for (i > 0) {
out[i] = ((v: u8) & 0x3Fu8) | 0x80u8;
v = v >> 6u32;
i -= 1;
};
out[0] = (v: u8) | first;
return n;
};
// ref/hare/encoding/utf8/decode.ha:52. Walks back from `d.offs` to a
// byte that could start a codepoint (state-0 dfa cell != -1), re-decodes
// forward from there, and confirms the forward decode lands back at the
// original offset. Returns `done` at start-of-input; `invalid` if no
// initial byte appears within 4 steps (no legal UTF-8 codepoint exceeds
// 4 bytes), if the forward decode returns `more`/`invalid`, or if it
// lands at a different offset than expected. Returns `more` when the
// walk reaches byte 0 without finding any initial byte.
//
// Hare's `for (d.offs < len(d.src); d.offs -= 1)` relies on size_t
// wrap-around to exit when offs underflows past 0; ww's offs is i32,
// so we spell the same exit as `d.offs >= 0`. Hare's `defer d.offs = t`
// is inlined in each match arm — ww has no defer.
export fn prev(d: *decoder) (rune | done | more | invalid) = {
if (d.offs == 0) {
let dn: done; return dn;
};
let n: i32 = d.offs;
d.offs -= 1;
for (d.offs >= 0) {
let b: u8 = d.src[d.offs];
let bi: i32 = b: i32;
let cell: i8 = dfa[bi];
if (cell: i32 != -1) {
let t: i32 = d.offs;
match (next(d)) {
case let r: rune => {
let landed: i32 = d.offs;
d.offs = t;
if (landed != n) {
let e: invalid; return e;
};
return r;
};
case let dn: done => {
d.offs = t;
let e: invalid; return e;
};
case let m: more => {
d.offs = t;
let e: invalid; return e;
};
case let e: invalid => {
d.offs = t;
let e2: invalid; return e2;
};
};
};
if (n - d.offs == 4) {
let e: invalid; return e;
};
d.offs -= 1;
};
let mr: more; return mr;
};
// ref/hare/encoding/utf8/decode.ha:74. Borrowed view of the bytes from
// the decoder's current position to the end of its source.
export fn remaining(d: *decoder) []u8 = {
let r: []u8;
r.ptr = d.src.ptr + (d.offs: u64);
r.len = d.src.len - d.offs;
r.cap = d.src.len - d.offs;
return r;
};
// ref/hare/encoding/utf8/decode.ha:80. Borrowed view of the bytes
// between two decoders' positions. Precondition (Hare asserts both):
// the decoders share the same source, and `begin.offs <= end.offs`.
export fn slice(begin: *decoder, end: *decoder) []u8 = {
if (begin.src.ptr != end.src.ptr) {
abort("utf8.slice: decoders from different sources");
};
if (begin.offs > end.offs) {
abort("utf8.slice: begin past end");
};
let r: []u8;
r.ptr = begin.src.ptr + (begin.offs: u64);
r.len = end.offs - begin.offs;
r.cap = end.offs - begin.offs;
return r;
};
// ref/hare/encoding/utf8/decode.ha:203. Byte position of the decoder
// in its source.
export fn position(d: *decoder) i32 = {
return d.offs;
};
// strings — operations over str ({ptr,len}). Hare port; see
// ref/hare/strings/.
//
// Documented divergences from Hare:
//
// - `byteindex` / `rbyteindex` rune arms encode via
// `utf8.encoderune`; the legacy impls scanned for `r: u8` (an
// undocumented ASCII-only restriction that silently dropped
// to the wrong byte for U+80..U+7FF and higher).
// - `dup(s: str) str` — Hare returns `(str | nomem)`. ww's
// `os.alloc` aborts on OOM (no `nomem` type), so we return plain
// `str`. Empty input returns `{nil, 0}`; Hare returns the static
// empty string — same observable result.
// - `iterator` is flattened (`offs`, `src`, `reverse` fields).
// Hare uses anonymous-embedded `utf8::decoder`
// (ref/hare/strings/iter.ha:6-9); ww has no anonymous-embed
// syntax, so `next`/`prev`/`slice` copy `offs`/`src` into a
// local `utf8.decoder` for the call (and `next`/`prev` write
// `offs` back).
// - Hare's private `move()` helper dispatches on a `forward: bool`
// using a function-pointer `let fun = if (forward) &utf8::next
// else &utf8::prev`. ww has no fn-pointers in scope yet, so the
// dispatch is a branch on `forward` selecting the call site.
package strings;
import bytes;
import encoding.utf8;
import os;
import rt;
import types;
// toutf8 — borrowed []u8 view of `s`. ref/hare/strings/utf8.ha:29.
// `cap` equals `len`; the slice does not own a separate allocation.
export fn toutf8(s: str) []u8 = {
let r: []u8;
r.ptr = s.ptr;
r.len = s.len;
r.cap = s.len;
return r;
};
// frombytes — borrowed str view of `in`. Pure reinterpret per
// CLAUDE.md rule 9 carve-out; ref/hare/strings/utf8.ha:10.
export fn frombytes(in: []u8) str = {
let r: str;
r.ptr = in.ptr;
r.len = in.len;
return r;
};
// compare — three-way bytewise codepoint-order comparison. Return is
// a sign (neg/zero/pos), not an index, so it tracks Hare's `int`
// rather than the str-index i32 (#8). ref/hare/strings/compare.ha:12.
export fn compare(a: str, b: str) int = {
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]: int) - (b[i]: int); };
i += 1;
};
return (a.len: int) - (b.len: int);
};
// dup — allocate a fresh copy of `s`. Caller releases with
// `os.free(r.ptr, r.len: u64)`. ref/hare/strings/dup.ha:7.
export fn dup(s: str) str = {
let r: str;
r.ptr = nil;
r.len = 0;
if (s.len == 0) { return r; };
let buf: []u8 = alloc([], s.len: u64)!;
let i: i32 = 0;
for (i < s.len) { buf[i] = s[i]; i += 1; };
buf.len = s.len;
return frombytes(buf);
};
// dupall — fresh `[]str` whose elements are independent copies of
// `s`'s elements. Caller releases via [[freeall]].
// ref/hare/strings/dup.ha:26 (#6).
//
// Hare gates the per-element dup behind `?` and rolls back via
// `defer if (!ok) freeall(newsl)`. ww has no `defer if`; more
// importantly, ww's [[dup]] is still unchecked (returns plain `str`,
// aborts via os.alloc on OOM — see top-of-file divergence note),
// so the only nomem propagation point is the initial slice alloc.
// With no inner failure path, the rollback is structurally a no-op
// and is omitted; it returns once dup graduates to `(str | nomem)`
// (#46). The pre-allocated slice has `cap == s.len`, so appendstr's
// rt_ensure call never reaches the grow branch.
//
// Empty input bypasses the alloc: rt_malloc(0) is an mmap of 0 bytes
// which returns -EINVAL, and the alloc-slice `?` shortcut routes
// that through nomem — Hare's heap allocator hands back a sentinel
// instead (#47). Return `{nil, 0, 0}` directly so callers get the
// Hare-observable shape (len==0, freeall is a no-op via cap==0).
export fn dupall(s: []str) ([]str | nomem) = {
if (s.len == 0) {
let r: []str;
r.ptr = nil: *str;
r.len = 0;
r.cap = 0;
return r;
};
let newsl: []str = alloc([], s.len)?;
let i: i32 = 0;
for (i < s.len) {
appendstr(&newsl, dup(s[i]));
i += 1;
};
return newsl;
};
// freeall — release each element + the slice header. The natural
// disposer for any `[]str` of dup'd elements (e.g. shlex.split).
// ref/hare/strings/dup.ha:38.
//
// Empty elements (`{nil, 0}` from a zero-length dup) are skipped:
// os.free on a nil pointer at len 0 tickles the rt_free guard. The
// slice header itself is freed at `cap * size(str)` — the literal
// would drift under #1's str-layout bump, so route through the
// typ.ww SSoT. A never-grown slice (cap == 0) skips the header free.
export fn freeall(s: []str) void = {
let i: i32 = 0;
for (i < s.len) {
if (s[i].len > 0) {
os.free(s[i].ptr: *void, s[i].len: u64);
};
i += 1;
};
if (s.cap > 0) {
os.free(s.ptr: *void, (s.cap: u64) * size(str): u64);
};
};
// concat — fresh allocation containing each element of `strs` in
// order. Caller releases with `os.free(r.ptr, r.len: u64)`.
// ref/hare/strings/concat.ha:5. Hare's `nomem` return is dropped:
// `os.alloc` aborts on OOM.
export fn concat(strs: str...) str = {
let total: i32 = 0;
let i: i32 = 0;
for (i < strs.len) { total += strs[i].len; i += 1; };
let r: str;
r.ptr = nil;
r.len = 0;
if (total == 0) { return r; };
let buf: []u8 = alloc([], total: u64)!;
let off: i32 = 0;
i = 0;
for (i < strs.len) {
let j: i32 = 0;
for (j < strs[i].len) {
buf[off + j] = strs[i][j];
j += 1;
};
off += strs[i].len;
i += 1;
};
buf.len = total;
return frombytes(buf);
};
// join — fresh allocation with `delim` placed between each element of
// `strs`. Caller releases with `os.free(r.ptr, r.len: u64)`.
// ref/hare/strings/concat.ha:46. Hare's `nomem` return is dropped:
// `os.alloc` aborts on OOM.
export fn join(delim: str, strs: str...) str = {
let total: i32 = 0;
let i: i32 = 0;
for (i < strs.len) {
total += strs[i].len;
if (i + 1 < strs.len) { total += delim.len; };
i += 1;
};
let r: str;
r.ptr = nil;
r.len = 0;
if (total == 0) { return r; };
let buf: []u8 = alloc([], total: u64)!;
let off: i32 = 0;
i = 0;
for (i < strs.len) {
let j: i32 = 0;
for (j < strs[i].len) {
buf[off + j] = strs[i][j];
j += 1;
};
off += strs[i].len;
if (i + 1 < strs.len) {
j = 0;
for (j < delim.len) {
buf[off + j] = delim[j];
j += 1;
};
off += delim.len;
};
i += 1;
};
buf.len = total;
return frombytes(buf);
};
// utf8bytelenbounded — walk `it` forward `end` runes and return the
// resulting byte offset. ref/hare/strings/sub.ha:10. Aborts on
// short input per Hare's contract for the rune-wise [[sub]].
fn utf8bytelenbounded(it: *iterator, end: i32) i32 = {
let i: i32 = 0;
for (i < end) {
match (next(it)) {
case let r: rune => void;
case utf8.done => abort("strings.sub: index exceeds string length");
};
i += 1;
};
return it.offs;
};
// sub — borrowed substring [start, end) where start/end are rune
// indices. ref/hare/strings/sub.ha:30. Hare's 2-arg `sub(s, start)`
// defaulting end=END is omitted: ww has no default-parameter syntax
// (filed as #37). Byte-indexed counterpart: [[bytesub]].
export fn sub(s: str, start: i32, end: i32) str = {
os.assert(start <= end, "strings.sub: start is higher than end");
let it: iterator = iter(s);
let starti: i32 = utf8bytelenbounded(&it, start);
let endi: i32 = utf8bytelenbounded(&it, end - start);
let r: str;
r.ptr = s.ptr + (starti: u64);
r.len = endi - starti;
return r;
};
// bytesub — borrowed substring [start, end) where start/end are byte
// offsets. ref/hare/strings/sub.ha:59 (#7). Returns `utf8.invalid` if
// either endpoint lands on a continuation byte (would split a
// codepoint); the equivalent Hare predicate is `s[i] & 0xc0 == 0x80`
// at ref/hare/strings/sub.ha:72-73.
export fn bytesub(s: str, start: i32, end: i32) (str | utf8.invalid) = {
os.assert(start <= end, "strings.bytesub: start is higher than end");
os.assert(end <= s.len, "strings.bytesub: end exceeds string length");
if (start < s.len) {
if ((s[start] & 0xC0u8) == 0x80u8) {
let e: utf8.invalid; return e;
};
};
if (end < s.len) {
if ((s[end] & 0xC0u8) == 0x80u8) {
let e: utf8.invalid; return e;
};
};
let r: str;
r.ptr = s.ptr + (start: u64);
r.len = end - start;
return r;
};
// runebytes — encode `r` into caller's `scratch` (must hold 4 bytes)
// and return the borrowed slice trimmed to the encoded length. Hare
// inlines the same shape at ref/hare/strings/index.ha:132.
fn runebytes(scratch: []u8, r: rune) []u8 = {
let n: i32 = utf8.encoderune(scratch, r);
let s: []u8;
s.ptr = scratch.ptr;
s.len = n;
s.cap = n;
return s;
};
// hasprefix — true iff `in` begins with `prefix`.
// ref/hare/strings/suffix.ha:8.
export fn hasprefix(in: str, prefix: (str | rune)) bool = {
let scratch: [4]u8;
let p: []u8 = match (prefix) {
case let s: str => yield toutf8(s);
case let r: rune => yield runebytes(scratch[0:4], r);
};
return bytes.hasprefix(toutf8(in), p);
};
// hassuffix — true iff `in` ends with `suff`.
// ref/hare/strings/suffix.ha:26.
export fn hassuffix(in: str, suff: (str | rune)) bool = {
let scratch: [4]u8;
let s: []u8 = match (suff) {
case let v: str => yield toutf8(v);
case let r: rune => yield runebytes(scratch[0:4], r);
};
return bytes.hassuffix(toutf8(in), s);
};
// byteindex — byte-wise offset of `needle` in `haystack`, or void if
// absent. ref/hare/strings/index.ha:127. Rune arm encodes via
// utf8.encoderune (Hare passes the encoded slice straight to
// bytes::index).
export fn byteindex(haystack: str, needle: (str | rune)) (i32 | void) = {
let scratch: [4]u8;
let n: []u8 = match (needle) {
case let s: str => yield toutf8(s);
case let r: rune => yield runebytes(scratch[0:4], r);
};
return bytes.index(toutf8(haystack), n);
};
// rbyteindex — byte-wise offset of the last `needle` in `haystack`.
// ref/hare/strings/index.ha:138.
export fn rbyteindex(haystack: str, needle: (str | rune)) (i32 | void) = {
let scratch: [4]u8;
let n: []u8 = match (needle) {
case let s: str => yield toutf8(s);
case let r: rune => yield runebytes(scratch[0:4], r);
};
return bytes.rindex(toutf8(haystack), n);
};
// indexstring — str-arm of [[index]]. Dual-rune-iterator walk: at each
// candidate rune index `i`, compare `haystack` from that position
// against `needle` rune-by-rune until needle is exhausted (match) or
// a mismatch / haystack-exhaustion breaks the inner loop. Mirrors
// ref/hare/strings/index.ha:59 (#10). Hare copies `rest_iter = s_iter`
// directly via struct assignment; ww re-seats `rest_iter` field-wise
// because the let-init struct-copy form diverges between cstage and
// wwstage on this iterator type (993_ww_ww + 995_self_rebuild fail,
// filed as #41) and rule #10 (CLAUDE.md) forbids stage asymmetry.
fn indexstring(haystack: str, needle: str) (i32 | void) = {
let s_iter: iterator = iter(haystack);
let i: i32 = 0;
for (true) {
let rest_iter: iterator;
rest_iter.src = s_iter.src;
rest_iter.offs = s_iter.offs;
rest_iter.reverse = s_iter.reverse;
let needle_iter: iterator = iter(needle);
let matched: bool = false;
for (true) {
let rest_done: bool = false;
let rest_r: rune;
match (next(&rest_iter)) {
case let r: rune => rest_r = r;
case utf8.done => rest_done = true;
};
let needle_done: bool = false;
let needle_r: rune;
match (next(&needle_iter)) {
case let r: rune => needle_r = r;
case utf8.done => needle_done = true;
};
if (rest_done && !needle_done) { break; };
if (needle_done) { matched = true; break; };
if (rest_r != needle_r) { break; };
};
if (matched) { return i; };
match (next(&s_iter)) {
case let r: rune => i += 1;
case utf8.done => return;
};
};
return;
};
// index — rune-wise offset of `needle`'s first occurrence in
// `haystack`, or void if absent. ref/hare/strings/index.ha:10. The
// str-arm delegates to [[indexstring]] (dual-iterator rune-by-rune
// walk per Hare's `index_string`, #10); the rune-arm mirrors Hare's
// `index_rune` (ref/hare/strings/index.ha:31).
export fn index(haystack: str, needle: (str | rune)) (i32 | void) = {
match (needle) {
case let s: str => return indexstring(haystack, s);
case let r: rune => {
let it: iterator = iter(haystack);
let i: i32 = 0;
for (true) {
match (next(&it)) {
case let n: rune => {
if (n == r) { return i; };
i += 1;
};
case utf8.done => return;
};
};
};
};
return;
};
// rindex — rune-wise offset of `needle`'s last occurrence in
// `haystack`, or void if absent. ref/hare/strings/index.ha:22. The
// str-arm reuses `rbyteindex`; the rune-arm walks forward tracking
// the most recent matching rune index (Hare's `rindex_rune` with
// `riter` returns a byte-offset value for multibyte strings, which
// disagrees with the rune-wise docstring; we keep the docstring's
// contract).
export fn rindex(haystack: str, needle: (str | rune)) (i32 | void) = {
match (needle) {
case let s: str => {
match (rbyteindex(haystack, s)) {
case void => return;
case let bo: i32 => {
let it: iterator = iter(haystack);
let i: i32 = 0;
for (position(&it) < bo) {
match (next(&it)) {
case let r: rune => i += 1;
case utf8.done => break;
};
};
return i;
};
};
};
case let r: rune => {
let it: iterator = iter(haystack);
let i: i32 = 0;
let last: i32 = -1;
for (true) {
match (next(&it)) {
case let n: rune => {
if (n == r) { last = i; };
i += 1;
};
case utf8.done => break;
};
};
if (last < 0) { return; };
return last;
};
};
return;
};
// contains — true iff any of `needles` occurs in `haystack`.
// ref/hare/strings/contains.ha:9.
export fn contains(haystack: str, needles: (str | rune)...) bool = {
let i: i32 = 0;
for (i < needles.len) {
match (needles[i]) {
case let s: str => {
match (byteindex(haystack, s)) {
case let bo: i32 => return true;
case void => void;
};
};
case let r: rune => {
match (byteindex(haystack, r)) {
case let bo: i32 => return true;
case void => void;
};
};
};
i += 1;
};
return false;
};
// trimprefix — `s` with `prefix` stripped from the front, or `s`
// unchanged if it doesn't start with `prefix`. Borrowed view.
// ref/hare/strings/trim.ha:60.
export fn trimprefix(input: str, prefix: str) str = {
if (!hasprefix(input, prefix)) { return input; };
let r: str;
r.ptr = input.ptr + (prefix.len: u64);
r.len = input.len - prefix.len;
return r;
};
// trimsuffix — symmetric. ref/hare/strings/trim.ha:69.
export fn trimsuffix(input: str, suffix: str) str = {
if (!hassuffix(input, suffix)) { return input; };
let r: str;
r.ptr = input.ptr;
r.len = input.len - suffix.len;
return r;
};
// whitespace — ASCII whitespace set used by the 0-arg ltrim/rtrim/trim
// branches (#9). ref/hare/strings/trim.ha:6.
let whitespace: [4]u8 = [0x20u8, 0x0Au8, 0x09u8, 0x0Du8];
// ltrim — strip leading runes that occur in `trim`. Borrowed view.
// 0-arg strips ASCII whitespace via [[bytes.ltrim]] (#9).
// ref/hare/strings/trim.ha:11. The spread expression is inlined
// because `let ws: []u8 = whitespace[0:4]` produces a slice whose
// ptr doesn't track the module-level array storage (filed as #40);
// `b.flush = flushdefault[0:1]` in lib/bufio is the same shape via
// the working field-assign path.
export fn ltrim(input: str, trim: rune...) str = {
if (trim.len == 0) {
return frombytes(bytes.ltrim(toutf8(input), whitespace[0:4]...));
};
let it: iterator = iter(input);
for (true) {
match (next(&it)) {
case let r: rune => {
let j: i32 = 0;
let found: bool = false;
for (j < trim.len) {
if (r == trim[j]) { found = true; j = trim.len; }
else { j += 1; };
};
if (!found) {
match (prev(&it)) {
case let r2: rune => void;
case utf8.done => void;
};
break;
};
};
case utf8.done => break;
};
};
return iterstr(&it);
};
// rtrim — strip trailing runes that occur in `trim`. Borrowed view.
// 0-arg strips ASCII whitespace via [[bytes.rtrim]] (#9). Spread is
// inlined to dodge #40 — see [[ltrim]].
// ref/hare/strings/trim.ha:32.
export fn rtrim(input: str, trim: rune...) str = {
if (trim.len == 0) {
return frombytes(bytes.rtrim(toutf8(input), whitespace[0:4]...));
};
let it: iterator = riter(input);
for (true) {
match (next(&it)) {
case let r: rune => {
let j: i32 = 0;
let found: bool = false;
for (j < trim.len) {
if (r == trim[j]) { found = true; j = trim.len; }
else { j += 1; };
};
if (!found) {
match (prev(&it)) {
case let r2: rune => void;
case utf8.done => void;
};
break;
};
};
case utf8.done => break;
};
};
return iterstr(&it);
};
// trim — strip from both ends. ref/hare/strings/trim.ha:54.
export fn trim(input: str, trim: rune...) str = {
return ltrim(rtrim(input, trim...), trim...);
};
// iterator — UTF-8 rune cursor over a `str`. Layout flattens Hare's
// anonymous-embedded `utf8::decoder` (ref/hare/strings/iter.ha:6-9) to
// explicit fields. `reverse` selects walk direction: forward iterators
// (`iter`) advance through utf8.next; reverse iterators (`riter`) advance
// through utf8.prev. May be copied to save state.
export type iterator = struct {
offs: i32,
src: []u8,
reverse: bool,
};
// iter — initialize a forward iterator at the start of `src`.
// ref/hare/strings/iter.ha:24.
export fn iter(src: str) iterator = {
let r: iterator;
r.src = toutf8(src);
r.offs = 0;
r.reverse = false;
return r;
};
// riter — initialize a reverse iterator at the end of `src`. `next`
// on a reverse iterator walks back through the string.
// ref/hare/strings/iter.ha:32.
export fn riter(src: str) iterator = {
let r: iterator;
r.src = toutf8(src);
r.offs = src.len;
r.reverse = true;
return r;
};
// move — private dispatch shared by next/prev. `forward` selects
// utf8.next vs utf8.prev. Aborts on more/invalid per Hare's
// ref/hare/strings/iter.ha:51-58 ("Invalid UTF-8 string (this should
// not happen)"). Hare picks the utf8 function via a fn-pointer; ww
// branches on `forward` at each call site instead.
fn move(forward: bool, it: *iterator) (rune | utf8.done) = {
let d: utf8.decoder;
d.src = it.src;
d.offs = it.offs;
if (forward) {
match (utf8.next(&d)) {
case let r: rune => { it.offs = d.offs; return r; };
case let dn: utf8.done => return dn;
case let m: utf8.more => abort("strings.move: invalid UTF-8");
case let e: utf8.invalid => abort("strings.move: invalid UTF-8");
};
} else {
match (utf8.prev(&d)) {
case let r: rune => { it.offs = d.offs; return r; };
case let dn: utf8.done => return dn;
case let m: utf8.more => abort("strings.move: invalid UTF-8");
case let e: utf8.invalid => abort("strings.move: invalid UTF-8");
};
};
};
// next — advance the iterator one rune. Forward iterators step
// through utf8.next; reverse iterators (riter) step backward through
// utf8.prev. Returns utf8.done at end-of-walk. ref/hare/strings/iter.ha:45.
export fn next(it: *iterator) (rune | utf8.done) = {
return move(!it.reverse, it);
};
// prev — step back one rune. Dual to next: on a forward iterator
// this walks utf8.prev; on a reverse iterator (riter) it walks
// utf8.next. ref/hare/strings/iter.ha:49.
export fn prev(it: *iterator) (rune | utf8.done) = {
return move(it.reverse, it);
};
// iterstr — borrowed view of the bytes remaining in the iterator's
// walk direction. Forward iter: bytes from offs to end; reverse iter:
// bytes from start to offs. ref/hare/strings/iter.ha:63.
export fn iterstr(it: *iterator) str = {
let r: []u8;
if (it.reverse) {
r = it.src[0:it.offs];
} else {
r = it.src[it.offs:it.src.len];
};
return frombytes(r);
};
// slice — borrowed substring between two iterator positions.
// ref/hare/strings/iter.ha:75. Hare passes `*iterator` directly where
// `*utf8::decoder` is expected via anonymous-embed coercion; ww has
// no anonymous embed, so we reconstruct a local utf8.decoder for each
// endpoint and forward — same pattern as `move` above.
export fn slice(begin: *iterator, end: *iterator) str = {
let b: utf8.decoder;
b.src = begin.src;
b.offs = begin.offs;
let e: utf8.decoder;
e.src = end.src;
e.offs = end.offs;
return frombytes(utf8.slice(&b, &e));
};
// position — byte-wise offset of the iterator in its source.
// ref/hare/strings/iter.ha:82.
export fn position(it: *iterator) i32 = {
return it.offs;
};
// tokenizer — re-export of bytes.tokenizer. ref/hare/strings/tokenize.ha:7.
// First cross-module type alias in tree; needs #22's transitive
// alias-chain unwrap (cstage type_chase_named + wwstage
// structlookupchain) to walk struct fields through the chain.
export type tokenizer = bytes.tokenizer;
// tokenize — yield substrings of `s` split on any byte in `delim`.
// Leading / trailing / adjacent delims yield empty tokens. `s` and
// `delim` are borrowed; caller keeps them live for the tokenizer's
// lifetime. ref/hare/strings/tokenize.ha:32. ASCII-only delim
// asserted per Hare lines 35-37: a multibyte rune in delim would
// split on a single continuation byte and yield invalid UTF-8.
export fn tokenize(s: str, delim: str) tokenizer = {
let d: []u8 = toutf8(delim);
let i: i32 = 0;
for (i < d.len) {
os.assert((d[i] & 0x80u8) == 0u8,
"strings.tokenize cannot tokenize on non-ASCII delimiters");
i += 1;
};
return bytes.tokenize(toutf8(s), d...);
};
// rtokenize — reverse-direction counterpart to [[tokenize]]. First
// next_token yields the last token, last yields the first.
// ref/hare/strings/tokenize.ha:44.
export fn rtokenize(s: str, delim: str) tokenizer = {
let d: []u8 = toutf8(delim);
let i: i32 = 0;
for (i < d.len) {
os.assert((d[i] & 0x80u8) == 0u8,
"strings.rtokenize cannot tokenize on non-ASCII delimiters");
i += 1;
};
return bytes.rtokenize(toutf8(s), d...);
};
// next_token — current token, advancing the cursor.
// ref/hare/strings/tokenize.ha:62.
export fn next_token(s: *tokenizer) (str | bytes.done) = {
let b: *bytes.tokenizer = s: *bytes.tokenizer;
match (bytes.next_token(b)) {
case let v: []u8 => return frombytes(v);
case bytes.done => { let d: bytes.done; return d; };
};
};
// peek_token — current token without advancing.
// ref/hare/strings/tokenize.ha:71.
export fn peek_token(s: *tokenizer) (str | bytes.done) = {
let b: *bytes.tokenizer = s: *bytes.tokenizer;
match (bytes.peek_token(b)) {
case let v: []u8 => return frombytes(v);
case bytes.done => { let d: bytes.done; return d; };
};
};
// remaining_tokens — unconsumed portion of the input ahead of the
// cursor. ref/hare/strings/tokenize.ha:79.
export fn remaining_tokens(s: *tokenizer) str = {
let b: *bytes.tokenizer = s: *bytes.tokenizer;
return frombytes(bytes.remaining_tokens(b));
};
// cut — split `in` along the first instance of `delim`, returning the
// portions before and after it. When `delim` is absent the whole input
// is the first half and the second is empty. Both halves are borrowed
// from `in`; caller ensures `delim` is non-empty.
// ref/hare/strings/tokenize.ha:288.
export fn cut(in: str, delim: str) (str, str) = {
let (a, b) = bytes.cut(toutf8(in), toutf8(delim));
return (frombytes(a), frombytes(b));
};
// rcut — like [[cut]] but split along the LAST instance of `delim`.
// ref/hare/strings/tokenize.ha:302.
export fn rcut(in: str, delim: str) (str, str) = {
let (a, b) = bytes.rcut(toutf8(in), toutf8(delim));
return (frombytes(a), frombytes(b));
};
// rt_ensure is the runtime slice-growth helper invoked by the
// `append(s, v)` builtin. Direct bind for the same reason as
// lib/shlex.shlex (appendstr, 16B): the builtin's expansion stores
// only 8B of the new element, losing the `.len` half of a `str`.
@symbol("rt_ensure") fn rtensure(s: *void, membsz: u64) void;
// appendstr — grow `*slice` by one and store `item` (16B). Mirror of
// lib/shlex.shlex appendstr. Collapses when the append builtin learns
// to store the full element width.
fn appendstr(slice: *[]str, item: str) void = {
let newlen: i32 = slice.len + 1;
slice.len = newlen;
rtensure(slice: *void, size(str): u64);
let dst: *str = &slice.ptr[newlen - 1];
dst.ptr = item.ptr;
dst.len = item.len;
};
// splitn — split `in` on any byte in `delim`, returning up to `n`
// tokens via forward iteration. The trailing slot (when more than
// `n - 1` tokens exist) holds the unconsumed remainder. Strings
// within the result are borrowed from `in`.
//
// The caller frees the returned slice via
// `os.free(r.ptr: *void, (r.cap: u64) * size(str): u64)`.
//
// Hare's `([]str | nomem)` collapses to `[]str` here: ww os.alloc
// has no recoverable failure path. Same precedent as
// shlex.split / bytes.splitn.
//
// ref/hare/strings/tokenize.ha:172.
export fn splitn(in: str, delim: str, n: i32) []str = {
let toks: []str;
toks.ptr = nil: *str;
toks.len = 0;
toks.cap = 0;
let tok: tokenizer = tokenize(in, delim);
let i: i32 = 0;
for (i < n - 1) {
match (next_token(&tok)) {
case let s: str => { appendstr(&toks, s); };
case bytes.done => { return toks; };
};
i += 1;
};
match (peek_token(&tok)) {
case bytes.done => void;
case let pk: str => {
let r: str = remaining_tokens(&tok);
appendstr(&toks, r);
};
};
return toks;
};
// rsplitn — reverse-direction counterpart to [[splitn]]: tokens are
// collected from the end of `in`. The trailing slot holds the
// unconsumed prefix (everything before the n-th-from-last delim hit).
//
// When the input has fewer than n tokens, the `done` short-circuit
// returns toks UN-reversed (in last-token-first order). Mirrors Hare
// at ref/hare/strings/tokenize.ha:219-224 where the in-place reverse
// step is gated behind the n-1 loop running to completion.
//
// ref/hare/strings/tokenize.ha:200.
export fn rsplitn(in: str, delim: str, n: i32) []str = {
let toks: []str;
toks.ptr = nil: *str;
toks.len = 0;
toks.cap = 0;
let tok: tokenizer = rtokenize(in, delim);
let i: i32 = 0;
for (i < n - 1) {
match (next_token(&tok)) {
case let s: str => { appendstr(&toks, s); };
case bytes.done => { return toks; };
};
i += 1;
};
match (peek_token(&tok)) {
case bytes.done => void;
case let pk: str => {
let r: str = remaining_tokens(&tok);
appendstr(&toks, r);
};
};
// In-place reverse so callers see argv-order, matching Hare
// (ref/hare/strings/tokenize.ha:220). Element copy is field-wise
// through `*str` because `toks[i] = toks[j]` (full 16B str store)
// lands in the multi-word-store gap noted at cmd/w6c/cgen.c:6515.
let a: i32 = 0;
let b: i32 = toks.len - 1;
for (a < b) {
let pa: *str = &toks.ptr[a];
let pb: *str = &toks.ptr[b];
let tp: *u8 = pa.ptr;
let tl: i32 = pa.len;
pa.ptr = pb.ptr;
pa.len = pb.len;
pb.ptr = tp;
pb.len = tl;
a += 1;
b -= 1;
};
return toks;
};
// split — full split of `in` on `delim` (no token cap). Mirrors
// `splitn(in, delim, types::SIZE_MAX)`. ww uses `types.I32_MAX`
// because the index type is i32 (lib/CLAUDE.md).
//
// ref/hare/strings/tokenize.ha:242.
export fn split(in: str, delim: str) []str = {
return splitn(in, delim, types.I32_MAX);
};
// lpad — left-pad `s` with `p` rune until the result reaches `maxlen`
// bytes. Length comparison is BYTES, mirroring Hare's `len(s) >= maxlen`
// at ref/hare/strings/pad.ha:9. A multibyte `p` whose encoded width
// doesn't divide `maxlen - s.len` evenly leaves a trailing pad byte
// pair sliced mid-codepoint at byte `maxlen-1`, exactly as Hare's
// `res[..maxlen]` does (ref/hare/strings/pad.ha:20). When
// `(maxlen - s.len) * pad.len >= maxlen` (multibyte pad overflows the
// budget), `s` is entirely sliced off — same as Hare. Caller releases
// with `os.free(r.ptr, r.len: u64)`. Hare's `nomem` return is dropped:
// `os.alloc` aborts on OOM. Buf size == r.len keeps the free-contract
// shape of [[dup]] / [[concat]] / [[join]]; Hare's `alloc([], maxlen)!`
// over-allocs via append then slices, but Hare's slice-free recovers
// the true capacity from the heap allocator (rt/ensure.ha:24), which
// ww's munmap-based `os.free` cannot do.
export fn lpad(s: str, p: rune, maxlen: i32) str = {
if (s.len >= maxlen) { return dup(s); };
let scratch: [4]u8;
let pad: []u8 = runebytes(scratch[0:4], p);
let buf: []u8 = alloc([], maxlen: u64)!;
let padwrite: i32 = (maxlen - s.len) * pad.len;
if (padwrite > maxlen) { padwrite = maxlen; };
let off: i32 = 0;
for (off < padwrite) {
buf[off] = pad.ptr[off % pad.len];
off += 1;
};
let k: i32 = 0;
let srem: i32 = maxlen - off;
if (srem > s.len) { srem = s.len; };
for (k < srem) {
buf[off + k] = s[k];
k += 1;
};
buf.len = maxlen;
return frombytes(buf);
};
// replace — fresh allocation of `s` with every non-overlapping
// occurrence of `needle` replaced by `target`. Caller releases with
// `os.free(r.ptr, r.len: u64)`. ref/hare/strings/replace.ha:8 (#4).
//
// Hare delegates to [[multireplace]] with a single pair; ww has no
// `(str, str)` variadic shape today (#39), so this is a standalone
// two-pass implementation: pass 1 counts matches to size the result,
// pass 2 copies chunks and `target` into a single fresh buffer.
// Single nomem path (the `alloc([], total)?`) preserves Hare's
// signature without a per-write `append(...)?` (ww's append builtin
// aborts on OOM, #11). Empty `needle` would hasprefix-match every
// position with a zero stride — same infinite loop Hare exhibits at
// ref/hare/strings/replace.ha:31; not gated.
export fn replace(s: str, needle: str, target: str) (str | nomem) = {
let sb: []u8 = toutf8(s);
let nb: []u8 = toutf8(needle);
let tb: []u8 = toutf8(target);
let count: i32 = 0;
let i: i32 = 0;
for (i < sb.len) {
if (bytes.hasprefix(sb[i:sb.len], nb)) {
count += 1;
i += nb.len;
} else {
i += 1;
};
};
let total: i32 = sb.len + count * (tb.len - nb.len);
if (total == 0) {
let r: str;
r.ptr = nil;
r.len = 0;
return r;
};
let res: []u8 = alloc([], total)?;
let off: i32 = 0;
i = 0;
for (i < sb.len) {
if (bytes.hasprefix(sb[i:sb.len], nb)) {
let j: i32 = 0;
for (j < tb.len) {
res.ptr[off + j] = tb.ptr[j];
j += 1;
};
off += tb.len;
i += nb.len;
} else {
res.ptr[off] = sb.ptr[i];
off += 1;
i += 1;
};
};
res.len = total;
return frombytes(res);
};
// rpad — right-pad `s` with `p` rune until the result reaches `maxlen`
// bytes. Symmetric with [[lpad]]. ref/hare/strings/pad.ha:39.
export fn rpad(s: str, p: rune, maxlen: i32) str = {
if (s.len >= maxlen) { return dup(s); };
let scratch: [4]u8;
let pad: []u8 = runebytes(scratch[0:4], p);
let buf: []u8 = alloc([], maxlen: u64)!;
let k: i32 = 0;
for (k < s.len) {
buf[k] = s[k];
k += 1;
};
let padwrite: i32 = maxlen - s.len;
let i: i32 = 0;
for (i < padwrite) {
buf[s.len + i] = pad.ptr[i % pad.len];
i += 1;
};
buf.len = maxlen;
return frombytes(buf);
};
// selfhost/cmd/ww/main.ww — port of cmd/ww/main.c.
//
// The user-facing driver. Plan 9 cc(1) / Hare hare(1) analogue:
//
// ww build foo.ww → w6c foo.ww > foo.s ; w6a foo.s > foo.o ;
// w6l -o foo foo.o libwwrt.a
// ww run foo.ww → build then exec
// ww version → print version
//
// Tool paths default to siblings of $0 so a fresh build runs out of
// out/bin/. Env-var overrides (WW_W6C / WW_W6A / WW_W6L / WW_LIB) are
// not yet supported in this port; the bootstrap doesn't need them.
package main;
import os;
import rt;
import strings;
// All path/string scratch buffers go on the runtime page allocator.
// One page is plenty for any path we build. PATH_MAX lives in lib/os
// (os.PATH_MAX: i32 = 4096) — the duplicate u64 def was dropped to close
// the cgen #127 mod-mangle attribution bug consumer per rule-7.
def CMD_MAX: u64 = 8192u64;
// ---- C-string helpers --------------------------------------------------
fn cstrlen(p: *u8) u64 = {
let n: u64 = 0u64;
for (p[n] != 0u8) { n += 1u64; };
return n;
};
// pathstr — view a NUL-terminated *u8 as a str. Bridges the
// driver's argv-style *u8 paths to lib/os entrypoints (str
// post-task-#23).
fn pathstr(p: *u8) str = {
let r: str;
r.ptr = p;
r.len = cstrlen(p): i32;
return r;
};
fn cstreq(a: *u8, b: *u8) bool = {
let i: u64 = 0u64;
for (a[i] == b[i]) {
if (a[i] == 0u8) { return true; };
i += 1u64;
};
return false;
};
// cstreqlit — compare a NUL-terminated *u8 to a ww string literal.
fn cstreqlit(a: *u8, lit: str) bool = {
let n: i32 = lit.len;
let i: i32 = 0;
for (i < n) {
if (a[i] != lit[i]) { return false; };
i += 1;
};
return a[n] == 0u8;
};
// startswith — does a have b as a prefix?
fn cstrstartswith(a: *u8, b: *u8) bool = {
let i: u64 = 0u64;
for (b[i] != 0u8) {
if (a[i] != b[i]) { return false; };
i += 1u64;
};
return true;
};
// memcpy
fn bytecpy(dst: *u8, src: *u8, n: u64) void = {
let i: u64 = 0u64;
for (i < n) {
dst[i] = src[i];
i += 1u64;
};
};
// Copy a NUL-terminated *u8 into dst starting at off; return the new
// offset (without writing a NUL).
fn cstrinto(dst: *u8, off: u64, src: *u8) u64 = {
let i: u64 = 0u64;
for (src[i] != 0u8) {
dst[off + i] = src[i];
i += 1u64;
};
return off + i;
};
// Same, but for a ww `str` (no NUL on the source side; we copy len bytes).
fn strinto(dst: *u8, off: u64, src: str) u64 = {
let n: i32 = src.len;
let i: i32 = 0;
for (i < n) {
let iu: u64 = i: u64;
dst[off + iu] = src[i];
i += 1;
};
let nu: u64 = n: u64;
return off + nu;
};
// Write a single byte, return new offset.
fn byteinto(dst: *u8, off: u64, c: u8) u64 = {
dst[off] = c;
return off + 1u64;
};
// NUL-terminate at off and return the same off (handy when passing the
// buffer to a syscall that expects a C-string).
fn cstrseal(dst: *u8, off: u64) void = {
dst[off] = 0u8;
};
// ---- Tool-path resolution ---------------------------------------------
// dirname-equivalent: copy argv[0] up to (but not including) the last
// '/' into dst, NUL-terminated. If no slash, write ".".
fn selfdirinto(dst: *u8, dstsz: u64, argv0: *u8) void = {
let n: u64 = cstrlen(argv0);
let cut: u64 = 0u64;
let i: u64 = 0u64;
for (i < n) {
if (argv0[i] == 47u8) { cut = i; }; // '/'
i += 1u64;
};
if (cut == 0u64) {
dst[0u64] = 46u8; // '.'
dst[1u64] = 0u8;
return;
};
if (cut + 1u64 >= dstsz) { cut = dstsz - 2u64; };
bytecpy(dst, argv0, cut);
dst[cut] = 0u8;
};
// Build "$dir/$name" (NUL-terminated) into a fresh page-sized buffer.
fn joinpath(dir: *u8, name: *u8) *u8 = {
let buf: []u8 = alloc([], (os.PATH_MAX: u64))!;
buf.len = os.PATH_MAX;
let off: u64 = cstrinto(buf.ptr, 0u64, dir);
off = byteinto(buf.ptr, off, 47u8);
off = cstrinto(buf.ptr, off, name);
cstrseal(buf.ptr, off);
return buf.ptr;
};
// Same, but the second component is a ww `str` literal.
fn joinpathlit(dir: *u8, name: str) *u8 = {
let buf: []u8 = alloc([], (os.PATH_MAX: u64))!;
buf.len = os.PATH_MAX;
let off: u64 = cstrinto(buf.ptr, 0u64, dir);
off = byteinto(buf.ptr, off, 47u8);
off = strinto(buf.ptr, off, name);
cstrseal(buf.ptr, off);
return buf.ptr;
};
// ---- Subprocess plumbing ----------------------------------------------
// procrun — fork, execve `path` with `argv` (NULL-terminated), wait.
// Returns 0 on clean exit-0, 1 on any non-zero exit or signal kill,
// -1 on fork/wait failure.
fn procrun(path: *u8, argv: **u8) i32 = {
let pid: i32 = os.fork();
if (pid < 0) {
os.write(2, "ww: fork failed\n".ptr, 16u64);
return -1;
};
if (pid == 0) {
os.execve(pathstr(path), argv, nil: **u8);
os.write(2, "ww: execve failed\n".ptr, 18u64);
os.exit(127);
};
let status: i32 = 0;
let r: i32 = os.wait4(pid, &status, 0i32, nil: *void);
if (r < 0) {
os.write(2, "ww: wait4 failed\n".ptr, 17u64);
return -1;
};
// Linux wait status: low byte = signal (0 if exited cleanly),
// next byte = exit code.
if ((status & 127i32) != 0) { return 1; };
let code: i32 = (status >> 8i32) & 255i32;
if (code != 0) { return 1; };
return 0;
};
// ---- `use` resolution + source concatenation --------------------------
//
// Recursive expansion: for each `use IDENT;` we find at the top of
// `path`, resolve via the colon-separated `dirs`, expand the imported
// file first, then append our own bytes. Already-visited paths are
// skipped (linear scan; typical builds visit a handful of modules).
type strnode = struct {
s: str,
snext: *strnode,
};
type expctx = struct {
out: i32, // fd we're writing the combined source to
dirs: *u8, // ":"-separated search path (NUL-terminated)
visit: *strnode,
};
fn visitseen(c: *expctx, path: str) bool = {
let n: *strnode = c.visit;
for (n != nil) {
if (n.s.len == path.len) {
let i: i32 = 0;
let eq: bool = true;
for (i < path.len) {
if (n.s[i] != path[i]) { eq = false; i = path.len; }
else { i += 1; };
};
if (eq) { return true; };
};
n = n.snext;
};
return false;
};
fn visitadd(c: *expctx, path: str) void = {
let n: *strnode = alloc(strnode{s=path, snext=c.visit})!;
c.visit = n;
};
// Translate dots in an `import` name to slashes for path lookup.
// `encoding.utf8` → `encoding/utf8`. Mirrors Hare's hare(1)
// use-path → fs-path mapping
// (ref/hare/hare/module/srcs.ha:78 builds the same shape via
// path::push per ident part).
fn importpathform(name: *u8, namelen: u64) *u8 = {
let buf: []u8 = alloc([], namelen + 1u64)!;
let i: u64 = 0u64;
for (i < namelen) {
if (name[i] == 46u8) { buf[i] = 47u8; } // '.' -> '/'
else { buf[i] = name[i]; };
i += 1u64;
};
buf[namelen] = 0u8;
return buf.ptr;
};
// Try <dir>/<path>/ as a directory, then <dir>/<path>.ww as a file.
// Sets *isdir on hit. Symmetric with cstage locate_import_in for
// byte-id driver output (rule 10). The legacy <dir>/<name>/<name>.ww
// form was dropped in task #22 — directory-as-module enumeration
// replaces it, mirroring ref/hare/hare/module/srcs.ha (Hare has no
// `foo/foo.ha` fallback; a module IS the directory).
fn locatein(dir: *u8, dirlen: u64,
pathform: *u8, pflen: u64, isdir: *i32) *u8 = {
let buf: []u8 = alloc([], (os.PATH_MAX: u64))!;
let off: u64 = 0u64;
let i: u64 = 0u64;
for (i < dirlen) { buf[off + i] = dir[i]; i += 1u64; };
off += dirlen;
buf[off] = 47u8; off += 1u64; // '/'
i = 0u64;
for (i < pflen) { buf[off + i] = pathform[i]; i += 1u64; };
off += pflen;
buf[off] = 0u8;
let fi: os.filestat;
let r: (void | os.oserror) = os.stat(&fi, pathstr(buf.ptr));
let isdirhit: bool = false;
match (r) {
case void => {
let t: u32 = (fi.mode: u32) & 61440u32; // S_IFMT
if (t == os.mode.DIR: u32) { isdirhit = true; };
};
case let e: os.oserror => void;
};
if (isdirhit) {
*isdir = 1;
return buf.ptr;
};
let buf2: []u8 = alloc([], (os.PATH_MAX: u64))!;
off = 0u64;
i = 0u64;
for (i < dirlen) { buf2[off + i] = dir[i]; i += 1u64; };
off += dirlen;
buf2[off] = 47u8; off += 1u64;
i = 0u64;
for (i < pflen) { buf2[off + i] = pathform[i]; i += 1u64; };
off += pflen;
buf2[off] = 46u8; off += 1u64; // '.'
buf2[off] = 119u8; off += 1u64; // 'w'
buf2[off] = 119u8; off += 1u64; // 'w'
buf2[off] = 0u8;
if (os.access(pathstr(buf2.ptr), 0i32) == 0) {
*isdir = 0;
return buf2.ptr;
};
return nil;
};
// Walk a colon-separated dirlist, return first hit or nil. Sets
// *isdir on hit.
fn locateimport(dirs: *u8, name: *u8, namelen: u64,
isdir: *i32) *u8 = {
let pathform: *u8 = importpathform(name, namelen);
let pflen: u64 = cstrlen(pathform);
let total: u64 = cstrlen(dirs);
let p: u64 = 0u64;
for (p < total) {
let q: u64 = p;
for (q < total) {
if (dirs[q] == 58u8) { break; }; // ':'
q += 1u64;
};
let seglen: u64 = q - p;
if (seglen > 0u64) {
let hit: *u8 = locatein(dirs + p, seglen,
pathform, pflen, isdir);
if (hit != nil) { return hit; };
};
p = q + 1u64;
};
return nil;
};
// Filter for dir enumeration: keep `*.ww` minus `*test.ww` and the
// `*.combined.ww` driver-generated concat artifacts (the previous
// build leaves them in the source tree; they parse-error when
// re-included). Returns true to keep.
fn dirfilekeep(name: *u8, nlen: u64) bool = {
if (nlen <= 3u64) { return false; };
if (name[nlen - 3u64] != 46u8) { return false; }; // '.'
if (name[nlen - 2u64] != 119u8) { return false; }; // 'w'
if (name[nlen - 1u64] != 119u8) { return false; }; // 'w'
if (nlen >= 7u64) {
if (name[nlen - 7u64] == 116u8) { // 't'
if (name[nlen - 6u64] == 101u8) { // 'e'
if (name[nlen - 5u64] == 115u8) { // 's'
if (name[nlen - 4u64] == 116u8) { // 't'
return false;
};
};
};
};
};
if (nlen >= 12u64) {
// ".combined.ww" — full 12-char match mirrors cstage
// cmd/ww/main.c enumerate_dir_ww strcmp (rule 10); the
// trailing .ww is pre-guaranteed by the early-out above.
if (name[nlen - 12u64] == 46u8) { // '.'
if (name[nlen - 11u64] == 99u8) { // 'c'
if (name[nlen - 10u64] == 111u8) { // 'o'
if (name[nlen - 9u64] == 109u8) { // 'm'
if (name[nlen - 8u64] == 98u8) { // 'b'
if (name[nlen - 7u64] == 105u8) { // 'i'
if (name[nlen - 6u64] == 110u8) { // 'n'
if (name[nlen - 5u64] == 101u8) { // 'e'
if (name[nlen - 4u64] == 100u8) { // 'd'
return false;
};
};
};
};
};
};
};
};
};
};
return true;
};
// Byte-wise memcmp returning < 0, 0, > 0. Rule-10 byte-id requires
// cstage and wwstage sort the same way; memcmp is the
// locale-independent total order (mirrors ref/hare/sort/cmp/cmp.ha
// strs).
fn bytecmp(a: *u8, alen: u64, b: *u8, blen: u64) i32 = {
let n: u64 = alen;
if (blen < n) { n = blen; };
let i: u64 = 0u64;
for (i < n) {
let av: i32 = (a[i]): i32;
let bv: i32 = (b[i]): i32;
if (av < bv) { return -1; };
if (av > bv) { return 1; };
i += 1u64;
};
if (alen < blen) { return -1; };
if (alen > blen) { return 1; };
return 0;
};
// enumeratedir — list *.ww entries of `dirpath` (less *test.ww and
// *.combined.ww), byte-sort. Returns (names[], nnames) with each
// name a NUL-terminated heap copy.
fn enumeratedir(dirpath: *u8) (**u8, i32) = {
let fd: i32 = os.open(pathstr(dirpath), os.flag.RDONLY, 0i32);
if (fd < 0) { return nil: **u8, 0; };
let maxnames: i32 = 256;
let names: []*u8 = alloc([], maxnames: u64)!;
let nlens: []u64 = alloc([], maxnames: u64)!;
let n: i32 = 0;
let buf: []u8 = alloc([], 8192u64)!;
buf.len = 8192;
let r: i64 = os.getdents64(fd, buf.ptr, 8192u64);
for (r > 0i64) {
let off: u64 = 0u64;
let ru: u64 = r: u64;
for (off < ru) {
let blo: u64 = (buf[off + 16u64]): u64;
let bhi: u64 = (buf[off + 17u64]): u64;
let reclen: u64 = blo + (bhi * 256u64);
let nm: *u8 = buf.ptr + off + 19u64;
let nl: u64 = cstrlen(nm);
if (dirfilekeep(nm, nl)) {
if (n < maxnames) {
let cp: []u8 = alloc([], nl + 1u64)!;
let i: u64 = 0u64;
for (i < nl) { cp[i] = nm[i]; i += 1u64; };
cp[nl] = 0u8;
names[n] = cp.ptr;
nlens[n] = nl;
n += 1;
};
};
off += reclen;
};
r = os.getdents64(fd, buf.ptr, 8192u64);
};
os.close(fd);
// Insertion sort, byte-wise. n is small (≤16 in practice).
let i: i32 = 1;
for (i < n) {
let j: i32 = i;
for (j > 0) {
if (bytecmp(names[j - 1], nlens[j - 1],
names[j], nlens[j]) <= 0) { j = 0; }
else {
let t: *u8 = names[j];
names[j] = names[j - 1];
names[j - 1] = t;
let tl: u64 = nlens[j];
nlens[j] = nlens[j - 1];
nlens[j - 1] = tl;
j -= 1;
};
};
i += 1;
};
return names.ptr, n;
};
// ---- file slurp -------------------------------------------------------
fn slurp(pathcs: *u8) (*u8, u64) = {
let fd: i32 = os.open(pathstr(pathcs), os.flag.RDONLY, 0i32);
if (fd < 0) { return nil, 0u64; };
let szr: (i64 | os.oserror) = os.filesize(fd);
let n: i64 = 0i64;
match (szr) {
case let v: i64 => n = v;
case let e: os.oserror => { os.close(fd); return nil, 0u64; };
};
let nu: u64 = n: u64;
let buf: []u8 = alloc([], nu + 1u64)!;
buf.len = (nu + 1u64): i32;
let rr: (i64 | os.oserror) = os.readall(fd, buf.ptr, nu);
os.close(fd);
let got: i64 = 0i64;
match (rr) {
case let v: i64 => got = v;
case let e: os.oserror => return nil, 0u64;
};
if (got != n) { return nil, 0u64; };
buf[nu] = 0u8;
return buf.ptr, nu;
};
fn isidentbyte(c: u8) bool = {
if (c >= 97u8) { if (c <= 122u8) { return true; }; }; // a..z
if (c >= 65u8) { if (c <= 90u8) { return true; }; }; // A..Z
if (c >= 48u8) { if (c <= 57u8) { return true; }; }; // 0..9
if (c == 95u8) { return true; }; // _
if (c == 46u8) { return true; }; // .
return false;
};
// Scan one `import IDENT;` line out of [start, end). Returns the start
// of the ident and its length, or (nil, 0) if no `import` here. The
// caller passes a slice of the source: src points at the line start.
fn scanuse(src: *u8, len: u64) (*u8, u64) = {
let i: u64 = 0u64;
// skip leading whitespace
for (i < len) {
if (src[i] != 32u8) { if (src[i] != 9u8) { break; }; };
i += 1u64;
};
if (i + 7u64 > len) { return nil, 0u64; };
if (src[i] != 105u8) { return nil, 0u64; }; // 'i'
if (src[i + 1u64] != 109u8) { return nil, 0u64; }; // 'm'
if (src[i + 2u64] != 112u8) { return nil, 0u64; }; // 'p'
if (src[i + 3u64] != 111u8) { return nil, 0u64; }; // 'o'
if (src[i + 4u64] != 114u8) { return nil, 0u64; }; // 'r'
if (src[i + 5u64] != 116u8) { return nil, 0u64; }; // 't'
let sep: u8 = src[i + 6u64];
if (sep != 32u8) { if (sep != 9u8) { return nil, 0u64; }; };
i += 7u64;
for (i < len) {
if (src[i] != 32u8) { if (src[i] != 9u8) { break; }; };
i += 1u64;
};
let idstart: u64 = i;
for (i < len) {
if (!isidentbyte(src[i])) { break; };
i += 1u64;
};
let idlen: u64 = i - idstart;
if (idlen == 0u64) { return nil, 0u64; };
return src + idstart, idlen;
};
// expand — emit one file's bytes verbatim into the combined stream,
// after recursive-expanding its top-of-file `import X;` imports.
// Each source declares its own `package <name>;` (parser stamps
// decls).
fn expand(c: *expctx, pathcs: *u8) void = {
let plen: u64 = cstrlen(pathcs);
let view: str;
view.ptr = pathcs;
view.len = plen: i32;
let pathstr: str = strings.dup(view);
if (visitseen(c, pathstr)) { return; };
visitadd(c, pathstr);
let bufp: *u8;
let blen: u64;
bufp, blen = slurp(pathcs);
if (bufp == nil) {
os.write(2, "ww: cannot read source\n".ptr, 23u64);
return;
};
// Pass 1: scan top-of-file `import X;` lines, recursively expand.
let i: u64 = 0u64;
for (i < blen) {
let j: u64 = i;
for (j < blen) {
if (bufp[j] == 10u8) { break; }; // '\n'
j += 1u64;
};
let idp: *u8;
let idn: u64;
idp, idn = scanuse(bufp + i, j - i);
if (idp != nil) {
let isdir: i32 = 0;
let ipath: *u8 = locateimport(c.dirs, idp, idn,
&isdir);
if (ipath != nil) {
if (isdir != 0) { expanddir(c, ipath); }
else { expand(c, ipath); };
};
};
i = j + 1u64;
};
os.writeall(c.out, bufp, blen);
os.writeall(c.out, "\n".ptr, 1u64);
};
// Scan `pathcs` for its first non-comment-non-blank line; if it
// starts with `package <name>;` return the package name as a fresh
// heap-allocated NUL-terminated *u8, else nil. Same shape as cstage
// peek_package.
fn peekpackage(pathcs: *u8) *u8 = {
let fd: i32 = os.open(pathstr(pathcs), os.flag.RDONLY, 0i32);
if (fd < 0) { return nil; };
let buf: []u8 = alloc([], 2048u64)!;
buf.len = 2048;
let n: i64 = os.read(fd, buf.ptr, 2048u64);
os.close(fd);
if (n <= 0i64) { return nil; };
let nu: u64 = n: u64;
let p: u64 = 0u64;
for (p < nu) {
let q: u64 = p;
for (q < nu) {
if (buf[q] == 10u8) { break; }; // '\n'
q += 1u64;
};
let s: u64 = p;
for (s < q) {
if (buf[s] != 32u8) {
if (buf[s] != 9u8) { break; };
};
s += 1u64;
};
if (s < q) {
if (s + 1u64 < q) {
if (buf[s] == 47u8) {
if (buf[s + 1u64] == 47u8) {
p = q + 1u64;
continue;
};
};
};
if (s + 8u64 <= q) {
if (buf[s] == 112u8) { // 'p'
if (buf[s + 1u64] == 97u8) { // 'a'
if (buf[s + 2u64] == 99u8) { // 'c'
if (buf[s + 3u64] == 107u8) { // 'k'
if (buf[s + 4u64] == 97u8) { // 'a'
if (buf[s + 5u64] == 103u8) { // 'g'
if (buf[s + 6u64] == 101u8) { // 'e'
let sep: u8 = buf[s + 7u64];
if (sep == 32u8) { }
else { if (sep != 9u8) { return nil; }; };
let t: u64 = s + 8u64;
for (t < q) {
if (buf[t] != 32u8) {
if (buf[t] != 9u8) { break; };
};
t += 1u64;
};
let start: u64 = t;
for (t < q) {
let ch: u8 = buf[t];
let isalpha: bool = false;
if (ch >= 97u8) { if (ch <= 122u8) { isalpha = true; }; };
if (ch >= 65u8) { if (ch <= 90u8) { isalpha = true; }; };
if (ch >= 48u8) { if (ch <= 57u8) { isalpha = true; }; };
if (ch == 95u8) { isalpha = true; };
if (!isalpha) { break; };
t += 1u64;
};
let plen: u64 = t - start;
if (plen == 0u64) { return nil; };
let r: []u8 = alloc([], plen + 1u64)!;
let k: u64 = 0u64;
for (k < plen) { r[k] = buf[start + k]; k += 1u64; };
r[plen] = 0u8;
return r.ptr;
}; }; }; }; }; }; };
};
return nil;
};
p = q + 1u64;
};
return nil;
};
// Strict-same-package error helper. Bundled here per task #22
// brief — failure mode is dir-enum's own.
fn strictpkgmismatch(file: *u8, pkg: *u8, dirpkg: *u8, dirpath: *u8) void = {
os.write(2, "ww: ".ptr, 4u64);
os.write(2, file, cstrlen(file));
os.write(2, ": package ".ptr, 10u64);
os.write(2, pkg, cstrlen(pkg));
os.write(2, " differs from ".ptr, 14u64);
os.write(2, dirpkg, cstrlen(dirpkg));
os.write(2, " in same module dir ".ptr, 20u64);
os.write(2, dirpath, cstrlen(dirpath));
os.write(2, "\n".ptr, 1u64);
os.exit(1);
};
// expanddir — enumerate <dirpath>/*.ww (skip *test.ww and
// *.combined.ww), byte-sort, recurse into each. Mirrors
// ref/hare/hare/module/srcs.ha:183 `_findsrcs` minus tag handling.
// The visited set keys on concrete file paths so multi-file modules
// are pulled once. Strict-same-package: all enumerated files must
// declare the same `package <name>;` (task #23 subset; failure
// mode native to dir-enum).
fn expanddir(c: *expctx, dirpath: *u8) void = {
let names: **u8;
let n: i32;
names, n = enumeratedir(dirpath);
let dlen: u64 = cstrlen(dirpath);
let dirpkg: *u8 = nil;
let i: i32 = 0;
for (i < n) {
let nlen: u64 = cstrlen(names[i]);
let fp: []u8 = alloc([], dlen + 1u64 + nlen + 1u64)!;
let k: u64 = 0u64;
for (k < dlen) { fp[k] = dirpath[k]; k += 1u64; };
fp[dlen] = 47u8; // '/'
k = 0u64;
for (k < nlen) { fp[dlen + 1u64 + k] = names[i][k]; k += 1u64; };
fp[dlen + 1u64 + nlen] = 0u8;
let pkg: *u8 = peekpackage(fp.ptr);
if (pkg != nil) {
if (dirpkg == nil) { dirpkg = pkg; }
else { if (!cstreq(dirpkg, pkg)) {
strictpkgmismatch(fp.ptr, pkg, dirpkg, dirpath);
}; };
};
expand(c, fp.ptr);
i += 1;
};
};
// ---- Build pipeline ---------------------------------------------------
// Strip the trailing ".ww" off `src` (a NUL-terminated path) into
// `stem`, NUL-terminated. If there's no .ww, the stem is the whole
// path.
fn makestem(stem: *u8, src: *u8) void = {
let n: u64 = cstrlen(src);
let stop: u64 = n;
if (n >= 3u64) {
if (src[n - 3u64] == 46u8) { // '.'
if (src[n - 2u64] == 119u8) { // 'w'
if (src[n - 1u64] == 119u8) { // 'w'
stop = n - 3u64;
};
};
};
};
let i: u64 = 0u64;
for (i < stop) { stem[i] = src[i]; i += 1u64; };
stem[stop] = 0u8;
};
// Append a literal suffix to `stem` (which already lives in a buffer).
fn appendlit(stem: *u8, suffix: str) *u8 = {
let buf: []u8 = alloc([], (os.PATH_MAX: u64))!;
buf.len = os.PATH_MAX;
let off: u64 = cstrinto(buf.ptr, 0u64, stem);
off = strinto(buf.ptr, off, suffix);
cstrseal(buf.ptr, off);
return buf.ptr;
};
// linker flags bundled as a struct so buildone stays at the wwstage
// w6c's 6-argument calling-convention limit.
type lflags = struct {
libdirs: **u8,
nlibdirs: i32,
libs: **u8,
nlibs: i32,
};
// buildone — compile `src` (file or directory) into the executable
// named `out`.
// selfdir: NUL-terminated dir containing this driver and the
// wwstage tools (w6c_ww/w6a_ww/w6l_ww)
// src: NUL-terminated entry path (file or directory).
// entryisdir: non-zero when src is a module directory.
// out: NUL-terminated desired output path
// incs: NUL-terminated colon-list of -I dirs (may be empty)
// lf: extra linker flags (-L<dir>, -l<name>); may be nil
//
// The ww-side driver shells to the ww-side tools so a `ww_ww build`
// touches no C-built code at runtime. The C `ww` driver in cmd/ww/
// still drives the C-built w6c/w6a/w6l. Test 993 pins the two
// pipelines to byte-identical output on a corpus.
fn buildone(selfdir: *u8, src: *u8, entryisdir: i32, out: *u8, incs: *u8, lf: *lflags) i32 = {
let c6: *u8 = joinpathlit(selfdir, "w6c_ww");
let a6: *u8 = joinpathlit(selfdir, "w6a_ww");
let l6: *u8 = joinpathlit(selfdir, "w6l_ww");
// Default lib search path: <selfdir>/../../lib
let dotdotlib: []u8 = alloc([], (os.PATH_MAX: u64))!;
dotdotlib.len = os.PATH_MAX;
{
let off: u64 = cstrinto(dotdotlib.ptr, 0u64, selfdir);
off = strinto(dotdotlib.ptr, off, "/../../lib");
cstrseal(dotdotlib.ptr, off);
};
// Compute the source directory. For a file entry: bytes of `src`
// up to the last '/' (or "." when src has no '/'). For a dir
// entry: the dir itself (less trailing slashes). Hare's CWD-first
// convention assumes you're running from the module dir; our
// wrappers don't cd, so dirname(src) stands in as the closest
// analog. Source-dir wins ties over the system path (cc -I.).
let srcd: []u8 = alloc([], (os.PATH_MAX: u64))!;
srcd.len = os.PATH_MAX;
if (entryisdir != 0) {
let slen: u64 = cstrlen(src);
let k: u64 = 0u64;
for (k < slen) { srcd[k] = src[k]; k += 1u64; };
for (slen > 1u64) {
if (srcd[slen - 1u64] != 47u8) { break; };
slen -= 1u64;
};
srcd[slen] = 0u8;
} else {
let slen: u64 = cstrlen(src);
let last: u64 = slen;
let found: bool = false;
let i: u64 = slen;
for (i > 0u64) {
i -= 1u64;
if (src[i] == 47u8) { // '/'
last = i;
found = true;
i = 0u64;
};
};
if (found) {
let k: u64 = 0u64;
for (k < last) { srcd[k] = src[k]; k += 1u64; };
srcd[last] = 0u8;
} else {
srcd[0] = 46u8; // '.'
srcd[1] = 0u8;
};
};
// Compose searchpath: srcd + ':' + incs + ':' + dotdotlib.
let searchpath: []u8 = alloc([], (os.PATH_MAX: u64) * 3u64)!;
searchpath.len = ((os.PATH_MAX: u64) * 3u64): i32;
{
let off: u64 = cstrinto(searchpath.ptr, 0u64, srcd.ptr);
off = byteinto(searchpath.ptr, off, 58u8); // ':'
if (incs[0u64] != 0u8) {
off = cstrinto(searchpath.ptr, off, incs);
off = byteinto(searchpath.ptr, off, 58u8); // ':'
};
off = cstrinto(searchpath.ptr, off, dotdotlib.ptr);
cstrseal(searchpath.ptr, off);
};
// Stem for .s/.o/.combined.ww side files. Dir entry: <dir>/<base>;
// file entry: src stripped of .ww.
let stem: []u8 = alloc([], (os.PATH_MAX: u64))!;
stem.len = os.PATH_MAX;
if (entryisdir != 0) {
let dlen: u64 = cstrlen(srcd.ptr);
let bo: u64 = basenameoff(srcd.ptr, dlen);
let off: u64 = cstrinto(stem.ptr, 0u64, srcd.ptr);
stem[off] = 47u8; off += 1u64; // '/'
let i: u64 = bo;
for (i < dlen) { stem[off] = srcd[i]; off += 1u64; i += 1u64; };
cstrseal(stem.ptr, off);
} else {
makestem(stem.ptr, src);
};
let asmf: *u8 = appendlit(stem.ptr, ".s");
let objf: *u8 = appendlit(stem.ptr, ".o");
let combined: *u8 = appendlit(stem.ptr, ".combined.ww");
// libwwrt.a path: <selfdir>/../lib/libwwrt.a
let libwwrt: []u8 = alloc([], (os.PATH_MAX: u64))!;
libwwrt.len = os.PATH_MAX;
{
let off: u64 = cstrinto(libwwrt.ptr, 0u64, selfdir);
off = strinto(libwwrt.ptr, off, "/../lib/libwwrt.a");
cstrseal(libwwrt.ptr, off);
};
// Step 1: expand imports into the combined file. Dir entry →
// enumerate the module dir; file entry → start at the file.
let cf: i32 = os.open(pathstr(combined), os.flag.WRONLY | os.flag.CREATE | os.flag.TRUNC, 420i32); // 0o644
if (cf < 0) {
os.write(2, "ww: cannot open combined\n".ptr, 25u64);
return 1;
};
{
let c: expctx;
c.out = cf;
c.dirs = searchpath.ptr;
c.visit = nil;
if (entryisdir != 0) { expanddir(&c, srcd.ptr); }
else { expand(&c, src); };
};
os.close(cf);
// Step 2: w6c -o <stem>.s <stem>.combined.ww
{
let argv: []*u8 = alloc([], 5u64)!;
argv.len = 5;
argv[0] = "w6c\0".ptr;
argv[1] = "-o\0".ptr;
argv[2] = asmf;
argv[3] = combined;
argv[4] = nil;
if (procrun(c6, argv.ptr) != 0) {
os.write(2, "ww: w6c failed\n".ptr, 15u64);
return 1;
};
};
// Step 3: w6a -o <stem>.o <stem>.s
{
let argv: []*u8 = alloc([], 5u64)!;
argv.len = 5;
argv[0] = "w6a\0".ptr;
argv[1] = "-o\0".ptr;
argv[2] = objf;
argv[3] = asmf;
argv[4] = nil;
if (procrun(a6, argv.ptr) != 0) {
os.write(2, "ww: w6a failed\n".ptr, 15u64);
return 1;
};
};
// Step 4: w6l -o <out> <stem>.o libwwrt.a [-L<dir>...] [-l<name>...]
{
let nldirs: i32 = 0;
let nllibs: i32 = 0;
let ldirs: **u8 = nil;
let llibs: **u8 = nil;
if (lf != nil) {
nldirs = lf.nlibdirs;
nllibs = lf.nlibs;
ldirs = lf.libdirs;
llibs = lf.libs;
};
// argv slots: 5 fixed (w6l, -o, out, objf, libwwrt)
// + 2 * nlibdirs (-L, dir)
// + 2 * nlibs (-l, name)
// + 1 nil terminator.
let total: i32 = 5 + 2 * nldirs + 2 * nllibs + 1;
let argv: []*u8 = alloc([], total: u64)!;
argv.len = total;
argv[0] = "w6l\0".ptr;
argv[1] = "-o\0".ptr;
argv[2] = out;
argv[3] = objf;
argv[4] = libwwrt.ptr;
let pos: i32 = 5;
let k: i32 = 0;
for (k < nldirs) {
argv[pos] = "-L\0".ptr;
argv[pos + 1] = ldirs[k];
pos += 2;
k += 1;
};
k = 0;
for (k < nllibs) {
argv[pos] = "-l\0".ptr;
argv[pos + 1] = llibs[k];
pos += 2;
k += 1;
};
argv[pos] = nil;
if (procrun(l6, argv.ptr) != 0) {
os.write(2, "ww: w6l failed\n".ptr, 15u64);
return 1;
};
};
return 0;
};
// ---- Module-by-name resolution ----------------------------------------
//
// Mirrors cmd/ww/main.c:resolvemodule. Maps a name like "foo", "lib/foo",
// "foo.ww", or "." to a concrete .ww file path:
// 1. literal <name>.ww that exists → use as-is
// 2. "." → <cwd>/<basename(cwd)>.ww → that, if it exists
// 3. <name>/<basename(name)>.ww → that, if it exists
// 4. walk search path (cwd:incs:<selfdir>/../../lib):
// <dir>/<name>.ww or <dir>/<name>/<name>.ww
fn cstrendswithlit(p: *u8, lit: str) bool = {
let plen: u64 = cstrlen(p);
let slen: u64 = lit.len: u64;
if (plen < slen) { return false; };
let off: u64 = plen - slen;
let i: i32 = 0;
for (i < lit.len) {
let iu: u64 = i: u64;
if (p[off + iu] != lit[i]) { return false; };
i += 1;
};
return true;
};
// basenameoff — return the offset of the last path segment within `p`
// (i.e. one past the final '/'). Returns 0 if there's no slash.
fn basenameoff(p: *u8, plen: u64) u64 = {
let start: u64 = 0u64;
let i: u64 = 0u64;
for (i < plen) {
if (p[i] == 47u8) { start = i + 1u64; }; // '/'
i += 1u64;
};
return start;
};
// arenadupcstr — copy `plen` bytes from `src` into a fresh NUL-sealed
// heap buffer.
fn arenadupcstr(src: *u8, plen: u64) *u8 = {
let buf: []u8 = alloc([], plen + 1u64)!;
let i: u64 = 0u64;
for (i < plen) { buf[i] = src[i]; i += 1u64; };
buf[plen] = 0u8;
return buf.ptr;
};
// buildsearchpath — compose the colon-separated lookup path used by
// resolvemodule's case (4). Order: "." : <incs> : <selfdir>/../../lib
fn buildsearchpath(selfdir: *u8, incs: *u8) *u8 = {
let buf: []u8 = alloc([], (os.PATH_MAX: u64) * 2u64)!;
let off: u64 = 0u64;
buf[off] = 46u8; off += 1u64; // '.'
if (incs != nil) {
if (incs[0u64] != 0u8) {
buf[off] = 58u8; off += 1u64; // ':'
off = cstrinto(buf.ptr, off, incs);
};
};
buf[off] = 58u8; off += 1u64;
off = cstrinto(buf.ptr, off, selfdir);
off = strinto(buf.ptr, off, "/../../lib");
cstrseal(buf.ptr, off);
return buf.ptr;
};
// resolvemodule — map a name like "foo", "lib/foo", "foo.ww", or
// "." to a concrete entry path. Sets *isdir when the entry is a
// module directory (caller will dir-enumerate).
fn resolvemodule(selfdir: *u8, name: *u8, incs: *u8, isdir: *i32) *u8 = {
let nlen: u64 = cstrlen(name);
// (1) Literal file that exists → use as-is.
if (cstrendswithlit(name, ".ww")) {
if (os.access(pathstr(name), 0i32) == 0) {
*isdir = 0;
return arenadupcstr(name, nlen);
};
};
// (2) Existing path → use as-is, dir vs file via stat.
let fi: os.filestat;
let sr: (void | os.oserror) = os.stat(&fi, pathstr(name));
let found: bool = false;
let foundisdir: i32 = 0;
match (sr) {
case void => {
let t: u32 = (fi.mode: u32) & 61440u32; // S_IFMT
if (t == os.mode.DIR: u32) { foundisdir = 1; };
found = true;
};
case let e: os.oserror => void;
};
if (found) {
*isdir = foundisdir;
return arenadupcstr(name, nlen);
};
// (3) Search-path lookup with dot-to-slash path translation.
let search: *u8 = buildsearchpath(selfdir, incs);
return locateimport(search, name, nlen, isdir);
};
// ---- Subcommand handlers ----------------------------------------------
fn writeusage(fd: i32) void = {
let s: str = "usage: ww [-V] <subcommand> [args...]\n -V print version and exit\n build [path] compile module to a static binary (path defaults to cwd)\n run [path] ... build then exec, passing extra args to the program\n test [path] build and run *_test.ww in the module (path defaults to cwd)\n version print version and exit\n\n path forms:\n foo.ww literal file\n foo search cwd, -I dirs, then $WW_LIB-equiv for foo.ww or foo/foo.ww\n lib/foo directory: build lib/foo/foo.ww\n . build the cwd's <basename>.ww\n";
os.write(fd, s.ptr, s.len: u64);
};
fn doversion() i32 = {
os.write(1, "ww 0.0\n".ptr, 7u64);
return 0;
};
// Compute the basename of src (without trailing ".ww") into a fresh
// buffer. Used as the default output path for `ww build`.
fn defaultoutpath(src: *u8) *u8 = {
let n: u64 = cstrlen(src);
let start: u64 = 0u64;
let i: u64 = 0u64;
for (i < n) {
if (src[i] == 47u8) { start = i + 1u64; }; // '/'
i += 1u64;
};
let out: []u8 = alloc([], (os.PATH_MAX: u64))!;
out.len = os.PATH_MAX;
let off: u64 = 0u64;
let j: u64 = start;
for (j < n) {
out[off] = src[j];
off += 1u64;
j += 1u64;
};
// Strip ".ww" if present.
if (off >= 3u64) {
if (out[off - 3u64] == 46u8) {
if (out[off - 2u64] == 119u8) {
if (out[off - 1u64] == 119u8) {
off -= 3u64;
};
};
};
};
cstrseal(out.ptr, off);
return out.ptr;
};
fn dobuild(selfdir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
let src: *u8 = nil;
let incs: []u8 = alloc([], (os.PATH_MAX: u64) * 2u64)!;
incs.len = ((os.PATH_MAX: u64) * 2u64): i32;
let incoff: u64 = 0u64;
cstrseal(incs.ptr, 0u64);
let maxlflags: i32 = 32;
let libdirs: []*u8 = alloc([], maxlflags: u64)!;
libdirs.len = maxlflags;
let nlibdirs: i32 = 0;
let libs: []*u8 = alloc([], maxlflags: u64)!;
libs.len = maxlflags;
let nlibs: i32 = 0;
let i: i32 = start;
for (i < argc) {
let p: *u8 = argv[i];
if (p[0u64] == 45u8) { // '-'
if (p[1u64] == 73u8) { // '-I'
let dir: *u8 = nil;
if (p[2u64] != 0u8) {
dir = p + 2u64;
} else {
if (i + 1 >= argc) {
os.write(2, "ww build: -I needs an argument\n".ptr, 31u64);
return 2;
};
i += 1;
dir = argv[i];
};
if (incoff > 0u64) {
incs[incoff] = 58u8; // ':'
incoff += 1u64;
};
incoff = cstrinto(incs.ptr, incoff, dir);
cstrseal(incs.ptr, incoff);
} else { if (p[1u64] == 76u8) { // '-L'
let dir: *u8 = nil;
if (p[2u64] != 0u8) {
dir = p + 2u64;
} else {
if (i + 1 >= argc) {
os.write(2, "ww build: -L needs an argument\n".ptr, 31u64);
return 2;
};
i += 1;
dir = argv[i];
};
if (nlibdirs >= maxlflags) {
os.write(2, "ww build: too many -L\n".ptr, 22u64);
return 2;
};
libdirs[nlibdirs] = dir;
nlibdirs += 1;
} else { if (p[1u64] == 108u8) { // '-l'
let nm: *u8 = nil;
if (p[2u64] != 0u8) {
nm = p + 2u64;
} else {
if (i + 1 >= argc) {
os.write(2, "ww build: -l needs an argument\n".ptr, 31u64);
return 2;
};
i += 1;
nm = argv[i];
};
if (nlibs >= maxlflags) {
os.write(2, "ww build: too many -l\n".ptr, 22u64);
return 2;
};
libs[nlibs] = nm;
nlibs += 1;
} else {
os.write(2, "ww build: unknown flag\n".ptr, 23u64);
return 2;
}; }; };
} else {
if (src == nil) { src = p; };
};
i += 1;
};
if (src == nil) {
// default to cwd module
let dot: [2]u8 = ['.': u8, 0u8];
src = &dot[0];
};
let isdir: i32 = 0;
let resolved: *u8 = resolvemodule(selfdir, src, incs.ptr, &isdir);
if (resolved == nil) {
os.write(2, "ww build: cannot find module\n".ptr, 29u64);
return 1;
};
let out: *u8 = nil;
if (isdir != 0) {
let rlen: u64 = cstrlen(resolved);
for (rlen > 1u64) {
if (resolved[rlen - 1u64] != 47u8) { break; };
rlen -= 1u64;
};
let bo: u64 = basenameoff(resolved, rlen);
let outbuf: []u8 = alloc([], (os.PATH_MAX: u64))!;
outbuf.len = os.PATH_MAX;
out = outbuf.ptr;
let i: u64 = bo;
let off: u64 = 0u64;
for (i < rlen) { out[off] = resolved[i]; off += 1u64; i += 1u64; };
cstrseal(out, off);
} else {
out = defaultoutpath(resolved);
};
let lf: lflags;
lf.libdirs = libdirs.ptr;
lf.nlibdirs = nlibdirs;
lf.libs = libs.ptr;
lf.nlibs = nlibs;
return buildone(selfdir, resolved, isdir, out, incs.ptr, &lf);
};
// Format the scratch path /tmp/ww_run_<pid> into buf. Returns NUL-
// terminated buf. Pid is folded in decimal manually since we don't
// import strconv.
fn makeruntmp(buf: *u8) void = {
let off: u64 = 0u64;
off = strinto(buf, off, "/tmp/ww_run_");
let pid: i32 = os.getpid();
// itoa for non-negative pid
let dig: [16]u8;
let n: i32 = 0;
if (pid <= 0) {
dig[n] = 48u8; // '0'
n += 1;
} else {
let v: i32 = pid;
for (v > 0) {
dig[n] = ((v % 10) + 48): u8;
n += 1;
v = v / 10;
};
};
let k: i32 = n - 1;
for (k >= 0) {
buf[off] = dig[k];
off += 1u64;
k -= 1;
};
cstrseal(buf, off);
};
fn dorun(selfdir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
let src: *u8 = nil;
let passstart: i32 = -1; // first argv idx to pass through to program
let incs: []u8 = alloc([], (os.PATH_MAX: u64) * 2u64)!;
incs.len = ((os.PATH_MAX: u64) * 2u64): i32;
let incoff: u64 = 0u64;
cstrseal(incs.ptr, 0u64);
let maxlflags: i32 = 32;
let libdirs: []*u8 = alloc([], maxlflags: u64)!;
libdirs.len = maxlflags;
let nlibdirs: i32 = 0;
let libs: []*u8 = alloc([], maxlflags: u64)!;
libs.len = maxlflags;
let nlibs: i32 = 0;
let i: i32 = start;
for (i < argc) {
if (passstart >= 0) { i = argc; } // stop, leave rest for exec
else {
let p: *u8 = argv[i];
if (p[0u64] == 45u8) {
if (p[1u64] == 73u8) {
let dir: *u8 = nil;
if (p[2u64] != 0u8) {
dir = p + 2u64;
} else {
if (i + 1 >= argc) {
os.write(2, "ww run: -I needs an argument\n".ptr, 29u64);
return 2;
};
i += 1;
dir = argv[i];
};
if (incoff > 0u64) {
incs[incoff] = 58u8;
incoff += 1u64;
};
incoff = cstrinto(incs.ptr, incoff, dir);
cstrseal(incs.ptr, incoff);
} else { if (p[1u64] == 76u8) {
let dir: *u8 = nil;
if (p[2u64] != 0u8) {
dir = p + 2u64;
} else {
if (i + 1 >= argc) {
os.write(2, "ww run: -L needs an argument\n".ptr, 29u64);
return 2;
};
i += 1;
dir = argv[i];
};
if (nlibdirs >= maxlflags) {
os.write(2, "ww run: too many -L\n".ptr, 20u64);
return 2;
};
libdirs[nlibdirs] = dir;
nlibdirs += 1;
} else { if (p[1u64] == 108u8) {
let nm: *u8 = nil;
if (p[2u64] != 0u8) {
nm = p + 2u64;
} else {
if (i + 1 >= argc) {
os.write(2, "ww run: -l needs an argument\n".ptr, 29u64);
return 2;
};
i += 1;
nm = argv[i];
};
if (nlibs >= maxlflags) {
os.write(2, "ww run: too many -l\n".ptr, 20u64);
return 2;
};
libs[nlibs] = nm;
nlibs += 1;
} else {
os.write(2, "ww run: unknown flag\n".ptr, 21u64);
return 2;
}; }; };
i += 1;
} else {
if (src == nil) {
src = p;
i += 1;
} else {
passstart = i; // remaining args go to the program
};
};
};
};
if (src == nil) {
let dot: [2]u8 = ['.': u8, 0u8];
src = &dot[0];
};
let isdir: i32 = 0;
let resolved: *u8 = resolvemodule(selfdir, src, incs.ptr, &isdir);
if (resolved == nil) {
os.write(2, "ww run: cannot find module\n".ptr, 27u64);
return 1;
};
let tmp: []u8 = alloc([], (os.PATH_MAX: u64))!;
tmp.len = os.PATH_MAX;
makeruntmp(tmp.ptr);
let lf: lflags;
lf.libdirs = libdirs.ptr;
lf.nlibdirs = nlibdirs;
lf.libs = libs.ptr;
lf.nlibs = nlibs;
if (buildone(selfdir, resolved, isdir, tmp.ptr, incs.ptr, &lf) != 0) {
os.remove(pathstr(tmp.ptr));
return 1;
};
// exec with [tmp, argv[passstart..argc), nil]
let nextra: i32 = 0;
if (passstart >= 0) { nextra = argc - passstart; };
let total: i32 = nextra + 2;
let execargv: []*u8 = alloc([], total: u64)!;
execargv.len = total;
execargv[0] = tmp.ptr;
let k: i32 = 0;
for (k < nextra) {
execargv[k + 1] = argv[passstart + k];
k += 1;
};
execargv[nextra + 1] = nil;
let rc: i32 = procrun(tmp.ptr, execargv.ptr);
os.remove(pathstr(tmp.ptr));
return rc;
};
// ---- ww test ----------------------------------------------------------
//
// Mirrors cmd/ww/main.c:dotest. Two modes:
// single-file: build+run a literal *.ww file, return its exit code
// directory: open the dir, getdents64, build+run each *_test.ww,
// report ok/FAIL per file, return 0 iff all pass.
fn runsingletest(selfdir: *u8, src: *u8) i32 = {
let tmp: []u8 = alloc([], (os.PATH_MAX: u64))!;
tmp.len = os.PATH_MAX;
makeruntmp(tmp.ptr);
if (buildone(selfdir, src, 0, tmp.ptr, "\0".ptr, nil) != 0) {
os.remove(pathstr(tmp.ptr));
return 1;
};
let execargv: []*u8 = alloc([], 2u64)!;
execargv.len = 2;
execargv[0] = tmp.ptr;
execargv[1] = nil;
let rc: i32 = procrun(tmp.ptr, execargv.ptr);
os.remove(pathstr(tmp.ptr));
return rc;
};
fn rundirtests(selfdir: *u8, dir: *u8) i32 = {
let fd: i32 = os.open(pathstr(dir), os.flag.RDONLY, 0i32);
if (fd < 0) {
os.write(2, "ww test: cannot open directory\n".ptr, 31u64);
return 1;
};
let pass: i32 = 0;
let fail: i32 = 0;
let buf: []u8 = alloc([], 8192u64)!;
buf.len = 8192;
let dirlen: u64 = cstrlen(dir);
let n: i64 = os.getdents64(fd, buf.ptr, 8192u64);
for (n > 0i64) {
let off: u64 = 0u64;
let nu: u64 = n: u64;
for (off < nu) {
// d_reclen at offset+16 (u16 LE), d_name at offset+19 (cstr)
let blo: u64 = (buf[off + 16u64]): u64;
let bhi: u64 = (buf[off + 17u64]): u64;
let reclen: u64 = blo + (bhi * 256u64);
let name: *u8 = buf.ptr + off + 19u64;
if (cstrendswithlit(name, "_test.ww")) {
let nlen: u64 = cstrlen(name);
// path = <dir>/<name>
let path: []u8 = alloc([], (os.PATH_MAX: u64))!;
path.len = os.PATH_MAX;
let poff: u64 = cstrinto(path.ptr, 0u64, dir);
path[poff] = 47u8; poff += 1u64;
let i: u64 = 0u64;
for (i < nlen) { path[poff + i] = name[i]; i += 1u64; };
poff += nlen;
cstrseal(path.ptr, poff);
// incs = <dir> so test files can `use ` siblings
let tincs: []u8 = alloc([], (os.PATH_MAX: u64))!;
tincs.len = os.PATH_MAX;
let ic: u64 = cstrinto(tincs.ptr, 0u64, dir);
cstrseal(tincs.ptr, ic);
let tmp: []u8 = alloc([], (os.PATH_MAX: u64))!;
tmp.len = os.PATH_MAX;
makeruntmp(tmp.ptr);
let bres: i32 = buildone(selfdir, path.ptr, 0, tmp.ptr, tincs.ptr, nil);
if (bres != 0) {
fail += 1;
os.write(2, "FAIL ".ptr, 5u64);
os.write(2, name, nlen);
os.write(2, " (build)\n".ptr, 9u64);
} else {
let execargv: []*u8 = alloc([], 2u64)!;
execargv.len = 2;
execargv[0] = tmp.ptr;
execargv[1] = nil;
let rc: i32 = procrun(tmp.ptr, execargv.ptr);
if (rc == 0) {
pass += 1;
os.write(1, "ok ".ptr, 5u64);
os.write(1, name, nlen);
os.write(1, "\n".ptr, 1u64);
} else {
fail += 1;
os.write(2, "FAIL ".ptr, 5u64);
os.write(2, name, nlen);
os.write(2, "\n".ptr, 1u64);
};
};
os.remove(pathstr(tmp.ptr));
};
off += reclen;
};
n = os.getdents64(fd, buf.ptr, 8192u64);
};
os.close(fd);
if (fail == 0) { return 0; };
return 1;
};
fn dotest(selfdir: *u8, argv: **u8, argc: i32, start: i32) i32 = {
let target: *u8;
if (start >= argc) {
let dot: [2]u8 = ['.': u8, 0u8];
target = &dot[0];
} else {
target = argv[start];
};
// single-file mode: literal *.ww that exists
if (cstrendswithlit(target, ".ww")) {
if (os.access(pathstr(target), 0i32) == 0) {
return runsingletest(selfdir, target);
};
};
// otherwise treat target as a directory; enumerate *_test.ww
return rundirtests(selfdir, target);
};
// ---- Entry -------------------------------------------------------------
export fn main(argc: i32, argv: **u8) i32 = {
if (argc < 1) {
writeusage(2);
return 2;
};
// selfdir = dirname(argv[0])
let selfdir: []u8 = alloc([], (os.PATH_MAX: u64))!;
selfdir.len = os.PATH_MAX;
selfdirinto(selfdir.ptr, (os.PATH_MAX: u64), argv[0]);
if (argc < 2) {
writeusage(2);
return 2;
};
let cmd: *u8 = argv[1];
if (cstreqlit(cmd, "-V")) { return doversion(); };
if (cstreqlit(cmd, "version")) { return doversion(); };
if (cstreqlit(cmd, "-h")) {
writeusage(1);
return 0;
};
if (cstreqlit(cmd, "--help")) {
writeusage(1);
return 0;
};
if (cstreqlit(cmd, "build")) {
return dobuild(selfdir.ptr, argv, argc, 2);
};
if (cstreqlit(cmd, "run")) {
return dorun(selfdir.ptr, argv, argc, 2);
};
if (cstreqlit(cmd, "test")) {
return dotest(selfdir.ptr, argv, argc, 2);
};
os.write(2, "ww: unknown subcommand\n".ptr, 23u64);
writeusage(2);
return 2;
};