1 /**
2 * Authors: k.inaba
3 * License: NYSL 0.9982 http://www.kmonos.net/nysl/
4 *
5 * Parser for Polemy programming language
6 */
7 module polemy.parse;
8 import polemy._common;
9 import polemy.failure;
10 import polemy.lex;
11 import polemy.ast;
12 import polemy.layer;
13 import polemy.fresh;
14
15 /// Parse a string and return its AST
16
17 AST parseString(S, T...)(S str, T fn_ln_cn)
18 {
19 return parserFromString(str, fn_ln_cn).parse();
20 }
21
22 /// Parse the content of a file and return its AST
23
24 AST parseFile(S, T...)(S filename, T ln_cn)
25 {
26 return parserFromFile(filename, ln_cn).parse();
27 }
28
29 // Named Constructors of Parser
30
31 private auto parserFromLexer(Lexer)(Lexer lex)
32 { return new Parser!Lexer(lex); }
33
34 private auto parserFromString(T...)(T params)
35 { return parserFromLexer(lexerFromString(params)); }
36
37 private auto parserFromFile(T...)(T params)
38 { return parserFromLexer(lexerFromFile(params)); }
39
40 // Parser
41
42 private class Parser(Lexer)
43 if( isForwardRange!(Lexer) && is(ElementType!(Lexer) == Token) )
44 {
45 AST parse()
46 {
47 auto e = Body();
48 if( !lex.empty )
49 throw genex!ParseException(currentPosition(), "parsing ended but some tokens left");
50 return e;
51 }
52
53 AST Body()
54 {
55 /// Body ::= Declaration
56 /// | TopLevelExpression
57
58 if( closingBracket() )
59 return doNothingExpression();
60
61 auto saved = lex.save;
62 if( auto e = Declaration() )
63 return e;
64 lex = saved;
65 return TopLevelExpression();
66 }
67
68 AST Declaration() // returns null if it is not a declaration
69 {
70 /// Declaration ::=
71 /// ["@" Layer|"let"|"var"|"def"] Var "=" Expression ([";"|"in"] Body?)?
72 /// | ["@" Layer|"let"|"var"|"def"] Var "(" Param%"," ")" "{" Body "}" ([";"|"in"] Body?)?
73 /// | ["@" "@" Layer "=" Expression ([";"|"in"] Body?)?
74 /// | ["@" "@" Layer "(" Param%"," ")" "{" Body "}" ([";"|"in"] Body?)?
75
76 auto pos = currentPosition();
77 Layer layer = "";
78 bool layerLiftDecl = false;
79
80 if( tryEat("@") )
81 {
82 layer = "@" ~ eatId("after @", AllowQuoted);
83 if( layer == "@@" )
84 {
85 layer = "@" ~ eatId("after @@", AllowQuoted);
86 layerLiftDecl = true;
87 }
88 else
89 {
90 if( tryEat("(") )
91 return null; // @lay(...) expression, not a declaration
92 }
93 }
94
95 // [TODO] Refactor
96 if( layerLiftDecl )
97 {
98 string kwd = "@" ~ layer;
99 string var = layer;
100
101 auto e = tryEat("(")
102 ? parseLambdaAfterOpenParen(pos) // let var ( ...
103 : (eat("=", "after "~kwd), E(0)); // let var = ...
104 if( moreDeclarationExists() )
105 return new Let(pos, var, SystemLayer, e, Body());
106 else
107 return new Let(pos, var, SystemLayer, e,
108 new Lay(pos, SystemLayer, new Var(pos, var))
109 );
110 }
111 else
112 {
113 string kwd = layer;
114 if( layer.empty && !tryEat(kwd="let") && !tryEat(kwd="var") && !tryEat(kwd="def") )
115 return null; // none of {@lay, let, var, def} occurred, it's not a declaration
116
117 auto varpos = currentPosition();
118 string var = eatId("after "~kwd, AllowQuoted); // name of the declared variable
119
120 auto e = tryEat("(")
121 ? parseLambdaAfterOpenParen(pos) // let var ( ...
122 : (eat("=", "after "~kwd), E(0)); // let var = ...
123 if( moreDeclarationExists() )
124 return new Let(pos, var, layer, e, Body());
125 else
126 return new Let(pos, var, layer, e, new Var(varpos, var));
127 }
128 }
129
130 AST TopLevelExpression()
131 {
132 /// TopLevelExpression ::= Expression ([";"|"in"] Body?)?
133
134 auto pos = currentPosition();
135 auto e = E(0);
136 if( moreDeclarationExists() )
137 return new Let(pos, "_", "", e, Body());
138 else
139 return e;
140 }
141
142 private bool moreDeclarationExists()
143 {
144 return (tryEat(";") || tryEat("in")) && !closingBracket();
145 }
146
147 private bool closingBracket()
148 {
149 return lex.empty || !lex.front.quoted && ["}",")","]",","].canFind(lex.front.str);
150 }
151
152 // [TODO] make this customizable from program
153 private static string[][] operator_perferences = [
154 ["||"],
155 ["&&"],
156 ["!="],
157 ["=="],
158 ["<","<=",">",">="],
159 ["|"],
160 ["^"],
161 ["&"],
162 ["<<", ">>", "<<<", ">>>"],
163 ["+","-"],
164 ["~"],
165 ["*","/","%"],
166 ["^^","**"],
167 [".",".?"]
168 ];
169
170 AST E(size_t level)
171 {
172 /// Expression ::= (Binary left-associative operators over) Funcall
173
174 AST rec(AST lhs)
175 {
176 if( closingBracket() )
177 return lhs;
178
179 auto pos = currentPosition();
180 foreach(op; operator_perferences[level])
181 if( tryEat(op) )
182 if( op[0]=='.' )
183 return rec(
184 new App(lhs.pos, new Var(pos, op), lhs, parseId()));
185 else
186 return rec(
187 new App(lhs.pos, new Var(pos, op), lhs, E(level+1)));
188 return lhs;
189 }
190
191 if( operator_perferences.length <= level )
192 return Funcall();
193 else
194 return rec(E(level+1));
195 }
196
197 AST Funcall()
198 {
199 /// Funcall ::= BaseExpression ["(" Expression%"," ")" | "{" ENTRIES "}"]*
200
201 auto e = BaseExpression();
202 for(;;)
203 if( tryEat("(") )
204 {
205 auto pos = currentPosition();
206 AST[] args;
207 while( !tryEat(")") ) {
208 if( lex.empty )
209 throw genex!UnexpectedEOF(pos, "closing ')' for arguments not found");
210 args ~= E(0);
211 if( !tryEat(",") ) {
212 eat(")", "after function parameters");
213 break;
214 }
215 }
216 e = new App(e.pos, e, args);
217 }
218 else if( tryEat("{") )
219 {
220 e = parseTableSetAfterBrace(e);
221 }
222 else
223 break;
224 return e;
225 }
226
227 AST parseTableSetAfterBrace(AST e)
228 {
229 /// TableSet ::= "{" (ID ":" E) % "," "}"
230
231 if( tryEat("}") )
232 return e;
233 auto pos = currentPosition();
234 for(;;)
235 {
236 string key = eatId("for table key", AllowQuoted);
237 eat(":", "after table key");
238 AST val = E(0);
239 e = new App(pos, new Var(pos,".="),
240 e, new Str(pos,key), val);
241 if( !tryEat(",") )
242 {
243 eat("}", "for the end of table literal");
244 break;
245 }
246 }
247 return e;
248 }
249
250 AST BaseExpression()
251 {
252 if( lex.empty )
253 throw genex!UnexpectedEOF(currentPosition(), "Reached EOF when tried to parse an expression");
254
255 auto pos = lex.front.pos;
256 if( lex.front.quoted )
257 {
258 scope(exit) lex.popFront;
259 return new Str(pos, lex.front.str);
260 }
261 if( isNumber(lex.front.str) )
262 {
263 scope(exit) lex.popFront;
264 return new Int(pos, BigInt(cast(string)lex.front.str));
265 }
266 if( tryEat("@") )
267 {
268 auto lay = "@"~eatId("for layer ID");
269 eat("(", "for layered execution");
270 auto e = Body();
271 eat(")", "after "~lay~"(...");
272 return new Lay(pos, lay, e);
273 }
274 if( tryEat("(") )
275 {
276 auto e = Body();
277 eat(")", "after parenthesized expression");
278 return e;
279 }
280 if( tryEat("{") )
281 {
282 AST e = new App(pos, new Var(pos,"{}"));
283 return parseTableSetAfterBrace(e);
284 }
285 if( tryEat("if") )
286 {
287 return parseIfAfterIf(pos);
288 }
289 if( tryEat("case") )
290 {
291 return parsePatternMatch(pos);
292 }
293 if( tryEat("fun") || tryEat("\u03BB") ) // lambda!!
294 {
295 eat("(", "after fun");
296 return parseLambdaAfterOpenParen(pos);
297 }
298 scope(exit) lex.popFront;
299 return new Var(pos, lex.front.str);
300 }
301
302 AST parseIfAfterIf(LexPosition pos)
303 {
304 eat("(", "after if");
305 auto cond = E(0);
306 eat(")", "after if condition");
307 auto thenPos = lex.front.pos;
308 AST th;
309 if( tryEat("{") ) {
310 th = Body();
311 eat("}", "after if-then body");
312 } else {
313 th = E(0);
314 }
315 auto el = doNothingExpression();
316 auto elsePos = (lex.empty ? LexPosition.dummy : lex.front.pos);
317 if( tryEat("else") )
318 if( tryEat("{") ) {
319 el = Body();
320 eat("}", "after else body");
321 } else {
322 el = E(0);
323 }
324 return new App(pos, new Var(pos,"if"), cond, new Fun(thenPos,[],th), new Fun(elsePos,[],el));
325 }
326
327 AST parsePatternMatch(LexPosition pos)
328 {
329 // case pmExpr CASES
330 //==>
331 // let pmVar = pmExpr in (... let pmTryFirst = ... in pmTryFirst())
332 AST pmExpr = E(0);
333 string pmVar = freshVarName();
334 string pmTryFirst = freshVarName();
335 AST pmBody = parsePatternMatchCases(pmVar, pmTryFirst,
336 new App(pos, new Var(pos, pmTryFirst)));
337 return new Let(pos, pmVar, [], pmExpr, pmBody);
338 }
339
340 AST parsePatternMatchCases(string pmVar, string tryThisBranchVar, AST thenDoThis)
341 {
342 // when pat: cBody
343 //==>
344 // ... let failBranchVar = ... in
345 // let tryThisBranchVar = fun(){ if(test){cBody}else{failBranchVar()} } in thenDoThis
346 if( tryEat("when") )
347 {
348 auto pos = currentPosition();
349 string failBranchVar = freshVarName();
350
351 auto pr = parsePattern();
352 eat(":", "after when pattern");
353 AST cBody = E(0);
354 AST judgement = new App(pos, new Var(pos, "if"),
355 ppTest(pmVar, pr), new Fun(pos,[],ppBind(pmVar, pr, cBody)),
356 new Var(pos, failBranchVar));
357 return parsePatternMatchCases(pmVar, failBranchVar,
358 new Let(pos, tryThisBranchVar, [],
359 new Fun(pos,[],judgement), thenDoThis)
360 );
361 }
362 else
363 {
364 auto pos = currentPosition();
365 AST doNothing = new Fun(pos,[],
366 new Str(pos, sprintf!"(pattern match failure:%s)"(pos)));
367 return new Let(currentPosition(), tryThisBranchVar, [], doNothing, thenDoThis);
368 }
369 }
370
371 // hageshiku tenuki
372 abstract class SinglePattern
373 {
374 string[] path;
375 mixin SimpleClass;
376 private AST access(string pmVar, string[] path) {
377 auto pos = currentPosition();
378 AST e = new Var(pos, pmVar);
379 foreach(p; path)
380 e = new App(pos, new Var(pos, "."), e, new Str(pos, p));
381 return e;
382 }
383 private AST has(AST e, string k) {
384 auto pos = currentPosition();
385 return opAndAnd(
386 new App(pos, new Var(pos, "_istable"), e),
387 new App(pos, new Var(pos, ".?"), e, new Str(pos, k))
388 );
389 }
390 private AST opAndAnd(AST a, AST b) {
391 if( a is null ) return b;
392 if( b is null ) return a;
393 auto pos = currentPosition();
394 return new App(pos,
395 new Var(pos, "if"),
396 a,
397 new Fun(pos, [], b),
398 new Fun(pos, [], new Int(pos, 0))
399 );
400 }
401 AST ppTest(string pmVar) {
402 AST c = null;
403 for(int i=0; i<path.length; ++i)
404 c = opAndAnd(c, has(access(pmVar,path[0..i]), path[i]));
405 return c;
406 }
407 AST ppBind(string pmVar, AST thenDoThis) { return thenDoThis; }
408 }
409 class WildPattern : SinglePattern
410 {
411 mixin SimpleClass;
412 }
413 class VarPattern : SinglePattern
414 {
415 string name;
416 mixin SimpleClass;
417 AST ppBind(string pmVar, AST thenDoThis) {
418 auto pos = currentPosition();
419 return new Let(pos, name, [], access(pmVar,path), thenDoThis);
420 }
421 }
422 class ConstantPattern : SinglePattern
423 {
424 AST e;
425 mixin SimpleClass;
426 AST ppTest(string pmVar) {
427 auto pos = currentPosition();
428 return opAndAnd( super.ppTest(pmVar),
429 new App(pos, new Var(pos,"=="), access(pmVar,path), e)
430 );
431 }
432 }
433
434 SinglePattern[] parsePattern(string[] path = null)
435 {
436 SinglePattern[] result;
437 if( tryEat("{") )
438 {
439 if( !tryEat("}") ) {
440 do {
441 string key = eatId("in table pattern", AllowQuoted);
442 eat(":", "after field-id in table pattern");
443 result ~= parsePattern(path ~ key);
444 } while( tryEat(",") );
445 eat("}", "at the end of table pattern");
446 }
447 }
448 else
449 {
450 AST e = E(0);
451 if(auto ev = cast(Var)e)
452 if(ev.name == "_")
453 result ~= new WildPattern(path);
454 else
455 result ~= new VarPattern(path, ev.name);
456 else
457 result ~= new ConstantPattern(path, e);
458 }
459 return result;
460 }
461
462 AST ppTest(string pmVar, SinglePattern[] pats)
463 {
464 auto pos = currentPosition();
465 AST cond = null;
466 foreach(p; pats) {
467 AST c2 = p.ppTest(pmVar);
468 if( c2 !is null )
469 cond = cond is null ? c2
470 : new App(pos, new Var(pos,"&&"), cond, c2);
471 }
472 return cond is null ? new Int(currentPosition(), 1) : cond;
473 }
474
475 AST ppBind(string pmVar, SinglePattern[] pats, AST thenDoThis)
476 {
477 foreach(p; pats)
478 thenDoThis = p.ppBind(pmVar, thenDoThis);
479 return thenDoThis;
480 }
481
482 AST parseId()
483 {
484 scope(exit) lex.popFront;
485 return new Str(currentPosition(), lex.front.str);
486 }
487
488 AST parseLambdaAfterOpenParen(LexPosition pos)
489 {
490 Parameter[] params;
491 while( !tryEat(")") )
492 {
493 params ~= parseParam();
494 if( !tryEat(",") ) {
495 eat(")", "after function parameters");
496 break;
497 }
498 }
499 eat("{", "after function parameters");
500 auto funbody = Body();
501 eat("}", "after function body");
502 return new Fun(pos, params, funbody);
503 }
504
505 Parameter parseParam()
506 {
507 string var;
508 string[] lay;
509 while( !closingBracket() && !lex.empty && lex.front.str!="," )
510 {
511 auto pos = currentPosition();
512 string p = eatId("for function parameter", AllowQuoted);
513 if( p == "@" )
514 lay ~= "@" ~ eatId("after @", AllowQuoted);
515 else if( var.empty )
516 var = p;
517 else
518 throw genex!ParseException(pos, "one parameter has two names");
519 }
520 return new Parameter(var, lay);
521 }
522
523 private:
524 Lexer lex;
525 this(Lexer lex) { this.lex = lex; }
526
527 bool isNumber(string s)
528 {
529 return find!(`a<'0' || '9'<a`)(s).empty;
530 }
531
532 void eat(string kwd, lazy string msg)
533 {
534 if( !tryEat(kwd) )
535 if( lex.empty )
536 throw genex!UnexpectedEOF(
537 currentPosition(), sprintf!"%s is expected %s but not found"(kwd,msg));
538 else
539 throw genex!ParseException(
540 currentPosition(), sprintf!"%s is expected for %s but not found"(kwd,msg));
541 }
542
543 bool tryEat(string kwd)
544 {
545 if( lex.empty || lex.front.quoted || lex.front.str!=kwd )
546 return false;
547 lex.popFront;
548 return true;
549 }
550
551 enum {AllowQuoted=true, DisallowQuoted=false};
552 string eatId(lazy string msg, bool aq=DisallowQuoted)
553 {
554 if( lex.empty )
555 throw genex!UnexpectedEOF(currentPosition(), "identifier is expected but not found "~msg);
556 if( !aq && lex.front.quoted )
557 throw genex!ParseException(currentPosition(), "identifier is expected but not found "~msg);
558 scope(exit) lex.popFront;
559 return lex.front.str;
560 }
561
562 AST doNothingExpression()
563 {
564 return new Str(currentPosition(), "(empty function body)");
565 }
566
567 LexPosition currentPosition()
568 {
569 return lex.empty ? null : lex.front.pos;
570 }
571 }
572
573 unittest
574 {
575 mixin EasyAST;
576
577 assert_eq(parseString(`123`), intl(123));
578 assert_eq(parseString(`"foo"`), strl("foo"));
579 assert_eq(parseString(`fun(){1}`), fun([],intl(1)));
580 assert_eq(parseString(`fun(x){1}`), fun(["x"],intl(1)));
581 assert_eq(parseString("\u03BB(){1}"), fun([],intl(1)));
582 assert_eq(parseString("\u03BB(x){1}"), fun(["x"],intl(1)));
583 assert_eq(parseString(`1;2`), let("_","",intl(1),intl(2)));
584 assert_eq(parseString(`1;2;`), let("_","",intl(1),intl(2)));
585 assert_eq(parseString(`let x=1 in 2`), let("x","",intl(1),intl(2)));
586 assert_eq(parseString(`var x=1;2;`), let("x","",intl(1),intl(2)));
587 assert_eq(parseString(`def x=1`), let("x","",intl(1),var("x")));
588 assert_eq(parseString(`@val x=1;`), let("x","@val",intl(1),var("x")));
589 assert_eq(parseString(`@typ x="#int";`), let("x","@typ",strl("#int"),var("x")));
590 assert_eq(parseString(`f(1,2)`), call(var("f"),intl(1),intl(2)));
591 assert_eq(parseString(`if(1){2}`), call(var("if"),intl(1),fun([],intl(2)),fun([],strl("(empty function body)"))));
592 assert_eq(parseString(`if(1){2}else{3}`), call(var("if"),intl(1),fun([],intl(2)),fun([],intl(3))));
593 assert_eq(parseString(`if(1){}else{3}()()`),
594 call(call(call(var("if"),intl(1),fun([],strl("(empty function body)")),fun([],intl(3))))));
595 assert_eq(parseString(`1+2*3`), call(var("+"),intl(1),call(var("*"),intl(2),intl(3))));
596 assert_eq(parseString(`(1+2)*3`), call(var("*"),call(var("+"),intl(1),intl(2)),intl(3)));
597 assert_eq(parseString(`1*(2+3)`), call(var("*"),intl(1),call(var("+"),intl(2),intl(3))));
598 assert_eq(parseString(`1*2+3`), call(var("+"),call(var("*"),intl(1),intl(2)),intl(3)));
599 assert_eq(parseString(`@x(1)`), lay("@x", intl(1)));
600 assert_eq(parseString(`fun(x @v @t, y, z @t){}`),
601 funp([param("x",["@v","@t"]), param("y",[]), param("z",["@t"])], strl("(empty function body)")));
602
603 assert_eq(parseString(`
604 let x = 100; #comment
605 let y = 200; #comment!!!!!
606 x+y
607 `),
608 let("x", "", intl(100), let("y", "", intl(200), call(var("+"), var("x"), var("y"))))
609 );
610
611 assert_eq(parseString(`
612 var fac = fun(x){ if(x <= 1) {1} else {x*fac(x-1)} };
613 fac(10)
614 `),
615 let("fac", "", fun(["x"],
616 call(var("if"),
617 call(var("<="), var("x"), intl(1)),
618 fun([], intl(1)),
619 fun([], call(var("*"), var("x"), call(var("fac"),call(var("-"),var("x"),intl(1)))))
620 )),
621 call(var("fac"),intl(10))
622 )
623 );
624 }
625
626 unittest
627 {
628 assert_throw!UnexpectedEOF(parseString(`1+`));
629 assert_throw!ParseException(parseString(`1+2}`));
630 assert_throw!UnexpectedEOF(parseString(`let "x"`));
631 assert_throw!UnexpectedEOF(parseString(`var`));
632 assert_throw!ParseException(parseString(`@val x ==`));
633 assert_throw!ParseException(parseString(`if(){1}`));
634 assert_throw!UnexpectedEOF(parseString(`f(`));
635 }
636
637 unittest
638 {
639 mixin EasyAST;
640 assert_eq(parseString(`def foo(x) { x+1 }; foo`),
641 let("foo", "",
642 fun(["x"], call(var("+"), var("x"), intl(1))),
643 var("foo"))
644 );
645
646 assert_eq(parseString(`@@type ( x ) { x }`),
647 let("@type", SystemLayer, fun(["x"], var("x")), lay(SystemLayer, var("@type"))) );
648
649 assert_eq(parseString(`{}`), call(var("{}")));
650 assert_eq(parseString(`{foo:1,"bar":2}`),
651 call(var(".="), call(var(".="), call(var("{}")), strl("foo"), intl(1)), strl("bar"), intl(2)));
652 assert_eq(parseString(`{}.foo`), call(var("."),call(var("{}")),strl("foo")));
653 assert_eq(parseString(`{}.?foo`), call(var(".?"),call(var("{}")),strl("foo")));
654 assert_eq(parseString(`x{y:1}`), call(var(".="),var("x"),strl("y"),intl(1)));
655 }
656
657 unittest
658 {
659 assert_nothrow(parseString(`
660 case( 1 )
661 when(x): 1
662 `));
663 assert_nothrow(parseString(`
664 case 1
665 when {aaaa:_}: 1
666 `));
667 assert_nothrow(parseString(`
668 case 1
669 when {aaaa:@value(x)}: 1
670 when {aaaa:{bbb:_}, ccc:123}: 1
671 `));
672 }
673
674 unittest
675 {
676 // test for omitting { .. }
677 assert_nothrow(parseString(`
678 if(1) 2 else 3
679 `));
680 assert_nothrow(parseString(`
681 if(1) x{y:z} else 3
682 `));
683 }