commit d4f2f64
shrub
·
2026-11-17 12:54:41 +0000 UTC
parent d4f2f64
initial import
36 files changed,
+3654,
-0
A
LICENSE
+16,
-0
1@@ -0,0 +1,16 @@
2+Copyright (c) 2026 SHRUB900 <maybeshrub@gmail.com>
3+
4+Permission to use, copy, modify, and distribute this software for any
5+purpose with or without fee is hereby granted, provided that the above
6+copyright notice and this permission notice appear in all copies.
7+
8+The Software shall be used for Good, not Evil.
9+
10+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17+
A
Makefile
+25,
-0
1@@ -0,0 +1,25 @@
2+.POSIX:
3+
4+CC = cc
5+CPP = $(CC) -E
6+CFLAGS = -std=c11 -O2 -Wall -Wextra -pedantic -Wno-implicit-fallthrough -Wno-parentheses
7+OBJ = main.o util.o lex.o parse.o ast.o resolve.o \
8+ run.o check.o type.o module.o linear.o
9+HDR = util.h kav.h tokens.h punc.h kws.h exprs.h builtins.h
10+
11+.PHONY: all clean
12+
13+all : kav
14+kav: $(OBJ)
15+ $(CC) $(LDFLAGS) -o $@ $^
16+
17+lex.c: lex.re rules.re
18+ re2c -W -o $@ lex.re
19+
20+rules.re: rules.h kws.h punc.h
21+ $(CPP) -P -x c rules.h > $@
22+
23+$(OBJ): $(HDR)
24+main.o: arg.h
25+
26+clean: ; rm -f kav rules.re lex.c $(OBJ)
A
README
+5,
-0
1@@ -0,0 +1,5 @@
2++++
3+KAV
4++++
5+
6+a programming language!
A
TODO
+8,
-0
1@@ -0,0 +1,8 @@
2+qbe codegen
3+pragmas
4+incremental
5+first calss functions
6+sort arrows
7+doc comments
8+struct stuff
9+solver
A
arg.h
+19,
-0
1@@ -0,0 +1,19 @@
2+#define ARGBEGIN \
3+ for(;;) { \
4+ if(argc > 0) \
5+ ++argv, --argc; \
6+ if(argc == 0 || (*argv)[0] != '-') \
7+ break; \
8+ if((*argv)[1] == '-' && !(*argv)[2]) { \
9+ ++argv, --argc; \
10+ break; \
11+ } \
12+ for(char *opt_ = &(*argv)[1], done_ = 0; !done_ && *opt_; ++opt_) { \
13+ switch(*opt_)
14+
15+#define ARGEND \
16+ } \
17+ }
18+
19+#define EARGF(x) \
20+ (done_ = 1, opt_[1] ? ++opt_ : argv[1] ? --argc, *++argv : ((x), abort(), (char *)0))
A
ast.c
+333,
-0
1@@ -0,0 +1,333 @@
2+#include <stdio.h>
3+
4+#include "util.h"
5+#include "kav.h"
6+
7+static void paramsput(struct param *p);
8+
9+struct expr *
10+mkexpr(enum exprkind kind, struct token tok) {
11+ struct expr *e;
12+
13+ e = zalloc(sizeof(*e));
14+ e->kind = kind;
15+ e->tok = tok;
16+ return e;
17+}
18+
19+struct expr *
20+mkbinary(struct token op, struct expr *l, struct expr *r) {
21+ struct expr *e;
22+
23+ e = mkexpr(ECALL, op);
24+ e->args = l;
25+ l->next = r;
26+ return e;
27+}
28+
29+struct arm *
30+mkarm(struct location loc) {
31+ struct arm *a;
32+
33+ a = zalloc(sizeof(*a));
34+ a->loc = loc;
35+ return a;
36+}
37+
38+
39+struct val *
40+mkval(struct pat *pat) {
41+ struct val *v;
42+
43+ v = zalloc(sizeof(*v));
44+ v->pat = pat;
45+ return v;
46+}
47+
48+struct param *
49+mkparam(struct token name) {
50+ struct param *p;
51+
52+ p = zalloc(sizeof(*p));
53+ p->name = name;
54+ return p;
55+}
56+
57+struct ctor *
58+mkctor(struct token name) {
59+ struct ctor *c;
60+
61+ c = zalloc(sizeof(*c));
62+ c->name = name;
63+ return c;
64+}
65+
66+struct decl *
67+mkdecl(enum declkind kind, struct token name) {
68+ struct decl *d;
69+
70+ d = zalloc(sizeof(*d));
71+ d->name = name;
72+ d->kind = kind;
73+ return d;
74+}
75+
76+struct pat *
77+mkpat(enum patkind kind, struct token name) {
78+ struct pat *p;
79+
80+ p = zalloc(sizeof(*p));
81+ p->name = name;
82+ p->kind = kind;
83+ return p;
84+}
85+
86+struct binding *
87+mkbinding(enum bindkind kind, struct token name) {
88+ struct binding *b;
89+
90+ b = zalloc(sizeof(*b));
91+ b->name = name;
92+ b->kind = kind;
93+ return b;
94+}
95+
96+
97+static void
98+nsput(struct token ns) {
99+ if(ns.kind != TNONE) {
100+ fwrite(ns.str, 1, ns.length, stdout);
101+ fputs("::", stdout);
102+ }
103+}
104+
105+static void
106+patput(struct pat *p) {
107+ struct pat *a;
108+
109+ if(p->tilde)
110+ fputs("~", stdout);
111+ switch(p->kind) {
112+ case PWILD:
113+ fputs("_", stdout);
114+ break;
115+ case PNAME:
116+ nsput(p->ns);
117+ fwrite(p->name.str, 1, p->name.length, stdout);
118+ break;
119+ case PCON:
120+ fputs("(", stdout);
121+ nsput(p->ns);
122+ fwrite(p->name.str, 1, p->name.length, stdout);
123+ for(a = p->args; a; a = a->next) {
124+ fputs(" ", stdout);
125+ patput(a);
126+ }
127+ fputs(")", stdout);
128+ break;
129+ case PTUPLE:
130+ fputs("(tuple", stdout);
131+ for(a = p->args; a; a = a->next) {
132+ fputs(" ", stdout);
133+ patput(a);
134+ }
135+ fputs(")", stdout);
136+ break;
137+ case PNUM:
138+ fwrite(p->name.str, 1, p->name.length, stdout);
139+ break;
140+ }
141+}
142+
143+static void
144+exprput(struct expr *e) {
145+ struct expr *a;
146+ struct val *v;
147+ struct arm *r;
148+
149+ switch(e->kind) {
150+ case EIDENT:
151+ case ENUMBER:
152+ case ESTRING:
153+ case EHOLE:
154+ nsput(e->ns);
155+ fwrite(e->tok.str, 1, e->tok.length, stdout);
156+ break;
157+ case ECALL:
158+ case ESAPP:
159+ fputs("(", stdout);
160+ nsput(e->ns);
161+ fwrite(e->tok.str, 1, e->tok.length, stdout);
162+ for(a = e->args; a; a = a->next) {
163+ fputs(" ", stdout);
164+ exprput(a);
165+ }
166+ fputs(")", stdout);
167+ break;
168+ case ETUPLE:
169+ fputs("(tuple", stdout);
170+ for(a = e->args; a; a = a->next) {
171+ fputs(" ", stdout);
172+ exprput(a);
173+ }
174+ fputs(")", stdout);
175+ break;
176+ case EBLOCK:
177+ fputs("(block", stdout);
178+ for(v = e->vals; v; v = v->next) {
179+ fputs(" (val ", stdout);
180+ patput(v->pat);
181+ fputs(" ", stdout);
182+ exprput(v->init);
183+ fputs(")", stdout);
184+ }
185+ fputs(" ", stdout);
186+ exprput(e->body);
187+ fputs(")", stdout);
188+ break;
189+ case EGUARD:
190+ fputs("(guard", stdout);
191+ for(r = e->arm; r; r = r->next) {
192+ fputs(" (", stdout);
193+ if(!r->cond)
194+ fputs("else", stdout);
195+ else
196+ exprput(r->cond);
197+ fputs(" ", stdout);
198+ exprput(r->body);
199+ fputs(")", stdout);
200+ }
201+ fputs(")", stdout);
202+ break;
203+ case ECASE:
204+ fputs("(case ", stdout);
205+ exprput(e->scrut);
206+ for(r = e->arm; r; r = r->next) {
207+ fputs(" (", stdout);
208+ patput(r->pat);
209+ fputs(" ", stdout);
210+ exprput(r->body);
211+ fputs(")", stdout);
212+ }
213+ fputs(")", stdout);
214+ break;
215+ case EEXISTS:
216+ fputs("(exist ", stdout);
217+ paramsput(e->sparams);
218+ fputs(" ", stdout);
219+ exprput(e->body);
220+ fputs(")", stdout);
221+ break;
222+ case EBORROW:
223+ fputs("(! ", stdout);
224+ exprput(e->body);
225+ fputs(")", stdout);
226+ break;
227+ default:
228+ fputs("[?]", stdout);
229+ break;
230+ }
231+}
232+
233+static void
234+paramsput(struct param *p) {
235+ struct param *i;
236+
237+ fputs("(", stdout);
238+ for(i = p; i; i = i->next) {
239+ if(i != p)
240+ fputs(" ", stdout);
241+ fputs("(", stdout);
242+ fwrite(i->name.str, 1, i->name.length, stdout);
243+ fputs(" ", stdout);
244+ exprput(i->ann);
245+ if(i->cond) {
246+ fputs(" ", stdout);
247+ exprput(i->cond);
248+ }
249+ fputs(")", stdout);
250+ }
251+ fputs(")", stdout);
252+}
253+
254+
255+void
256+declput(struct decl *d) {
257+ struct ctor *c;
258+ struct expr *a;
259+ fputs("(", stdout);
260+ if(d->pub)
261+ fputs("pub ", stdout);
262+ if(d->linear)
263+ fputs("linear ", stdout);
264+ switch(d->kind) {
265+ case DFN:
266+ fputs("fn ", stdout);
267+ fwrite(d->name.str, 1, d->name.length, stdout);
268+ fputs(" ", stdout);
269+ paramsput(d->sparams);
270+ fputs(" ", stdout);
271+ paramsput(d->params);
272+ fputs(" ", stdout);
273+ exprput(d->ret);
274+ fputs(" ", stdout);
275+ exprput(d->body);
276+ break;
277+ case DSTRUCT:
278+ fputs("struct ", stdout);
279+ fwrite(d->name.str, 1, d->name.length, stdout);
280+ fputs(" ", stdout);
281+ paramsput(d->params);
282+ break;
283+ case DDATA:
284+ fputs("datatype ", stdout);
285+ fwrite(d->name.str, 1, d->name.length, stdout);
286+ fputs(" ", stdout);
287+ paramsput(d->sparams);
288+ for(c = d->ctors; c; c = c->next) {
289+ fputs(" (", stdout);
290+ fwrite(c->name.str, 1, c->name.length, stdout);
291+ fputs(" ", stdout);
292+ paramsput(c->sparams);
293+ fputs(" ", stdout);
294+ fputs("(", stdout);
295+ for(a = c->args; a; a = a->next) {
296+ if(a != c->args)
297+ fputs(" ", stdout);
298+ exprput(a);
299+ }
300+ fputs(")", stdout);
301+ fputs(" ", stdout);
302+ if(c->ret)
303+ exprput(c->ret);
304+ fputs(")", stdout);
305+ }
306+ break;
307+ case DTYPEDEF:
308+ fputs("typedef ", stdout);
309+ fwrite(d->name.str, 1, d->name.length, stdout);
310+ fputs(" ", stdout);
311+ paramsput(d->sparams);
312+ fputs(" ", stdout);
313+ exprput(d->ret);
314+ break;
315+ case DSORTDEF:
316+ fputs("sortdef ", stdout);
317+ fwrite(d->name.str, 1, d->name.length, stdout);
318+ fputs(" ", stdout);
319+ if(d->sparams)
320+ paramsput(d->sparams);
321+ if(d->ret)
322+ exprput(d->ret);
323+ break;
324+ case DUSE:
325+ fputs("use ", stdout);
326+ fwrite(d->name.str, 1, d->name.length, stdout);
327+ if(d->alias.kind != TNONE) {
328+ fputs(" as ", stdout);
329+ fwrite(d->alias.str, 1, d->alias.length, stdout);
330+ }
331+ break;
332+ }
333+ fputs(")", stdout);
334+}
+12,
-0
1@@ -0,0 +1,12 @@
2+BUILTIN(STYPE, BTYPE, "int", bint)
3+BUILTIN(STYPE, BTYPE, "bool", bbool)
4+BUILTIN(STYPE, BTYPE, "one", bone)
5+
6+BUILTIN(SSORT, BSORT, "type", btype)
7+BUILTIN(SSORT, BSORT, "utype", butype)
8+BUILTIN(SSORT, BSORT, "int", bsint)
9+BUILTIN(SSORT, BSORT, "bool", bsbool)
10+
11+BUILTIN(SVALUE, BCTOR, "one", bcone)
12+BUILTIN(SVALUE, BCTOR, "true", btrue)
13+BUILTIN(SVALUE, BCTOR, "false", bfalse)
A
check.c
+398,
-0
1@@ -0,0 +1,398 @@
2+#include "util.h"
3+#include "kav.h"
4+
5+struct blank {
6+ struct blank *next;
7+ struct type *meta;
8+ struct location loc;
9+ int unrestricted;
10+};
11+
12+static struct blank *blanks;
13+
14+static int
15+istypesort(struct expr *ann) {
16+ return ann->kind == EIDENT && (ann->binding == btype || ann->binding == butype);
17+}
18+
19+static struct type *
20+totype(struct expr *e) {
21+ struct type *t;
22+ struct type *a;
23+ struct type *head = nil;
24+ struct type **end = &head;
25+ struct expr *x;
26+ struct param *sp;
27+
28+ switch(e->kind) {
29+ case EIDENT:
30+ if(e->binding->kind == BPARAM)
31+ return mktype(YVAR, e->binding);
32+ else
33+ return mktype(YNAME, e->binding);
34+ case ETUPLE:
35+ t = mktype(YTUPLE, nil);
36+ for(x = e->args; x; x = x->next) {
37+ a = totype(x);
38+ *end = a;
39+ end = &a->next;
40+ }
41+ t->args = head;
42+ return t;
43+ case ESAPP:
44+ t = mktype(YNAME, e->binding);
45+ /* walk the type's sort params alongside, builtin types have no decl */
46+ sp = e->binding->decl ? e->binding->decl->sparams : nil;
47+ for(x = e->args; x; x = x->next, sp = sp ? sp->next : nil) {
48+ /* solver later */
49+ if(sp && !istypesort(sp->ann))
50+ continue;
51+ a = totype(x);
52+ *end = a;
53+ end = &a->next;
54+ }
55+ t->args = head;
56+ return t;
57+ case EBORROW:
58+ t = totype(e->body);
59+ t->borrow = 1;
60+ return t;
61+ case EEXISTS:
62+ return totype(e->body);
63+ default:
64+ errorat(&e->tok.loc, "not a type");
65+ }
66+}
67+
68+static struct type *
69+fnsig(struct decl *d) {
70+ struct type *params = nil;
71+ struct type **link = ¶ms;
72+ struct param *p;
73+
74+ for(p = d->params; p; p = p->next) {
75+ *link = totype(p->ann);
76+ link = &(*link)->next;
77+ }
78+ return mkfntype(params, totype(d->ret));
79+}
80+
81+/* constructors, what it builds if it takes nothing, else fn(args) -> what it builds */
82+static struct type *
83+ctorsig(struct decl *d, struct ctor *c) {
84+ struct type *params = nil;
85+ struct type **link = ¶ms;
86+ struct type *ret;
87+ struct type **rlink;
88+ struct param *sp;
89+ struct expr *x;
90+
91+ if(c->ret) {
92+ ret = totype(c->ret);
93+ } else {
94+ ret = mktype(YNAME, d->binding);
95+ rlink = &ret->args;
96+ for(sp = d->sparams; sp; sp = sp->next) {
97+ if(!istypesort(sp->ann))
98+ errorat(&c->name.loc, "constructor needs a result type");
99+ *rlink = mktype(YVAR, sp->binding);
100+ rlink = &(*rlink)->next;
101+ }
102+ }
103+ if(!c->args)
104+ return ret;
105+ for(x = c->args; x; x = x->next) {
106+ *link = totype(x);
107+ link = &(*link)->next;
108+ }
109+ return mkfntype(params, ret);
110+}
111+
112+static void
113+sigs(struct decl *d) {
114+ struct ctor *c;
115+
116+ for(; d; d = d->next) {
117+ switch(d->kind) {
118+ case DFN:
119+ d->binding->type = fnsig(d);
120+ break;
121+ case DDATA:
122+ for(c = d->ctors; c; c = c->next)
123+ c->binding->type = ctorsig(d, c);
124+ break;
125+ default:
126+ break;
127+ }
128+ }
129+}
130+
131+
132+static struct type *
133+instantiate(struct binding *b, struct location *loc) {
134+ struct type *metas = nil;
135+ struct type **link = &metas;
136+ struct param *p;
137+ struct blank *k;
138+
139+ if(!b->decl || !b->decl->sparams)
140+ return b->type;
141+ for(p = b->decl->sparams; p; p = p->next) {
142+ *link = mkmeta();
143+ if(istypesort(p->ann)) {
144+ k = alloc(sizeof(*k));
145+ k->meta = *link;
146+ k->loc = *loc;
147+ k->next = blanks;
148+ k->unrestricted = p->ann->binding == butype;
149+ blanks = k;
150+ }
151+ link = &(*link)->next;
152+ }
153+ return subst(b->type, b->decl->sparams, metas);
154+}
155+
156+
157+static void
158+bindpat(struct pat *p, struct type *t) {
159+ struct pat *a;
160+ struct type *y;
161+ struct type *u;
162+
163+ t = deref(t);
164+ /* record the type we match */
165+ p->type = t;
166+ switch(p->kind) {
167+ case PWILD:
168+ break;
169+ case PNAME:
170+ p->binding->type = t;
171+ break;
172+ case PNUM:
173+ u = mktype(YNAME, bint);
174+ if(!unify(u, t))
175+ errorat(&p->name.loc, "type mismatch: expected ", typestr(t), ", got ", typestr(u));
176+ break;
177+ case PTUPLE:
178+ if(t->kind != YTUPLE)
179+ errorat(&p->name.loc, "tuple pattern, but value has type ", typestr(t));
180+ for(a = p->args, y = t->args; a && y; a = a->next, y = y->next)
181+ bindpat(a, y);
182+ if(a)
183+ errorat(&a->name.loc, "tuple pattern has too many elements");
184+ if(y)
185+ errorat(&p->name.loc, "tuple pattern has too few elements");
186+ break;
187+ case PCON:
188+ /* a constructor taking args has a fn type so match its result, pair its params with the sub patterns */
189+ u = instantiate(p->binding, &p->name.loc);
190+ y = nil;
191+ if(u->kind == YFN) {
192+ y = u->args;
193+ u = u->ret;
194+ }
195+ if(!unify(u, t))
196+ errorat(&p->name.loc, "type mismatch: expected ", typestr(t), ", got ", typestr(u));
197+ for(a = p->args; a && y; a = a->next, y = y->next)
198+ bindpat(a, y);
199+ if(a)
200+ errorat(&a->name.loc, "pattern has too many arguments");
201+ if(y)
202+ errorat(&p->name.loc, "pattern has too few arguments");
203+ break;
204+ }
205+}
206+
207+static struct type *trup(struct expr *);
208+static void trdn(struct expr *, struct type *);
209+
210+/* type a block's vals and give the names in their patterns types */
211+static void
212+vals(struct expr *e) {
213+ struct val *v;
214+ struct type *t;
215+
216+ for(v = e->vals; v; v = v->next) {
217+ /* use the annotation */
218+ if(v->ann) {
219+ t = totype(v->ann);
220+ trdn(v->init, t);
221+ } else {
222+ t = trup(v->init);
223+ }
224+ bindpat(v->pat, t);
225+ }
226+}
227+
228+static void
229+casepats(struct expr *e) {
230+ struct type *t;
231+ struct arm *arm;
232+
233+ t = trup(e->scrut);
234+ for(arm = e->arm; arm; arm = arm->next)
235+ bindpat(arm->pat, t);
236+}
237+
238+/* every guard cond must be bool */
239+static void
240+guardconds(struct expr *e) {
241+ struct arm *arm;
242+
243+ for(arm = e->arm; arm; arm = arm->next)
244+ if(arm->cond)
245+ trdn(arm->cond, mktype(YNAME, bbool));
246+}
247+
248+static struct type *
249+armsup(struct expr *e) {
250+ struct arm *arm;
251+ struct type *bt;
252+
253+ bt = trup(e->arm->body);
254+ for(arm = e->arm->next; arm; arm = arm->next)
255+ trdn(arm->body, bt);
256+ return bt;
257+}
258+
259+static void
260+trdn(struct expr *e, struct type *t) {
261+ struct type *u;
262+ struct arm *arm;
263+
264+ switch(e->kind) {
265+ case EBLOCK:
266+ vals(e);
267+ trdn(e->body, t);
268+ break;
269+ case ECASE:
270+ casepats(e);
271+ for(arm = e->arm; arm; arm = arm->next)
272+ trdn(arm->body, t);
273+ break;
274+ case EGUARD:
275+ guardconds(e);
276+ for(arm = e->arm; arm; arm = arm->next)
277+ trdn(arm->body, t);
278+ break;
279+ default:
280+ u = trup(e);
281+ if(!unify(u, t))
282+ errorat(&e->tok.loc, "type mismatch: expected ", typestr(t), ", got ", typestr(u));
283+ }
284+ e->type = t;
285+}
286+
287+
288+static struct type *
289+apply(struct expr *e) {
290+ struct type *ft;
291+ struct type *y;
292+ struct expr *a;
293+
294+ if(e->tok.kind != TIDENT) {
295+ for(a = e->args; a; a = a->next)
296+ trdn(a, mktype(YNAME, bint));
297+ switch(e->tok.kind) {
298+ case TEQ:
299+ case TNEQ:
300+ case TLEQ:
301+ case TLESS:
302+ case TMORE:
303+ case TMEQ:
304+ return mktype(YNAME, bbool);
305+ default:
306+ return mktype(YNAME, bint);
307+ }
308+ }
309+
310+ ft = instantiate(e->binding, &e->tok.loc);
311+ if(!ft || ft->kind != YFN)
312+ errorat(&e->tok.loc, "not a function or constructor");
313+
314+ for(a = e->args, y = ft->args; a && y; a = a->next, y = y->next)
315+ trdn(a, y);
316+ if(a)
317+ errorat(&a->tok.loc, "arity mismatch: too many arguments");
318+ if(y)
319+ errorat(&e->tok.loc, "arity mismatch: too few arguments");
320+ return ft->ret;
321+}
322+
323+
324+static struct type *
325+trup(struct expr *e) {
326+ struct type *t;
327+ struct type **link;
328+ struct expr *a;
329+
330+ switch(e->kind) {
331+ case ENUMBER:
332+ return e->type = mktype(YNAME, bint);
333+ case EIDENT:
334+ if(!e->binding->type)
335+ errorat(&e->tok.loc, "sorry, cant type this yet");
336+ if(e->binding->kind == BFN || e->binding->kind == BCTOR)
337+ return e->type = instantiate(e->binding, &e->tok.loc);
338+ return e->type = e->binding->type;
339+ case EBLOCK:
340+ vals(e);
341+ return e->type = trup(e->body);
342+ case ECALL:
343+ return e->type = apply(e);
344+ case ETUPLE:
345+ t = mktype(YTUPLE, nil);
346+ link = &t->args;
347+ for(a = e->args; a; a = a->next) {
348+ *link = tydup(trup(a));
349+ link = &(*link)->next;
350+ }
351+ return e->type = t;
352+ default:
353+ errorat(&e->tok.loc, "sorry, can't type this yet");
354+ case EGUARD:
355+ guardconds(e);
356+ return e->type = armsup(e);
357+ case ECASE:
358+ casepats(e);
359+ return e->type = armsup(e);
360+ }
361+}
362+
363+static void
364+checkfn(struct decl *d) {
365+ struct param *p;
366+ struct type *y;
367+
368+ for(p = d->params, y = d->binding->type->args; p; p = p->next, y = y->next)
369+ p->binding->type = y;
370+ trdn(d->body, d->binding->type->ret);
371+}
372+
373+
374+void
375+check(struct module *m) {
376+ struct module *x;
377+ struct decl *d;
378+ struct blank *k;
379+
380+ btrue->type = mktype(YNAME, bbool);
381+ bfalse->type = mktype(YNAME, bbool);
382+ bcone->type = mktype(YNAME, bone);
383+ for(x = m; x; x = x->next)
384+ sigs(x->decls);
385+ for(x = m; x; x = x->next) {
386+ for(d = x->decls; d; d = d->next) {
387+ if(d->kind != DFN)
388+ continue;
389+ blanks = nil;
390+ checkfn(d);
391+ for(k = blanks; k; k = k->next) {
392+ if(deref(k->meta)->kind == YMETA)
393+ errorat(&k->loc, "cannot infer type, add an annotation");
394+ if(k->unrestricted && islinear(k->meta))
395+ errorat(&k->loc, "expected unrestricted type, got linear '", typestr(k->meta), "'");
396+ }
397+ }
398+ }
399+}
+15,
-0
1@@ -0,0 +1,15 @@
2+use "prelude.kav"
3+use "list.kav"
4+
5+fn bad[n: nat](l: List[int, n]) -> int {
6+ case l of {
7+ | Nil => {
8+ val u = list_free(l)
9+ 0
10+ }
11+ | Cons(x, r) => {
12+ val u = list_free(l)
13+ x
14+ }
15+ }
16+}
+13,
-0
1@@ -0,0 +1,13 @@
2+datatype Coin {
3+ | Heads
4+ | Tails
5+}
6+
7+fn pick(b: bool) -> Coin {
8+ if b then Heads else Tails
9+}
10+
11+fn main() -> int {
12+ val c = pick(false)
13+ 7
14+}
+28,
-0
1@@ -0,0 +1,28 @@
2+datatype Color {
3+ | Red
4+ | Green
5+ | Blue
6+}
7+
8+
9+fn next(c: Color) -> Color {
10+ case c of {
11+ | Red => Green
12+ | Green => Blue
13+ | Blue => Red
14+ }
15+}
16+
17+fn col2int(c: Color) -> int {
18+ case c of {
19+ | Red => 1
20+ | Green => 2
21+ | Blue => 3
22+ }
23+}
24+
25+pub fn main() -> int {
26+ val c = next(Red)
27+ val d = next(c)
28+ col2int(c) + col2int(d)
29+}
+131,
-0
1@@ -0,0 +1,131 @@
2+KAV is a statically typed, purely functional systems language making use of linear types, and dependent types.
3+
4+
5+// line comment
6+/* block comment */
7+/% doc comment %/
8+
9+list.kav
10+--------
11+
12+/* doc comments are only allowed above pub functions */
13+/% a linearly typed singly linked list of either linear or non linear elements, of length n %/
14+pub linear datatype List[a: type, n: nat] {
15+ | Nil : List[a, 0]
16+ | [m: nat] Cons(a, List[a, m]) : List[a, m+1]
17+}
18+
19+/* you could actually do this much easier by just doing List[a, n + 1] , but example for examples sake */
20+/% a linearly typed singly linked list of either linear or non linear elements, of length n where n > 0 %/
21+pub linear datatype List1[a: type, n: nat | n > 0] { // prob will have a pos sort as shorthand for [n: nat | n > 0 ], so just [n: pos]
22+ | One(a) : List1[a, 0]
23+ | [m: nat] More(a, List1[a, m]) : List1[a, m+1]
24+}
25+
26+
27+/% free a linearly typed singly linked list of non-linear elements %/
28+pub fn list_free[a: utype, n: nat](list: List[a, n]) -> one {
29+ case list of {
30+ /* ~ consumes the list wrapper */
31+ | ~Nil => ()
32+ | ~Cons(_, rest) => list_free(rest)
33+ }
34+}
35+
36+
37+main.kav
38+--------
39+
40+/* import pub functions from a local file. */
41+use "list.kav"
42+/* you could also do 'use "list.kav" as list' to namespace it*/
43+/* std library search: 'use <std.kav>' */
44+
45+/* i think it will be optional to use all the sorts. like you could just remove n and m from here and it will still be allowed.
46+ * but in a case where you need to be presice, you can have them. */
47+fn reverse[a: type,n: nat, m: nat](l: List[a, n], acc: List[a, m]) -> List[a, n + m] {
48+ case l of {
49+ | ~Nil => acc
50+ | ~Cons(entry, rest) => reverse(rest, Cons(entry, acc))
51+ }
52+}
53+
54+/* one is similar to void in that it produces no result but it's not called void because it can't have side effects on any mutable
55+ * global state, its more like a bool except with only one option */
56+/% main has to be public so the language runtime can reach it. %/
57+pub fn main() -> one {
58+ /* we dont care about restricting the list length here so hopefully the checker will fill it for us */
59+ /* we could even drop the type declaration entirely and it would recognise something constucted of 3 cons with ints
60+ * is List[int, 3] */
61+ val list: List[int, _] = Cons(1, Cons(2, Cons(3, Nil)))
62+ val reversed = reverse(list, Nil) /* again, we dont need to declare the type of reversed, it will be inferred from reverse's sig*/
63+ list_free(reversed)
64+}
65+
66+other langauge features
67+-----------------------
68+
69+/% a type alias for int. int's and numbers are interchangeable. a function that takes one as an argument can also take the other. %/
70+pub typedef number = int
71+
72+/% a nominal type. int and id have the same internal representation, an id is at it's core an int, but
73+ % functions that take id's cannot take ints and vice versa. %/
74+pub newtype id = int
75+/* constuctor to make an id of int 42 */
76+/* val u = id(42) */
77+/* unwrap
78+ case u of {
79+ | id(n) => // do something
80+ }
81+*/
82+
83+/* guard syntax */
84+fn howbigisx(x: int) -> int {
85+ guard {
86+ | x == 0 => 0
87+ | x < 5 => 5
88+ | _ => 100 /* else */
89+ }
90+}
91+
92+/* comptime execution of a pure function with a value known at compile time */
93+fn factorial(n: int) -> int {
94+ if n <= 1 then 1
95+ else n * factorial(n - 1)
96+}
97+
98+fn main() -> int {
99+ comptime factorial(5)
100+}
101+
102+/* structs */
103+/% a utype struct of utype elements %/
104+pub struct Point {
105+ x: int,
106+ y: int
107+}
108+
109+fn right(p: Point) -> Point {
110+ p with { x = p.x + 1 } // construct a new Point based on the one taken as an argument and return it.
111+}
112+
113+pub fn main() -> one {
114+ val p: Point = Point { x = 5, y = 10 }
115+ val q = right(p)
116+ ()
117+}
118+
119+
120+cli commands
121+------------
122+
123+kav build main.kav | -> lexes -> parses -> resolve imported funcs -> AST -> type check -> QBE -> native exe
124+kav doc list.kav | ->
125+
126+ pub linear datatype List[a: type, n: nat]
127+ a linearly typed singly linked list of either linear or non linear elements, of length n
128+
129+
130+ pub fn list_free[a: utype, n: nat](list: List[a, n]) -> one
131+ free a linearly typed singly linked list of non-linear elements, of length n
132+
+24,
-0
1@@ -0,0 +1,24 @@
2+use "prelude.kav"
3+use "list.kav"
4+
5+fn evens[n: nat](l: List[int, n]) -> [m: nat] List[int, m] {
6+ case l of {
7+ | ~Nil => Nil
8+ | ~Cons(x, rest) => if x % 2 == 0 then Cons(x, evens(rest)) else evens(rest)
9+ }
10+}
11+
12+fn sum[n: nat](l: !List[int, n]) -> int {
13+ case l of {
14+ | Nil => 0
15+ | Cons(x, rest) => x + sum(rest)
16+ }
17+}
18+
19+fn main() -> int {
20+ val l = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
21+ val e: [m: nat] List[int, m] = evens(l)
22+ val s = sum(e)
23+ val u = list_free(e)
24+ s
25+}
+37,
-0
1@@ -0,0 +1,37 @@
2+//line comment
3+/* block comment */
4+
5+newtype id = int
6+
7+sortdef nat = [n: int | n >= 0]
8+
9+typedef List1[a: type, n: type] = List[a, n + 1]
10+
11+pub linear datatype List[a: type, n: nat] {
12+ | Nil : List[a, 0]
13+ | [m: nat] Cons(a, List[a, m]) : List[a, m+1]
14+}
15+
16+pub struct Point {
17+ x: int,
18+ y: int
19+}
20+
21+fn factorial(n: int) -> int {
22+ if n <= 1 then 1
23+ else n * factorial(n - 1)
24+}
25+
26+fn howbigisx(x: int) -> int {
27+ guard {
28+ | x == 0 => 0
29+ | x < 5 => 5
30+ | _ => 100
31+ }
32+}
33+
34+pub fn main() -> int {
35+ val a = factorial(5)
36+ val b: int = howbigisx(3)
37+ a + b /* returns int */
38+}
+16,
-0
1@@ -0,0 +1,16 @@
2+use "prelude.kav"
3+
4+pub linear datatype List[a: type, n: nat] {
5+ | Nil : List[a, 0]
6+ | [m: nat] Cons(a, List[a, m]) : List[a, m+1]
7+}
8+
9+typedef List1[a: type, n: nat] = List[a, n + 1]
10+
11+pub fn list_free[a: utype, n: nat](list: List[a, n]) -> one {
12+ case list of {
13+ /* ~ consumes the list wrapper */
14+ | ~Nil => one
15+ | ~Cons(_, rest) => list_free(rest)
16+ }
17+}
+17,
-0
1@@ -0,0 +1,17 @@
2+use "prelude.kav"
3+
4+newtype Id = int
5+
6+fn add(x: int, y: int) -> Id {
7+ val add = x + y
8+ val id = Id(add)
9+ id
10+}
11+
12+/* entry point */
13+fn main() -> int {
14+ val res = add(7, 5)
15+ val Id(x) = res
16+ x
17+}
18+
+9,
-0
1@@ -0,0 +1,9 @@
2+pub sortdef nat = [n: int | n >= 0]
3+pub sortdef pos = [n: int | n >= 1]
4+
5+pub datatype Maybe[a:type] {
6+ | None
7+ | Some(a)
8+}
9+
10+
+15,
-0
1@@ -0,0 +1,15 @@
2+use "prelude.kav"
3+use "list.kav"
4+
5+fn reverse[a: type,n: nat, m: nat](l: List[a, n], acc: List[a, m]) -> List[a, n + m] {
6+ case l of {
7+ | ~Nil => acc
8+ | ~Cons(entry, rest) => reverse(rest, Cons(entry, acc))
9+ }
10+}
11+
12+pub fn main() -> one {
13+ val list: List[int, 3] = Cons(1, Cons(2, Cons(3, Nil)))
14+ val reversed = reverse(list, Nil)
15+ list_free(reversed)
16+}
+10,
-0
1@@ -0,0 +1,10 @@
2+fn factorial(n: int) -> int {
3+ if n <= 1 then 1
4+ else n * factorial(n - 1)
5+}
6+
7+fn main() -> int {
8+ val a = factorial(4)
9+ val b = 7
10+ a + b
11+}
+28,
-0
1@@ -0,0 +1,28 @@
2+fn divmod(a: int, b: int) -> (int, int) {
3+ (a / b, a % b)
4+}
5+
6+fn swapsies(p: (int, int)) -> (int, int) {
7+ val (x, y) = p
8+ (y, x)
9+}
10+
11+fn sum3(t: (int, int, int)) -> int {
12+ case t of {
13+ | (a, b, c) => a + b + c
14+ }
15+}
16+
17+fn sign(p: (int, int)) -> int {
18+ case p of {
19+ | (0, _) => 0
20+ | (_, 0) => 1
21+ | _ => 2
22+ }
23+}
24+
25+fn main() -> int {
26+ val (q, r) = divmod(17, 5)
27+ val (a, b) = swapsies((q, r))
28+ sum3((a, b, 10)) + sign((0, 9)) + sign((4, 0))
29+}
A
exprs.h
+12,
-0
1@@ -0,0 +1,12 @@
2+EXPR(EIDENT)
3+EXPR(ENUMBER)
4+EXPR(ECALL)
5+EXPR(EGUARD)
6+EXPR(ECASE)
7+EXPR(EBLOCK)
8+EXPR(ESAPP) /* static application */
9+EXPR(EEXISTS) /* existentials */
10+EXPR(ESTRING)
11+EXPR(EHOLE)
12+EXPR(ETUPLE)
13+EXPR(EBORROW)
A
kav.h
+225,
-0
1@@ -0,0 +1,225 @@
2+#pragma once
3+
4+#include "util.h"
5+
6+enum tokenkind {
7+#define TOKEN(t, s) t,
8+#include "tokens.h"
9+#undef TOKEN
10+};
11+
12+struct location {
13+ usize line, col;
14+ const char *file;
15+};
16+
17+struct token {
18+ enum tokenkind kind;
19+ struct location loc;
20+ const char *str;
21+ usize length;
22+};
23+
24+struct lexer {
25+ const char *cur;
26+ const char *mar;
27+ const char *tok;
28+ const char *linestart;
29+ const char *file;
30+ usize line;
31+};
32+
33+void lex(struct lexer *, struct token *);
34+const char *tokstr(enum tokenkind);
35+const char *tokwhat(enum tokenkind);
36+
37+struct decl *parse(const char *, const char *);
38+
39+struct scope;
40+
41+struct module {
42+ struct module *next;
43+ struct module *nextseen;
44+ struct scope *scope;
45+ const char *path;
46+ stralloc src;
47+ struct decl *decls;
48+ int state;
49+};
50+
51+struct module *loadall(const char *);
52+void resolve(struct module *);
53+void check(struct module *);
54+void linear(struct module *);
55+int run(struct decl *);
56+noreturn void erroratv(const struct location *, const char *const *, usize);
57+char *tokdup(struct token);
58+int tokeqb(struct token, const char *, usize);
59+#define tokis(t, lit) tokeqb((t), (lit), sizeof(lit) - 1)
60+
61+/* if we're going to have variatic arity we're going to do it properly. */
62+#define errorat(loc, ...) erroratv(loc, STRS(__VA_ARGS__))
63+
64+enum exprkind {
65+#define EXPR(e) e,
66+#include "exprs.h"
67+#undef EXPR
68+};
69+
70+enum bindkind {
71+ BFN,
72+ BCTOR,
73+ BTYPE,
74+ BSORT,
75+ BPARAM,
76+ BVAL,
77+ BPAT,
78+};
79+
80+struct binding {
81+ struct decl *decl;
82+ struct binding *next;
83+ enum bindkind kind;
84+ struct type *type;
85+ struct token name;
86+ struct ctor *ctor; /*constructors only */
87+ struct param *param;
88+};
89+
90+#define BUILTIN(sp, kind, str, var) extern struct binding *var;
91+#include "builtins.h"
92+#undef BUILTIN
93+
94+struct val {
95+ struct val *next;
96+ struct pat *pat;
97+ struct expr *ann; /* the type annotation */
98+ struct expr *init;
99+};
100+
101+enum typekind {
102+ YNAME,
103+ YVAR,
104+ YTUPLE,
105+ YFN,
106+ YMETA,
107+};
108+
109+struct type {
110+ struct type *next;
111+ enum typekind kind;
112+ struct binding *binding;
113+ struct type *args; /* type args, tuple elements, or a function's params */
114+ struct type *ret; /* functions only */
115+ struct type *link; /* metas only: the type it was solved to or nil if blank */
116+ int borrow;
117+};
118+
119+struct param;
120+
121+struct type *mktype(enum typekind, struct binding *);
122+struct type *mkfntype(struct type *, struct type *);
123+struct type *tydup(struct type *);
124+char *typestr(struct type *);
125+struct type *mkmeta(void);
126+struct type *deref(struct type *);
127+struct type *subst(struct type *, struct param *, struct type *);
128+int unify(struct type *, struct type *);
129+
130+
131+struct expr {
132+ struct expr *next;
133+ enum exprkind kind;
134+ struct token tok; /* the token it came from */
135+ struct expr *args; /* the first argument for calls only */
136+ struct arm *arm; /* the first arm, only gaurds use it */
137+ struct val *vals; /* the first val, only blocks use it*/
138+ struct expr *body; /* the final expression, the blocks value */
139+ struct param *sparams; /* sort params for existentials */
140+ struct token ns; /* namespace */
141+ struct binding *binding;
142+ struct type *type;
143+ struct expr *scrut;
144+};
145+
146+enum patkind {
147+ PWILD,
148+ PNAME,
149+ PCON,
150+ PTUPLE,
151+ PNUM,
152+};
153+
154+struct pat {
155+ struct pat *next;
156+ enum patkind kind;
157+ struct token name;
158+ int tilde;
159+ struct pat *args;
160+ struct token ns;
161+ struct binding *binding;
162+ struct type *type;
163+};
164+
165+struct arm {
166+ struct arm *next;
167+ struct location loc;
168+ struct expr *cond;
169+ struct expr *body;
170+ struct pat *pat;
171+};
172+
173+struct param {
174+ struct param *next;
175+ struct token name;
176+ struct expr *ann;
177+ struct expr *cond;
178+ struct binding *binding;
179+};
180+
181+enum declkind {
182+ DFN,
183+ DSTRUCT,
184+ DDATA,
185+ DTYPEDEF,
186+ DSORTDEF,
187+ DUSE,
188+};
189+
190+struct ctor {
191+ struct ctor *next;
192+ struct token name;
193+ struct param *sparams;
194+ struct expr *args;
195+ struct expr *ret;
196+ struct binding *binding;
197+};
198+
199+struct decl {
200+ struct decl *next;
201+ enum declkind kind;
202+ struct token name;
203+ int pub;
204+ int linear;
205+ int newtype;
206+ struct param *sparams;
207+ struct param *params;
208+ struct expr *ret;
209+ struct expr *body;
210+ struct ctor *ctors;
211+ struct token alias;
212+ struct binding *binding;
213+ struct module *mod;
214+};
215+
216+struct expr *mkexpr(enum exprkind, struct token);
217+struct expr *mkbinary(struct token, struct expr *, struct expr *);
218+struct arm *mkarm(struct location);
219+struct val *mkval(struct pat *);
220+struct param *mkparam(struct token);
221+struct ctor *mkctor(struct token);
222+struct decl *mkdecl(enum declkind, struct token);
223+struct pat *mkpat(enum patkind, struct token);
224+struct binding *mkbinding(enum bindkind, struct token);
225+void declput(struct decl *);
226+int islinear(struct type *);
A
kws.h
+19,
-0
1@@ -0,0 +1,19 @@
2+TOKEN(TFN, "fn")
3+TOKEN(TPUB, "pub")
4+TOKEN(TVAL, "val")
5+TOKEN(TIF, "if")
6+TOKEN(TTHEN, "then")
7+TOKEN(TELSE, "else")
8+TOKEN(TGUARD, "guard")
9+TOKEN(TCASE, "case")
10+TOKEN(TOF, "of")
11+TOKEN(TSTRUCT, "struct")
12+TOKEN(TLINEAR, "linear")
13+TOKEN(TDATATYPE, "datatype")
14+TOKEN(TNEWTYPE, "newtype")
15+TOKEN(TTYPEDEF, "typedef")
16+TOKEN(TSORTDEF, "sortdef")
17+TOKEN(TUSE, "use")
18+TOKEN(TAS, "as")
19+
20+
A
lex.re
+68,
-0
1@@ -0,0 +1,68 @@
2+#include "util.h"
3+#include "kav.h"
4+
5+static void settok(struct lexer *l, struct token *t, enum tokenkind k) {
6+ t->kind = k;
7+ t->str = l->tok;
8+ /*we moved past the matched text already */
9+ t->length = l->cur - l->tok;
10+ t->loc.line = l->line;
11+ t->loc.col = l->tok - l->linestart + 1;
12+ t->loc.file = l->file;
13+}
14+
15+void lex(struct lexer *l, struct token *t) {
16+ loop:
17+ l->tok = l->cur;
18+ /*!re2c
19+ re2c:define:YYCTYPE = char;
20+ re2c:define:YYCURSOR = "l->cur";
21+ re2c:define:YYMARKER = "l->mar";
22+ re2c:yyfill:enable = 0;
23+
24+ [ \t\r]+ { goto loop; }
25+ "\n" { l->line++; l->linestart = l->cur; goto loop; }
26+ "\x00" { settok(l, t, TEOF); return; }
27+ "//" [^\n\x00]* { goto loop; }
28+ "/*" { settok(l, t, TNONE); goto comment; }
29+
30+ //I LOVE MACROHACKS
31+ !include "rules.re";
32+
33+ [a-zA-Z_] [a-zA-Z_0-9]* { settok(l, t, TIDENT); return; }
34+ [0-9]+ { settok(l, t, TNUMBER); return; }
35+ '"' ( [^"\n\x00\\] | "\\" [^\n\x00] )* '"' { settok(l, t, TSTRING); return; }
36+
37+ * { settok(l, t, TNONE); errorat(&t->loc, "unexpected character"); }
38+ */
39+ comment:
40+ /*!re2c
41+ "*/" { goto loop; }
42+ "\n" { l->line++; l->linestart = l->cur; goto comment; }
43+ "\x00" { errorat(&t->loc, "unertminated comment"); }
44+ * { goto comment; }
45+ */
46+}
47+
48+static const char *const tokname[] = {
49+#define TOKEN(t, s) #t,
50+#include "tokens.h"
51+#undef TOKEN
52+};
53+
54+static const char *const tokspell[] = {
55+#define TOKEN(t, s) "" s,
56+#include "tokens.h"
57+#undef TOKEN
58+};
59+
60+
61+const char *tokstr(enum tokenkind k){
62+ return tokname[k];
63+
64+}
65+
66+const char *tokwhat(enum tokenkind k){
67+ return tokspell[k];
68+
69+}
A
linear.c
+295,
-0
1@@ -0,0 +1,295 @@
2+#include "util.h"
3+#include "kav.h"
4+
5+struct lvar {
6+ struct lvar *next;
7+ struct binding *binding;
8+ int used;
9+ int borrowed;
10+};
11+
12+static struct lvar *vars;
13+
14+int
15+islinear(struct type *t) {
16+ struct type *a;
17+
18+ t = deref(t);
19+ switch(t->kind) {
20+ case YNAME:
21+ return t->binding->decl && t->binding->decl->linear;
22+ case YTUPLE:
23+ for(a = t->args; a; a = a->next)
24+ if(islinear(a))
25+ return 1;
26+ return 0;
27+ case YVAR:
28+ /*linear unless its utype */
29+ return t->binding->param->ann->binding != butype;
30+ case YFN:
31+ case YMETA:
32+ return 0;
33+ }
34+ return 0;
35+}
36+
37+static void
38+track(struct binding *b, int borrowed) {
39+ struct lvar *v;
40+
41+ v = alloc(sizeof(*v));
42+ v->binding = b;
43+ v->borrowed = borrowed;
44+ v->used = 0;
45+ v->next = vars;
46+ vars = v;
47+}
48+
49+static void
50+trackpat(struct pat *p, int borrowed) {
51+ struct pat *a;
52+
53+ switch(p->kind) {
54+ case PNAME:
55+ if(islinear(p->binding->type))
56+ track(p->binding, borrowed);
57+ break;
58+ case PCON:
59+ if(p->tilde && borrowed)
60+ errorat(&p->name.loc, "destructor on a borrowed pattern");
61+ if(p->tilde && !islinear(p->type))
62+ errorat(&p->name.loc, "destructor on nonlinear value");
63+ /* we're borrowing*/
64+ if(!p->tilde)
65+ borrowed = 1;
66+ /* from here the case is the same */
67+ case PTUPLE:
68+ for(a = p->args; a; a = a->next)
69+ trackpat(a, borrowed);
70+ break;
71+ case PWILD:
72+ if(!borrowed && islinear(p->type))
73+ errorat(&p->name.loc, "linear value discarded by _");
74+ break;
75+ default:
76+ break;
77+ }
78+}
79+
80+static int
81+count(struct lvar *v) {
82+ int n = 0;
83+ for(; v; v = v->next)
84+ n++;
85+ return n;
86+}
87+
88+static int *
89+snapshot(struct lvar *mark) {
90+ int *flags;
91+ int i = 0;
92+ struct lvar *v;
93+
94+ flags = alloc(count(mark) * sizeof(*flags));
95+ for(v = mark; v; v = v->next) {
96+ flags[i] = v->used;
97+ i++;
98+ }
99+ return flags;
100+}
101+
102+static void
103+restore(struct lvar *mark, int *flags) {
104+ int i = 0;
105+ struct lvar *v;
106+
107+ for(v = mark; v; v = v->next) {
108+ v->used = flags[i];
109+ i++;
110+ }
111+}
112+
113+static void
114+endscope(struct lvar *mark) {
115+ struct lvar *v;
116+
117+ for(v = vars; v != mark; v = v->next)
118+ if(!v->used && !v->borrowed)
119+ errorat(&v->binding->name.loc, "linear value '", tokdup(v->binding->name), "' is never used");
120+ vars = mark;
121+}
122+
123+static void use(struct expr *);
124+static void look(struct expr *e);
125+
126+static void
127+arms(struct expr *e) {
128+ struct arm *r;
129+ struct lvar *mark;
130+ int *before;
131+ int *after = nil;
132+ int *pre;
133+ struct lvar *v;
134+ int i;
135+
136+ mark = vars;
137+ before = snapshot(mark);
138+ for(r = e->arm; r; r = r->next) {
139+ restore(mark, before);
140+ if(r->cond) {
141+ pre = snapshot(mark);
142+ look(r->cond);
143+ for(v = mark, i = 0; v; v = v->next, i++)
144+ if(v->used != pre[i])
145+ errorat(&r->loc, "condition consumes '", tokdup(v->binding->name), "'");
146+ }
147+ if(r->pat)
148+ trackpat(r->pat, 0);
149+ use(r->body);
150+ endscope(mark);
151+ if(r == e->arm)
152+ after = snapshot(mark);
153+ else
154+ for(v = mark, i = 0; v; v = v->next, i++)
155+ if(v->used != after[i])
156+ errorat(&r->loc, "arms disagree about '", tokdup(v->binding->name), "'");
157+ }
158+ restore(mark, after);
159+}
160+
161+static void
162+look(struct expr *e) {
163+ struct lvar *v;
164+
165+ if(e->kind != EIDENT) {
166+ if(islinear(e->type))
167+ errorat(&e->tok.loc, "linear temporary is borrowed and never freed");
168+ use(e);
169+ return;
170+ }
171+ for(v = vars; v; v = v->next) {
172+ if(v->binding != e->binding)
173+ continue;
174+ if(v->used)
175+ errorat(&e->tok.loc, "linear value '", tokdup(e->tok), "' used after it was consumed");
176+ }
177+}
178+
179+static void
180+use(struct expr *e) {
181+ struct lvar *v;
182+ struct expr *a;
183+ struct val *l;
184+ struct arm *r;
185+ struct type *y;
186+ struct lvar *mark;
187+ int tilde = 0;
188+ int old;
189+ struct type *ps;
190+
191+ switch(e->kind) {
192+ case EIDENT:
193+ for(v = vars; v; v = v->next) {
194+ if(v->binding != e->binding)
195+ continue;
196+ if(v->borrowed)
197+ errorat(&e->tok.loc, "cannot consume borrowed value '", tokdup(e->tok), "'");
198+ if(v->used)
199+ errorat(&e->tok.loc, "linear value '", tokdup(e->tok), "' used twice");
200+ v->used = 1;
201+ }
202+ break;
203+ case ECALL:
204+ if(e->tok.kind == TIDENT && e->binding->type->kind == YFN)
205+ ps = e->binding->type->args;
206+ else
207+ ps = nil;
208+ /* for a case where a function with two arguments of the same type borrows one
209+ * and consumes the other; the caller passes the same value twice; we cannot
210+ * allow that */
211+ for(a = e->args, y = ps; a; a = a->next) {
212+ if(!y || !y->borrow)
213+ use(a);
214+ if(y)
215+ y = y->next;
216+ }
217+ for(a = e->args, y = ps; a; a = a->next) {
218+ if(y && y->borrow)
219+ look(a);
220+ if(y)
221+ y = y->next;
222+ }
223+ break;
224+ case ETUPLE:
225+ for(a = e->args; a; a = a->next)
226+ use(a);
227+ break;
228+ case EBLOCK:
229+ mark = vars;
230+ for(l = e->vals; l; l = l->next) {
231+ use(l->init);
232+ trackpat(l->pat, 0);
233+ }
234+ use(e->body);
235+ endscope(mark);
236+ break;
237+ case ECASE:
238+ for(r = e->arm; r; r = r->next) {
239+ if(r->pat->tilde) {
240+ tilde = 1;
241+ break;
242+ }
243+ }
244+ if(tilde) {
245+ use(e->scrut);
246+ arms(e);
247+ break;
248+ }
249+ v = nil;
250+ if(e->scrut->kind == EIDENT) {
251+ for(v = vars; v; v = v->next)
252+ if(v->binding == e->scrut->binding)
253+ break;
254+ }
255+ if(!v) {
256+ /*look at it for a linear temporary like case f(l) of */
257+ look(e->scrut);
258+ arms(e);
259+ break;
260+ }
261+ look(e->scrut);
262+ old = v->borrowed;
263+ v->borrowed = 1;
264+ arms(e);
265+ v->borrowed = old;
266+ break;
267+ case EGUARD:
268+ arms(e);
269+ break;
270+ default:
271+ break;
272+ }
273+}
274+
275+static void
276+linfn(struct decl *d) {
277+ struct param *p;
278+
279+ vars = nil;
280+ for(p = d->params; p; p = p->next)
281+ if(islinear(p->binding->type))
282+ track(p->binding, p->binding->type->borrow);
283+ use(d->body);
284+ endscope(nil);
285+}
286+
287+void
288+linear(struct module *m) {
289+ struct decl *d;
290+
291+ for(; m; m = m->next) {
292+ for(d = m->decls; d; d = d->next)
293+ if(d->kind == DFN)
294+ linfn(d);
295+ }
296+}
A
main.c
+124,
-0
1@@ -0,0 +1,124 @@
2+#include <stdio.h>
3+#include <stdlib.h>
4+
5+#include "util.h"
6+#include "kav.h"
7+#include "arg.h"
8+
9+static noreturn void
10+usage(void) {
11+ fputs("usage: ", stderr);
12+ fputs(PROG, stderr);
13+ fputs(" [-c|-l|-p|-r] file\n", stderr);
14+ exit(100);
15+}
16+
17+static void
18+putnum(usize u) {
19+ char num[FMTUSIZE];
20+
21+ fwrite(num, 1, fmtusize(num, u), stdout);
22+}
23+
24+static int
25+dolex(const char *path) {
26+ stralloc sa = {0};
27+ struct lexer l = {0};
28+ struct token t;
29+
30+ if(!openreadclose(path, &sa))
31+ diesys("unable to read ", path);
32+ sa0(&sa);
33+ l.cur = sa.s;
34+ l.linestart = sa.s;
35+ l.line = 1;
36+ l.file = path;
37+ /* filthy */
38+ for(;;) {
39+ lex(&l, &t);
40+ if(t.kind == TEOF)
41+ return 0;
42+ putnum(t.loc.line);
43+ fputs(":", stdout);
44+ putnum(t.loc.col);
45+ fputs("\t", stdout);
46+ fputs(tokstr(t.kind), stdout);
47+ fputs("\t", stdout);
48+ fwrite(t.str, 1, t.length, stdout);
49+ fputs("\n", stdout);
50+ }
51+}
52+
53+static int
54+doparse(const char *path) {
55+ struct module *m;
56+ struct decl *d;
57+
58+ for(m = loadall(path); m; m = m->next) {
59+ fputs(m->path, stdout);
60+ fputs("\n", stdout);
61+ for(d = m->decls; d; d = d->next) {
62+ declput(d);
63+ fputs("\n", stdout);
64+ }
65+ }
66+ return 0;
67+}
68+
69+static int
70+doresolve(const char *path) {
71+ resolve(loadall(path));
72+ return 0;
73+}
74+
75+static struct module *
76+build(const char *path) {
77+ struct module *m;
78+
79+ m = loadall(path);
80+ resolve(m);
81+ check(m);
82+ linear(m);
83+ return m;
84+}
85+
86+static int
87+docheck(const char *path) {
88+ build(path);
89+ return 0;
90+}
91+
92+static int
93+dorun(const char *path) {
94+ struct module *m;
95+
96+ for(m = build(path); m->next; m = m->next)
97+ ;
98+ return run(m->decls);
99+}
100+
101+int
102+main(int argc, char **argv) {
103+ int (*mode)(const char *) = dorun;
104+
105+ PROG = argv[0];
106+ ARGBEGIN {
107+ case 'c':
108+ mode = docheck;
109+ break;
110+ case 'l':
111+ mode = dolex;
112+ break;
113+ case 'p':
114+ mode = doparse;
115+ break;
116+ case 'r':
117+ mode = doresolve;
118+ break;
119+ default:
120+ usage();
121+ } ARGEND
122+ if(argc != 1)
123+ usage();
124+ return mode(argv[0]);
125+}
A
module.c
+57,
-0
1@@ -0,0 +1,57 @@
2+#include <string.h>
3+
4+#include "util.h"
5+#include "kav.h"
6+
7+static struct module *seen;
8+static struct module *head;
9+static struct module **end = &head;
10+
11+static const char *
12+usepath(const char *from, struct token name) {
13+ stralloc sa = {0};
14+ const char *slash;
15+
16+ if(slash = strrchr(from, '/'))
17+ sacatb(&sa, from, slash - from + 1);
18+ sacatb(&sa, name.str + 1, name.length - 2);
19+ sa0(&sa);
20+ return sa.s;
21+}
22+
23+static struct module *
24+load(const char *path) {
25+ struct module *m;
26+ struct module *s;
27+ struct decl *d;
28+
29+ for(s = seen; s; s = s->nextseen) {
30+ if(strcmp(s->path, path) == 0) {
31+ if(s->state == 1)
32+ die("import cycle through ", path);
33+ return s;
34+ }
35+ }
36+ m = zalloc(sizeof(*m));
37+ m->state = 1;
38+ m->nextseen = seen;
39+ seen = m;
40+ m->path = path;
41+ if(!openreadclose(path, &m->src))
42+ diesys("unable to read ", path);
43+ sa0(&m->src);
44+ m->decls = parse(path, m->src.s);
45+ for(d = m->decls; d; d = d->next)
46+ if(d->kind == DUSE)
47+ d->mod = load(usepath(path, d->name));
48+ m->state = 2;
49+ *end = m;
50+ end = &m->next;
51+ return m;
52+}
53+
54+struct module *
55+loadall(const char *path) {
56+ load(path);
57+ return head;
58+}
A
parse.c
+626,
-0
1@@ -0,0 +1,626 @@
2+#include <stdio.h>
3+
4+#include "util.h"
5+#include "kav.h"
6+
7+static struct lexer lx;
8+static struct token tok;
9+static struct expr *expr(void);
10+static struct expr *block(void);
11+static struct expr *call(void);
12+static struct param *sortparams(void);
13+
14+static void
15+next(void) {
16+ lex(&lx, &tok);
17+}
18+
19+static int
20+consume(enum tokenkind k) {
21+ if(tok.kind == k) {
22+ next();
23+ return 1;
24+ }
25+ return 0;
26+}
27+
28+static void
29+expect(enum tokenkind k) {
30+ if(!consume(k)) {
31+ if(tokwhat(k)[0] != '\0')
32+ errorat(&tok.loc, "expected '", tokwhat(k), "'");
33+ else
34+ errorat(&tok.loc, "expected ", tokstr(k));
35+ }
36+}
37+
38+static struct expr *
39+type(void) {
40+ struct expr *e;
41+ /* it's an existential. */
42+ if(tok.kind == TLBRACK) {
43+ e = mkexpr(EEXISTS, tok);
44+ e->sparams = sortparams();
45+ e->body = type();
46+ return e;
47+ }
48+ /* we're borrowing */
49+ if(tok.kind == TBANG) {
50+ e = mkexpr(EBORROW, tok);
51+ next();
52+ e->body = type();
53+ return e;
54+ }
55+ return call();
56+}
57+
58+static struct param *
59+param(void) {
60+ struct param *p;
61+
62+ p = mkparam(tok);
63+ expect(TIDENT);
64+ expect(TCOLON);
65+ p->ann = type();
66+ return p;
67+}
68+
69+
70+static struct expr *
71+primary(void) {
72+ struct expr *e;
73+ struct expr *a;
74+ struct expr *tup;
75+ struct expr *head = nil;
76+ struct expr **end = &head;
77+ struct token opener;
78+
79+ switch(tok.kind) {
80+ case TNUMBER:
81+ e = mkexpr(ENUMBER, tok);
82+ next();
83+ return e;
84+ /* allow a hole anywhere an expression can go, so we can do List[int, _].
85+ * later we will disallow things like val x = _. */
86+ case TUS:
87+ e = mkexpr(EHOLE, tok);
88+ next();
89+ return e;
90+ case TSTRING:
91+ e = mkexpr(ESTRING, tok);
92+ next();
93+ return e;
94+ case TIDENT:
95+ e = mkexpr(EIDENT, tok);
96+ next();
97+ if(consume(TDCOLON)) {
98+ /* the ident tok was actually the namespace */
99+ e->ns = e->tok;
100+ /* the current token is the ident tok */
101+ e->tok = tok;
102+ expect(TIDENT);
103+ }
104+ return e;
105+ case TLBRACE:
106+ return block();
107+ case TLPAREN:
108+ opener = tok;
109+ next();
110+ e = expr();
111+ if(tok.kind != TCOMMA) {
112+ expect(TRPAREN);
113+ return e;
114+ }
115+ *end = e;
116+ end = &e->next;
117+ while(consume(TCOMMA)) {
118+ a = expr();
119+ *end = a;
120+ end = &a->next;
121+ }
122+ expect(TRPAREN);
123+ tup = mkexpr(ETUPLE, opener);
124+ tup->args = head;
125+ return tup;
126+ default:
127+ errorat(&tok.loc, "expected expression");
128+ }
129+}
130+
131+/*
132+ * parse an operand with an optional arg list following
133+ * f(x, 1)
134+ * List[a, n]
135+ */
136+static struct expr *
137+call(void) {
138+ struct expr *e;
139+ struct expr *a;
140+ struct expr *head = nil;
141+ struct expr **end = &head;
142+ enum tokenkind closer;
143+
144+ e = primary();
145+ /* a ( or [ on a new line is never a call. */
146+ if((tok.kind == TLPAREN || tok.kind == TLBRACK) && tok.loc.line == e->tok.loc.line) {
147+ if(e->kind != EIDENT)
148+ errorat(&e->tok.loc, "expected function name");
149+ if(tok.kind == TLPAREN) {
150+ e->kind = ECALL;
151+ closer = TRPAREN;
152+ } else {
153+ e->kind = ESAPP;
154+ closer = TRBRACK;
155+ }
156+ next();
157+ if(tok.kind != closer) {
158+ do {
159+ a = expr();
160+ *end = a;
161+ end = &a->next;
162+ } while(consume(TCOMMA));
163+ }
164+ expect(closer);
165+ e->args = head;
166+ }
167+ return e;
168+}
169+
170+static struct expr *
171+unary(void) {
172+ struct expr *e;
173+
174+ if(tok.kind == TSUB) {
175+ e = mkexpr(ECALL, tok);
176+ next();
177+ e->args = unary();
178+ return e;
179+ }
180+ return call();
181+}
182+
183+static int
184+prec(enum tokenkind k) {
185+ switch(k) {
186+ case TEQ:
187+ case TNEQ:
188+ case TLESS:
189+ case TMORE:
190+ case TLEQ:
191+ case TMEQ:
192+ return 1;
193+ case TADD:
194+ case TSUB:
195+ return 2;
196+ case TMUL:
197+ case TDIV:
198+ case TMOD:
199+ return 3;
200+ default:
201+ return 0;
202+ }
203+}
204+
205+static struct expr *
206+binary(int min) {
207+ struct expr *l;
208+ struct token op;
209+ int p;
210+
211+ l = unary();
212+ while((p = prec(tok.kind)) >= min) {
213+ op = tok;
214+ next();
215+ l = mkbinary(op, l, binary(p + 1));
216+ if(p == 1 && prec(tok.kind) == 1)
217+ errorat(&tok.loc, "comparisons can't be chained");
218+ }
219+ return l;
220+}
221+
222+static struct pat *
223+pattern(void) {
224+ struct pat *p;
225+ struct pat *a;
226+ struct pat *head = nil;
227+ struct pat **end = &head;
228+ struct token opener;
229+ int tilde;
230+
231+ tilde = consume(TTILDE);
232+ if(tok.kind == TUS) {
233+ p = mkpat(PWILD, tok);
234+ next();
235+ } else if(tok.kind == TLPAREN) {
236+ opener = tok;
237+ next();
238+ p = pattern();
239+ if(tok.kind != TCOMMA)
240+ expect(TRPAREN);
241+ else {
242+ *end = p;
243+ end = &p->next;
244+ while(consume(TCOMMA)) {
245+ a = pattern();
246+ *end = a;
247+ end = &a->next;
248+ }
249+ expect(TRPAREN);
250+ p = mkpat(PTUPLE, opener);
251+ p->args = head;
252+ }
253+ } else if(tok.kind == TNUMBER) {
254+ p = mkpat(PNUM, tok);
255+ next();
256+ } else {
257+ p = mkpat(PNAME, tok);
258+ expect(TIDENT);
259+ if(consume(TDCOLON)) {
260+ /* the ident was the namespace */
261+ p->ns = p->name;
262+ p->name = tok;
263+ expect(TIDENT);
264+ }
265+ if(consume(TLPAREN)) {
266+ p->kind = PCON;
267+ do {
268+ a = pattern();
269+ *end = a;
270+ end = &a->next;
271+ } while(consume(TCOMMA));
272+ expect(TRPAREN);
273+ p->args = head;
274+ }
275+ }
276+ p->tilde = tilde;
277+ return p;
278+}
279+
280+
281+static struct expr *
282+expr(void) {
283+ struct expr *e;
284+ struct arm *a;
285+ struct arm *head = nil;
286+ struct arm **end = &head;
287+
288+ if(tok.kind == TIF) {
289+ e = mkexpr(EGUARD, tok);
290+ next();
291+ a = mkarm(tok.loc);
292+ a->cond = expr();
293+ expect(TTHEN);
294+ a->body = expr();
295+ a->next = mkarm(tok.loc);
296+ expect(TELSE);
297+ a->next->body = expr();
298+ e->arm = a;
299+ return e;
300+ }
301+ /* guard { | cond_expr => expr | _ => expr } */
302+ if(tok.kind == TGUARD) {
303+ e = mkexpr(EGUARD, tok);
304+ next();
305+ expect(TLBRACE);
306+ while(tok.kind == TBAR) {
307+ a = mkarm(tok.loc);
308+ next();
309+ if(!consume(TUS))
310+ a->cond = expr();
311+ expect(TEQARROW);
312+ a->body = expr();
313+ *end = a;
314+ end = &a->next;
315+ }
316+ if(!head)
317+ errorat(&e->tok.loc, "guard needs atleast one arm");
318+ expect(TRBRACE);
319+ e->arm = head;
320+ return e;
321+ }
322+ /* case thing of { | pat => expr | _ => expr } */
323+ if(tok.kind == TCASE) {
324+ e = mkexpr(ECASE, tok);
325+ next();
326+ e->scrut = expr();
327+ expect(TOF);
328+ expect(TLBRACE);
329+ while(tok.kind == TBAR) {
330+ a = mkarm(tok.loc);
331+ next();
332+ a->pat = pattern();
333+ expect(TEQARROW);
334+ a->body = expr();
335+ *end = a;
336+ end = &a->next;
337+ }
338+ if(!head)
339+ errorat(&e->tok.loc, "case needs atleast one arm");
340+ expect(TRBRACE);
341+ e->arm = head;
342+ return e;
343+ }
344+ return binary(1);
345+}
346+
347+static struct expr *
348+block(void) {
349+ struct expr *e;
350+ struct val *v;
351+ struct val *head = nil;
352+ struct val **end = &head;
353+
354+ e = mkexpr(EBLOCK, tok);
355+ expect(TLBRACE);
356+ while(tok.kind == TVAL) {
357+ next();
358+ /* val (q, r) = expr */
359+ v = mkval(pattern());
360+ if(consume(TCOLON))
361+ /* val thing: Type = expr */
362+ v->ann = type();
363+ expect(TASSIGN);
364+ /* val thing = expr */
365+ v->init = expr();
366+ *end = v;
367+ end = &v->next;
368+ }
369+ e->body = expr(); /*final expression, the return value */
370+ expect(TRBRACE);
371+ e->vals = head;
372+ return e;
373+}
374+
375+static struct param *
376+sortparam(void) {
377+ struct param *p;
378+
379+ p = param();
380+ if(consume(TBAR))
381+ p->cond = expr();
382+ return p;
383+}
384+
385+
386+/*
387+ * static sorts in the form [n: type, x: type, etc: type] .
388+ * allows refinement like [n: type | n > 0]
389+ * */
390+static struct param *
391+sortparams(void) {
392+ struct param *p;
393+ struct param *head = nil;
394+ struct param **end = &head;
395+
396+ if(consume(TLBRACK)) {
397+ do {
398+ p = sortparam();
399+ *end = p;
400+ end = &p->next;
401+ } while(consume(TCOMMA));
402+ expect(TRBRACK);
403+ }
404+ return head;
405+}
406+
407+/*
408+ * params in the form { a: thing, b: thing }
409+ * or (n: int, x: int)
410+ */
411+static struct param *
412+params(enum tokenkind closer) {
413+ struct param *p;
414+ struct param *head = nil;
415+ struct param **end = &head;
416+
417+ if(tok.kind != closer) {
418+ do {
419+ p = param();
420+ *end = p;
421+ end = &p->next;
422+ } while(consume(TCOMMA));
423+ }
424+ expect(closer);
425+ return head;
426+}
427+
428+static struct decl *
429+fndecl(void) {
430+ struct decl *d;
431+
432+ expect(TFN);
433+ d = mkdecl(DFN, tok);
434+ expect(TIDENT);
435+ d->sparams = sortparams();
436+ expect(TLPAREN);
437+ d->params = params(TRPAREN);
438+ expect(TARROW);
439+ d->ret = type();
440+ d->body = block();
441+ return d;
442+}
443+
444+static struct decl *
445+structdecl(void) {
446+ struct decl *d;
447+
448+ expect(TSTRUCT);
449+ d = mkdecl(DSTRUCT, tok);
450+ expect(TIDENT);
451+ expect(TLBRACE);
452+ d->params = params(TRBRACE);
453+ return d;
454+}
455+
456+
457+static struct expr *
458+types(void) {
459+ struct expr *t;
460+ struct expr *head = nil;
461+ struct expr **end = &head;
462+
463+ do {
464+ t = type();
465+ *end = t;
466+ end = &t->next;
467+ } while(consume(TCOMMA));
468+ return head;
469+}
470+
471+static struct decl *
472+datadecl(void) {
473+ struct decl *d;
474+ struct ctor *c;
475+ struct ctor *head = nil;
476+ struct ctor **end = &head;
477+ struct param *sp;
478+
479+ /* the declaration */
480+ expect(TDATATYPE);
481+ d = mkdecl(DDATA, tok);
482+ expect(TIDENT);
483+ d->sparams = sortparams();
484+ expect(TLBRACE);
485+ /* the constructors */
486+ while(consume(TBAR)) {
487+ /* constructor-local sorts */
488+ sp = sortparams();
489+ c = mkctor(tok);
490+ expect(TIDENT);
491+ c->sparams = sp;
492+ if(consume(TLPAREN)) {
493+ c->args = types();
494+ expect(TRPAREN);
495+ }
496+ /*if we declared the consructors result type */
497+ if(consume(TCOLON))
498+ c->ret = type();
499+ else if(!d->sparams)
500+ c->ret = mkexpr(EIDENT, d->name);
501+ *end = c;
502+ end = &c->next;
503+ }
504+ expect(TRBRACE);
505+ d->ctors = head;
506+ return d;
507+}
508+
509+/* desugar a newtype declaration to a single-constuctor datatype */
510+static struct decl *
511+newtypedecl(void) {
512+ struct decl *d;
513+ struct ctor *c;
514+
515+ expect(TNEWTYPE);
516+ d = mkdecl(DDATA, tok);
517+ expect(TIDENT);
518+ expect(TASSIGN);
519+ c = mkctor(d->name);
520+ c->args = type();
521+ c->ret = mkexpr(EIDENT, d->name);
522+ d->ctors = c;
523+ d->newtype = 1;
524+ return d;
525+}
526+
527+static struct decl *
528+sortdefdecl(void) {
529+ struct decl *d;
530+
531+ expect(TSORTDEF);
532+ d = mkdecl(DSORTDEF, tok);
533+ expect(TIDENT);
534+ expect(TASSIGN);
535+ if(tok.kind == TLBRACK) {
536+ d->sparams = sortparams();
537+ if(d->sparams->next)
538+ errorat(&d->name.loc, "a sortdef takes only one parameter");
539+ } else
540+ d->ret = type();
541+ return d;
542+}
543+
544+static struct decl *
545+typedefdecl(void) {
546+ struct decl *d;
547+
548+ expect(TTYPEDEF);
549+ d = mkdecl(DTYPEDEF, tok);
550+ expect(TIDENT);
551+ d->sparams = sortparams();
552+ expect(TASSIGN);
553+ d->ret = type();
554+ return d;
555+}
556+
557+static struct decl *
558+usedecl(void) {
559+ struct decl *d;
560+
561+ expect(TUSE);
562+ d = mkdecl(DUSE, tok);
563+ expect(TSTRING);
564+ if(consume(TAS)) {
565+ d->alias = tok;
566+ expect(TIDENT);
567+ }
568+ return d;
569+}
570+
571+static struct decl *
572+decl(void) {
573+ struct decl *d;
574+ int pub;
575+ int linear;
576+
577+ pub = consume(TPUB);
578+ linear = consume(TLINEAR);
579+ if(tok.kind == TFN) {
580+ if(linear)
581+ errorat(&tok.loc, "functions cannot be linear");
582+ d = fndecl();
583+ } else if(tok.kind == TSTRUCT)
584+ d = structdecl();
585+ else if(tok.kind == TDATATYPE)
586+ d = datadecl();
587+ else if(tok.kind == TNEWTYPE)
588+ d = newtypedecl();
589+ else if(tok.kind == TTYPEDEF) {
590+ if(linear)
591+ errorat(&tok.loc, "typedefs cannot be linear");
592+ d = typedefdecl();
593+ } else if(tok.kind == TSORTDEF) {
594+ if(linear)
595+ errorat(&tok.loc, "sortdefs cannot be linear");
596+ d = sortdefdecl();
597+ } else if(tok.kind == TUSE) {
598+ if(linear)
599+ errorat(&tok.loc, "module imports cannot be linear");
600+ d = usedecl();
601+ } else
602+ errorat(&tok.loc, "malformed declaration");
603+
604+ d->pub = pub;
605+ d->linear = linear;
606+ return d;
607+}
608+
609+struct decl *
610+parse(const char *file, const char *src) {
611+ struct decl *d;
612+ struct decl *head = nil;
613+ struct decl **end = &head;
614+
615+ lx.cur = src;
616+ lx.linestart = src;
617+ lx.line = 1;
618+ lx.file = file;
619+
620+ next();
621+ while(tok.kind != TEOF) {
622+ d = decl();
623+ *end = d;
624+ end = &d->next;
625+ }
626+ return head;
627+}
A
punc.h
+27,
-0
1@@ -0,0 +1,27 @@
2+TOKEN(TLPAREN, "(" )
3+TOKEN(TRPAREN, ")" )
4+TOKEN(TLBRACE, "{" )
5+TOKEN(TRBRACE, "}" )
6+TOKEN(TLBRACK, "[" )
7+TOKEN(TRBRACK, "]" )
8+TOKEN(TCOLON, ":" )
9+TOKEN(TARROW, "->" )
10+TOKEN(TEQARROW, "=>" )
11+TOKEN(TASSIGN, "=" )
12+TOKEN(TEQ, "==" )
13+TOKEN(TLEQ, "<=" )
14+TOKEN(TLESS, "<" )
15+TOKEN(TMORE, ">" )
16+TOKEN(TBAR, "|" )
17+TOKEN(TADD, "+" )
18+TOKEN(TSUB, "-" )
19+TOKEN(TMUL, "*" )
20+TOKEN(TDIV, "/" )
21+TOKEN(TMOD, "%" )
22+TOKEN(TNEQ, "!=" )
23+TOKEN(TMEQ, ">=" )
24+TOKEN(TCOMMA, "," )
25+TOKEN(TUS, "_" )
26+TOKEN(TTILDE, "~")
27+TOKEN(TDCOLON, "::")
28+TOKEN(TBANG, "!")
+368,
-0
1@@ -0,0 +1,368 @@
2+#include <string.h>
3+
4+#include "util.h"
5+#include "kav.h"
6+
7+#define BUILTIN(sp, kind, str, var) struct binding *var;
8+#include "builtins.h"
9+#undef BUILTIN
10+
11+
12+enum space {
13+ STYPE,
14+ SVALUE,
15+ SSORT,
16+};
17+
18+struct scope {
19+ struct scope *up;
20+ struct module *mod;
21+ struct binding *names[3];
22+};
23+
24+static void walksparams(struct scope *s, struct param *p);
25+
26+static int
27+tokeq(struct token a, struct token b) {
28+ return (a.length == b.length && memcmp(a.str, b.str, a.length) == 0);
29+}
30+
31+static struct binding *
32+lookin(struct scope *s, enum space sp, struct token name) {
33+ struct binding *b;
34+ for(b = s->names[sp]; b; b = b->next)
35+ if(tokeq(name, b->name))
36+ return b;
37+ return nil;
38+}
39+
40+static struct binding *
41+findused(struct scope *s, enum space sp, struct token name) {
42+ struct decl *d;
43+ struct binding *b;
44+ struct binding *found = nil;
45+
46+ for(d = s->mod->decls; d; d = d->next) {
47+ if(d->kind != DUSE || d->alias.length != 0)
48+ continue;
49+ b = lookin(d->mod->scope, sp, name);
50+ if(!b || !b->decl || !b->decl->pub)
51+ continue;
52+ if(found && found != b)
53+ errorat(&name.loc, "'", tokdup(name), "' is provided by multiple modules");
54+ found = b;
55+ }
56+ return found;
57+}
58+
59+static struct binding *
60+lookup(struct scope *s, enum space sp, struct token name) {
61+ struct binding *b;
62+ for(; s; s = s->up) {
63+ b = lookin(s, sp, name);
64+ if(!b && s->mod)
65+ b = findused(s, sp, name);
66+ if(b)
67+ return b;
68+ }
69+ return nil;
70+}
71+
72+static struct binding *
73+find(struct scope *s, enum space sp, struct token name) {
74+ struct binding *b;
75+ if(!(b = lookup(s, sp, name)))
76+ errorat(&name.loc, "undefined name '", tokdup(name), "'");
77+ return b;
78+}
79+
80+static struct binding *
81+declare(struct scope *s, enum space sp, enum bindkind kind, struct token name) {
82+ struct binding *b;
83+
84+ b = mkbinding(kind, name);
85+ b->next = s->names[sp];
86+ s->names[sp] = b;
87+ return b;
88+}
89+
90+static struct binding *
91+define(struct scope *s, enum space sp, enum bindkind kind, struct token name) {
92+ if(lookin(s, sp, name))
93+ errorat(&name.loc, "duplicate definition '", tokdup(name), "'");
94+ if(s->mod && findused(s, sp, name))
95+ errorat(&name.loc, "'", tokdup(name), "' is already imported");
96+ return declare(s, sp, kind, name);
97+}
98+
99+
100+static struct scope *
101+newscope(struct scope *up) {
102+ struct scope *s;
103+
104+ s = zalloc(sizeof(*s));
105+ s->up = up;
106+ return s;
107+}
108+
109+static struct binding *
110+findns(struct scope *s, enum space sp, struct token ns, struct token name) {
111+ struct decl *d;
112+ struct binding *b;
113+
114+ while(!s->mod)
115+ s = s->up;
116+ for(d = s->mod->decls; d; d = d->next) {
117+ if(d->kind != DUSE)
118+ continue;
119+ if(!tokeq(d->alias, ns))
120+ continue;
121+ if(!(b = lookin(d->mod->scope, sp, name)))
122+ errorat(&name.loc, "'", tokdup(name), "' is not defined in module '", tokdup(ns), "'");
123+ if(!b->decl || !b->decl->pub)
124+ errorat(&name.loc, "'", tokdup(name), "' is not public in module '", tokdup(ns), "'");
125+ return b;
126+ }
127+ errorat(&ns.loc, "no module named '", tokdup(ns), "'");
128+}
129+
130+static void
131+walkpat(struct scope *s, struct pat *p) {
132+ struct binding *b;
133+ struct pat *a;
134+
135+ if(p->ns.length != 0) {
136+ p->binding = findns(s, SVALUE, p->ns, p->name);
137+ if(p->binding->kind != BCTOR)
138+ errorat(&p->name.loc, "not a constructor");
139+ p->kind = PCON;
140+ for(a = p->args; a; a = a->next)
141+ walkpat(s, a);
142+ return;
143+ }
144+ switch(p->kind) {
145+ case PWILD:
146+ break;
147+ case PCON:
148+ p->binding = find(s, SVALUE, p->name);
149+ if(p->binding->kind != BCTOR)
150+ errorat(&p->name.loc, "not a constructor");
151+ for(a = p->args; a; a = a->next)
152+ walkpat(s, a);
153+ break;
154+ case PTUPLE:
155+ for(a = p->args; a; a = a->next)
156+ walkpat(s, a);
157+ break;
158+ case PNAME:
159+ /* there is some ambiguity in this case. */
160+ b = lookup(s, SVALUE, p->name);
161+ /* it's a constructor. */
162+ if(b && b->kind == BCTOR) {
163+ p->binding = b;
164+ p->kind = PCON;
165+ /* it's a variable */
166+ } else {
167+ p->binding = define(s, SVALUE, BPAT, p->name);
168+ }
169+ break;
170+ case PNUM:
171+ break;
172+ }
173+}
174+
175+static void
176+walk(struct scope *s, enum space sp, struct expr *e) {
177+ struct expr *a;
178+ struct val *v;
179+ struct arm *r;
180+ struct scope inner = {0};
181+ struct scope *cur;
182+
183+ if(!e)
184+ return;
185+ switch(e->kind) {
186+ case ENUMBER:
187+ case ESTRING:
188+ case EHOLE:
189+ break;
190+ case EIDENT:
191+ if(e->ns.length != 0)
192+ e->binding = findns(s, sp, e->ns, e->tok);
193+ else
194+ e->binding = find(s, sp, e->tok);
195+ break;
196+ case ECALL:
197+ case ESAPP:
198+ if(e->tok.kind == TIDENT) {
199+ if(e->ns.length != 0)
200+ e->binding = findns(s, sp, e->ns, e->tok);
201+ else
202+ e->binding = find(s, sp, e->tok);
203+ }
204+ for(a = e->args; a; a = a->next)
205+ walk(s, sp, a);
206+ break;
207+ case ETUPLE:
208+ for(a = e->args; a; a = a->next)
209+ walk(s, sp, a);
210+ break;
211+ case EBLOCK:
212+ cur = s;
213+ for(v = e->vals; v; v = v->next) {
214+ walk(cur, STYPE, v->ann);
215+ /* walk the init before binding so shadowing works */
216+ walk(cur, sp, v->init);
217+ /* each val gets its own scope so it can shadow earlier
218+ * vals but one pattern can't bind the name twice like
219+ * val (x, x) = return2ofem(x) isnt allowed */
220+ cur = newscope(cur);
221+ walkpat(cur, v->pat);
222+ }
223+ walk(cur, sp, e->body);
224+ break;
225+ case EGUARD:
226+ for(r = e->arm; r; r = r->next) {
227+ walk(s, sp, r->cond);
228+ walk(s, sp, r->body);
229+ }
230+ break;
231+ case ECASE:
232+ walk(s, sp, e->scrut);
233+ inner.up = s;
234+ for(r = e->arm; r; r = r->next) {
235+ inner.names[SVALUE] = nil;
236+ walkpat(&inner, r->pat);
237+ walk(&inner, sp, r->body);
238+ }
239+ break;
240+ case EEXISTS:
241+ inner.up = s;
242+ walksparams(&inner, e->sparams);
243+ walk(&inner, sp, e->body);
244+ break;
245+ case EBORROW:
246+ walk(s, sp, e->body);
247+ break;
248+ default:
249+ break;
250+ }
251+}
252+
253+static void
254+walksparams(struct scope *s, struct param *p) {
255+ for(; p; p = p->next) {
256+ walk(s, SSORT, p->ann);
257+ p->binding = define(s, STYPE, BPARAM, p->name);
258+ p->binding->param = p;
259+ walk(s, STYPE, p->cond);
260+ }
261+}
262+
263+static void
264+walkfn(struct scope *up, struct decl *d) {
265+ struct scope s = {0};
266+ struct param *p;
267+
268+ s.up = up;
269+ walksparams(&s, d->sparams);
270+ for(p = d->params; p; p = p->next) {
271+ walk(&s, STYPE, p->ann);
272+ p->binding = define(&s, SVALUE, BPARAM, p->name);
273+ }
274+ walk(&s, STYPE, d->ret);
275+ walk(&s, SVALUE, d->body);
276+}
277+
278+static void
279+walktypedecl(struct scope *up, struct decl *d) {
280+ struct scope s = {0};
281+ struct scope inner = {0};
282+ struct param *p;
283+ struct ctor *c;
284+ struct expr *a;
285+ enum space sp = STYPE;
286+
287+ if(d->kind == DSORTDEF)
288+ sp = SSORT;
289+ s.up = up;
290+ walksparams(&s, d->sparams);
291+ walk(&s, sp, d->ret);
292+ for(p = d->params; p; p = p->next)
293+ walk(&s, STYPE, p->ann);
294+ inner.up = &s;
295+ for(c = d->ctors; c; c = c->next) {
296+ inner.names[STYPE] = nil;
297+ /* constuctor local static sorts */
298+ walksparams(&inner, c->sparams);
299+ for(a = c->args; a; a = a->next)
300+ walk(&inner, STYPE, a);
301+ /* the constructor's result type */
302+ walk(&inner, STYPE, c->ret);
303+ }
304+}
305+static struct binding *
306+builtin(struct scope *s, enum space sp, enum bindkind kind, const char *str) {
307+ struct token t = {0};
308+ t.kind = TIDENT;
309+ t.str = str;
310+ t.length = strlen(str);
311+ return declare(s, sp, kind, t);
312+}
313+
314+static void
315+builtins(struct scope *s) {
316+#define BUILTIN(sp, kind, str, var) var = builtin(s, sp, kind, str);
317+#include "builtins.h"
318+#undef BUILTIN
319+}
320+
321+static void
322+collect(struct scope *s, struct decl *d) {
323+ struct ctor *c;
324+
325+ for(; d; d = d->next) {
326+ switch(d->kind) {
327+ case DFN:
328+ d->binding = define(s, SVALUE, BFN, d->name);
329+ break;
330+ case DSTRUCT:
331+ case DTYPEDEF:
332+ d->binding = define(s, STYPE, BTYPE, d->name);
333+ break;
334+ case DSORTDEF:
335+ d->binding = define(s, SSORT, BSORT, d->name);
336+ break;
337+ case DDATA:
338+ d->binding = define(s, STYPE, BTYPE, d->name);
339+ for(c = d->ctors; c; c = c->next) {
340+ c->binding = define(s, SVALUE, BCTOR, c->name);
341+ c->binding->decl = d;
342+ c->binding->ctor = c;
343+ }
344+ break;
345+ case DUSE:
346+ break;
347+ }
348+ /* every declared name knows its declaration */
349+ if(d->binding)
350+ d->binding->decl = d;
351+ }
352+}
353+
354+void
355+resolve(struct module *m) {
356+ struct scope univ = {0};
357+ struct decl *d;
358+ builtins(&univ);
359+ for(; m; m = m->next) {
360+ m->scope = newscope(&univ);
361+ m->scope->mod = m;
362+ collect(m->scope, m->decls);
363+ for(d = m->decls; d; d = d->next)
364+ if(d->kind == DFN)
365+ walkfn(m->scope, d);
366+ else
367+ walktypedecl(m->scope, d);
368+ }
369+}
A
rules.h
+5,
-0
1@@ -0,0 +1,5 @@
2+/* we need to do it like this because the cpp sees the re2c block as a comment */
3+#define TOKEN(k, s) s {settok(l, t, k); return;}
4+#include "punc.h"
5+#include "kws.h"
6+
A
run.c
+268,
-0
1@@ -0,0 +1,268 @@
2+#include "util.h"
3+#include "kav.h"
4+
5+enum valkind {
6+ VINT,
7+ VCON,
8+ VTUPLE,
9+};
10+
11+struct value {
12+ enum valkind kind;
13+ i64 num;
14+ struct binding *con;
15+ struct value **fields;
16+};
17+
18+static struct value *
19+mkint(i64 n) {
20+ struct value *v;
21+
22+ v = zalloc(sizeof(*v));
23+ v->kind = VINT;
24+ v->num = n;
25+ return v;
26+}
27+
28+static struct value *
29+mkcon(struct binding *con) {
30+ struct value *v;
31+
32+ v = zalloc(sizeof(*v));
33+ v->kind = VCON;
34+ v->con = con;
35+ return v;
36+}
37+
38+static struct value *
39+mktuple(void) {
40+ struct value *v;
41+
42+ v = zalloc(sizeof(*v));
43+ v->kind = VTUPLE;
44+ return v;
45+}
46+
47+
48+static struct value *
49+mkbool(int b) {
50+ return mkcon(b ? btrue : bfalse);
51+}
52+
53+static i64
54+tonum(struct token t) {
55+ i64 n = 0;
56+ usize i;
57+
58+ for(i = 0; i < t.length; i++)
59+ n = n * 10 + (t.str[i] - '0');
60+ return n;
61+}
62+
63+struct env {
64+ struct env *next;
65+ struct binding *binding;
66+ struct value *value;
67+};
68+
69+static struct env *
70+bind(struct env *up, struct binding *b, struct value *v) {
71+ struct env *env;
72+
73+ env = alloc(sizeof(*env));
74+ env->next = up;
75+ env->binding = b;
76+ env->value = v;
77+ return env;
78+}
79+
80+static struct value *
81+getvar(struct env *env, struct binding *b) {
82+ for(; env; env = env->next)
83+ if(env->binding == b)
84+ return env->value;
85+ die("unbound variable");
86+}
87+
88+static struct value *
89+binop(struct token op, i64 a, i64 b) {
90+ switch(op.kind) {
91+ case TADD:
92+ return mkint(a + b);
93+ case TSUB:
94+ return mkint(a - b);
95+ case TMUL:
96+ return mkint(a * b);
97+ case TDIV:
98+ if(b == 0)
99+ errorat(&op.loc, "division by zero");
100+ return mkint(a / b);
101+ case TMOD:
102+ if(b == 0)
103+ errorat(&op.loc, "mod by zero");
104+ return mkint(a % b);
105+ case TEQ:
106+ return mkbool(a == b);
107+ case TNEQ:
108+ return mkbool(a != b);
109+ case TLESS:
110+ return mkbool(a < b);
111+ case TMORE:
112+ return mkbool(a > b);
113+ case TLEQ:
114+ return mkbool(a <= b);
115+ case TMEQ:
116+ return mkbool(a >= b);
117+ default:
118+ errorat(&op.loc, "sorry, no idea how to handle this operator");
119+ }
120+ return nil;
121+}
122+
123+static int
124+match(struct env **envp, struct pat *p, struct value *v) {
125+ struct pat *a;
126+ usize i;
127+
128+ switch(p->kind) {
129+ case PWILD:
130+ return 1;
131+ case PNAME:
132+ *envp = bind(*envp, p->binding, v);
133+ return 1;
134+ case PCON:
135+ if(v->con != p->binding)
136+ return 0;
137+ i = 0;
138+ for(a = p->args; a; a = a->next) {
139+ if(!match(envp, a, v->fields[i]))
140+ return 0;
141+ i++;
142+ }
143+ return 1;
144+ case PTUPLE:
145+ if(v->kind != VTUPLE)
146+ return 0;
147+ i = 0;
148+ for(a = p->args; a; a = a->next) {
149+ if(!match(envp, a, v->fields[i]))
150+ return 0;
151+ i++;
152+ }
153+ return 1;
154+ case PNUM:
155+ if(v->kind != VINT)
156+ return 0;
157+ if(v->num != tonum(p->name))
158+ return 0;
159+ return 1;
160+ }
161+ return 0;
162+}
163+
164+static struct value *
165+eval(struct env *env, struct expr *e) {
166+ struct val *v;
167+ struct decl *f;
168+ struct param *p;
169+ struct expr *a;
170+ struct env *callenv = nil;
171+ struct value *l;
172+ struct value *r;
173+ struct value *s;
174+ struct arm *arm;
175+ struct env *armenv;
176+ usize i;
177+ usize n;
178+
179+ switch(e->kind) {
180+ case ENUMBER:
181+ return mkint(tonum(e->tok));
182+ case EBLOCK:
183+ for(v = e->vals; v; v = v->next) {
184+ /* the checker will make sure val patterns can't fail */
185+ if(!match(&env, v->pat, eval(env, v->init)))
186+ errorat(&v->pat->name.loc, "val pattern didn't match");
187+ }
188+ return eval(env, e->body);
189+ case EIDENT:
190+ if(e->binding->kind == BCTOR)
191+ return mkcon(e->binding);
192+ return getvar(env, e->binding);
193+ case ECALL:
194+ if(e->tok.kind != TIDENT) {
195+ l = eval(env, e->args);
196+ if(!e->args->next)
197+ return mkint(-l->num);
198+ r = eval(env, e->args->next);
199+ return binop(e->tok, l->num, r->num);
200+ }
201+ if(e->binding->kind == BCTOR) {
202+ n = 0;
203+ for(a = e->args; a; a = a->next)
204+ n++;
205+ l = mkcon(e->binding);
206+ l->fields = alloc(n * sizeof(*l->fields));
207+ i = 0;
208+ for(a = e->args; a; a = a->next) {
209+ l->fields[i] = eval(env, a);
210+ i++;
211+ }
212+ return l;
213+ }
214+ if(!e->binding || e->binding->kind != BFN)
215+ errorat(&e->tok.loc, "sorry, no idea what to do!");
216+ f = e->binding->decl;
217+ for(p = f->params, a = e->args; p && a; p = p->next, a = a->next)
218+ callenv = bind(callenv, p->binding, eval(env, a));
219+ return eval(callenv, f->body);
220+ case ETUPLE:
221+ n = 0;
222+ for(a = e->args; a; a = a->next)
223+ n++;
224+ l = mktuple();
225+ l->fields = alloc(n * sizeof(*l->fields));
226+ i = 0;
227+ for(a = e->args; a; a = a->next) {
228+ l->fields[i] = eval(env, a);
229+ i++;
230+ }
231+ return l;
232+ case ECASE:
233+ s = eval(env, e->scrut);
234+ for(arm = e->arm; arm; arm = arm->next) {
235+ armenv = env;
236+ if(match(&armenv, arm->pat, s))
237+ return eval(armenv, arm->body);
238+ }
239+ errorat(&e->tok.loc, "no case arm matched");
240+ case EGUARD:
241+ for(arm = e->arm; arm; arm = arm->next) {
242+ if(!arm->cond)
243+ return eval(env, arm->body);
244+ s = eval(env, arm->cond);
245+ if(s->con == btrue)
246+ return eval(env, arm->body);
247+ }
248+ errorat(&e->tok.loc, "no guard arm matched");
249+ default:
250+ errorat(&e->tok.loc, "sorry, no idea what to do!");
251+ break;
252+ }
253+ return nil;
254+}
255+
256+int
257+run(struct decl *d) {
258+ struct value *v;
259+
260+ for(; d; d = d->next)
261+ if(d->kind == DFN && tokis(d->name, "main"))
262+ break;
263+ if(!d)
264+ die("no entry point found!?");
265+ v = eval(nil, d->body);
266+ if(v->kind == VINT)
267+ return v->num;
268+ return 0;
269+}
A
tokens.h
+8,
-0
1@@ -0,0 +1,8 @@
2+TOKEN(TNONE, )
3+TOKEN(TEOF, )
4+TOKEN(TIDENT, )
5+TOKEN(TNUMBER, )
6+TOKEN(TSTRING, )
7+
8+#include "kws.h"
9+#include "punc.h"
A
type.c
+181,
-0
1@@ -0,0 +1,181 @@
2+#include "util.h"
3+#include "kav.h"
4+
5+struct type *
6+mktype(enum typekind kind, struct binding *b) {
7+ struct type *t;
8+
9+ t = zalloc(sizeof(*t));
10+ t->kind = kind;
11+ t->binding = b;
12+ return t;
13+}
14+
15+static int
16+occurs(struct type *m, struct type *t) {
17+ struct type *a;
18+
19+ t = deref(t);
20+ if(t == m)
21+ return 1;
22+ if(t->ret && occurs(m, t->ret))
23+ return 1;
24+ for(a = t->args; a; a = a->next)
25+ if(occurs(m, a))
26+ return 1;
27+ return 0;
28+}
29+
30+int
31+unify(struct type *a, struct type *b) {
32+ struct type *x;
33+ struct type *y;
34+
35+ a = deref(a);
36+ b = deref(b);
37+ if(a == b)
38+ return 1;
39+ if(a->kind == YMETA) {
40+ if(occurs(a, b))
41+ return 0;
42+ a->link = b;
43+ return 1;
44+ }
45+ if(b->kind == YMETA) {
46+ if(occurs(b, a))
47+ return 0;
48+ b->link = a;
49+ return 1;
50+ }
51+ if(a->kind != b->kind)
52+ return 0;
53+ if((a->kind == YNAME || a->kind == YVAR) && a->binding != b->binding)
54+ return 0;
55+ if(a->kind == YFN && !unify(a->ret, b->ret))
56+ return 0;
57+ for(x = a->args, y = b->args; x && y; x = x->next, y = y->next)
58+ if(!unify(x, y))
59+ return 0;
60+ return (!x && !y);
61+}
62+
63+
64+static void
65+typecat(stralloc *sa, struct type *t) {
66+ struct type *a;
67+
68+ t = deref(t);
69+ if(t->borrow)
70+ sacatl(sa, "!");
71+ switch(t->kind) {
72+ case YNAME:
73+ case YVAR:
74+ sacatb(sa, t->binding->name.str, t->binding->name.length);
75+ if(!t->args)
76+ return;
77+ sacatl(sa, "[");
78+ break;
79+ case YTUPLE:
80+ sacatl(sa, "(");
81+ break;
82+ case YFN:
83+ sacatl(sa, "fn(");
84+ break;
85+ case YMETA:
86+ sacatl(sa, "?");
87+ return;
88+ }
89+ for(a = t->args; a; a = a->next) {
90+ typecat(sa, a);
91+ if(a->next)
92+ sacatl(sa, ", ");
93+ }
94+ if(t->kind == YFN) {
95+ sacatl(sa, ") -> ");
96+ typecat(sa, t->ret);
97+ return;
98+ }
99+ sacatb(sa, t->kind == YTUPLE ? ")" : "]", 1);
100+}
101+
102+char *
103+typestr(struct type *t) {
104+ stralloc sa = {0};
105+
106+ typecat(&sa, t);
107+ sa0(&sa);
108+ return sa.s;
109+}
110+
111+struct type *
112+mkfntype(struct type *params, struct type *ret) {
113+ struct type *t;
114+
115+ t = mktype(YFN, nil);
116+ t->args = params;
117+ t->ret = ret;
118+ return t;
119+}
120+
121+/* copy of t that can be linked into a new list without touching t->next */
122+struct type *
123+tydup(struct type *t) {
124+ struct type *u;
125+
126+ if(t->kind == YMETA) {
127+ u = mkmeta();
128+ u->link = t;
129+ return u;
130+ }
131+ u = mktype(t->kind, t->binding);
132+ u->args = t->args;
133+ u->ret = t->ret;
134+ u->borrow = t->borrow;
135+ return u;
136+}
137+
138+struct type *
139+mkmeta(void) {
140+ return mktype(YMETA, nil);
141+}
142+
143+struct type *
144+deref(struct type *t) {
145+ while(t->kind == YMETA && t->link)
146+ t = t->link;
147+ return t;
148+}
149+
150+/* a copy of t with each param in from replaced by the matching type in to */
151+struct type *
152+subst(struct type *t, struct param *from, struct type *to) {
153+ struct type *a;
154+ struct type *b;
155+ struct type **link;
156+ struct param *p;
157+
158+ t = deref(t);
159+ switch(t->kind) {
160+ case YVAR:
161+ for(p = from, b = to; p && b; p = p->next, b = b->next)
162+ if(p->binding == t->binding)
163+ return tydup(b);
164+ return mktype(YVAR, t->binding);
165+ case YMETA:
166+ return tydup(t);
167+ case YNAME:
168+ case YTUPLE:
169+ case YFN:
170+ a = mktype(t->kind, t->binding);
171+ a->borrow = t->borrow;
172+ link = &a->args;
173+ for(b = t->args; b; b = b->next) {
174+ *link = subst(b, from, to);
175+ link = &(*link)->next;
176+ }
177+ if(t->ret)
178+ a->ret = subst(t->ret, from, to);
179+ return a;
180+ }
181+ return t;
182+}
A
util.c
+167,
-0
1@@ -0,0 +1,167 @@
2+#include <errno.h>
3+#include <stdio.h>
4+#include <stdlib.h>
5+#include <string.h>
6+#include <fcntl.h>
7+#include <unistd.h>
8+
9+#include "util.h"
10+#include "kav.h"
11+
12+#define CHUNK 4096
13+
14+const char *PROG;
15+
16+void
17+diev(int sys, const char *const *v, usize n) {
18+ int e = errno;
19+ usize i;
20+
21+ fputs(PROG, stderr);
22+ fputs(": fatal: ", stderr);
23+ for(i = 0; i < n; i++)
24+ fputs(v[i], stderr);
25+ if(sys) {
26+ fputs(": ", stderr);
27+ fputs(strerror(e), stderr);
28+ }
29+ fputs("\n", stderr);
30+ exit(1);
31+}
32+
33+void *
34+alloc(usize n) {
35+ void *p = malloc(n);
36+
37+ if(!p)
38+ die("out of memory");
39+ return p;
40+}
41+
42+
43+void *
44+zalloc(usize n) {
45+ void *p;
46+
47+ p = alloc(n);
48+ memset(p, 0, n);
49+ return p;
50+}
51+
52+void *
53+allocre(void *p, usize n) {
54+ void *q = realloc(p, n);
55+
56+ if(!q)
57+ die("out of memory");
58+ return q;
59+}
60+
61+void
62+sagrow(stralloc *sa, usize n) {
63+ usize size;
64+ usize extra;
65+
66+ if(n > SIZE_MAX - sa->len)
67+ die("out of memory");
68+ size = sa->len + n;
69+ if(size <= sa->a)
70+ return;
71+ extra = size / 8 + 30;
72+ if(extra <= SIZE_MAX - size)
73+ size += extra;
74+ sa->s = allocre(sa->s, size);
75+ sa->a = size;
76+}
77+
78+/* append n bytes of s */
79+void
80+sacatb(stralloc *sa, const char *s, usize n) {
81+ sagrow(sa, n);
82+ memcpy(sa->s + sa->len, s, n);
83+ sa->len += n;
84+}
85+
86+void
87+sa0(stralloc *sa) {
88+ sagrow(sa, 1);
89+ sa->s[sa->len] = '\0';
90+}
91+
92+int
93+openreadclose(const char *fn, stralloc *sa) {
94+ int fd = open(fn, O_RDONLY);
95+ isize r;
96+
97+ if(fd == -1)
98+ return 0;
99+ for(;;) {
100+ sagrow(sa, CHUNK);
101+ r = read(fd, sa->s + sa->len, CHUNK);
102+ if(r == -1 && errno == EINTR)
103+ continue;
104+ if(r == -1) {
105+ close(fd);
106+ return 0;
107+ }
108+ if(r == 0) {
109+ close(fd);
110+ return 1;
111+ }
112+ sa->len = sa->len + r;
113+ }
114+}
115+
116+usize
117+fmtusize(char *s, usize u) {
118+ usize len;
119+ usize q;
120+
121+ len = 1;
122+ q = u;
123+ while(q > 9) {
124+ len++;
125+ q = q / 10;
126+ }
127+ if(s) {
128+ s = s + len;
129+ do {
130+ s = s - 1;
131+ *s = '0' + (u % 10);
132+ u = u / 10;
133+ } while(u);
134+ }
135+ return len;
136+}
137+
138+char *
139+tokdup(struct token t) {
140+ char *s;
141+
142+ s = alloc(t.length + 1);
143+ memcpy(s, t.str, t.length);
144+ s[t.length] = '\0';
145+ return s;
146+}
147+
148+int
149+tokeqb(struct token t, const char *s, usize n) {
150+ return t.length == n && memcmp(t.str, s, n) == 0;
151+}
152+
153+void
154+erroratv(const struct location *loc, const char *const *v, usize n) {
155+ char num[FMTUSIZE];
156+ usize i;
157+
158+ fputs(loc->file, stderr);
159+ fputs(":", stderr);
160+ fwrite(num, 1, fmtusize(num, loc->line), stderr);
161+ fputs(":", stderr);
162+ fwrite(num, 1, fmtusize(num, loc->col), stderr);
163+ fputs(": error: ", stderr);
164+ for(i = 0; i < n; i++)
165+ fputs(v[i], stderr);
166+ fputs("\n", stderr);
167+ exit(1);
168+}
A
util.h
+45,
-0
1@@ -0,0 +1,45 @@
2+#pragma once
3+
4+#include <stddef.h>
5+#include <stdint.h>
6+#include <stdnoreturn.h>
7+#define nil ((void *)0)
8+
9+typedef int8_t i8;
10+typedef int16_t i16;
11+typedef int32_t i32;
12+typedef int64_t i64;
13+typedef uint8_t u8;
14+typedef uint16_t u16;
15+typedef uint32_t u32;
16+typedef uint64_t u64;
17+typedef ptrdiff_t isize;
18+typedef size_t usize;
19+
20+extern const char *PROG;
21+
22+noreturn void diev(int, const char *const *, usize);
23+
24+#define STRS(...) (const char *const[]){__VA_ARGS__}, \
25+ sizeof((const char *const[]){__VA_ARGS__}) / sizeof(const char *)
26+#define die(...) diev(0, STRS(__VA_ARGS__))
27+#define diesys(...) diev(1, STRS(__VA_ARGS__))
28+
29+void *alloc(usize);
30+void *zalloc(usize);
31+void *allocre(void *, usize);
32+
33+typedef struct stralloc {
34+ char *s;
35+ usize len; /* how many bytes are in use */
36+ usize a; /* how many are allocated */
37+} stralloc;
38+
39+void sagrow(stralloc *, usize);
40+void sacatb(stralloc *, const char *, usize);
41+void sa0(stralloc *);
42+#define sacatl(sa, lit) sacatb((sa), (lit), sizeof(lit) - 1)
43+int openreadclose(const char *, stralloc *);
44+
45+#define FMTUSIZE 20
46+usize fmtusize(char *, usize);