Add os.alloc(n: u64) *void and os.free(p: *void, n: u64) void as
`export fn` via @symbol("rt_alloc") / @symbol("rt_free"). Signatures
mirror lib/memio's existing internal bindings byte-for-byte — only
the name and `export` keyword change. lib/memio + lib/shlex + lib/
getopt drop their own copies in a follow-up commit.
Doc comment spells out the actual failure ABI: rt_alloc wraps the
raw mmap syscall (no libc), so OOM yields a negative-errno cast to
`*void` (e.g. (void*)-12 for ENOMEM). Neither `== nil` nor the libc
MAP_FAILED `(void*)-1` value catches it; deref faults. A typed
fallible variant is future work (alongside #16 fmt.asprintf).
Test (ostest test_alloc_free_roundtrip, signalled=5): alloc 4096B,
write 0x5a at head + 0xa5 at tail, read-back asserts both, free.
The head+tail write/read prevents DCE (failure path calls os.exit)
and proves a real page is backing the returned pointer.
1291 lines
39 KiB
Plaintext
1291 lines
39 KiB
Plaintext
// MODULE: os
|
|
// os — process and filesystem facade. The body of each call lands
|
|
// either in libwwrt.a (rt_syscall trampoline) or libc bindings,
|
|
// depending on how the program was linked.
|
|
|
|
@symbol("rt_syscall") fn syscall0(num: nr) i64;
|
|
@symbol("rt_syscall") fn syscall1(num: nr, a: i64) i64;
|
|
@symbol("rt_syscall") fn syscall2(num: nr, a: i64, b: i64) i64;
|
|
@symbol("rt_syscall") fn syscall3(num: nr, a: i64, b: i64, c: i64) i64;
|
|
@symbol("rt_syscall") fn syscall4(num: nr, a: i64, b: i64, c: i64, d: i64) i64;
|
|
|
|
// alloc / free — runtime mmap-backed page allocator. Untyped:
|
|
// `alloc(n)` returns a `*void` and `free(p, n)` requires the byte
|
|
// count back because rt_free is munmap-based and doesn't track
|
|
// mapping sizes (the kernel needs the length to release the
|
|
// reservation).
|
|
//
|
|
// Diverges from Hare. Hare exposes `alloc` / `free` as typed
|
|
// language builtins (`alloc(value, cap)?` / `free(ptr)`) 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_alloc 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_alloc 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.
|
|
@symbol("rt_alloc") export fn alloc(n: u64) *void;
|
|
@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,
|
|
};
|
|
|
|
// 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);
|
|
};
|
|
|
|
// Raw, non-fallible primitives. These return Linux's int conventions
|
|
// (negative = -errno, non-negative = bytes/fd/etc). Callers wanting a
|
|
// Hare-style fallible API use the wrappers below.
|
|
export fn write(fd: i32, buf: *u8, n: u64) i64 = {
|
|
return syscall3(nr.WRITE, fd: i64, buf: i64, n: i64);
|
|
};
|
|
|
|
export fn read(fd: i32, buf: *u8, n: u64) i64 = {
|
|
return syscall3(nr.READ, fd: i64, buf: i64, n: i64);
|
|
};
|
|
|
|
export fn close(fd: i32) i32 = {
|
|
return syscall1(nr.CLOSE, fd: i64): i32;
|
|
};
|
|
|
|
// dup2(2): make `newfd` refer to the same description as `oldfd`,
|
|
// closing `newfd` first if open. Returns `newfd` on success or a
|
|
// negative errno. Used by w6c_ww to redirect stdout into an output
|
|
// file without changing the cgen emit path.
|
|
export fn dup2(oldfd: i32, newfd: i32) i32 = {
|
|
return syscall2(nr.DUP2, oldfd: i64, newfd: i64): i32;
|
|
};
|
|
|
|
// Fallible wrappers. The error variant is `oserror` (an i64 carrying
|
|
// -errno). The sum type makes success/failure explicit and lets
|
|
// callers `?` the result up the stack.
|
|
export fn tryread(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
|
|
let r: i64 = read(fd, buf, n);
|
|
if (r < 0) { return r: oserror; };
|
|
return r;
|
|
};
|
|
|
|
export fn trywrite(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
|
|
let r: i64 = write(fd, buf, n);
|
|
if (r < 0) { return r: oserror; };
|
|
return r;
|
|
};
|
|
|
|
// open — Linux open(2). Path must be NUL-terminated; callers using ww
|
|
// `str` must ensure the bytes are followed by a 0 byte (literals are,
|
|
// arena-copied paths usually are by construction). Returns -errno on
|
|
// failure, fd otherwise. Higher-level callers prefer `tryopen`.
|
|
export fn open(path: *u8, flags: flag, mode: i32) i32 = {
|
|
return syscall3(nr.OPEN, path: i64, (flags as i32): i64, mode: i64): i32;
|
|
};
|
|
|
|
export fn tryopen(path: *u8, flags: flag, mode: i32) (i32 | oserror) = {
|
|
let fd: i32 = open(path, flags, mode);
|
|
if (fd < 0) { return fd: i64: oserror; };
|
|
return fd;
|
|
};
|
|
|
|
// lseek — set/inspect the fd's position. Returns the new offset or
|
|
// a negative errno. We use this for fstat-free file-size discovery
|
|
// (open ⇒ lseek to end ⇒ lseek back).
|
|
export fn lseek(fd: i32, off: i64, w: whence) i64 = {
|
|
return syscall3(nr.LSEEK, fd: i64, off, (w as i32): i64);
|
|
};
|
|
|
|
// oserror — the underlying errno from a failed syscall, as a
|
|
// negative i64 (Linux's int convention; e.g. -2 = ENOENT). The
|
|
// `!`-flagged alias makes ?-propagation pick this variant as the
|
|
// error half of any (T | oserror) shape. Hare's analogue is
|
|
// errors::errno carried inside io::error.
|
|
export type oserror = !i64;
|
|
|
|
// filesize — byte length of an open fd via lseek-to-end-and-back.
|
|
export fn filesize(fd: i32) (i64 | oserror) = {
|
|
let end: i64 = lseek(fd, 0i64, whence.END);
|
|
if (end < 0) { return end: oserror; };
|
|
let r: i64 = lseek(fd, 0i64, whence.SET);
|
|
if (r < 0) { return r: oserror; };
|
|
return end;
|
|
};
|
|
|
|
// readall — keep reading until `n` bytes have arrived or the fd
|
|
// closes early. Hare name (io::readall); the buffer is caller-
|
|
// supplied, matching the Plan 9 subset convention.
|
|
export fn readall(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
|
|
let got: u64 = 0u64;
|
|
for (got < n) {
|
|
let r: i64 = read(fd, buf + got, n - got);
|
|
if (r < 0) { return r: oserror; };
|
|
if (r == 0) { return got: i64; }; // short read: caller decides
|
|
got += r: u64;
|
|
};
|
|
return got: i64;
|
|
};
|
|
|
|
// writeall — keep writing until `n` bytes have been accepted or the
|
|
// fd refuses progress. Hare name (io::writeall).
|
|
export fn writeall(fd: i32, buf: *u8, n: u64) (i64 | oserror) = {
|
|
let sent: u64 = 0u64;
|
|
for (sent < n) {
|
|
let r: i64 = write(fd, buf + sent, n - sent);
|
|
if (r < 0) { return r: oserror; };
|
|
if (r == 0) { return sent: i64; };
|
|
sent += r: u64;
|
|
};
|
|
return sent: i64;
|
|
};
|
|
|
|
// ---- process and filesystem helpers used by the `ww` driver ----------
|
|
|
|
// access(2): returns 0 if the file is reachable, negative errno
|
|
// otherwise. mode is the bitset described in <unistd.h> (F_OK=0).
|
|
export fn access(path: *u8, mode: i32) i32 = {
|
|
return syscall2(nr.ACCESS, path: i64, mode: i64): i32;
|
|
};
|
|
|
|
// remove — unlink(2). Hare name; the underlying syscall is unlink(2).
|
|
export fn remove(path: *u8) i32 = {
|
|
return syscall1(nr.UNLINK, path: i64): i32;
|
|
};
|
|
|
|
// mkdir — mkdir(2). Path must be NUL-terminated. Mode is the unix
|
|
// permission bitset (e.g. 0o700). Returns 0 on success, negative
|
|
// errno otherwise. Hare name (os::mkdir).
|
|
export fn mkdir(path: *u8, mode: i32) i32 = {
|
|
return syscall2(nr.MKDIR, path: i64, mode: i64): i32;
|
|
};
|
|
|
|
// rmdir — rmdir(2). Path must be NUL-terminated. Returns 0 on
|
|
// success, negative errno otherwise. Hare name (os::rmdir).
|
|
export fn rmdir(path: *u8) i32 = {
|
|
return syscall1(nr.RMDIR, path: 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`.
|
|
//
|
|
// `path` must be NUL-terminated AND its bytes must be writable —
|
|
// mkdirs temporarily replaces '/' separators with NUL while
|
|
// invoking [[mkdir]] on each prefix, then restores them. Pointing
|
|
// `path` at a string literal will segfault. Callers hold the bytes
|
|
// in a writable buffer (rt_alloc'd, a static `[N]u8`, etc.) — same
|
|
// precedent as [[temp.named]]'s pathbuf.
|
|
//
|
|
// Mirrors Hare's os::mkdirs (recursive variant of os::mkdir).
|
|
export fn mkdirs(path: *u8, mode: i32) (void | oserror) = {
|
|
// Find the path length (excluding trailing NUL).
|
|
let n: i32 = 0;
|
|
for (path[n] != 0u8) { n += 1; };
|
|
if (n == 0) { return; };
|
|
|
|
// Walk forward; at each '/' boundary, NUL-terminate the prefix,
|
|
// mkdir it, 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 (path[i] == 47u8) { // '/'
|
|
path[i] = 0u8;
|
|
let r: i32 = mkdir(path, mode);
|
|
path[i] = 47u8;
|
|
if (r < 0) {
|
|
if (r != -17) { return r: i64: oserror; };
|
|
};
|
|
};
|
|
i += 1;
|
|
};
|
|
|
|
// mkdir the full path.
|
|
let r: i32 = mkdir(path, mode);
|
|
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.
|
|
export fn execve(path: *u8, argv: **u8, envp: **u8) i32 = {
|
|
return syscall3(nr.EXECVE, path: i64, argv: i64, envp: i64): i32;
|
|
};
|
|
|
|
// wait4(2): wait for `pid` (or any child if -1), store status in
|
|
// `*status`, return the pid that ended (or negative errno).
|
|
export fn wait4(pid: i32, status: *i32, options: i32, rusage: *void) i32 = {
|
|
return syscall4(nr.WAIT4, pid: i64, status: i64,
|
|
options: i64, rusage: i64): i32;
|
|
};
|
|
|
|
// getcwd(2) — Linux flavour. Writes the NUL-terminated cwd into `buf`
|
|
// and returns the number of bytes written (including the NUL), or a
|
|
// negative errno. The driver uses it to expand `.` to the cwd's
|
|
// basename for `ww build` / `ww test`.
|
|
export fn getcwd(buf: *u8, n: u64) i64 = {
|
|
return syscall2(nr.GETCWD, buf: i64, n: i64);
|
|
};
|
|
|
|
// getdents64(2) — Linux directory enumeration. The fd must be opened
|
|
// with O_RDONLY on a directory. `buf` receives a packed sequence of
|
|
// linux_dirent64 records:
|
|
//
|
|
// struct linux_dirent64 {
|
|
// u64 d_ino; // 0..7
|
|
// i64 d_off; // 8..15
|
|
// u16 d_reclen; // 16..17 — total bytes for this record
|
|
// u8 d_type; // 18 — DT_REG/DT_DIR/...
|
|
// u8 d_name[]; // 19.. — NUL-terminated name + padding
|
|
// };
|
|
//
|
|
// Returns bytes written into `buf` (advance by d_reclen to walk),
|
|
// 0 at end-of-directory, or a negative errno.
|
|
export fn getdents64(fd: i32, buf: *u8, n: u64) i64 = {
|
|
return syscall3(nr.GETDENTS64, fd: i64, buf: i64, n: i64);
|
|
};
|
|
|
|
// ---- 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_alloc / 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] == 61u8) { // '='
|
|
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;
|
|
};
|
|
|
|
// MODULE: strings
|
|
// strings — operations over the immutable str type ({ *u8, len }).
|
|
// Mirrors Hare's strings::; `len` and `is-empty` aren't functions
|
|
// (callers use `s.len` and `s.len == 0` directly).
|
|
|
|
use os;
|
|
|
|
// compare — bytewise three-way comparison: negative if a<b, 0 if equal,
|
|
// positive if a>b. Matches Hare's strings::compare. ASCII-order, not
|
|
// locale-aware. Callers that just need equality use `compare(a, b) == 0`.
|
|
export fn compare(a: str, b: str) i32 = {
|
|
let n: i32 = a.len;
|
|
if (b.len < n) { n = b.len; };
|
|
let i: i32 = 0;
|
|
for (i < n) {
|
|
if (a[i] != b[i]) { return (a[i]: i32) - (b[i]: i32); };
|
|
i += 1;
|
|
};
|
|
return a.len - b.len;
|
|
};
|
|
|
|
export fn hasprefix(s: str, p: str) bool = {
|
|
if (p.len > s.len) { return false; };
|
|
let i: i32 = 0;
|
|
for (i < p.len) {
|
|
if (s[i] != p[i]) { return false; };
|
|
i += 1;
|
|
};
|
|
return true;
|
|
};
|
|
|
|
export fn hassuffix(s: str, suf: str) bool = {
|
|
if (suf.len > s.len) { return false; };
|
|
let off: i32 = s.len - suf.len;
|
|
let i: i32 = 0;
|
|
for (i < suf.len) {
|
|
if (s[off + i] != suf[i]) { return false; };
|
|
i += 1;
|
|
};
|
|
return true;
|
|
};
|
|
|
|
// byteindex — first byte position of `needle` in `s`. Mirrors Hare's
|
|
// strings::byteindex: a single-codepoint rune scans for the byte that
|
|
// encodes it (ASCII only here — multi-byte UTF-8 awaits utf8 encode),
|
|
// a str needle scans for the substring. Returns void if absent.
|
|
export fn byteindex(s: str, needle: (str | rune)) (i32 | void) = {
|
|
match (needle) {
|
|
case let r: rune => {
|
|
let c: u8 = r: u8;
|
|
let i: i32 = 0;
|
|
for (i < s.len) {
|
|
if (s[i] == c) { return i; };
|
|
i += 1;
|
|
};
|
|
return;
|
|
};
|
|
case let sub: str => {
|
|
if (sub.len == 0) { return 0; };
|
|
if (sub.len > s.len) { return; };
|
|
let last: i32 = s.len - sub.len;
|
|
let i: i32 = 0;
|
|
for (i <= last) {
|
|
let j: i32 = 0;
|
|
let ok: bool = true;
|
|
for (j < sub.len) {
|
|
if (s[i + j] != sub[j]) { ok = false; j = sub.len; }
|
|
else { j += 1; };
|
|
};
|
|
if (ok) { return i; };
|
|
i += 1;
|
|
};
|
|
return;
|
|
};
|
|
};
|
|
return;
|
|
};
|
|
|
|
// contains — true iff `sub` appears in `s`. Mirrors Hare's
|
|
// strings::contains shape (byte-wise on the str-needle case).
|
|
export fn contains(s: str, sub: str) bool = {
|
|
let r: (i32 | void) = byteindex(s, sub);
|
|
match (r) {
|
|
case let i: i32 => return true;
|
|
case void => return false;
|
|
};
|
|
return false;
|
|
};
|
|
|
|
// concat — joins two strings into a fresh str. Caller owns the
|
|
// returned str's storage; release via `os.free(r.ptr, r.len)`. Mirrors
|
|
// Hare's strings::concat shape.
|
|
export fn concat(a: str, b: str) str = {
|
|
let total: i32 = a.len + b.len;
|
|
let buf: *u8 = os.alloc(total: u64): *u8;
|
|
let i: i32 = 0;
|
|
for (i < a.len) { buf[i] = a[i]; i += 1; };
|
|
let j: i32 = 0;
|
|
for (j < b.len) { buf[a.len + j] = b[j]; j += 1; };
|
|
let r: str;
|
|
r.ptr = buf;
|
|
r.len = total;
|
|
return r;
|
|
};
|
|
|
|
// dup — duplicate a string into a fresh allocation. Caller owns the
|
|
// returned str's storage; release via `os.free(r.ptr, r.len)`. Mirrors
|
|
// Hare's strings::dup shape — Hare returns `(str | nomem)`, ww doesn't
|
|
// have nomem (os.alloc aborts on OOM), so we return plain `str`.
|
|
//
|
|
// Empty input yields a `{nil, 0}` str — Hare returns the static empty
|
|
// string; same observable result.
|
|
export fn dup(s: str) str = {
|
|
let r: str;
|
|
r.ptr = nil;
|
|
r.len = 0;
|
|
if (s.len == 0) { return r; };
|
|
let buf: *u8 = os.alloc(s.len: u64): *u8;
|
|
let i: i32 = 0;
|
|
for (i < s.len) { buf[i] = s[i]; i += 1; };
|
|
r.ptr = buf;
|
|
r.len = s.len;
|
|
return r;
|
|
};
|
|
|
|
// freeall — release every str element in `s` (those that were
|
|
// individually allocated) plus the slice's backing storage. Mirrors
|
|
// Hare's strings::freeall — the natural disposer for any function
|
|
// returning a fresh `[]str` of dup'd elements (e.g. shlex.split).
|
|
//
|
|
// Each element is freed via os.free at its own length; the slice
|
|
// header storage is freed at `cap * 16` bytes (one str = 16B). Empty
|
|
// elements (`{nil, 0}` from a zero-length dup) are skipped — calling
|
|
// os.free on a nil pointer at len 0 would tickle the rt_free guard
|
|
// that the runtime treats as a logic bug.
|
|
//
|
|
// `cap == 0` means the slice was never grown (empty `[]str` with no
|
|
// backing allocation); skip the header free in that case too.
|
|
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) * 16u64);
|
|
};
|
|
};
|
|
|
|
// rbyteindex — last byte position of `needle` in `s`. Mirrors Hare's
|
|
// strings::rbyteindex. Rune needle scans for the byte that encodes it
|
|
// (ASCII only); str needle scans for the substring. Empty str needle
|
|
// matches at s.len.
|
|
export fn rbyteindex(s: str, needle: (str | rune)) (i32 | void) = {
|
|
match (needle) {
|
|
case let r: rune => {
|
|
let c: u8 = r: u8;
|
|
let i: i32 = s.len - 1;
|
|
for (i >= 0) {
|
|
if (s[i] == c) { return i; };
|
|
i -= 1;
|
|
};
|
|
return;
|
|
};
|
|
case let sub: str => {
|
|
if (sub.len == 0) { return s.len; };
|
|
if (sub.len > s.len) { return; };
|
|
let i: i32 = s.len - sub.len;
|
|
for (i >= 0) {
|
|
let j: i32 = 0;
|
|
let ok: bool = true;
|
|
for (j < sub.len) {
|
|
if (s[i + j] != sub[j]) { ok = false; j = sub.len; }
|
|
else { j += 1; };
|
|
};
|
|
if (ok) { return i; };
|
|
i -= 1;
|
|
};
|
|
return;
|
|
};
|
|
};
|
|
return;
|
|
};
|
|
|
|
// sub — borrowed substring `s[start..end]`. Mirrors Hare's
|
|
// strings::sub. Caller must ensure 0 <= start <= end <= s.len; out-of-
|
|
// range indices are clamped silently here, where Hare aborts.
|
|
export fn sub(s: str, start: i32, end: i32) str = {
|
|
let lo: i32 = start;
|
|
let hi: i32 = end;
|
|
if (lo < 0) { lo = 0; };
|
|
if (hi > s.len) { hi = s.len; };
|
|
if (hi < lo) { hi = lo; };
|
|
let r: str;
|
|
r.ptr = s.ptr + (lo: u64);
|
|
r.len = hi - lo;
|
|
return r;
|
|
};
|
|
|
|
// trimprefix — `s` with `pre` stripped from the front, or `s`
|
|
// unchanged if it doesn't start with `pre`. Returns a borrowed view.
|
|
// Mirrors Hare's strings::trimprefix.
|
|
export fn trimprefix(s: str, pre: str) str = {
|
|
if (!hasprefix(s, pre)) { return s; };
|
|
let r: str;
|
|
r.ptr = s.ptr + (pre.len: u64);
|
|
r.len = s.len - pre.len;
|
|
return r;
|
|
};
|
|
|
|
// trimsuffix — `s` with `suf` stripped from the end, or `s` unchanged
|
|
// if it doesn't end with `suf`. Returns a borrowed view. Mirrors
|
|
// Hare's strings::trimsuffix.
|
|
export fn trimsuffix(s: str, suf: str) str = {
|
|
if (!hassuffix(s, suf)) { return s; };
|
|
let r: str;
|
|
r.ptr = s.ptr;
|
|
r.len = s.len - suf.len;
|
|
return r;
|
|
};
|
|
|
|
// ltrimbyte / rtrimbyte / trimbyte — strip occurrences of a single
|
|
// byte from the left, right, or both ends. Returns a borrowed view.
|
|
// Hare's strings::ltrim / rtrim / trim take a rune varargs set; ww's
|
|
// subset takes a single byte (the common ASCII case).
|
|
export fn ltrimbyte(s: str, c: u8) str = {
|
|
let i: i32 = 0;
|
|
for (i < s.len) {
|
|
if (s[i] != c) { break; };
|
|
i += 1;
|
|
};
|
|
let r: str;
|
|
r.ptr = s.ptr + (i: u64);
|
|
r.len = s.len - i;
|
|
return r;
|
|
};
|
|
|
|
export fn rtrimbyte(s: str, c: u8) str = {
|
|
let n: i32 = s.len;
|
|
for (n > 0) {
|
|
if (s[n - 1] != c) { break; };
|
|
n -= 1;
|
|
};
|
|
let r: str;
|
|
r.ptr = s.ptr;
|
|
r.len = n;
|
|
return r;
|
|
};
|
|
|
|
export fn trimbyte(s: str, c: u8) str = {
|
|
return rtrimbyte(ltrimbyte(s, c), c);
|
|
};
|
|
|
|
// MODULE: strconv
|
|
// strconv — number↔string conversions.
|
|
//
|
|
// Mirrors Hare's strconv:: surface. The *tos functions return a
|
|
// `const str` view into a module-level buffer that is overwritten on
|
|
// the next call to the same function; callers must copy the bytes if
|
|
// they need to outlive the next invocation. See [[strings.dup]] to
|
|
// duplicate. Matches Hare's strconv::*tos semantics.
|
|
|
|
use os;
|
|
use strings;
|
|
|
|
// invalid — input wasn't a valid number in the requested format.
|
|
// Payload is the byte index of the first offending position.
|
|
// Mirrors Hare's strconv::invalid = !size.
|
|
export type invalid = !i32;
|
|
|
|
// overflow — input was valid but doesn't fit the target type.
|
|
// Mirrors Hare's strconv::overflow = !void.
|
|
export type overflow = !void;
|
|
|
|
// error — any error from a strconv call. Mirrors Hare's strconv::error.
|
|
export type error = !(invalid | overflow);
|
|
|
|
// base — numeric base for parsing/formatting. Mirrors Hare's
|
|
// `strconv::base` (Hare uses `enum uint`; we pick `enum i32` since
|
|
// the underlying parse/format loops index with i32).
|
|
//
|
|
// HEX is an alias for HEX_UPPER; HEX_LOWER is a pseudo-base that
|
|
// produces lowercase a-f digits.
|
|
export type base = enum i32 {
|
|
DEFAULT = 0,
|
|
BIN = 2,
|
|
OCT = 8,
|
|
DEC = 10,
|
|
HEX_UPPER = 16,
|
|
HEX = 16,
|
|
HEX_LOWER = 17,
|
|
};
|
|
|
|
fn basenum(b: base) i64 = {
|
|
if (b == base.BIN) { return 2; };
|
|
if (b == base.OCT) { return 8; };
|
|
if (b == base.HEX) { return 16; };
|
|
if (b == base.HEX_UPPER) { return 16; };
|
|
if (b == base.HEX_LOWER) { return 16; };
|
|
return 10; // DEC and DEFAULT
|
|
};
|
|
|
|
fn basedigit(d: i64, b: base) u8 = {
|
|
if (d < 10) { return (d + 48): u8; };
|
|
let off: i64 = d - 10;
|
|
if (b == base.HEX_LOWER) { return (off + 97): u8; };
|
|
return (off + 65): u8;
|
|
};
|
|
|
|
// u64tos — convert v to a base-b numeric string. Returns a view into
|
|
// `u64tos_buf` which is overwritten on the next call. Matches Hare's
|
|
// strconv::u64tos.
|
|
let u64tos_buf: [65]u8;
|
|
|
|
export fn u64tos(v: u64, b: base) str = {
|
|
let nb: u64 = basenum(b): u64;
|
|
let tmp: [65]u8;
|
|
let i: i32 = 0;
|
|
let n: u64 = v;
|
|
if (n == 0u64) { tmp[0] = 48u8; i = 1; };
|
|
for (n > 0u64) {
|
|
let d: i64 = (n % nb): i64;
|
|
tmp[i] = basedigit(d, b);
|
|
n = n / nb;
|
|
i += 1;
|
|
};
|
|
let out: i32 = 0;
|
|
for (i > 0) {
|
|
i -= 1;
|
|
u64tos_buf[out] = tmp[i];
|
|
out += 1;
|
|
};
|
|
let r: str;
|
|
r.ptr = &u64tos_buf[0];
|
|
r.len = out;
|
|
return r;
|
|
};
|
|
|
|
// i64tos — convert v to a base-b numeric string. Returns a view into
|
|
// `i64tos_buf` which is overwritten on the next call. Independent
|
|
// buffer from u64tos so i64tos's own call to u64tos doesn't clobber
|
|
// the in-flight result. Matches Hare's strconv::i64tos.
|
|
let i64tos_buf: [66]u8;
|
|
|
|
export fn i64tos(v: i64, b: base) str = {
|
|
let neg: bool = false;
|
|
let n: i64 = v;
|
|
if (n < 0) { neg = true; n = -n; };
|
|
let nb: i64 = basenum(b);
|
|
let tmp: [65]u8;
|
|
let i: i32 = 0;
|
|
if (n == 0) { tmp[0] = 48u8; i = 1; };
|
|
for (n > 0) {
|
|
let d: i64 = n % nb;
|
|
tmp[i] = basedigit(d, b);
|
|
n = n / nb;
|
|
i += 1;
|
|
};
|
|
let out: i32 = 0;
|
|
if (neg) { i64tos_buf[out] = 45u8; out += 1; }; // '-'
|
|
for (i > 0) {
|
|
i -= 1;
|
|
i64tos_buf[out] = tmp[i];
|
|
out += 1;
|
|
};
|
|
let r: str;
|
|
r.ptr = &i64tos_buf[0];
|
|
r.len = out;
|
|
return r;
|
|
};
|
|
|
|
export fn i32tos(v: i32, b: base) str = { return i64tos(v: i64, b); };
|
|
export fn i16tos(v: i16, b: base) str = { return i64tos(v: i64, b); };
|
|
export fn i8tos(v: i8, b: base) str = { return i64tos(v: i64, b); };
|
|
|
|
export fn u32tos(v: u32, b: base) str = { return u64tos(v: u64, b); };
|
|
export fn u16tos(v: u16, b: base) str = { return u64tos(v: u64, b); };
|
|
export fn u8tos(v: u8, b: base) str = { return u64tos(v: u64, b); };
|
|
|
|
// digval — value of digit byte `c` under base `b`, or -1 if not a
|
|
// valid digit. Letters are accepted case-insensitively under HEX /
|
|
// HEX_UPPER; only lowercase under HEX_LOWER.
|
|
fn digval(c: u8, b: base) i32 = {
|
|
if (c >= 48u8) { if (c <= 57u8) { return (c - 48u8): i32; }; };
|
|
if (b == base.HEX_LOWER) {
|
|
if (c >= 97u8) { if (c <= 102u8) { return ((c - 97u8) + 10u8): i32; }; };
|
|
return -1;
|
|
};
|
|
if (c >= 65u8) { if (c <= 70u8) { return ((c - 65u8) + 10u8): i32; }; };
|
|
if (c >= 97u8) { if (c <= 102u8) { return ((c - 97u8) + 10u8): i32; }; };
|
|
return -1;
|
|
};
|
|
|
|
// stoi64 — parse signed base-b number. Mirrors Hare's strconv::stoi64.
|
|
// No locale, no whitespace, no underscores: optional leading '-' then
|
|
// digits. Returns invalid with the offending index or overflow on
|
|
// out-of-range.
|
|
export fn stoi64(s: str, b: base) (i64 | invalid | overflow) = {
|
|
if (s.len == 0) { return 0: invalid; };
|
|
let i: i32 = 0;
|
|
let neg: bool = false;
|
|
if (s[0] == 45u8) { neg = true; i = 1; };
|
|
if (i >= s.len) { return i: invalid; };
|
|
let nb: i32 = basenum(b): i32;
|
|
let v: i64 = 0;
|
|
for (i < s.len) {
|
|
let c: u8 = s[i];
|
|
let d: i32 = digval(c, b);
|
|
if (d < 0) { return i: invalid; };
|
|
if (d >= nb) { return i: invalid; };
|
|
v = v * (nb: i64) + (d: i64);
|
|
i += 1;
|
|
};
|
|
if (neg) { v = -v; };
|
|
return v;
|
|
};
|
|
|
|
// stou64 — parse unsigned base-b number. Mirrors Hare's strconv::stou64.
|
|
export fn stou64(s: str, b: base) (u64 | invalid | overflow) = {
|
|
if (s.len == 0) { return 0: invalid; };
|
|
let nb: u64 = basenum(b): u64;
|
|
let v: u64 = 0u64;
|
|
let i: i32 = 0;
|
|
for (i < s.len) {
|
|
let c: u8 = s[i];
|
|
let d: i32 = digval(c, b);
|
|
if (d < 0) { return i: invalid; };
|
|
if ((d: u64) >= nb) { return i: invalid; };
|
|
v = v * nb + (d: u64);
|
|
i += 1;
|
|
};
|
|
return v;
|
|
};
|
|
|
|
export fn stoi32(s: str, b: base) (i32 | invalid | overflow) = {
|
|
let r = stoi64(s, b);
|
|
match (r) {
|
|
case let v: i64 => {
|
|
if (v > 2147483647i64) { return overflow{}; };
|
|
if (v < -2147483648i64) { return overflow{}; };
|
|
return v: i32;
|
|
};
|
|
case let e: invalid => return e;
|
|
case let e: overflow => return e;
|
|
};
|
|
return 0: invalid; // unreachable; appeases the path-cov checker
|
|
};
|
|
|
|
export fn stoi16(s: str, b: base) (i16 | invalid | overflow) = {
|
|
let r = stoi64(s, b);
|
|
match (r) {
|
|
case let v: i64 => {
|
|
if (v > 32767i64) { return overflow{}; };
|
|
if (v < -32768i64) { return overflow{}; };
|
|
return v: i16;
|
|
};
|
|
case let e: invalid => return e;
|
|
case let e: overflow => return e;
|
|
};
|
|
return 0: invalid;
|
|
};
|
|
|
|
export fn stoi8(s: str, b: base) (i8 | invalid | overflow) = {
|
|
let r = stoi64(s, b);
|
|
match (r) {
|
|
case let v: i64 => {
|
|
if (v > 127i64) { return overflow{}; };
|
|
if (v < -128i64) { return overflow{}; };
|
|
return v: i8;
|
|
};
|
|
case let e: invalid => return e;
|
|
case let e: overflow => return e;
|
|
};
|
|
return 0: invalid;
|
|
};
|
|
|
|
export fn stou32(s: str, b: base) (u32 | invalid | overflow) = {
|
|
let r = stou64(s, b);
|
|
match (r) {
|
|
case let v: u64 => {
|
|
if (v > 4294967295u64) { return overflow{}; };
|
|
return v: u32;
|
|
};
|
|
case let e: invalid => return e;
|
|
case let e: overflow => return e;
|
|
};
|
|
return 0: invalid;
|
|
};
|
|
|
|
export fn stou16(s: str, b: base) (u16 | invalid | overflow) = {
|
|
let r = stou64(s, b);
|
|
match (r) {
|
|
case let v: u64 => {
|
|
if (v > 65535u64) { return overflow{}; };
|
|
return v: u16;
|
|
};
|
|
case let e: invalid => return e;
|
|
case let e: overflow => return e;
|
|
};
|
|
return 0: invalid;
|
|
};
|
|
|
|
export fn stou8(s: str, b: base) (u8 | invalid | overflow) = {
|
|
let r = stou64(s, b);
|
|
match (r) {
|
|
case let v: u64 => {
|
|
if (v > 255u64) { return overflow{}; };
|
|
return v: u8;
|
|
};
|
|
case let e: invalid => return e;
|
|
case let e: overflow => return e;
|
|
};
|
|
return 0: invalid;
|
|
};
|
|
|
|
// f64tos — convert v to a decimal string. Returns owned str; release
|
|
// via os.free. Mirrors Hare's strconv::f64tos (current ww impl is
|
|
// fixed-point only, max 6 fractional digits, no NaN/Inf support —
|
|
// see graduate-to-Ryū note below).
|
|
//
|
|
// Surface:
|
|
//
|
|
// - finite values only. NaN/±Inf detection needs an f64→u64 bit
|
|
// reinterpret cast that the cgen doesn't expose yet.
|
|
// - fixed-point only, up to 6 fractional digits. Trailing zeros
|
|
// after the decimal point are trimmed. Trailing '.' is dropped.
|
|
// - magnitudes ≥ 9e18 (overflows i64 in the integer-part cast)
|
|
// fall back to the literal token "huge". Hare would print these
|
|
// in scientific notation via Ryū; we will graduate when the
|
|
// compiler grows the bit-reinterpret cast.
|
|
//
|
|
// Round-trip is therefore lossy past 6 fractional digits.
|
|
//
|
|
// No float literals in the body — 990's wwdump diff requires this
|
|
// file's TK_FLOAT count to match between C and ww front-ends, and
|
|
// the ww-side wwdump currently skips TK_FLOAT.fval while the C side
|
|
// %g-formats it. Same trick lib/ww/lex/lex.ww's parsef64 uses:
|
|
// build f64 constants via int-to-f64 casts.
|
|
let f64tos_buf: [64]u8;
|
|
|
|
export fn f64tos(v: f64) str = {
|
|
let out: i32 = 0;
|
|
let f: f64 = v;
|
|
let zero: f64 = 0: f64;
|
|
if (f < zero) {
|
|
f64tos_buf[out] = 45u8; // '-'
|
|
out += 1;
|
|
f = -f;
|
|
};
|
|
// 9e18 is comfortably under I64_MAX (9.22e18). Past this the
|
|
// `f: i64` cast wraps and the integer part comes back as garbage.
|
|
let cap: f64 = 9000000000000000000i64: f64;
|
|
if (f >= cap) {
|
|
let s: str = "huge";
|
|
let k: i32 = 0;
|
|
for (k < s.len) { f64tos_buf[out] = s[k]; out += 1; k += 1; };
|
|
let r: str;
|
|
r.ptr = &f64tos_buf[0];
|
|
r.len = out;
|
|
return r;
|
|
};
|
|
let ip: i64 = f: i64;
|
|
// Fractional part scaled to 6 decimal digits, with round-to-
|
|
// nearest via +0.5. (f64 compound assigns mis-lower in cgen —
|
|
// use the explicit form, as the rest of lib does.)
|
|
let frac: f64 = f - (ip: f64);
|
|
let scale: f64 = 1000000: f64;
|
|
frac = frac * scale;
|
|
let half: f64 = (1: f64) / (2: f64);
|
|
let fp: i64 = (frac + half): i64;
|
|
// Carry: e.g. 0.9999996 rounds fp up to 1000000 and the integer
|
|
// part needs to advance.
|
|
if (fp >= 1000000) {
|
|
ip += 1;
|
|
fp = 0;
|
|
};
|
|
let intstr: str = i64tos(ip, base.DEC);
|
|
let k: i32 = 0;
|
|
for (k < intstr.len) { f64tos_buf[out] = intstr.ptr[k]; out += 1; k += 1; };
|
|
if (fp != 0) {
|
|
f64tos_buf[out] = 46u8; // '.'
|
|
out += 1;
|
|
let fracstr: str = u64tos(fp: u64, base.DEC);
|
|
// Pad fractional to 6 digits with leading zeros (e.g. 0.05 →
|
|
// fp=50000, fracstr="50000", pad one '0' before).
|
|
let z: i32 = 6 - fracstr.len;
|
|
for (z > 0) { f64tos_buf[out] = 48u8; out += 1; z -= 1; };
|
|
k = 0;
|
|
for (k < fracstr.len) { f64tos_buf[out] = fracstr.ptr[k]; out += 1; k += 1; };
|
|
// Trim trailing zeros in the fractional part.
|
|
for (out > 0) {
|
|
if (f64tos_buf[out - 1] != 48u8) { break; };
|
|
out -= 1;
|
|
};
|
|
};
|
|
let r: str;
|
|
r.ptr = &f64tos_buf[0];
|
|
r.len = out;
|
|
return r;
|
|
};
|
|
|
|
// strerror — convert an strconv error to a user-readable string.
|
|
// Returns owned str; release via os.free. Mirrors Hare's
|
|
// strconv::strerror.
|
|
export fn strerror(e: error) str = {
|
|
match (e) {
|
|
case let v: invalid => return strings.dup("input is not a valid number");
|
|
case let v: overflow => return strings.dup("input number doesn't fit target type");
|
|
};
|
|
return strings.dup("");
|
|
};
|
|
|
|
// MODULE: ascii
|
|
// ascii — rune-class predicates and case folding for the ASCII range.
|
|
// Matches Hare's ascii::isdigit family (rune-taking signature). Runes
|
|
// outside 0..127 always answer `false`. The lexer hot path uses these
|
|
// inline; they are expected to inline to a couple of compares.
|
|
|
|
export fn isdigit(c: rune) bool = {
|
|
if (c < 48) { return false; };
|
|
if (c > 57) { return false; };
|
|
return true;
|
|
};
|
|
|
|
export fn isupper(c: rune) bool = {
|
|
if (c < 65) { return false; };
|
|
if (c > 90) { return false; };
|
|
return true;
|
|
};
|
|
|
|
export fn islower(c: rune) bool = {
|
|
if (c < 97) { return false; };
|
|
if (c > 122) { return false; };
|
|
return true;
|
|
};
|
|
|
|
export fn isalpha(c: rune) bool = {
|
|
if (isupper(c)) { return true; };
|
|
return islower(c);
|
|
};
|
|
|
|
export fn isalnum(c: rune) bool = {
|
|
if (isalpha(c)) { return true; };
|
|
return isdigit(c);
|
|
};
|
|
|
|
// isspace — the C/Hare set: space, tab, NL, VT, FF, CR.
|
|
export fn isspace(c: rune) bool = {
|
|
if (c == 32) { return true; }; // ' '
|
|
if (c == 9) { return true; }; // '\t'
|
|
if (c == 10) { return true; }; // '\n'
|
|
if (c == 11) { return true; }; // '\v'
|
|
if (c == 12) { return true; }; // '\f'
|
|
if (c == 13) { return true; }; // '\r'
|
|
return false;
|
|
};
|
|
|
|
export fn isxdigit(c: rune) bool = {
|
|
if (isdigit(c)) { return true; };
|
|
if (c >= 65) {
|
|
if (c <= 70) { return true; }; // 'A'..'F'
|
|
};
|
|
if (c >= 97) {
|
|
if (c <= 102) { return true; }; // 'a'..'f'
|
|
};
|
|
return false;
|
|
};
|
|
|
|
// valid — `c` is in the 0..127 ASCII range.
|
|
export fn valid(c: rune) bool = {
|
|
if (c < 0) { return false; };
|
|
if (c > 127) { return false; };
|
|
return true;
|
|
};
|
|
|
|
// validstr — every byte in `s` is ASCII (0..127).
|
|
export fn validstr(s: str) bool = {
|
|
let i: i32 = 0;
|
|
for (i < s.len) {
|
|
// High-bit test rather than `> 127u8`; both cgens lower
|
|
// the bitwise form identically. The `> u8` form picks
|
|
// JA vs JG depending on signed/unsigned dispatch.
|
|
if ((s[i] & 128u8) != 0u8) { return false; };
|
|
i += 1;
|
|
};
|
|
return true;
|
|
};
|
|
|
|
// iscntrl — control chars: 0..31 and 127.
|
|
export fn iscntrl(c: rune) bool = {
|
|
if (c >= 0) { if (c <= 31) { return true; }; };
|
|
if (c == 127) { return true; };
|
|
return false;
|
|
};
|
|
|
|
// isblank — space and tab.
|
|
export fn isblank(c: rune) bool = {
|
|
if (c == 32) { return true; }; // ' '
|
|
if (c == 9) { return true; }; // '\t'
|
|
return false;
|
|
};
|
|
|
|
// isprint — printable: space through '~'.
|
|
export fn isprint(c: rune) bool = {
|
|
if (c < 32) { return false; };
|
|
if (c > 126) { return false; };
|
|
return true;
|
|
};
|
|
|
|
// isgraph — printable, non-space.
|
|
export fn isgraph(c: rune) bool = {
|
|
if (c < 33) { return false; };
|
|
if (c > 126) { return false; };
|
|
return true;
|
|
};
|
|
|
|
// ispunct — printable, non-alnum, non-space.
|
|
export fn ispunct(c: rune) bool = {
|
|
if (!isgraph(c)) { return false; };
|
|
if (isalnum(c)) { return false; };
|
|
return true;
|
|
};
|
|
|
|
// tolower / toupper — fold ASCII case. Non-letters pass through.
|
|
export fn tolower(c: rune) rune = {
|
|
if (isupper(c)) { return c + 32; };
|
|
return c;
|
|
};
|
|
|
|
export fn toupper(c: rune) rune = {
|
|
if (islower(c)) { return c - 32; };
|
|
return c;
|
|
};
|
|
|
|
// strcasecmp — three-way ASCII case-insensitive compare.
|
|
export fn strcasecmp(a: str, b: str) i32 = {
|
|
let n: i32 = a.len;
|
|
if (b.len < n) { n = b.len; };
|
|
let i: i32 = 0;
|
|
for (i < n) {
|
|
let ca: rune = tolower(a[i]: rune);
|
|
let cb: rune = tolower(b[i]: rune);
|
|
if (ca != cb) { return (ca - cb): i32; };
|
|
i += 1;
|
|
};
|
|
return a.len - b.len;
|
|
};
|
|
|
|
// MODULE: test
|
|
// selfhost/test/smoke.ww — end-to-end smoke for the selfhost path.
|
|
//
|
|
// Exercises the patterns the real ww-side compiler port will use:
|
|
// - bump arena allocator (mem.ww shape)
|
|
// - error idiom (T | str)
|
|
// - struct of fn pointers + ctx pointer (the io.stream-style
|
|
// polymorphism we use instead of interfaces)
|
|
// - byte-level scanning that mirrors the hot path inside lex.ww
|
|
// - strconv round-trip via the real stdlib
|
|
//
|
|
// `main` returns 42 when every check passes, 1..N on failure
|
|
// indicating which probe broke. The 990_selfhost test asserts 42.
|
|
//
|
|
// Note: only stack-local mutable state. Top-level `let` mutation
|
|
// requires a writable .data segment in w6l, which is a separate
|
|
// task; until then we exercise polymorphism via ctx pointers, which
|
|
// is what the real port wants anyway.
|
|
|
|
use os;
|
|
use strconv;
|
|
use ascii;
|
|
|
|
// --- bump arena ---------------------------------------------------------
|
|
|
|
type arena = struct {
|
|
buf: *u8,
|
|
off: u64,
|
|
cap: u64,
|
|
};
|
|
|
|
// In-place init. Returning a 24-byte struct by value isn't yet
|
|
// supported in w6c (SysV requires a hidden return-slot pointer for
|
|
// structs >16 bytes), so we initialize through a pointer like the
|
|
// real compiler does today.
|
|
fn arena_init(a: *arena, buf: *u8, cap: u64) void = {
|
|
a.buf = buf;
|
|
a.off = 0u64;
|
|
a.cap = cap;
|
|
};
|
|
|
|
fn arena_alloc(a: *arena, n: u64) *u8 = {
|
|
if (n > a.cap - a.off) { return nil; };
|
|
let p: *u8 = a.buf + a.off;
|
|
a.off += n;
|
|
return p;
|
|
};
|
|
|
|
// --- (i32 | str) error idiom -------------------------------------------
|
|
|
|
fn checked_div(num: i32, den: i32) (i32 | str) = {
|
|
if (den == 0) { return "div by zero"; };
|
|
return num / den;
|
|
};
|
|
|
|
// --- struct-of-fn-pointer polymorphism ---------------------------------
|
|
//
|
|
// A trivial "writer" abstraction: a function pointer plus a context.
|
|
// This mirrors how io.stream / Plan 9 Bio work. The ctx pointer lets
|
|
// the implementation own its own state without a global.
|
|
|
|
type counter = struct {
|
|
n: i32,
|
|
};
|
|
|
|
type writer = struct {
|
|
ctx: *void,
|
|
emit: fn(ctx: *void, b: u8) void,
|
|
};
|
|
|
|
fn count_emit(ctx: *void, b: u8) void = {
|
|
let c: *counter = ctx: *counter;
|
|
c.n += 1;
|
|
};
|
|
|
|
// --- byte scanner like lex.ww's hot path -------------------------------
|
|
|
|
fn count_digits(s: str) i32 = {
|
|
let i: i32 = 0;
|
|
let n: i32 = 0;
|
|
for (i < s.len) {
|
|
let c: u8 = s[i];
|
|
if (c >= 48u8) {
|
|
if (c <= 57u8) { n += 1; };
|
|
};
|
|
i += 1;
|
|
};
|
|
return n;
|
|
};
|
|
|
|
// --- entry --------------------------------------------------------------
|
|
|
|
export fn main() i32 = {
|
|
// Probe 1 — arena hands out distinct pointers, refuses oversize.
|
|
let buf: [256]u8;
|
|
let a: arena;
|
|
arena_init(&a, buf.ptr, 256u64);
|
|
let p1: *u8 = arena_alloc(&a, 32u64);
|
|
let p2: *u8 = arena_alloc(&a, 32u64);
|
|
if (p1 == nil) { return 1; };
|
|
if (p2 == nil) { return 2; };
|
|
if (p1 == p2) { return 3; };
|
|
let p3: *u8 = arena_alloc(&a, 1024u64);
|
|
if (p3 != nil) { return 4; };
|
|
|
|
// Probe 2 — error union both ways.
|
|
let r_ok: (i32 | str) = checked_div(84, 2);
|
|
let r_bad: (i32 | str) = checked_div(1, 0);
|
|
let acc: i32 = 0;
|
|
match (r_ok) {
|
|
case let v: i32 => acc = v;
|
|
case let e: str => return 5;
|
|
};
|
|
if (acc != 42) { return 6; };
|
|
match (r_bad) {
|
|
case let v: i32 => return 7;
|
|
case let e: str => acc = e.len: i32;
|
|
};
|
|
if (acc != 11) { return 8; }; // len("div by zero") == 11
|
|
|
|
// Probe 3 — struct-of-fn-pointer dispatch via ctx pointer.
|
|
let c: counter = counter { n = 0 };
|
|
let w: writer = writer { ctx = (&c): *void, emit = count_emit };
|
|
w.emit(w.ctx, 65u8);
|
|
w.emit(w.ctx, 66u8);
|
|
w.emit(w.ctx, 67u8);
|
|
if (c.n != 3) { return 9; };
|
|
|
|
// Probe 4 — byte scan over a literal.
|
|
let dn: i32 = count_digits("ww123abc");
|
|
if (dn != 3) { return 10; };
|
|
|
|
// Probe 5 — strconv round-trip via the real stdlib.
|
|
let s: str = strconv.i64tos(4242i64, strconv.base.DEC);
|
|
if (s.len != 4) { return 11; };
|
|
if (s.ptr[0] != 52u8) { return 12; }; // '4'
|
|
if (s.ptr[3] != 50u8) { return 13; }; // '2'
|
|
|
|
// Probe 6 — ascii classifications (rune-taking, Hare-shaped).
|
|
if (!ascii.isdigit(53)) { return 14; }; // '5'
|
|
if (ascii.isdigit(65)) { return 15; }; // 'A' is not a digit
|
|
if (!ascii.isalpha(122)) { return 16; }; // 'z'
|
|
if (!ascii.isxdigit(70)) { return 17; }; // 'F'
|
|
if (ascii.isxdigit(71)) { return 18; }; // 'G' is not hex
|
|
if (ascii.tolower(65) != 97) { return 19; }; // 'A' -> 'a'
|
|
if (ascii.toupper(122) != 90) { return 20; }; // 'z' -> 'Z'
|
|
|
|
// Probe 7 — file open/read via the new os APIs. /proc/self/cmdline
|
|
// always exists on Linux, no write side, and is non-empty.
|
|
let path: str = "/proc/self/cmdline";
|
|
// Use raw os.open here (returns i32 with -errno) for the same
|
|
// reason as os.read below: probe 6 in 990_selfhost compiles
|
|
// smoke.ww standalone (no `use` expansion), so cross-module type
|
|
// references like `os.oserror` and `os.flag` don't resolve at
|
|
// that step. RDONLY is 0; passing the literal keeps the call
|
|
// site standalone-compilable to byte-identical asm on both
|
|
// compilers.
|
|
let fd: i32 = os.open(path.ptr, 0, 0i32);
|
|
if (fd < 0) { return 21; };
|
|
let rbuf: [128]u8;
|
|
// Use raw os.read here (single syscall, plain i64) instead of
|
|
// os.readall: the 990 cgen-match probe compiles smoke.ww
|
|
// standalone without `use os;` expansion, so cross-module type
|
|
// references like `os.oserror` can't be resolved.
|
|
let n: i64 = os.read(fd, rbuf.ptr, 128u64);
|
|
os.close(fd);
|
|
if (n <= 0i64) { return 22; };
|
|
|
|
return 42;
|
|
};
|
|
|