aboutsummaryrefslogtreecommitdiff
path: root/examples/staged.zc
blob: 23453f98da73fa2e2fc9fa8dcab9e9b319f960de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
namespace;
include rt, run;

// 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;
void put(s) { let i = 0; while (s[i]) { buf[n] = s[i]; n++; i++; } return; }
void putnum(int v) { if (v >= 10) putnum(v / 10); buf[n] = '0' + v % 10; n++; return; }

// 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;
}
void main() {
	int[4] c;
	c[0] = 7; c[1] = 0 - 3; c[2] = 0; c[3] = 2;	// 2x^3 - 3x + 7
	let src = specialize(c, 3), q = run.tokens(src);
	rt.put_s(src); rt.put_c(10);
	run.load(q);			// compiled now, into the running program
	rt.free(q);
	let f = run.sval[run.lookups("poly")];	// and found by name in the compiler's symbol table
	for (int x = 0 - 2; x <= 3; x++) { rt.put_n(f(x)); rt.put_c(' '); }
	rt.put_c(10);
	return;
}