w6c: lower append() to rt_ensure + inline store (hare model)

This commit is contained in:
2026-05-11 17:02:32 +09:00
parent 5408160d49
commit 9e383b7ba0
4 changed files with 100 additions and 65 deletions

View File

@@ -1,49 +0,0 @@
// rt/append.ww — slice runtime helpers, archived into libwwrt.a.
//
// The compiler lowers `append(s, v)` to a CALL to one of these by
// element size (1 byte → appendu8, else → appendi64). User code
// never `use`s this — the symbol comes in via the runtime archive,
// like rt_alloc and rt_streq.
@symbol("rt_alloc") fn alloc(n: u64) *void;
@symbol("rt_free") fn free(p: *void, n: u64) void;
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 = alloc(nc: u64): *u8;
let i: i32 = 0;
for (i < s.len) {
np[i] = s.ptr[i];
i += 1;
};
if (s.cap > 0) {
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 = alloc((nc * 8): u64): *i64;
let i: i32 = 0;
for (i < s.len) {
np[i] = s.ptr[i];
i += 1;
};
if (s.cap > 0) {
free(s.ptr: *void, (s.cap * 8): u64);
};
s.ptr = np;
s.cap = nc;
};
s.ptr[s.len] = v;
s.len += 1;
};

49
rt/ensure.ww Normal file
View File

@@ -0,0 +1,49 @@
// rt/ensure.ww — slice growth helper, archived into libwwrt.a.
//
// Companion to the `append(s, v)` builtin. The compiler lowers
// `append(s, v)` to:
//
// ; push v
// ; s.len += 1
// ; CALL rt_ensure(&s, sizeof(elem))
// ; ; ensure may have realloc'd, so re-read s.ptr
// ; pop v
// ; *(s.ptr + (s.len - 1) * elem_size) = v
//
// One helper handles every element width via the membsz parameter —
// no per-type wrapper functions (appendu8 / appendi64) needed.
//
// User code never `use`s this — the symbol is resolved at link time
// from libwwrt.a, like rt_alloc and rt_streq.
@symbol("rt_alloc") fn alloc(n: u64) *void;
@symbol("rt_free") fn free(p: *void, n: u64) void;
// Mirrors ww's []T header layout: 24 bytes with 8-byte slots.
// ww's source uses i32 for len/cap but the compiler stores them in
// 8-byte slots; declaring as i64 here keeps the field offsets right
// for this polymorphic alias.
type slice = struct {
ptr: *u8,
len: i64,
cap: i64,
};
export fn rt_ensure(s: *slice, membsz: u64) void = {
if (s.cap >= s.len) { return; };
let nc: i64 = s.cap * 2i64;
if (nc < 8i64) { nc = 8i64; };
for (nc < s.len) { nc *= 2i64; };
let np: *u8 = alloc((nc: u64) * membsz): *u8;
let n: u64 = (s.cap: u64) * membsz;
let i: u64 = 0u64;
for (i < n) {
np[i] = s.ptr[i];
i += 1u64;
};
if (s.cap > 0i64) {
free(s.ptr: *void, (s.cap: u64) * membsz);
};
s.ptr = np;
s.cap = nc;
};