commit c3a43cb
shrub
·
2026-11-20 23:05:12 +0000 UTC
parent 95b8069
implement qbe codegen
11 files changed,
+963,
-31
M
Makefile
+2,
-2
1@@ -4,8 +4,8 @@ CC = cc
2 CPP = $(CC) -E
3 CFLAGS = -std=c11 -O2 -Wall -Wextra -pedantic -Wno-implicit-fallthrough -Wno-parentheses
4 OBJ = main.o util.o lex.o parse.o ast.o resolve.o \
5- run.o check.o type.o module.o linear.o
6-HDR = util.h kav.h tokens.h punc.h kws.h exprs.h builtins.h
7+ run.o check.o type.o module.o linear.o qbe.o
8+HDR = util.h kav.h tokens.h punc.h kws.h exprs.h builtins.h ops.h
9
10 .PHONY: all clean
11
M
arg.h
+1,
-1
1@@ -2,7 +2,7 @@
2 for(;;) { \
3 if(argc > 0) \
4 ++argv, --argc; \
5- if(argc == 0 || (*argv)[0] != '-') \
6+ if(argc == 0 || (*argv)[0] != '-' || !(*argv)[1]) \
7 break; \
8 if((*argv)[1] == '-' && !(*argv)[2]) { \
9 ++argv, --argc; \
M
kav.h
+10,
-0
1@@ -46,6 +46,9 @@ struct module {
2 const char *canonical;
3 stralloc src;
4 struct decl *decls;
5+ const char *name; /* name from the use path */
6+ const char *qname;
7+ int sys; /* got here from <> */
8 int state;
9 };
10
11@@ -54,8 +57,10 @@ void resolve(struct module *);
12 void check(struct module *);
13 void linear(struct module *);
14 int run(struct decl *);
15+void qbe(struct module *);
16 noreturn void erroratv(const struct location *, const char *const *, usize);
17 char *tokdup(struct token);
18+i64 tonum(struct token);
19 int tokeqb(struct token, const char *, usize);
20 #define tokis(t, lit) tokeqb((t), (lit), sizeof(lit) - 1)
21 #define tokeq(a, b) tokeqb((a), (b).str, (b).length)
22@@ -79,6 +84,8 @@ enum bindkind {
23 BPAT,
24 };
25
26+struct operand;
27+
28 struct binding {
29 struct decl *decl;
30 struct binding *next;
31@@ -87,6 +94,7 @@ struct binding {
32 struct token name;
33 struct ctor *ctor; /*constructors only */
34 struct param *param;
35+ struct operand *qval; /* qbe */
36 };
37
38 #define BUILTIN(sp, kind, str, var) extern struct binding *var;
39@@ -162,6 +170,7 @@ struct pat {
40 struct token ns;
41 struct binding *binding;
42 struct type *type;
43+ struct operand *qval; /* qbe: the value this pattern matched */
44 };
45
46 struct arm {
47@@ -202,6 +211,7 @@ struct decl {
48 struct decl *next;
49 enum declkind kind;
50 struct token name;
51+ const char *qname; /* name for qbe */
52 int pub;
53 int linear;
54 int newtype;
M
linear.c
+2,
-6
1@@ -12,17 +12,13 @@ static struct lvar *vars;
2
3 int
4 islinear(struct type *t) {
5- struct type *a;
6-
7 t = deref(t);
8 switch(t->kind) {
9 case YNAME:
10 return t->binding->decl && t->binding->decl->linear;
11 case YTUPLE:
12- for(a = t->args; a; a = a->next)
13- if(islinear(a))
14- return 1;
15- return 0;
16+ /* all tuples are linear */
17+ return 1;
18 case YVAR:
19 /*linear unless its utype */
20 return t->binding->param->ann->binding != butype;
M
main.c
+10,
-8
1@@ -9,17 +9,10 @@ static noreturn void
2 usage(void) {
3 fputs("usage: ", stderr);
4 fputs(PROG, stderr);
5- fputs(" [-c|-l|-p|-r] file\n", stderr);
6+ fputs(" [-c|-l|-p|-q|-r] file\n", stderr);
7 exit(100);
8 }
9
10-static void
11-putnum(usize u) {
12- char num[FMTUSIZE];
13-
14- fwrite(num, 1, fmtusize(num, u), stdout);
15-}
16-
17 static int
18 dolex(const char *path) {
19 stralloc sa = {0};
20@@ -97,6 +90,12 @@ dorun(const char *path) {
21 return run(m->decls);
22 }
23
24+static int
25+doqbe(const char *path) {
26+ qbe(build(path));
27+ return 0;
28+}
29+
30 int
31 main(int argc, char **argv) {
32 int (*mode)(const char *) = dorun;
33@@ -112,6 +111,9 @@ main(int argc, char **argv) {
34 case 'p':
35 mode = doparse;
36 break;
37+ case 'q':
38+ mode = doqbe;
39+ break;
40 case 'r':
41 mode = doresolve;
42 break;
M
module.c
+41,
-3
1@@ -62,8 +62,41 @@ usepath(const char *from, struct token name) {
2 return sa.s;
3 }
4
5+/* a module's logical name, we need it later for qbe */
6+static char *
7+usename(struct module *from, struct token use) {
8+ stralloc sa = {0};
9+ const char *s = use.str + 1;
10+ const char *slash;
11+ usize len = use.length - 2;
12+
13+ if(use.kind != TUSEPATH && (slash = strrchr(from->name, '/')))
14+ sacatb(&sa, from->name, slash - from->name + 1);
15+ if(len > 4 && memcmp(s + len - 4, ".kav", 4) == 0)
16+ len -= 4;
17+ sacatb(&sa, s, len);
18+ sa0(&sa);
19+ return sa.s;
20+}
21+
22+static char *
23+rootname(const char *path) {
24+ stralloc sa = {0};
25+ const char *s;
26+ usize len;
27+
28+ s = strrchr(path, '/');
29+ s = s ? s + 1 : path;
30+ len = strlen(s);
31+ if(len > 4 && strcmp(s + len - 4, ".kav") == 0)
32+ len -= 4;
33+ sacatb(&sa, s, len);
34+ sa0(&sa);
35+ return sa.s;
36+}
37+
38 static struct module *
39-load(const char *path, const char *file, const struct location *at) {
40+load(const char *path, const char *file, char *name, int sys, const struct location *at) {
41 struct module *m;
42 struct module *s;
43 struct decl *d;
44@@ -83,11 +116,14 @@ load(const char *path, const char *file, const struct location *at) {
45 if(s->state == 1)
46 die("import cycle through ", file);
47 free(canonical);
48+ free(name);
49 return s;
50 }
51 }
52 m = zalloc(sizeof(*m));
53 m->state = 1;
54+ m->name = name;
55+ m->sys = sys;
56 m->nextseen = seen;
57 seen = m;
58 sourcepath = alloc(strlen(file) + 1);
59@@ -105,7 +141,9 @@ load(const char *path, const char *file, const struct location *at) {
60 if(d->kind == DUSE) {
61 importpath = usepath(canonical, d->name);
62 importfile = d->name.kind == TUSEPATH ? importpath : usepath(m->path, d->name);
63- d->mod = load(importpath, importfile, &d->name.loc);
64+ /* system modules and anything they import get k.sys. names */
65+ d->mod = load(importpath, importfile, usename(m, d->name),
66+ d->name.kind == TUSEPATH || m->sys, &d->name.loc);
67 if(importfile != importpath)
68 free(importfile);
69 free(importpath);
70@@ -121,6 +159,6 @@ loadall(const char *path) {
71 seen = nil;
72 head = nil;
73 end = &head;
74- load(path, path, nil);
75+ load(path, path, rootname(path), 0, nil);
76 return head;
77 }
M
parse.c
+1,
-1
1@@ -75,7 +75,7 @@ type(void) {
2 e->body = type();
3 return e;
4 }
5- /* a tuple type, or a parenthesized one. the elements are types so they can be fn types */
6+ /* a tuple type. the elements are types so they can be fn types */
7 if(tok.kind == TLPAREN) {
8 struct expr *a;
9 struct expr *head = nil;
A
qbe.c
+877,
-0
1@@ -0,0 +1,877 @@
2+#include <stdio.h>
3+#include <string.h>
4+
5+#include "util.h"
6+#include "kav.h"
7+
8+enum instkind {
9+#define OP(op, name) op,
10+#include "ops.h"
11+#undef OP
12+};
13+
14+static const char *const instname[] = {
15+#define OP(op, name) name,
16+#include "ops.h"
17+#undef OP
18+};
19+
20+enum oprkind {
21+ VNONE,
22+ VTEMP,
23+ VCONST,
24+ VGLOBAL,
25+ VLABEL
26+};
27+
28+struct operand {
29+ enum oprkind kind;
30+ usize id; /* vtemp/vlabel */
31+ i64 i; /* vconst */
32+ const char *name;
33+};
34+
35+struct inst {
36+ struct inst *next;
37+ enum instkind kind;
38+ int class;
39+ struct operand res;
40+ struct operand *arg[2];
41+};
42+
43+struct block;
44+
45+enum jumpkind {
46+ JNONE,
47+ JJMP,
48+ JJNZ,
49+ JRET,
50+ JHLT,
51+};
52+
53+struct jump {
54+ enum jumpkind kind;
55+ struct operand *arg;
56+ struct block *block[2];
57+};
58+
59+struct block {
60+ struct block *next;
61+ struct operand label;
62+ struct inst *insts;
63+ struct inst **instend;
64+ struct jump jump;
65+};
66+
67+struct func {
68+ struct decl *decl;
69+ const char *name;
70+ struct operand *params;
71+ usize nparams;
72+ struct block *start;
73+ struct block *body;
74+ struct block *end;
75+ usize lastid;
76+};
77+
78+
79+static struct operand *
80+mkconst(i64 n) {
81+ struct operand *v;
82+
83+ v = zalloc(sizeof(*v));
84+ v->kind = VCONST;
85+ v->i = n;
86+ return v;
87+}
88+
89+static struct operand *
90+mkglobal(const char *name) {
91+ struct operand *v;
92+
93+ v = zalloc(sizeof(*v));
94+ v->kind = VGLOBAL;
95+ v->name = name;
96+ return v;
97+}
98+
99+static struct block *
100+mkblock(const char *name) {
101+ struct block *b;
102+ static usize id;
103+
104+ b = zalloc(sizeof(*b));
105+ b->label.kind = VLABEL;
106+ b->label.name = name;
107+ b->label.id = ++id;
108+ b->instend = &b->insts;
109+ return b;
110+}
111+
112+static void
113+functemp(struct func *f, struct operand *v) {
114+ v->kind = VTEMP;
115+ v->id = ++f->lastid;
116+}
117+
118+static void
119+funclabel(struct func *f, struct block *b) {
120+ f->end->next = b;
121+ f->end = b;
122+}
123+
124+static void
125+funcappend(struct func *f, struct inst *inst) {
126+ /*nothing follows a jump */
127+ if(f->end->jump.kind != JNONE)
128+ funclabel(f, mkblock("dead"));
129+ *f->end->instend = inst;
130+ f->end->instend = &inst->next;
131+}
132+
133+static struct operand *
134+funcinst(struct func *f, enum instkind op, int class, struct operand *a0, struct operand *a1) {
135+ struct inst *inst;
136+
137+ inst = zalloc(sizeof(*inst));
138+ inst->kind = op;
139+ inst->class = class;
140+ inst->arg[0] = a0;
141+ inst->arg[1] = a1;
142+ if(class)
143+ functemp(f, &inst->res);
144+ funcappend(f, inst);
145+ return &inst->res;
146+}
147+
148+static void
149+funccopy(struct func *f, struct operand *dst, struct operand *src) {
150+ struct inst *inst;
151+
152+ inst = zalloc(sizeof(*inst));
153+ inst->kind = ICOPY;
154+ inst->class = 'l';
155+ inst->res = *dst;
156+ inst->arg[0] = src;
157+ funcappend(f, inst);
158+}
159+
160+
161+static void
162+funcjmp(struct func *f, struct block *to) {
163+ struct block *b = f->end;
164+
165+ if(b->jump.kind != JNONE)
166+ return;
167+ b->jump.kind = JJMP;
168+ b->jump.block[0] = to;
169+}
170+
171+static void
172+funcjnz(struct func *f, struct operand *cond, struct block *yes, struct block *no) {
173+ struct block *b = f->end;
174+
175+ if(b->jump.kind != JNONE)
176+ return;
177+ b->jump.kind = JJNZ;
178+ b->jump.arg = cond;
179+ b->jump.block[0] = yes;
180+ b->jump.block[1] = no;
181+}
182+
183+static void
184+funcret(struct func *f, struct operand *v) {
185+ struct block *b = f->end;
186+
187+ if(b->jump.kind != JNONE)
188+ return;
189+ b->jump.kind = JRET;
190+ b->jump.arg = v;
191+}
192+
193+static void
194+funchlt(struct func *f) {
195+ struct block *b = f->end;
196+
197+ if(b->jump.kind != JNONE)
198+ return;
199+ b->jump.kind = JHLT;
200+}
201+
202+static struct operand *funcexpr(struct func *, struct expr *);
203+static void functail(struct func *, struct expr *);
204+
205+static usize
206+ctoridx(struct binding *b) {
207+ struct ctor *c;
208+ usize i = 0;
209+
210+ for(c = b->decl->ctors; c != b->ctor; c = c->next)
211+ i++;
212+ return i;
213+}
214+
215+static struct operand *
216+funcctor(struct func *f, struct expr *e) {
217+ struct operand **args;
218+ struct operand *p;
219+ struct operand *a;
220+ struct expr *x;
221+ usize n = 0;
222+ usize i;
223+
224+ /* the value is the field */
225+ if(e->binding->decl->newtype)
226+ return funcexpr(f, e->args);
227+
228+ for(x = e->args; x; x = x->next)
229+ n++;
230+ args = alloc(n * sizeof(*args));
231+ for(x = e->args, i = 0; x; x = x->next, i++)
232+ args[i] = funcexpr(f, x);
233+
234+ p = funcinst(f, ICALL, 'l', mkglobal("k.alloc"), nil);
235+ funcinst(f, IARG, 0, mkconst(8 * (n + 1)), nil);
236+ funcinst(f, ISTORE, 0, mkconst(ctoridx(e->binding)), p);
237+ for(i = 0; i < n; i++) {
238+ a = funcinst(f, IADD, 'l', p, mkconst(8 * (i + 1)));
239+ funcinst(f, ISTORE, 0, args[i], a);
240+ }
241+ return p;
242+}
243+
244+static struct operand *
245+functuple(struct func *f, struct expr *e) {
246+ struct operand **args;
247+ struct operand *p;
248+ struct operand *a;
249+ struct expr *x;
250+ usize n = 0;
251+ usize i;
252+
253+ for(x = e->args; x; x = x->next)
254+ n++;
255+ args = alloc(n * sizeof(*args));
256+ for(x = e->args, i = 0; x; x = x->next, i++)
257+ args[i] = funcexpr(f, x);
258+
259+ p = funcinst(f, ICALL, 'l', mkglobal("k.alloc"), nil);
260+ funcinst(f, IARG, 0, mkconst(8 * n), nil);
261+ for(i = 0; i < n; i++) {
262+ a = funcinst(f, IADD, 'l', p, mkconst(8 * i));
263+ funcinst(f, ISTORE, 0, args[i], a);
264+ }
265+ return p;
266+}
267+
268+
269+static struct operand *
270+funccall(struct func *f, struct expr *e) {
271+ struct operand *callee;
272+ struct operand **args;
273+ struct operand *r;
274+ struct expr *a;
275+ usize n;
276+ usize i;
277+
278+ if(e->binding->kind == BCTOR)
279+ return funcctor(f, e);
280+ if(e->binding->kind == BFN)
281+ callee = mkglobal(e->binding->decl->qname);
282+ else
283+ callee = e->binding->qval;
284+ /* args first */
285+ n = 0;
286+ for(a = e->args; a; a = a->next)
287+ n++;
288+ args = alloc(n * sizeof(*args));
289+ for(a = e->args, i = 0; a; a = a->next, i++)
290+ args[i] = funcexpr(f, a);
291+ r = funcinst(f, ICALL, 'l', callee, nil);
292+ for(i = 0; i < n; i++)
293+ funcinst(f, IARG, 0, args[i], nil);
294+ return r;
295+}
296+
297+/* one arg is negation & two is a binop */
298+static struct operand *
299+funcop(struct func *f, struct expr *e) {
300+ struct operand *l;
301+ struct operand *r;
302+ enum instkind op;
303+
304+ l = funcexpr(f, e->args);
305+ if(!e->args->next)
306+ return funcinst(f, INEG, 'l', l, nil);
307+ r = funcexpr(f, e->args->next);
308+ switch(e->tok.kind) {
309+ case TADD: op = IADD; break;
310+ case TSUB: op = ISUB; break;
311+ case TMUL: op = IMUL; break;
312+ case TDIV: op = IDIV; break;
313+ case TMOD: op = IREM; break;
314+ case TEQ: op = ICEQ; break;
315+ case TNEQ: op = ICNE; break;
316+ case TLESS: op = ICLT; break;
317+ case TMORE: op = ICGT; break;
318+ case TLEQ: op = ICLE; break;
319+ case TMEQ: op = ICGE; break;
320+ default:
321+ errorat(&e->tok.loc, "sorry, no idea how to compile this operator");
322+ }
323+ return funcinst(f, op, 'l', l, r);
324+}
325+
326+/* an arm's body, in tail position it returns or loops by itself,
327+ * otherwise its value goes in r and it jumps to join */
328+static void
329+funcarm(struct func *f, struct expr *body, struct operand *r, struct block *join, int tail) {
330+ if(tail) {
331+ functail(f, body);
332+ return;
333+ }
334+ funccopy(f, r, funcexpr(f, body));
335+ funcjmp(f, join);
336+}
337+
338+static struct operand *
339+funcjoin(struct func *f, struct operand *r, struct block *join, int tail) {
340+ funchlt(f);
341+ if(tail)
342+ return nil;
343+ funclabel(f, join);
344+ return r;
345+}
346+
347+static struct operand *
348+funcguard(struct func *f, struct expr *e, int tail) {
349+ struct operand *r;
350+ struct block *join;
351+ struct block *yes;
352+ struct block *no;
353+ struct arm *arm;
354+
355+ r = zalloc(sizeof(*r));
356+ functemp(f, r);
357+ join = mkblock("join");
358+ for(arm = e->arm; arm; arm = arm->next) {
359+ if(!arm->cond) {
360+ funcarm(f, arm->body, r, join, tail);
361+ break;
362+ }
363+ yes = mkblock("then");
364+ no = mkblock("next");
365+ funcjnz(f, funcexpr(f, arm->cond), yes, no);
366+ funclabel(f, yes);
367+ funcarm(f, arm->body, r, join, tail);
368+ funclabel(f, no);
369+ }
370+ return funcjoin(f, r, join, tail);
371+}
372+
373+static void
374+functest(struct func *f, struct operand *c, struct block *fail) {
375+ struct block *ok;
376+
377+ ok = mkblock("ok");
378+ funcjnz(f, c, ok, fail);
379+ funclabel(f, ok);
380+}
381+
382+static void
383+funcmatch(struct func *f, struct pat *p, struct operand *v, struct block *fail) {
384+ struct operand *t;
385+ struct operand *a;
386+ struct pat *x;
387+ usize i;
388+
389+ /* funcfree needs it later */
390+ p->qval = v;
391+ switch(p->kind) {
392+ case PWILD:
393+ break;
394+ case PNAME:
395+ p->binding->qval = v;
396+ break;
397+ case PNUM:
398+ functest(f, funcinst(f, ICEQ, 'l', v, mkconst(tonum(p->name))), fail);
399+ break;
400+ case PCON:
401+ /* builtins have no decl */
402+ if(p->binding == btrue) {
403+ functest(f, funcinst(f, ICNE, 'l', v, mkconst(0)), fail);
404+ break;
405+ }
406+ if(p->binding == bfalse) {
407+ functest(f, funcinst(f, ICEQ, 'l', v, mkconst(0)), fail);
408+ break;
409+ }
410+ if(p->binding == bcone)
411+ break;
412+ if(p->binding->decl->newtype) {
413+ funcmatch(f, p->args, v, fail);
414+ break;
415+ }
416+ t = funcinst(f, ICALL, 'l', mkglobal("k.tag"), nil);
417+ funcinst(f, IARG, 0, v, nil);
418+ functest(f, funcinst(f, ICEQ, 'l', t, mkconst(ctoridx(p->binding))), fail);
419+ for(x = p->args, i = 0; x; x = x->next, i++) {
420+ a = funcinst(f, IADD, 'l', v, mkconst(8 * (i + 1)));
421+ a = funcinst(f, ILOAD, 'l', a, nil);
422+ funcmatch(f, x, a, fail);
423+ }
424+ break;
425+ case PTUPLE:
426+ for(x = p->args, i = 0; x; x = x->next, i++) {
427+ a = funcinst(f, IADD, 'l', v, mkconst(8 * i));
428+ a = funcinst(f, ILOAD, 'l', a, nil);
429+ funcmatch(f, x, a, fail);
430+ }
431+ break;
432+ default:
433+ errorat(&p->name.loc, "sorry, can't compile this pattern yet");
434+ }
435+}
436+
437+static void
438+funcfreecell(struct func *f, struct operand *v) {
439+ funcinst(f, ICALL, 0, mkglobal("k.free"), nil);
440+ funcinst(f, IARG, 0, v, nil);
441+}
442+
443+static void
444+funcfree(struct func *f, struct pat *p, int borrowed) {
445+ struct pat *x;
446+
447+ switch(p->kind) {
448+ case PCON:
449+ if(!p->tilde)
450+ return;
451+ if(p->binding == btrue || p->binding == bfalse || p->binding == bcone)
452+ return;
453+ for(x = p->args; x; x = x->next)
454+ funcfree(f, x, 0);
455+ if(p->binding->decl->newtype || !p->args)
456+ return;
457+ funcfreecell(f, p->qval);
458+ break;
459+ case PTUPLE:
460+ if(borrowed)
461+ return;
462+ for(x = p->args; x; x = x->next)
463+ funcfree(f, x, 0);
464+ funcfreecell(f, p->qval);
465+ break;
466+ default:
467+ break;
468+ }
469+}
470+
471+static int
472+anytilde(struct expr *e) {
473+ struct arm *arm;
474+
475+ for(arm = e->arm; arm; arm = arm->next)
476+ if(arm->pat->tilde)
477+ return 1;
478+ return 0;
479+}
480+
481+static struct operand *
482+funccase(struct func *f, struct expr *e, int tail) {
483+ struct operand *r;
484+ struct operand *s;
485+ struct block *join;
486+ struct block *next;
487+ struct arm *arm;
488+ int borrowed;
489+
490+ /* only a variable without ~ arms is borrowed, a temporary
491+ * like case (a, b) of is gone after the case so we free it */
492+ borrowed = e->scrut->kind == EIDENT && !anytilde(e);
493+ r = zalloc(sizeof(*r));
494+ functemp(f, r);
495+ join = mkblock("join");
496+ s = funcexpr(f, e->scrut);
497+ for(arm = e->arm; arm; arm = arm->next) {
498+ next = mkblock("next");
499+ funcmatch(f, arm->pat, s, next);
500+ funcfree(f, arm->pat, borrowed);
501+ funcarm(f, arm->body, r, join, tail);
502+ funclabel(f, next);
503+ }
504+ return funcjoin(f, r, join, tail);
505+}
506+
507+static struct operand *
508+funcblock(struct func *f, struct expr *e, int tail) {
509+ struct val *v;
510+ struct block *fail;
511+ struct block *ok;
512+
513+ for(v = e->vals; v; v = v->next) {
514+ /* the checker makes sure val patterns can't fail */
515+ fail = mkblock("fail");
516+ ok = mkblock("ok");
517+ funcmatch(f, v->pat, funcexpr(f, v->init), fail);
518+ funcjmp(f, ok);
519+ funclabel(f, fail);
520+ funchlt(f);
521+ funclabel(f, ok);
522+ funcfree(f, v->pat, 0);
523+ }
524+ if(tail) {
525+ functail(f, e->body);
526+ return nil;
527+ }
528+ return funcexpr(f, e->body);
529+}
530+
531+static int
532+isselfcall(struct func *f, struct expr *e) {
533+ return e->kind == ECALL && e->tok.kind == TIDENT
534+ && e->binding->kind == BFN && e->binding->decl == f->decl;
535+}
536+
537+static void
538+functail(struct func *f, struct expr *e) {
539+ struct operand **args;
540+ struct operand *t;
541+ struct expr *a;
542+ usize n = 0;
543+ usize i;
544+
545+ switch(e->kind) {
546+ case EGUARD:
547+ funcguard(f, e, 1);
548+ return;
549+ case ECASE:
550+ funccase(f, e, 1);
551+ return;
552+ case EBLOCK:
553+ funcblock(f, e, 1);
554+ return;
555+ default:
556+ break;
557+ }
558+ if(!isselfcall(f, e)) {
559+ funcret(f, funcexpr(f, e));
560+ return;
561+ }
562+ for(a = e->args; a; a = a->next)
563+ n++;
564+ args = alloc(n * sizeof(*args));
565+ for(a = e->args, i = 0; a; a = a->next, i++)
566+ args[i] = funcexpr(f, a);
567+ for(i = 0; i < n; i++) {
568+ t = zalloc(sizeof(*t));
569+ functemp(f, t);
570+ funccopy(f, t, args[i]);
571+ args[i] = t;
572+ }
573+ for(i = 0; i < n; i++)
574+ funccopy(f, &f->params[i], args[i]);
575+ funcjmp(f, f->body);
576+}
577+
578+static struct operand *
579+funcexpr(struct func *f, struct expr *e) {
580+ switch(e->kind) {
581+ case ENUMBER:
582+ return mkconst(tonum(e->tok));
583+ case EIDENT:
584+ if(e->binding->kind == BFN)
585+ return mkglobal(e->binding->decl->qname);
586+ if(e->binding->kind == BPARAM || e->binding->kind == BPAT)
587+ return e->binding->qval;
588+ if(e->binding == btrue)
589+ return mkconst(1);
590+ if(e->binding == bfalse || e->binding == bcone)
591+ return mkconst(0);
592+ if(e->binding->kind == BCTOR)
593+ return mkconst(ctoridx(e->binding));
594+ errorat(&e->tok.loc, "sorry, can't compile this yet");
595+ case EBLOCK:
596+ return funcblock(f, e, 0);
597+ case EGUARD:
598+ return funcguard(f, e, 0);
599+ case ECASE:
600+ return funccase(f, e, 0);
601+ case ETUPLE:
602+ return functuple(f, e);
603+ case ECALL:
604+ if(e->tok.kind == TIDENT)
605+ return funccall(f, e);
606+ return funcop(f, e);
607+ default:
608+ errorat(&e->tok.loc, "sorry, can't compile this yet");
609+ }
610+ return nil;
611+}
612+
613+
614+
615+static struct func *
616+mkfunc(struct decl *d, const char *name) {
617+ struct func *f;
618+ struct param *p;
619+ usize i;
620+
621+ f = zalloc(sizeof(*f));
622+ f->decl = d;
623+ f->name = name;
624+ f->start = f->end = mkblock("start");
625+ for(p = d->params; p; p = p->next) {
626+ f->nparams++;
627+ }
628+ f->params = zalloc(f->nparams * sizeof(*f->params));
629+ /* each param gets a temp and its binding remembers which */
630+ for(i = 0, p = d->params; p; i++, p = p->next) {
631+ functemp(f, &f->params[i]);
632+ p->binding->qval = &f->params[i];
633+ }
634+ f->body = mkblock("body");
635+ funclabel(f, f->body);
636+ return f;
637+}
638+
639+static void
640+emitoperand(struct operand *v) {
641+ switch(v->kind) {
642+ case VTEMP:
643+ fputs("%t", stdout);
644+ putnum(v->id);
645+ break;
646+ case VCONST:
647+ if(v->i < 0) {
648+ fputs("-", stdout);
649+ putnum(-v->i);
650+ } else
651+ putnum(v->i);
652+ break;
653+ case VGLOBAL:
654+ fputs("$", stdout);
655+ fputs(v->name, stdout);
656+ break;
657+ case VLABEL:
658+ fputs("@", stdout);
659+ fputs(v->name, stdout);
660+ fputs(".", stdout);
661+ putnum(v->id);
662+ break;
663+ /* shouldnt happen */
664+ case VNONE:
665+ die("bad operand (qbe emission)");
666+ }
667+}
668+
669+/* print one instruction & return the next one to print */
670+static struct inst *
671+emitinst(struct inst *i) {
672+ struct inst *j;
673+ char c;
674+
675+ fputs("\t", stdout);
676+ if(i->res.kind != VNONE) {
677+ emitoperand(&i->res);
678+ fputs(" =", stdout);
679+ c = i->class;
680+ fwrite(&c, 1, 1, stdout);
681+ fputs(" ", stdout);
682+ }
683+ fputs(instname[i->kind], stdout);
684+ fputs(" ", stdout);
685+ emitoperand(i->arg[0]);
686+ if(i->kind == ICALL) {
687+ fputs("(", stdout);
688+ for(j = i->next; j && j->kind == IARG; j = j->next) {
689+ if(j != i->next)
690+ fputs(", ", stdout);
691+ fputs("l ", stdout);
692+ emitoperand(j->arg[0]);
693+ }
694+ fputs(")\n", stdout);
695+ return j;
696+ }
697+ if(i->arg[1]) {
698+ fputs(", ", stdout);
699+ emitoperand(i->arg[1]);
700+ }
701+ fputs("\n", stdout);
702+ return i->next;
703+}
704+
705+static void
706+emitjump(struct jump *j) {
707+ switch(j->kind) {
708+ case JNONE:
709+ break;
710+ case JJMP:
711+ fputs("\tjmp ", stdout);
712+ emitoperand(&j->block[0]->label);
713+ fputs("\n", stdout);
714+ break;
715+ case JJNZ:
716+ fputs("\tjnz ", stdout);
717+ emitoperand(j->arg);
718+ fputs(", ", stdout);
719+ emitoperand(&j->block[0]->label);
720+ fputs(", ", stdout);
721+ emitoperand(&j->block[1]->label);
722+ fputs("\n", stdout);
723+ break;
724+ case JRET:
725+ fputs("\tret ", stdout);
726+ emitoperand(j->arg);
727+ fputs("\n", stdout);
728+ break;
729+ case JHLT:
730+ fputs("\thlt\n", stdout);
731+ break;
732+ }
733+}
734+
735+static void
736+emitfunc(struct func *f) {
737+ struct block *b;
738+ struct inst *i;
739+ usize n;
740+
741+ /* header */
742+ fputs("function l $", stdout);
743+ fputs(f->name, stdout);
744+ fputs("(", stdout);
745+ for(n = 0; n < f->nparams; n++) {
746+ if(n > 0)
747+ fputs(", ", stdout);
748+ fputs("l ", stdout);
749+ emitoperand(&f->params[n]);
750+ }
751+ fputs(") {\n", stdout);
752+ /* blocks & their insts, jumps*/
753+ for(b = f->start; b; b = b->next) {
754+ emitoperand(&b->label);
755+ fputs("\n", stdout);
756+ for(i = b->insts; i; )
757+ i = emitinst(i);
758+ emitjump(&b->jump);
759+ }
760+ fputs("}\n\n", stdout);
761+}
762+
763+static const char runtime[] =
764+ "function l $k.alloc(l %n) {\n"
765+ "@start\n"
766+ "\t%p =l call $malloc(l %n)\n"
767+ "\tjnz %p, @ok, @fail\n"
768+ "@fail\n"
769+ "\thlt\n"
770+ "@ok\n"
771+ "\tret %p\n"
772+ "}\n"
773+ "\n"
774+ "function $k.free(l %p) {\n"
775+ "@start\n"
776+ "\tcall $free(l %p)\n"
777+ "\tret\n"
778+ "}\n"
779+ "\n"
780+ "function l $k.tag(l %p) {\n"
781+ "@start\n"
782+ "\t%small =w cultl %p, 4096\n"
783+ "\tjnz %small, @imm, @box\n"
784+ "@imm\n"
785+ "\tret %p\n"
786+ "@box\n"
787+ "\t%t =l loadl %p\n"
788+ "\tret %t\n"
789+ "}\n";
790+
791+static void
792+rt(void) {
793+ fputs(runtime, stdout);
794+}
795+
796+static const char *
797+mangle(const char *mod, struct token name) {
798+ stralloc sa = {0};
799+
800+ sacatl(&sa, "k.");
801+ sacatb(&sa, mod, strlen(mod));
802+ sacatl(&sa, ".");
803+ sacatb(&sa, name.str, name.length);
804+ sa0(&sa);
805+ return sa.s;
806+}
807+
808+/* ill just explain the symbol naming ting here
809+ * "thing.kav" > k.thing
810+ * "dir/thing.kav" > k.dir.thing
811+ * <thing.kav> > k.sys.thing
812+ * <dir/thing.kav> k.sys.dir.thing
813+ * anything not allowed gets turned to _ */
814+
815+static const char *
816+modname(struct module *m) {
817+ stralloc sa = {0};
818+ const char *s;
819+ char c;
820+
821+ if(m->sys)
822+ sacatl(&sa, "sys.");
823+ for(s = m->name; *s; s++) {
824+ c = *s;
825+ if(c == '/')
826+ c = '.';
827+ else if(!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z')
828+ && !(c >= '0' && c <= '9') && c != '_')
829+ c = '_';
830+ sacatb(&sa, &c, 1);
831+ }
832+ sa0(&sa);
833+ return sa.s;
834+}
835+
836+
837+void
838+qbe(struct module *m) {
839+ struct module *x, *y, *last = nil;
840+ struct decl *d;
841+ struct func *f;
842+
843+ for(x = m; x; x = x->next) {
844+ x->qname = modname(x);
845+ for(y = m; y != x; y = y->next)
846+ if(!strcmp(y->qname, x->qname))
847+ die("modules ", y->path, " and ", x->path, " have the same name");
848+ for(d = x->decls; d; d = d->next)
849+ if(d->kind == DFN)
850+ d->qname = mangle(x->qname, d->name);
851+ }
852+
853+ for(x = m; x; x = x->next) {
854+ last = x;
855+ for(d = x->decls; d; d = d->next) {
856+ if(d->kind != DFN)
857+ continue;
858+ f = mkfunc(d, d->qname);
859+ functail(f, d->body);
860+ emitfunc(f);
861+ }
862+ }
863+
864+ /* the c entry point calls main in the root module */
865+ for(d = last->decls; d; d = d->next)
866+ if(d->kind == DFN && tokis(d->name, "main"))
867+ break;
868+ if(!d)
869+ die("no entry point found");
870+ fputs("export function w $main() {\n", stdout);
871+ fputs("@start\n", stdout);
872+ fputs("\t%r =l call $", stdout);
873+ fputs(d->qname, stdout);
874+ fputs("()\n", stdout);
875+ fputs("\tret %r\n", stdout);
876+ fputs("}\n\n", stdout);
877+ rt();
878+}
M
run.c
+0,
-10
1@@ -61,16 +61,6 @@ mkbool(int b) {
2 return mkcon(b ? btrue : bfalse);
3 }
4
5-static i64
6-tonum(struct token t) {
7- i64 n = 0;
8- usize i;
9-
10- for(i = 0; i < t.length; i++)
11- n = n * 10 + (t.str[i] - '0');
12- return n;
13-}
14-
15 struct env {
16 struct env *next;
17 struct binding *binding;
M
util.c
+18,
-0
1@@ -134,6 +134,24 @@ fmtusize(char *s, usize u) {
2 return len;
3 }
4
5+void
6+putnum(usize u) {
7+ char num[FMTUSIZE];
8+
9+ fwrite(num, 1, fmtusize(num, u), stdout);
10+}
11+
12+/* the value of a number token */
13+i64
14+tonum(struct token t) {
15+ i64 n = 0;
16+ usize i;
17+
18+ for(i = 0; i < t.length; i++)
19+ n = n * 10 + (t.str[i] - '0');
20+ return n;
21+}
22+
23 char *
24 tokdup(struct token t) {
25 char *s;
M
util.h
+1,
-0
1@@ -43,3 +43,4 @@ int openreadclose(const char *, stralloc *);
2
3 #define FMTUSIZE 20
4 usize fmtusize(char *, usize);
5+void putnum(usize);