selfhost: port forrange — N_FORRANGE parser + cgen + tuple destructure

This commit is contained in:
2026-05-12 16:21:13 +09:00
parent ce5d66e18a
commit e087c843e9
8 changed files with 1280 additions and 66 deletions

View File

@@ -345,6 +345,32 @@ probe_ww_compile(const char *bin)
" dec(&c); dec(&c); dec(&c);\n"
" return c.x;\n"
"};", 2 },
/* Hare-style for-range over a slice: `for (let b .. s)`.
* Allocates `.rgi`/`.rgl` scratch slots, walks i=0..s.len
* loading s.ptr[i] into the binding. esz=1 here so the
* load is MOVZBQ. Sum 10+20+30+40 = 100. */
{ "use os;\n"
"fn main() i32 = {\n"
" let s: []u8;\n"
" s.ptr = nil; s.len = 0; s.cap = 0;\n"
" append(s, 10u8, 20u8, 30u8, 40u8);\n"
" let total: i32 = 0;\n"
" for (let b .. s) { total += b: i32; };\n"
" return total;\n"
"};", 100 },
/* for-range with tuple destructure on `(i64, i64)`. Element
* size is 16 (sum of raw param sizes); each binding loads
* via BX+foff. Buf has (1,10) (2,20); sum = 33. */
{ "fn main() i32 = {\n"
" let buf: [4]i64;\n"
" buf[0] = 1i64; buf[1] = 10i64; buf[2] = 2i64; buf[3] = 20i64;\n"
" let s: [](i64, i64);\n"
" s.ptr = buf.ptr: *(i64, i64);\n"
" s.len = 2; s.cap = 2;\n"
" let total: i64 = 0i64;\n"
" for (let (k, v) .. s) { total += k + v; };\n"
" return total: i32;\n"
"};", 33 },
/* append(s, v, ...) builtin — Hare's rt::ensure model.
* Each value: PUSHQ AX, ADDQ $1 to s.len, LEAQ s/MOVQ esz
* args for rt_ensure, then write into the freshly-grown

View File

@@ -178,6 +178,27 @@ main(void)
" append(dst, src...);\n"
" return dst.len: i32;\n"
"};" },
{ "forrange",
"use os;\n"
"fn main() i32 = {\n"
" let s: []u8;\n"
" s.ptr = nil; s.len = 0; s.cap = 0;\n"
" append(s, 10u8, 20u8, 30u8);\n"
" let total: i32 = 0;\n"
" for (let b .. s) { total += b: i32; };\n"
" return total;\n"
"};" },
{ "forrange_tuple",
"fn main() i32 = {\n"
" let buf: [4]i64;\n"
" buf[0] = 1i64; buf[1] = 10i64; buf[2] = 2i64; buf[3] = 20i64;\n"
" let s: [](i64, i64);\n"
" s.ptr = buf.ptr: *(i64, i64);\n"
" s.len = 2; s.cap = 2;\n"
" let total: i64 = 0i64;\n"
" for (let (k, v) .. s) { total += k + v; };\n"
" return total: i32;\n"
"};" },
{ NULL, NULL },
};