aboutsummaryrefslogtreecommitdiff
path: root/examples/typed.zc
blob: 44aff88fbb8ec0bd17618b56e90ce88252fb3ac0 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// types: structs, a generic container, and looking at it all through reflection.
// a pointer type put_s its star after the type, like c: int*, point*, vec<T>*.
typecheck on;
struct point { int x, y; };
struct vec<T> { int len, cap; T* items; };

vec<T>*.u mkvec<T>(int cap) {
	vec<T>* v = new(vec<T>);
	v.cap = cap;
	v.items = new(T, cap);
	return u*v;
}

// x is given away (.d): the vector's memory holds it from now on, and the
// collector looks after it
bool push<T>(vec<T>* v, T.d x) {
	if (v.len == v.cap) { free(d*x); return 0; }
	v.items[v.len] = d*x;
	v.len++;
	return 1;
}

fn show(word t) {
	let i = 0;
	tprint(t); put_s(" is "); put_n(tsize(t)); put_s(" words: ");
	while (i < tnfields(t)) {
		if (i) put_s(", ");
		put_s(tfname(t, i)); put_s(" "); tprint(tftype(t, i));
		i++;
	}
	put_c(10);
	return 0;
}

int main() {
	vec<point*>* v = mkvec<point*>(4);
	int i = 0;
	while (i < 3) {
		point* p = new(point);
		p.x = i; p.y = i * i;
		push(v, d*p);
		i++;
	}
	put_s("last: "); put_n(v.items[2].y); put_c(10);
	show(typeof(point));
	show(typeof(*v));
	put_s("push is "); tprint(sigof(push)); put_c(10);
	// each set of type arguments gets its own copy of mkvec, so what it stamped is vec<point*>
	put_s("the heap says v is a "); tprint(typeof_obj(v)); put_s(", and v.items[0] is a "); tprint(typeof_obj(v.items[0])); put_c(10);
	return 0;
}