ww: import toolchain — C bootstrap + ww-side self-host (phases 0-10)

C bootstrap (phases 0-9):
  cmd/wwc, cmd/6c, cmd/6a, cmd/6l, cmd/ww, rt, lib/*.

ww-side self-host (phase 10):
  selfhost/cmd/wwc — ww-cgen frontend; bootstrap fixed point.
  selfhost/cmd/6a  — assembler; byte-identical to C 6a (test 991).
  selfhost/cmd/6l  — linker w/ archive (.a) support; byte-identical
                     to C 6l (test 992).
  selfhost/cmd/ww  — driver (build/run/version); byte-identical to
                     C ww (test 993).

make test: 15/15. make bootstrap: ww2.s == ww3.s, ww2.o == ww3.o,
ww2 == ww3 byte-identical, with the full ww-tooled chain.
This commit is contained in:
2026-05-11 02:17:47 +09:00
parent 4c8fc59ca1
commit 1657bdeda3
106 changed files with 35654 additions and 15 deletions

92
lib/ascii/ascii.ww Normal file
View File

@@ -0,0 +1,92 @@
// ascii — byte-class predicates and case folding for the ASCII range.
// Matches Hare's ascii::isdigit family. Bytes 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: u8) bool = {
if (c < 48u8) { return false; };
if (c > 57u8) { return false; };
return true;
};
export fn isupper(c: u8) bool = {
if (c < 65u8) { return false; };
if (c > 90u8) { return false; };
return true;
};
export fn islower(c: u8) bool = {
if (c < 97u8) { return false; };
if (c > 122u8) { return false; };
return true;
};
export fn isalpha(c: u8) bool = {
if (isupper(c)) { return true; };
return islower(c);
};
export fn isalnum(c: u8) bool = {
if (isalpha(c)) { return true; };
return isdigit(c);
};
// isspace — the C/Hare set: space, tab, NL, VT, FF, CR.
export fn isspace(c: u8) bool = {
if (c == 32u8) { return true; }; // ' '
if (c == 9u8) { return true; }; // '\t'
if (c == 10u8) { return true; }; // '\n'
if (c == 11u8) { return true; }; // '\v'
if (c == 12u8) { return true; }; // '\f'
if (c == 13u8) { return true; }; // '\r'
return false;
};
export fn ishex(c: u8) bool = {
if (isdigit(c)) { return true; };
if (c >= 65u8) {
if (c <= 70u8) { return true; }; // 'A'..'F'
};
if (c >= 97u8) {
if (c <= 102u8) { return true; }; // 'a'..'f'
};
return false;
};
// digitval — value of `c` as a hex/decimal digit, or -1 if not one.
// Useful when scanning numeric literals.
export fn digitval(c: u8) i32 = {
if (isdigit(c)) { return (c - 48u8): i32; };
if (c >= 65u8) {
if (c <= 70u8) { return ((c - 65u8) + 10u8): i32; };
};
if (c >= 97u8) {
if (c <= 102u8) { return ((c - 97u8) + 10u8): i32; };
};
return -1;
};
// isidstart / isidpart — identifier classes used by the lexer.
// Alpha or '_' starts; alnum or '_' continues.
export fn isidstart(c: u8) bool = {
if (isalpha(c)) { return true; };
if (c == 95u8) { return true; }; // '_'
return false;
};
export fn isidpart(c: u8) bool = {
if (isalnum(c)) { return true; };
if (c == 95u8) { return true; };
return false;
};
// tolower / toupper — fold ASCII case. Non-letters pass through.
export fn tolower(c: u8) u8 = {
if (isupper(c)) { return c + 32u8; };
return c;
};
export fn toupper(c: u8) u8 = {
if (islower(c)) { return c - 32u8; };
return c;
};

82
lib/bufio/bufio.ww Normal file
View File

@@ -0,0 +1,82 @@
// bufio — buffered reader/writer over io.stream. Plan 9 'bio'
// analogue, lowered to ww. The buffer is owned by the caller and
// passed in at init time; we don't allocate.
//
// We keep the stream pointer as *void here to avoid a cross-module
// type name (the module-import system isn't online yet); a later
// revision will replace it with *io.stream once `use` resolves
// types from imported modules.
type stream_p = *void;
type buf = struct {
s: stream_p,
data: *u8,
cap: i32,
r: i32, // read cursor
w: i32, // write cursor (for writers)
};
export fn rinit(b: *buf, s: stream_p, data: *u8, cap: i32) void = {
b.s = s;
b.data = data;
b.cap = cap;
b.r = 0;
b.w = 0;
};
// peek1 — look at the next byte without consuming. Returns -1 on
// empty buffer; the caller is responsible for refilling via the
// stream when this happens.
export fn peek1(b: *buf) i32 = {
if (b.r < b.w) {
return b.data[b.r]: i32;
};
return -1;
};
// take1 — pop one byte. -1 if empty.
export fn take1(b: *buf) i32 = {
if (b.r < b.w) {
let c: u8 = b.data[b.r];
b.r += 1;
return c: i32;
};
return -1;
};
// avail — bytes left to read out of the buffer.
export fn avail(b: *buf) i32 = {
return b.w - b.r;
};
// Distinct alias so `(str | linerr)` has two variant types the
// tagged-union machinery can keep apart at the tag level. The error
// variant carries a short description; callers compare with errors.is
// or just inspect by length.
type linerr = str;
// takeline — Hare-style fallible line read. Drains the buffer up to
// (but not including) the next '\n' and advances the cursor past the
// newline. Returns the line as a borrowed str on success, or a linerr
// describing why no line was available:
// - "eof" when the buffer is empty
// - "no newline" when the buffer contains data but no '\n'
//
// The returned str borrows from the underlying buffer; callers must
// consume it (or copy) before refilling.
export fn takeline(b: *buf) (str | linerr) = {
if (b.r >= b.w) { return "eof": linerr; };
let i: i32 = b.r;
for (i < b.w) {
if (b.data[i] == 10u8) {
let s: str;
s.ptr = b.data + b.r;
s.len = i - b.r;
b.r = i + 1;
return s;
};
i += 1;
};
return "no newline": linerr;
};

51
lib/bytes/bytes.ww Normal file
View File

@@ -0,0 +1,51 @@
// bytes — slice operations over []u8.
export fn equal(a: []u8, b: []u8) bool = {
let i: i32 = 0;
for (i < a.len) {
if (i >= b.len) { return false; };
if (a[i] != b[i]) { return false; };
i += 1;
};
return i == b.len;
};
export fn indexbyte(s: []u8, c: u8) i32 = {
let i: i32 = 0;
for (i < s.len) {
if (s[i] == c) { return i; };
i += 1;
};
return -1;
};
export fn copy(dst: []u8, src: []u8) i32 = {
let n: i32 = dst.len;
if (src.len < n) { n = src.len; };
let i: i32 = 0;
for (i < n) {
dst[i] = src[i];
i += 1;
};
return n;
};
// indexsub — first index of `sub` in `s`, or -1. Mirrors
// strings.index but on []u8. Empty `sub` matches at 0.
export fn indexsub(s: []u8, sub: []u8) i32 = {
if (sub.len == 0) { return 0; };
if (sub.len > s.len) { return -1; };
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 -1;
};

22
lib/c/libc/libc.ww Normal file
View File

@@ -0,0 +1,22 @@
// lib/c/libc — minimal libc bindings. Each declaration is body-less,
// imported from the C side at link time. The @symbol attribute pins
// the linker name; without it, the binding name itself is used.
//
// These declarations cover the small surface the bootstrap wants:
// process exit, three io syscalls, and the malloc/free pair. Higher
// ergonomics live in sibling pure-ww packages.
@symbol("malloc") fn malloc(n: u64) *void;
@symbol("free") fn free(p: *void) void;
@symbol("calloc") fn calloc(n: u64, sz: u64) *void;
@symbol("read") fn read(fd: i32, buf: *u8, n: u64) i64;
@symbol("write") fn write(fd: i32, buf: *u8, n: u64) i64;
@symbol("open") fn open(path: *u8, flags: i32, mode: i32) i32;
@symbol("close") fn close(fd: i32) i32;
@symbol("exit") fn exit(code: i32) void;
@symbol("strlen") fn strlen(s: *u8) u64;
@symbol("memcpy") fn memcpy(dst: *void, src: *void, n: u64) *void;
@symbol("memset") fn memset(p: *void, b: i32, n: u64) *void;

19
lib/encoding/hex/hex.ww Normal file
View File

@@ -0,0 +1,19 @@
// encoding/hex — encode/decode hexadecimal pairs.
export fn encode(dst: []u8, src: []u8) i32 = {
let i: i32 = 0;
let j: i32 = 0;
for (i < src.len) {
let b: u8 = src[i];
let hi: u8 = (b: i32 >> 4): u8 & ('\x0f': u8);
let lo: u8 = b & ('\x0f': u8);
if (hi < 10) { dst[j] = hi + ('0': u8); }
else { dst[j] = hi - 10 + ('a': u8); };
j += 1;
if (lo < 10) { dst[j] = lo + ('0': u8); }
else { dst[j] = lo - 10 + ('a': u8); };
j += 1;
i += 1;
};
return j;
};

14
lib/encoding/utf8/utf8.ww Normal file
View File

@@ -0,0 +1,14 @@
// encoding/utf8 — UTF-8 helpers. RFC 3629; we only handle the legal
// subset (no over-long encodings, no surrogates).
def MAX: rune = 1114111; // 0x10FFFF
def BAD: rune = -1;
export fn runelen(r: rune) i32 = {
if (r < 0) { return -1; };
if (r < 128) { return 1; };
if (r < 2048) { return 2; };
if (r < 65536) { return 3; };
if (r <= MAX) { return 4; };
return -1;
};

30
lib/errors/errors.ww Normal file
View File

@@ -0,0 +1,30 @@
// errors — error type (a string) and a few sentinels. Plan 9 model:
// the empty string means OK, a non-empty string is the message.
type error = str;
def eEOF: error = "eof";
def eShortRead: error = "short read";
def eShortWrite: error = "short write";
def eClosed: error = "closed";
def eInvalid: error = "invalid argument";
def ePerm: error = "permission denied";
def eNotFound: error = "not found";
def eExists: error = "already exists";
export fn isnil(e: error) bool = {
return e.len == 0;
};
// is — compare an error against a sentinel (or any other error). Pure
// byte equality; same shape as strings.equal but kept here so callers
// don't have to pull in strings just to compare.
export fn is(e: error, want: error) bool = {
if (e.len != want.len) { return false; };
let i: i32 = 0;
for (i < e.len) {
if (e[i] != want[i]) { return false; };
i += 1;
};
return true;
};

67
lib/fmt/fmt.ww Normal file
View File

@@ -0,0 +1,67 @@
// fmt — minimal formatting writers. All output goes through os.write
// to fd 1 (stdout). No printf-family yet — we don't have varargs in
// the language proper — but the typed entry points cover the common
// cases.
use os;
use strconv;
export fn print(s: str) i64 = {
return os.write(1, s.ptr, s.len: u64);
};
export fn println(s: str) void = {
os.write(1, s.ptr, s.len: u64);
os.write(1, "\n".ptr, 1u64);
};
export fn printint(v: i64) void = {
let buf: [32]u8;
let n: i32 = strconv.i64toa(buf[0:32], v);
os.write(1, buf.ptr, n: u64);
};
export fn printlnint(v: i64) void = {
printint(v);
os.write(1, "\n".ptr, 1u64);
};
// errln — write a message to stderr with a trailing newline.
export fn errln(s: str) void = {
os.write(2, s.ptr, s.len: u64);
os.write(2, "\n".ptr, 1u64);
};
// fprint / fprintln — same as print/println but on an arbitrary fd.
// Used by the compiler to write to its -o output file.
export fn fprint(fd: i32, s: str) i64 = {
return os.write(fd, s.ptr, s.len: u64);
};
export fn fprintln(fd: i32, s: str) void = {
os.write(fd, s.ptr, s.len: u64);
os.write(fd, "\n".ptr, 1u64);
};
export fn fprintint(fd: i32, v: i64) void = {
let buf: [32]u8;
let n: i32 = strconv.i64toa(buf[0:32], v);
os.write(fd, buf.ptr, n: u64);
};
// errpos — write "<file>:<line>:<col>: <msg>\n" to fd 2. The shape
// every compiler diagnostic uses; centralised so the format stays
// consistent across phases.
export fn errpos(file: str, line: i32, col: i32, msg: str) void = {
os.write(2, file.ptr, file.len: u64);
os.write(2, ":".ptr, 1u64);
let buf: [32]u8;
let n: i32 = strconv.i64toa(buf[0:32], line: i64);
os.write(2, buf.ptr, n: u64);
os.write(2, ":".ptr, 1u64);
n = strconv.i64toa(buf[0:32], col: i64);
os.write(2, buf.ptr, n: u64);
os.write(2, ": ".ptr, 2u64);
os.write(2, msg.ptr, msg.len: u64);
os.write(2, "\n".ptr, 1u64);
};

15
lib/hash/fnv/fnv.ww Normal file
View File

@@ -0,0 +1,15 @@
// hash/fnv — FNV-1a 64-bit. Pure ww. No dependencies.
def OFFSET: u64 = 14695981039346656037;
def PRIME: u64 = 1099511628211;
export fn fnv1a(buf: []u8) u64 = {
let h: u64 = OFFSET;
let i: i32 = 0;
for (i < buf.len) {
h = h ^ (buf[i]: u64);
h = h * PRIME;
i += 1;
};
return h;
};

28
lib/io/stream.ww Normal file
View File

@@ -0,0 +1,28 @@
// io — stream interface (Plan 9 Bio / Hare io::stream shape).
//
// No closures, no methods. A `stream` is a struct of function
// pointers plus a `ctx: *void`. The error channel is the return
// value of read/write/close. Negative i32 = errno-style code,
// non-negative = bytes transferred.
type stream = struct {
ctx: *void,
read: fn(s: *stream, buf: []u8) i32,
write: fn(s: *stream, buf: []u8) i32,
close: fn(s: *stream) i32,
};
def eof: i32 = -1;
def closed: i32 = -2;
export fn stream_read(s: *stream, buf: []u8) i32 = {
return s.read(s, buf);
};
export fn stream_write(s: *stream, buf: []u8) i32 = {
return s.write(s, buf);
};
export fn stream_close(s: *stream) i32 = {
return s.close(s);
};

48
lib/net/net.ww Normal file
View File

@@ -0,0 +1,48 @@
// net — minimal TCP. Sketched against the Linux syscall numbers
// 41 (socket), 42 (connect), 43 (accept), 49 (bind), 50 (listen).
// Real applications will want addrinfo + DNS; we leave that to
// higher layers.
@symbol("rt_syscall") fn syscall0(num: i64) i64;
@symbol("rt_syscall") fn syscall3(num: i64, a: i64, b: i64, c: i64) i64;
def AF_INET: i32 = 2;
def SOCK_STREAM:i32 = 1;
def IPPROTO_TCP:i32 = 6;
def SYS_SOCKET: i64 = 41;
def SYS_CONNECT: i64 = 42;
def SYS_ACCEPT: i64 = 43;
def SYS_BIND: i64 = 49;
def SYS_LISTEN: i64 = 50;
// sockaddr_in is laid out by the kernel: family u16, port u16 (BE),
// addr u32 (BE), padding 8B = 16B total. Caller fills it.
type sockaddr_in = struct {
family: u16,
port: u16,
addr: u32,
pad0: u64,
};
export fn socket() i32 = {
return syscall3(SYS_SOCKET, AF_INET: i64, SOCK_STREAM: i64,
IPPROTO_TCP: i64): i32;
};
export fn connect(fd: i32, sa: *sockaddr_in) i32 = {
return syscall3(SYS_CONNECT, fd: i64, sa: i64, 16): i32;
};
export fn bind(fd: i32, sa: *sockaddr_in) i32 = {
return syscall3(SYS_BIND, fd: i64, sa: i64, 16): i32;
};
export fn listen(fd: i32, backlog: i32) i32 = {
return syscall3(SYS_LISTEN, fd: i64, backlog: i64, 0): i32;
};
// htons-equivalent: byte-swap a 16-bit port into network order.
export fn htons(p: u16) u16 = {
return ((p << 8) | (p >> 8)) & 0xffff;
};

171
lib/os/os.ww Normal file
View File

@@ -0,0 +1,171 @@
// 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: i64) i64;
@symbol("rt_syscall") fn syscall1(num: i64, a: i64) i64;
@symbol("rt_syscall") fn syscall2(num: i64, a: i64, b: i64) i64;
@symbol("rt_syscall") fn syscall3(num: i64, a: i64, b: i64, c: i64) i64;
@symbol("rt_syscall") fn syscall4(num: i64, a: i64, b: i64, c: i64, d: i64) i64;
@symbol("rt_alloc") fn alloc(n: u64) *void;
@symbol("rt_free") fn free(p: *void, n: u64) void;
@symbol("rt_abort") fn abort(msg: str) void;
// Hare-style runtime check. Caller passes a message that's printed
// to stderr before exit(1).
export fn assert(cond: bool, msg: str) void = {
if (!cond) { abort(msg); };
};
def SYS_READ: i64 = 0;
def SYS_WRITE: i64 = 1;
def SYS_OPEN: i64 = 2;
def SYS_CLOSE: i64 = 3;
def SYS_LSEEK: i64 = 8;
def SYS_ACCESS: i64 = 21;
def SYS_GETPID: i64 = 39;
def SYS_FORK: i64 = 57;
def SYS_EXECVE: i64 = 59;
def SYS_EXIT: i64 = 60;
def SYS_WAIT4: i64 = 61;
def SYS_UNLINK: i64 = 87;
// open(2) flags. Linux values, matching <fcntl.h>.
def O_RDONLY: i32 = 0;
def O_WRONLY: i32 = 1;
def O_RDWR: i32 = 2;
def O_CREAT: i32 = 64; // 0x40
def O_TRUNC: i32 = 512; // 0x200
// lseek(2) whence.
def SEEK_SET: i32 = 0;
def SEEK_CUR: i32 = 1;
def SEEK_END: i32 = 2;
export fn exit(code: i32) void = {
syscall1(SYS_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(SYS_WRITE, fd: i64, buf: i64, n: i64);
};
export fn read(fd: i32, buf: *u8, n: u64) i64 = {
return syscall3(SYS_READ, fd: i64, buf: i64, n: i64);
};
export fn close(fd: i32) i32 = {
return syscall1(SYS_CLOSE, fd: i64): i32;
};
// Fallible wrappers. The error variant is a plain str (Plan 9 errstr
// model, see lib/errors); the sum type makes success/failure explicit
// without overloading length-zero.
export fn tryread(fd: i32, buf: *u8, n: u64) (i64 | str) = {
let r: i64 = read(fd, buf, n);
if (r < 0) { return "read failed"; };
return r;
};
export fn trywrite(fd: i32, buf: *u8, n: u64) (i64 | str) = {
let r: i64 = write(fd, buf, n);
if (r < 0) { return "write failed"; };
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: i32, mode: i32) i32 = {
return syscall3(SYS_OPEN, path: i64, flags: i64, mode: i64): i32;
};
export fn tryopen(path: *u8, flags: i32, mode: i32) (i32 | str) = {
let fd: i32 = open(path, flags, mode);
if (fd < 0) { return "open failed"; };
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, whence: i32) i64 = {
return syscall3(SYS_LSEEK, fd: i64, off, whence: i64);
};
// filesize — convenience: returns the byte length of an open fd by
// seeking to the end and back. -1 on error.
export fn filesize(fd: i32) i64 = {
let end: i64 = lseek(fd, 0i64, SEEK_END);
if (end < 0) { return -1i64; };
let r: i64 = lseek(fd, 0i64, SEEK_SET);
if (r < 0) { return -1i64; };
return end;
};
// readfull — keep reading until `n` bytes have arrived or the fd
// closes early. Returns bytes read (0..=n) or -1 on read error.
export fn readfull(fd: i32, buf: *u8, n: u64) i64 = {
let got: u64 = 0u64;
for (got < n) {
let r: i64 = read(fd, buf + got, n - got);
if (r < 0) { return -1i64; };
if (r == 0) { return got: i64; }; // short read: caller decides
got += r: u64;
};
return got: i64;
};
// writefull — keep writing until `n` bytes have been accepted or the
// fd refuses progress. Returns bytes written or -1.
export fn writefull(fd: i32, buf: *u8, n: u64) i64 = {
let sent: u64 = 0u64;
for (sent < n) {
let r: i64 = write(fd, buf + sent, n - sent);
if (r < 0) { return -1i64; };
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(SYS_ACCESS, path: i64, mode: i64): i32;
};
// unlink(2).
export fn unlink(path: *u8) i32 = {
return syscall1(SYS_UNLINK, path: i64): i32;
};
// getpid(2). Used by the driver to mint unique scratch paths.
export fn getpid() i32 = {
return syscall0(SYS_GETPID): i32;
};
// fork(2): 0 in the child, child pid in the parent, negative errno
// on failure.
export fn fork() i32 = {
return syscall0(SYS_FORK): i32;
};
// execve(2): on success, does not return.
export fn execve(path: *u8, argv: **u8, envp: **u8) i32 = {
return syscall3(SYS_EXECVE, path: i64, argv: i64, envp: i64): i32;
};
// wait4(2): wait for `pid` (or any child if -1), store status in
// `*status_out`, return the pid that ended (or negative errno).
export fn wait4(pid: i32, status_out: *i32, options: i32, rusage: *void) i32 = {
return syscall4(SYS_WAIT4, pid: i64, status_out: i64,
options: i64, rusage: i64): i32;
};

15
lib/path/path.ww Normal file
View File

@@ -0,0 +1,15 @@
// path — filesystem path manipulation. UTF-8 paths, '/' separator.
export fn isabs(p: str) bool = {
if (p.len == 0) { return false; };
return p[0] == ('/': u8);
};
export fn lastindex(p: str, c: u8) i32 = {
let i: i32 = p.len - 1;
for (i >= 0) {
if (p[i] == c) { return i; };
i -= 1;
};
return -1;
};

49
lib/slices/slices.ww Normal file
View File

@@ -0,0 +1,49 @@
// slices — generic slice helpers, written without generics.
//
// CLAUDE.md forbids generics, so we mint per-element-type variants.
// Hare's `append` builtin is what these stand in for: each takes a
// *[]T plus an item, grows the storage if needed, and updates the
// slice header in place. The user passes `&s` because we mutate
// through the pointer.
use os;
export fn appendu8(s: *[]u8, v: u8) void = {
if (s.len >= s.cap) {
let nc: i32 = s.cap * 2;
if (nc < 8) { nc = 8; };
let np: *u8 = os.alloc(nc: u64): *u8;
let i: i32 = 0;
for (i < s.len) {
np[i] = s.ptr[i];
i += 1;
};
if (s.cap > 0) {
os.free(s.ptr: *void, s.cap: u64);
};
s.ptr = np;
s.cap = nc;
};
s.ptr[s.len] = v;
s.len += 1;
};
export fn appendi64(s: *[]i64, v: i64) void = {
if (s.len >= s.cap) {
let nc: i32 = s.cap * 2;
if (nc < 8) { nc = 8; };
let np: *i64 = os.alloc((nc * 8): u64): *i64;
let i: i32 = 0;
for (i < s.len) {
np[i] = s.ptr[i];
i += 1;
};
if (s.cap > 0) {
os.free(s.ptr: *void, (s.cap * 8): u64);
};
s.ptr = np;
s.cap = nc;
};
s.ptr[s.len] = v;
s.len += 1;
};

27
lib/sort/sort.ww Normal file
View File

@@ -0,0 +1,27 @@
// sort — sorting helpers. The data is reached through a vtable so the
// algorithm stays generic without language-level generics.
type slice = struct {
ctx: *void,
len: i32,
less: fn(s: *slice, i: i32, j: i32) bool,
swap: fn(s: *slice, i: i32, j: i32) void,
};
// Insertion sort, fine for small inputs and stable. We'll grow into
// quicksort later when we have heavier tests.
export fn sort(s: *slice) void = {
let i: i32 = 1;
for (i < s.len) {
let j: i32 = i;
for (j > 0) {
if (s.less(s, j, j - 1)) {
s.swap(s, j, j - 1);
j -= 1;
} else {
j = 0;
};
};
i += 1;
};
};

119
lib/strconv/strconv.ww Normal file
View File

@@ -0,0 +1,119 @@
// strconv — number↔string conversions. Decimal i64 to/from a fixed
// buffer. Two error idioms ship side by side:
// - Plan 9 style (atoi64): tuple `(value, ok)`. Pre-dates the
// tagged-union work; kept for callers that already use it.
// - Hare style (parse64/parseu64): `(value | str)`. The error
// variant carries a short, allocation-free message describing
// why the parse failed. Prefer this for new code.
// u64toa — write `v` in decimal into `buf` and return the byte count.
// Unsigned-only so callers don't have to think about wraparound when
// printing a u64 that happens to have the high bit set.
export fn u64toa(buf: []u8, v: u64) i32 = {
let tmp: [32]u8;
let i: i32 = 0;
let n: u64 = v;
for (n > 0u64) {
tmp[i] = ((n % 10u64) + 48u64): u8;
n = n / 10u64;
i += 1;
};
if (i == 0) {
tmp[0] = 48u8;
i = 1;
};
let out: i32 = 0;
for (i > 0) {
i -= 1;
buf[out] = tmp[i];
out += 1;
};
return out;
};
export fn i64toa(buf: []u8, v: i64) i32 = {
let neg: bool = false;
let n: i64 = v;
if (n < 0) {
neg = true;
n = -n;
};
let tmp: [32]u8;
let i: i32 = 0;
for (n > 0) {
tmp[i] = ((n % 10) + 48): u8;
n = n / 10;
i += 1;
};
if (i == 0) {
tmp[0] = 48u8;
i = 1;
};
let out: i32 = 0;
if (neg) {
buf[out] = 45u8; // '-'
out += 1;
};
for (i > 0) {
i -= 1;
buf[out] = tmp[i];
out += 1;
};
return out;
};
export fn atoi64(s: str) (i64, bool) = {
let v: i64 = 0;
let i: i32 = 0;
let neg: bool = false;
if (s.len > 0) {
if (s[0] == 45u8) { neg = true; i = 1; };
};
if (i >= s.len) { return 0, false; };
for (i < s.len) {
let c: u8 = s[i];
if (c < 48u8) { return 0, false; };
if (c > 57u8) { return 0, false; };
v = v * 10 + ((c: i64) - 48);
i += 1;
};
if (neg) { v = -v; };
return v, true;
};
// parse64 — Hare-style fallible signed decimal parser. The value
// variant is i64; the error variant is a short str describing the
// reason. No locale, no whitespace, no underscores: a leading '-' is
// the only non-digit accepted, and only at position 0.
export fn parse64(s: str) (i64 | str) = {
if (s.len == 0) { return "parse: empty"; };
let i: i32 = 0;
let neg: bool = false;
if (s[0] == 45u8) { neg = true; i = 1; };
if (i >= s.len) { return "parse: lone sign"; };
let v: i64 = 0;
for (i < s.len) {
let c: u8 = s[i];
if (c < 48u8) { return "parse: invalid digit"; };
if (c > 57u8) { return "parse: invalid digit"; };
v = v * 10 + ((c: i64) - 48);
i += 1;
};
if (neg) { v = -v; };
return v;
};
// parseu64 — fallible unsigned decimal parser. No leading sign.
export fn parseu64(s: str) (u64 | str) = {
if (s.len == 0) { return "parse: empty"; };
let v: u64 = 0u64;
let i: i32 = 0;
for (i < s.len) {
let c: u8 = s[i];
if (c < 48u8) { return "parse: invalid digit"; };
if (c > 57u8) { return "parse: invalid digit"; };
v = v * 10u64 + ((c: u64) - 48u64);
i += 1;
};
return v;
};

95
lib/strings/strings.ww Normal file
View File

@@ -0,0 +1,95 @@
// strings — operations over the immutable str type ({ *u8, len }).
use os;
export fn len(s: str) i32 = {
return s.len;
};
export fn isempty(s: str) bool = {
return s.len == 0;
};
export fn equal(a: str, b: str) 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;
};
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;
};
// indexbyte — first index of `c` in `s`, or -1 if absent. Plan 9-
// style sentinel return; callers that prefer a fallible shape can
// wrap this in their own (i32 | str). No allocation.
export fn indexbyte(s: str, c: u8) i32 = {
let i: i32 = 0;
for (i < s.len) {
if (s[i] == c) { return i; };
i += 1;
};
return -1;
};
// index — first index of `sub` in `s`, or -1. Naive scan; fine for
// short patterns and small strings, which dominate config and CLI
// parsing. Empty `sub` matches at 0.
export fn index(s: str, sub: str) i32 = {
if (sub.len == 0) { return 0; };
if (sub.len > s.len) { return -1; };
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 -1;
};
export fn contains(s: str, sub: str) bool = {
return index(s, sub) >= 0;
};
// 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;
};

15
lib/time/time.ww Normal file
View File

@@ -0,0 +1,15 @@
// time — clocks. We expose monotonic-ns via a syscall trampoline.
// Linux clock_gettime is syscall 228; clock id 1 is CLOCK_MONOTONIC.
// Until we can pass struct-by-value the user supplies a buffer.
@symbol("rt_syscall") fn syscall(num: i64, a: i64, b: i64, c: i64) i64;
def CLOCK_MONOTONIC: i64 = 1;
def SYS_CLOCK_GETTIME: i64 = 228;
// timespec is {sec, nsec} — 16 bytes. Caller passes a pointer.
type timespec = struct { sec: i64, nsec: i64 };
export fn monotonic(ts: *timespec) i32 = {
return syscall(SYS_CLOCK_GETTIME, CLOCK_MONOTONIC, ts: i64, 0): i32;
};

48
lib/types/types.ww Normal file
View File

@@ -0,0 +1,48 @@
// types — integer limits and helpers, the seed module that the
// rest of the stdlib depends on. Plan 9-flavoured: the names are
// short and the constants are platform-fixed (we are amd64 only).
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;
export fn min_i32(a: i32, b: i32) i32 = {
if (a < b) { return a; };
return b;
};
export fn max_i32(a: i32, b: i32) i32 = {
if (a > b) { return a; };
return b;
};
export fn min_i64(a: i64, b: i64) i64 = {
if (a < b) { return a; };
return b;
};
export fn max_i64(a: i64, b: i64) i64 = {
if (a > b) { return a; };
return b;
};
export fn abs_i32(x: i32) i32 = {
if (x < 0) { return -x; };
return x;
};
export fn abs_i64(x: i64) i64 = {
if (x < 0) { return -x; };
return x;
};