aboutsummaryrefslogtreecommitdiff
path: root/examples/staged.zc
diff options
context:
space:
mode:
authorGravatar Moon Flower <moonflower@elhenney.local> 2026-10-12 08:46:23 +0330
committerGravatar Moon Flower <moonflower@elhenney.local> 2026-10-12 08:46:23 +0330
commitecc350ca5c2eb50be8309c5f14f8bf0d87db9a02 (patch)
tree70e0af76a1b13affff7c6cc8aac7b3e6ef960478 /examples/staged.zc
a
Diffstat (limited to 'examples/staged.zc')
-rw-r--r--examples/staged.zc33
1 files changed, 33 insertions, 0 deletions
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;
+}