From ecc350ca5c2eb50be8309c5f14f8bf0d87db9a02 Mon Sep 17 00:00:00 2001 From: Moon Flower Date: Mon, 12 Oct 2026 08:46:23 +0330 Subject: a --- examples/staged.zc | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 examples/staged.zc (limited to 'examples/staged.zc') diff --git a/examples/staged.zc b/examples/staged.zc new file mode 100644 index 0000000..a180ae3 --- /dev/null +++ b/examples/staged.zc @@ -0,0 +1,33 @@ +// staged code: a program writes a specialized function as source, compiles it +// while running, and calls it. here, polynomials with their coefficients baked +// in as constants, so there's no loop and no array left at runtime. +let buf[2000], n; +fn put(s) { let i = 0; while (s[i]) { buf[n] = s[i]; n++; i++; } return 0; } +fn putnum(int v) { if (v >= 10) putnum(v / 10); buf[n] = '0' + v % 10; n++; return 0; } + +// coefficients c[0] + c[1] x + ... in horner form: ((c3 x + c2) x + c1) x + c0 +fn specialize(int* c, int deg) { + n = 0; + put("fn poly(x) { return "); + for (int i = 0; i < deg; i++) put("("); + if (c[deg] < 0) { put("0 - "); putnum(0 - c[deg]); } else putnum(c[deg]); + for (int i = deg - 1; i >= 0; i--) { + put(") * x "); + if (c[i] < 0) { put("- "); putnum(0 - c[i]); } else { put("+ "); putnum(c[i]); } + } + put("; }"); + buf[n] = 0; + return buf; +} +fn main() { + [4]int c; + c[0] = 7; c[1] = 0 - 3; c[2] = 0; c[3] = 2; // 2x^3 - 3x + 7 + let src = specialize(c, 3), q = tokens(src); + put_s(src); put_c(10); + load(q); // compiled now, into the running program + free(d*q); + let f = sval[lookups("poly")]; // and found by name in the compiler's symbol table + for (int x = 0 - 2; x <= 3; x++) { put_n(f(x)); put_c(' '); } + put_c(10); + return 0; +} -- cgit v1.2.3