bitwise parse.c
  1#include <stdio.h>
  2
  3#include "util.h"
  4#include "kav.h"
  5
  6static struct lexer lx;
  7static struct token tok;
  8
  9static struct decl *curfn;
 10static struct decl *lambdas;
 11static struct decl **lambdaend;
 12static usize nlambdas;
 13static int inarm;
 14
 15static struct expr *expr(void);
 16static struct expr *block(void);
 17static struct expr *call(void);
 18static struct expr *pipe(void);
 19static struct expr *lambda(void);
 20static struct param *sortparams(void);
 21
 22static struct expr *
 23armbody(void) {
 24	struct expr *e;
 25	int saved = inarm;
 26
 27	inarm = 1;
 28	e = expr();
 29	inarm = saved;
 30	return e;
 31}
 32
 33static struct expr *
 34freeexpr(void) {
 35	struct expr *e;
 36	int saved = inarm;
 37
 38	inarm = 0;
 39	e = expr();
 40	inarm = saved;
 41	return e;
 42}
 43
 44static void
 45next(void) {
 46	/* skip doc comments for now */
 47	do {
 48		lex(&lx, &tok);
 49	} while(tok.kind == TDOC);
 50}
 51
 52static int
 53consume(enum tokenkind k) {
 54	if(tok.kind == k) {
 55		next();
 56		return 1;
 57	}
 58	return 0;
 59}
 60
 61static void
 62expect(enum tokenkind k) {
 63	if(!consume(k)) {
 64		if(tokwhat(k)[0] != '\0')
 65			errorat(&tok.loc, "expected '", tokwhat(k), "'");
 66		else
 67			errorat(&tok.loc, "expected ", tokstr(k));
 68	}
 69}
 70
 71static struct expr *
 72type(void) {
 73	struct expr *e;
 74	/* it's an existential. */
 75	if(tok.kind == TLBRACK) {
 76		e = mkexpr(EEXISTS, tok);
 77		e->sparams = sortparams();
 78		e->body = type();
 79		return e;
 80	}
 81	/* we're borrowing */
 82	if(tok.kind == TBANG) {
 83		e = mkexpr(EBORROW, tok);
 84		next();
 85		e->body = type();
 86		return e;
 87	}
 88	/* a function type, fn(int, !List[int, n]) -> int */
 89	if(tok.kind == TFN) {
 90		struct expr *a;
 91		struct expr **end;
 92
 93		e = mkexpr(EFNTYPE, tok);
 94		next();
 95		expect(TLPAREN);
 96		end = &e->args;
 97		if(tok.kind != TRPAREN) {
 98			do {
 99				a = type();
100				*end = a;
101				end = &a->next;
102			} while(consume(TCOMMA));
103		}
104		expect(TRPAREN);
105		expect(TARROW);
106		e->body = type();
107		return e;
108	}
109	/* a tuple type.  the elements are types so they can be fn types */
110	if(tok.kind == TLPAREN) {
111		struct expr *a;
112		struct expr *head = nil;
113		struct expr **end = &head;
114		struct token opener = tok;
115
116		next();
117		do {
118			a = type();
119			*end = a;
120			end = &a->next;
121		} while(consume(TCOMMA));
122		expect(TRPAREN);
123		if(!head->next)
124			return head;
125		e = mkexpr(ETUPLE, opener);
126		e->args = head;
127		return e;
128	}
129	return call();
130}
131
132static struct param *
133param(void) {
134	struct param *p;
135
136	p = mkparam(tok);
137	expect(TIDENT);
138	expect(TCOLON);
139	p->ann = type();
140	return p;
141}
142
143
144static struct expr *
145primary(void) {
146	struct expr *e;
147	struct expr *a;
148	struct expr *tup;
149	struct expr *head = nil;
150	struct expr **end = &head;
151	struct token opener;
152
153	switch(tok.kind) {
154	case TNUMBER:
155	case TCHAR:
156		e = mkexpr(ENUMBER, tok);
157		next();
158		return e;
159	/* allow a hole anywhere an expression can go, so we can do List[int, _].
160	 * later we will disallow things like val x = _. */
161	case TUS:
162		e = mkexpr(EHOLE, tok);
163		next();
164		return e;
165	case TSTRING:
166		e = mkexpr(ESTRING, tok);
167		next();
168		return e;
169	case TIDENT:
170		e = mkexpr(EIDENT, tok);
171		next();
172		if(consume(TDCOLON)) {
173			/* the ident tok was actually the namespace */
174			e->ns = e->tok;
175			/* the current token is the ident tok */
176			e->tok = tok;
177			expect(TIDENT);
178		}
179		return e;
180	case TLBRACE:
181		return block();
182	case TLPAREN:
183		opener = tok;
184		next();
185		e = freeexpr();
186		if(tok.kind != TCOMMA) {
187			expect(TRPAREN);
188			return e;
189		}
190		*end = e;
191		end = &e->next;
192		while(consume(TCOMMA)) {
193			a = freeexpr();
194			*end = a;
195			end = &a->next;
196		}
197		expect(TRPAREN);
198		tup = mkexpr(ETUPLE, opener);
199		tup->args = head;
200		return tup;
201	case TFN:
202		return lambda();
203	default:
204		errorat(&tok.loc, "expected expression");
205	}
206}
207
208/*
209 * parse an operand with an optional arg list following
210 * f(x, 1)
211 * List[a, n]
212 */
213static struct expr *
214call(void) {
215	struct expr *e;
216	struct expr *a;
217	struct expr *head = nil;
218	struct expr **end = &head;
219	enum tokenkind closer;
220
221	e = primary();
222	/* a ( or [ on a new line is never a call. */
223	if((tok.kind == TLPAREN || tok.kind == TLBRACK) && tok.loc.line == e->tok.loc.line) {
224		if(e->kind != EIDENT)
225			errorat(&e->tok.loc, "expected function name");
226		if(tok.kind == TLPAREN) {
227			e->kind = ECALL;
228			closer = TRPAREN;
229		} else {
230			e->kind = ESAPP;
231			closer = TRBRACK;
232		}
233		next();
234		if(tok.kind != closer) {
235			do {
236				a = freeexpr();
237				*end = a;
238				end = &a->next;
239			} while(consume(TCOMMA));
240		}
241		expect(closer);
242		e->args = head;
243	}
244	return e;
245}
246
247static struct expr *
248unary(void) {
249	struct expr *e;
250
251	if(tok.kind == TSUB || tok.kind == TBANG || tok.kind == TTILDE) {
252		e = mkexpr(ECALL, tok);
253		next();
254		e->args = unary();
255		return e;
256	}
257	return call();
258}
259
260static struct expr *
261cast(void) {
262	struct expr *e;
263	struct expr *c;
264
265	e = unary();
266	while(tok.kind == TAS) {
267		c = mkexpr(ECAST, tok);
268		next();
269		c->args = e;
270		c->body = type();
271		e = c;
272	}
273	return e;
274}
275
276static int
277prec(enum tokenkind k) {
278	switch(k) {
279	case TOR:
280		return 1;
281	case TAND:
282		return 2;
283	case TEQ:
284	case TNEQ:
285	case TLESS:
286	case TMORE:
287	case TLEQ:
288	case TMEQ:
289		return 3;
290	case TADD:
291	case TSUB:
292	case TBAR:
293	case TBXOR:
294		return 4;
295	case TMUL:
296	case TDIV:
297	case TMOD:
298	case TBAND:
299	case TBSHL:
300	case TBSHR:
301		return 5;
302	default:
303		return 0;
304	}
305}
306
307static struct expr *
308binary(int min) {
309	struct expr *l;
310	struct token op;
311	int p;
312
313	l = cast();
314	while((p = (tok.kind == TBAR && inarm) ? 0 : prec(tok.kind)) >= min) {
315		op = tok;
316		next();
317		l = mkbinary(op, l, binary(p + 1));
318		if(p == 3 && prec(tok.kind) == 3)
319			errorat(&tok.loc, "comparisons can't be chained");
320	}
321	return l;
322}
323
324static struct pat *
325pattern(void) {
326	struct pat *p;
327	struct pat *a;
328	struct pat *head = nil;
329	struct pat **end = &head;
330	struct token opener;
331	int tilde;
332
333	tilde = consume(TTILDE);
334	if(tok.kind == TUS) {
335		p = mkpat(PWILD, tok);
336		next();
337	} else if(tok.kind == TLPAREN) {
338		opener = tok;
339		next();
340		p = pattern();
341		if(tok.kind != TCOMMA)
342			expect(TRPAREN);
343		else {
344			*end = p;
345			end = &p->next;
346			while(consume(TCOMMA)) {
347				a = pattern();
348				*end = a;
349				end = &a->next;
350			}
351			expect(TRPAREN);
352			p = mkpat(PTUPLE, opener);
353			p->args = head;
354		}
355	} else if(tok.kind == TNUMBER || tok.kind == TCHAR) {
356		p = mkpat(PNUM, tok);
357		next();
358	} else {
359		p = mkpat(PNAME, tok);
360		expect(TIDENT);
361		if(consume(TDCOLON)) {
362			/* the ident was the namespace */
363			p->ns = p->name;
364			p->name = tok;
365			expect(TIDENT);
366		}
367		if(consume(TLPAREN)) {
368			p->kind = PCON;
369			do {
370				a = pattern();
371				*end = a;
372				end = &a->next;
373			} while(consume(TCOMMA));
374			expect(TRPAREN);
375			p->args = head;
376		}
377	}
378	p->tilde = tilde;
379	return p;
380}
381
382
383static struct expr *
384expr(void) {
385	struct expr *e;
386	struct arm *a;
387	struct arm *head = nil;
388	struct arm **end = &head;
389
390	if(tok.kind == TIF) {
391		e = mkexpr(EGUARD, tok);
392		next();
393		a = mkarm(tok.loc);
394		a->cond = freeexpr();
395		expect(TTHEN);
396		a->body = freeexpr();
397		a->next = mkarm(tok.loc);
398		expect(TELSE);
399		// cannot be freeexpr, consider this example:
400		// case list of { | Cons(x, _) => if x > 3 then 1 else 2 | _ => 0  }
401		// with freeexpr the second | would be interpreted as the bit-or of 2 and _
402		a->next->body = expr();
403		e->arm = a;
404		return e;
405	}
406	/* guard { | cond_expr => expr | _ => expr } */
407	if(tok.kind == TGUARD) {
408		e = mkexpr(EGUARD, tok);
409		next();
410		expect(TLBRACE);
411		while(tok.kind == TBAR) {
412			a = mkarm(tok.loc);
413			next();
414			if(!consume(TUS))
415				a->cond = freeexpr();
416			expect(TEQARROW);
417			a->body = armbody();
418			*end = a;
419			end = &a->next;
420		}
421		if(!head)
422			errorat(&e->tok.loc, "guard needs atleast one arm");
423		expect(TRBRACE);
424		e->arm = head;
425		return e;
426	}
427	/* case thing of { | pat => expr | _ => expr } */
428	if(tok.kind == TCASE) {
429		e = mkexpr(ECASE, tok);
430		next();
431		e->scrut = freeexpr();
432		expect(TOF);
433		expect(TLBRACE);
434		while(tok.kind == TBAR) {
435			a = mkarm(tok.loc);
436			next();
437			a->pat = pattern();
438			expect(TEQARROW);
439			a->body = armbody();
440			*end = a;
441			end = &a->next;
442		}
443		if(!head)
444			errorat(&e->tok.loc, "case needs atleast one arm");
445		expect(TRBRACE);
446		e->arm = head;
447		return e;
448	}
449	return pipe();
450}
451
452static struct expr *
453block(void) {
454	struct expr *e;
455	struct val *v;
456	struct val *head = nil;
457	struct val **end = &head;
458	int saved = inarm;
459
460	inarm = 0;
461	e = mkexpr(EBLOCK, tok);
462	expect(TLBRACE);
463	while(tok.kind == TVAL) {
464		next();
465		/* val (q, r) = expr */
466		v = mkval(pattern());
467		if(consume(TCOLON))
468			/* val thing: Type = expr */
469			v->ann = type();
470		expect(TASSIGN);
471		/* val thing = expr */
472		v->init = expr();
473		*end = v;
474		end = &v->next;
475	}
476	e->body = expr(); /*final expression, the return value */
477	expect(TRBRACE);
478	e->vals = head;
479	inarm = saved;
480	return e;
481}
482
483static struct expr *
484pipe(void) {
485	struct expr *l;
486	struct expr *r;
487	struct token op;
488	l = binary(1);
489	while(tok.kind == TPIPE) {
490		op = tok;
491		next();
492		r = call();
493		if(r->kind != ECALL)
494			errorat(&op.loc, "expected a function call after |>");
495		l->next = r->args;
496		r->args = l;
497		l = r;
498	}
499	return l;
500}
501
502static struct param *
503sortparam(void) {
504	struct param *p;
505
506	p = param();
507	if(consume(TBAR))
508		p->cond = freeexpr();
509	return p;
510}
511
512
513/*
514 * static sorts in the form [n: type, x: type, etc: type] .
515 * allows refinement like [n: type | n > 0]
516 * */
517static struct param *
518sortparams(void) {
519	struct param *p;
520	struct param *head = nil;
521	struct param **end = &head;
522
523	if(consume(TLBRACK)) {
524		do {
525			p = sortparam();
526			*end = p;
527			end = &p->next;
528		} while(consume(TCOMMA));
529		expect(TRBRACK);
530	}
531	return head;
532}
533
534/*
535 * params in the form { a: thing, b: thing }
536 * or                 (n: int, x: int)
537 */
538static struct param *
539params(enum tokenkind closer) {
540	struct param *p;
541	struct param *head = nil;
542	struct param **end = &head;
543
544	if(tok.kind != closer) {
545		do {
546			p = param();
547			*end = p;
548			end = &p->next;
549		} while(consume(TCOMMA));
550	}
551	expect(closer);
552	return head;
553}
554
555static struct decl *
556fndecl(int ext) {
557	struct decl *d;
558
559	expect(TFN);
560	d = mkdecl(DFN, tok);
561	if(ext && tokis(d->name, "main"))
562			errorat(&d->name.loc, "main can't be extern");
563	expect(TIDENT); 
564	d->sparams = sortparams();
565	expect(TLPAREN);
566	d->params = params(TRPAREN);
567	expect(TARROW);
568	d->ret = type();
569	if(ext) {
570		if(tok.kind == TLBRACE)
571			errorat(&tok.loc, "extern functions can't have a body");
572	} else {
573		curfn = d;
574		d->body = block();
575		curfn = nil;
576	}
577	return d;
578}
579
580/* lambda gets copies of the enclosing fns sort params */
581static struct param *
582outer(void) {
583	struct param *p, *q;
584	struct param *head = nil;
585	struct param **end = &head;
586
587	if(!curfn)
588		return nil;
589	for(p = curfn->sparams; p; p = p->next) {
590		q = mkparam(p->name);
591		q->ann = p->ann;
592		*end = q;
593		end = &q->next;
594	}
595	return head;
596}
597
598static struct expr *
599lambda(void) {
600	struct decl *d;
601	stralloc sa = {0};
602	char num[FMTUSIZE];
603	struct decl *saved;
604	struct param **end;
605
606	d = mkdecl(DFN, tok);
607	sacatl(&sa, "anon.");
608	sacatb(&sa, num, fmtusize(num, ++nlambdas));
609	d->name.str = sa.s;
610	d->name.length = sa.len;
611
612	expect(TFN);
613	/* the enclosing function's sorts */
614	d->sparams = outer();
615	for(end = &d->sparams; *end; end = &(*end)->next)
616		;
617	/* lambda-local sorts */
618	*end = sortparams();
619	expect(TLPAREN);
620	d->params = params(TRPAREN);
621	expect(TARROW);
622	d->ret = type();
623	saved = curfn;
624	curfn = d;
625	d->body = block();
626	curfn = saved;
627	*lambdaend = d;
628	lambdaend = &d->next;
629	return mkexpr(EIDENT, d->name);
630}
631
632static struct decl *
633structdecl(void) {
634	struct decl *d;
635
636	expect(TSTRUCT);
637	d = mkdecl(DSTRUCT, tok);
638	expect(TIDENT);
639	expect(TLBRACE);
640	d->params = params(TRBRACE);
641	return d;
642}
643
644
645static struct expr *
646types(void) {
647	struct expr *t;
648	struct expr *head = nil;
649	struct expr **end = &head;
650
651	do {
652		t = type();
653		*end = t;
654		end = &t->next;
655	} while(consume(TCOMMA));
656	return head;
657}
658
659static struct decl *
660datadecl(void) {
661	struct decl *d;
662	struct ctor *c;
663	struct ctor *head = nil;
664	struct ctor **end = &head;
665	struct param *sp;
666
667	/* the declaration */
668	expect(TDATATYPE);
669	d = mkdecl(DDATA, tok);
670	expect(TIDENT);
671	d->sparams = sortparams();
672	expect(TLBRACE);
673	/* the constructors */
674	while(consume(TBAR)) {
675		/* constructor-local sorts */
676		sp = sortparams();
677		c = mkctor(tok);
678		expect(TIDENT);
679		c->sparams = sp;
680		if(consume(TLPAREN)) {
681			c->args = types();
682			expect(TRPAREN);
683		}
684		/*if we declared the consructors result type */
685		if(consume(TCOLON))
686			c->ret = type();
687		else if(!d->sparams)
688			c->ret = mkexpr(EIDENT, d->name);
689		*end = c;
690		end = &c->next;
691	}
692	expect(TRBRACE);
693	d->ctors = head;
694	return d;
695}
696
697/* desugar a newtype declaration to a single-constuctor datatype */
698static struct decl *
699newtypedecl(void) {
700	struct decl *d;
701	struct ctor *c;
702
703	expect(TNEWTYPE);
704	d = mkdecl(DDATA, tok);
705	expect(TIDENT);
706	expect(TASSIGN);
707	c = mkctor(d->name);
708	c->args = type();
709	c->ret = mkexpr(EIDENT, d->name);
710	d->ctors = c;
711	d->newtype = 1;
712	return d;
713}
714
715static struct decl *
716sortdefdecl(void) {
717	struct decl *d;
718
719	expect(TSORTDEF);
720	d = mkdecl(DSORTDEF, tok);
721	expect(TIDENT);
722	expect(TASSIGN);
723	if(tok.kind == TLBRACK) {
724		d->sparams = sortparams();
725		if(d->sparams->next)
726			errorat(&d->name.loc, "a sortdef takes only one parameter");
727	} else
728		d->ret = type();
729	return d;
730}
731
732static struct decl *
733typedefdecl(void) {
734	struct decl *d;
735
736	expect(TTYPEDEF);
737	d = mkdecl(DTYPEDEF, tok);
738	expect(TIDENT);
739	d->sparams = sortparams();
740	expect(TASSIGN);
741	d->ret = type();
742	return d;
743}
744
745static struct decl *
746usedecl(void) {
747	struct decl *d;
748
749	expect(TUSE);
750	d = mkdecl(DUSE, tok);
751	if(tok.kind != TSTRING && tok.kind != TUSEPATH)
752		errorat(&tok.loc, "expected module path");
753	next();
754	if(consume(TAS)) {
755		d->alias = tok;
756		expect(TIDENT);
757	}
758	return d;
759}
760
761static struct decl *
762decl(void) {
763	struct decl *d;
764	int pub;
765	int linear;
766	int abstract;
767	int ext;
768
769	pub = consume(TPUB);
770	abstract = consume(TABSTRACT);
771	linear = consume(TLINEAR);
772	ext = consume(TEXTERN);
773	if(abstract && tok.kind != TDATATYPE && tok.kind != TNEWTYPE)
774		errorat(&tok.loc, "only datatypes and newtypes can be abstract");
775	if(ext && tok.kind != TFN) 
776		errorat(&tok.loc, "only functions can be extern");
777	if(tok.kind == TFN) {
778		if(linear)
779			errorat(&tok.loc, "functions cannot be linear");
780		d = fndecl(ext);
781	} else if(tok.kind == TSTRUCT)
782		d = structdecl();
783	else if(tok.kind == TDATATYPE)
784		d = datadecl();
785	else if(tok.kind == TNEWTYPE)
786		d = newtypedecl();
787	else if(tok.kind == TTYPEDEF) {
788		if(linear)
789			errorat(&tok.loc, "typedefs cannot be linear");
790		d = typedefdecl();
791	} else if(tok.kind == TSORTDEF) {
792		if(linear)
793			errorat(&tok.loc, "sortdefs cannot be linear");
794		d = sortdefdecl();
795	} else if(tok.kind == TUSE) {
796		if(linear)
797			errorat(&tok.loc, "module imports cannot be linear");
798		d = usedecl();
799	} else
800		errorat(&tok.loc, "malformed declaration");
801
802	d->pub = pub;
803	d->linear = linear;
804	d->abstract = abstract;
805	d->ext = ext;
806	return d;
807}
808
809struct decl *
810parse(const char *file, const char *src) {
811	struct decl *d;
812	struct decl *head = nil;
813	struct decl **end = &head;
814
815	lx.cur = src;
816	lx.linestart = src;
817	lx.line = 1;
818	lx.file = file;
819	lx.afteruse = 0;
820
821	next();
822	lambdas = nil;
823	lambdaend = &lambdas;
824	while(tok.kind != TEOF) {
825		d = decl();
826		*end = d;
827		end = &d->next;
828	}
829	*end = lambdas;
830	return head;
831}