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(varpos) // 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 eat("(", "after if");
288 auto cond = E(0);
289 eat(")", "after if condition");
290 auto thenPos = lex.front.pos;
291 eat("{", "after if condition");
292 auto th = Body();
293 eat("}", "after if-then body");
294 auto el = doNothingExpression();
295 auto elsePos = (lex.empty ? LexPosition.dummy : lex.front.pos);
296 if( tryEat("else") ) {
297 eat("{", "after else");
298 el = Body();
299 eat("}", "after else body");
300 }
301 return new App(pos,
302 new Var(pos, "if"),
303 cond,
304 new Fun(thenPos, [], th),
305 new Fun(elsePos, [], el)
306 );
307 }
308 if( tryEat("case") )
309 {
310 return parsePatternMatch(pos);
311 }
312 if( tryEat("fun") || tryEat("\u03BB") ) // lambda!!
313 {
314 eat("(", "after fun");
315 return parseLambdaAfterOpenParen(pos);
316 }
317 scope(exit) lex.popFront;
318 return new Var(pos, lex.front.str);
319 }
320
321 AST parsePatternMatch(LexPosition pos)
322 {
323 // case "(" pmExpr ")" CASES
324 //==>
325 // let pmVar = pmExpr in (... let pmTryFirst = ... in pmTryFirst())
326 eat("(", "after case");
327 AST pmExpr = E(0);
328 eat(")", "after case");
329 string pmVar = freshVarName();
330 string pmTryFirst = freshVarName();
331 AST pmBody = parsePatternMatchCases(pmVar, pmTryFirst,
332 new App(pos, new Var(pos, pmTryFirst)));
333 return new Let(pos, pmVar, [], pmExpr, pmBody);
334 }
335
336 AST parsePatternMatchCases(string pmVar, string tryThisBranchVar, AST thenDoThis)
337 {
338 // when( pat ) { cBody }
339 //==>
340 // ... let failBranchVar = ... in
341 // let tryThisBranchVar = fun(){ if(test){cBody}else{failBranchVar()} } in thenDoThis
342 if( tryEat("when") )
343 {
344 auto pos = currentPosition();
345 string failBranchVar = freshVarName();
346
347 eat("(", "after when");
348 auto pr = parsePattern();
349 eat(")", "after when");
350 eat("{", "after pattern");
351 AST cBody = Body();
352 AST judgement = new App(pos, new Var(pos, "if"),
353 ppTest(pmVar, pr), new Fun(pos,[],ppBind(pmVar, pr, cBody)),
354 new Var(pos, failBranchVar));
355 eat("}", "after pattern clause");
356 return parsePatternMatchCases(pmVar, failBranchVar,
357 new Let(pos, tryThisBranchVar, [],
358 new Fun(pos,[],judgement), thenDoThis)
359 );
360 }
361 else
362 {
363 auto pos = currentPosition();
364 AST doNothing = new Fun(pos,[],
365 new Str(pos, sprintf!"(pattern match failure:%s)"(pos)));
366 return new Let(currentPosition(), tryThisBranchVar, [], doNothing, thenDoThis);
367 }
368 }
369
370 // hageshiku tenuki
371 abstract class SinglePattern
372 {
373 string[] path;
374 mixin SimpleClass;
375 private AST access(string pmVar, string[] path) {
376 auto pos = currentPosition();
377 AST e = new Var(pos, pmVar);
378 foreach(p; path)
379 e = new App(pos, new Var(pos, "."), e, new Str(pos, p));
380 return e;
381 }
382 private AST has(AST e, string k) {
383 auto pos = currentPosition();
384 return opAndAnd(
385 new App(pos, new Var(pos, "_istable"), e),
386 new App(pos, new Var(pos, ".?"), e, new Str(pos, k))
387 );
388 }
389 private AST opAndAnd(AST a, AST b) {
390 if( a is null ) return b;
391 if( b is null ) return a;
392 auto pos = currentPosition();
393 return new App(pos,
394 new Var(pos, "if"),
395 a,
396 new Fun(pos, [], b),
397 new Fun(pos, [], new Int(pos, 0))
398 );
399 }
400 AST ppTest(string pmVar) {
401 AST c = null;
402 for(int i=0; i<path.length; ++i)
403 c = opAndAnd(c, has(access(pmVar,path[0..i]), path[i]));
404 return c;
405 }
406 AST ppBind(string pmVar, AST thenDoThis) { return thenDoThis; }
407 }
408 class WildPattern : SinglePattern
409 {
410 mixin SimpleClass;
411 }
412 class VarPattern : SinglePattern
413 {
414 string name;
415 mixin SimpleClass;
416 AST ppBind(string pmVar, AST thenDoThis) {
417 auto pos = currentPosition();
418 return new Let(pos, name, [], access(pmVar,path), thenDoThis);
419 }
420 }
421 class ConstantPattern : SinglePattern
422 {
423 AST e;
424 mixin SimpleClass;
425 AST ppTest(string pmVar) {
426 auto pos = currentPosition();
427 return opAndAnd( super.ppTest(pmVar),
428 new App(pos, new Var(pos,"=="), access(pmVar,path), e)
429 );
430 }
431 }
432
433 SinglePattern[] parsePattern(string[] path = null)
434 {
435 SinglePattern[] result;
436 if( tryEat("{") )
437 {
438 if( !tryEat("}") ) {
439 do {
440 string key = eatId("in table pattern");
441 eat(":", "after field-id in table pattern");
442 result ~= parsePattern(path ~ key);
443 } while( tryEat(",") );
444 eat("}", "at the end of table pattern");
445 }
446 }
447 else
448 {
449 AST e = E(0);
450 if(auto ev = cast(Var)e)
451 if(ev.name == "_")
452 result ~= new WildPattern(path);
453 else
454 result ~= new VarPattern(path, ev.name);
455 else
456 result ~= new ConstantPattern(path, e);
457 }
458 return result;
459 }
460
461 AST ppTest(string pmVar, SinglePattern[] pats)
462 {
463 auto pos = currentPosition();
464 AST cond = null;
465 foreach(p; pats) {
466 AST c2 = p.ppTest(pmVar);
467 if( c2 !is null )
468 cond = cond is null ? c2
469 : new App(pos, new Var(pos,"&&"), cond, c2);
470 }
471 return cond is null ? new Int(currentPosition(), 1) : cond;
472 }
473
474 AST ppBind(string pmVar, SinglePattern[] pats, AST thenDoThis)
475 {
476 foreach(p; pats)
477 thenDoThis = p.ppBind(pmVar, thenDoThis);
478 return thenDoThis;
479 }
480
481 AST parseId()
482 {
483 scope(exit) lex.popFront;
484 return new Str(currentPosition(), lex.front.str);
485 }
486
487 AST parseLambdaAfterOpenParen(immutable LexPosition pos)
488 {
489 Parameter[] params;
490 while( !tryEat(")") )
491 {
492 params ~= parseParam();
493 if( !tryEat(",") ) {
494 eat(")", "after function parameters");
495 break;
496 }
497 }
498 eat("{", "after function parameters");
499 auto funbody = Body();
500 eat("}", "after function body");
501 return new Fun(pos, params, funbody);
502 }
503
504 Parameter parseParam()
505 {
506 string var;
507 string[] lay;
508 while( !closingBracket() && !lex.empty && lex.front.str!="," )
509 {
510 auto pos = currentPosition();
511 string p = eatId("for function parameter", AllowQuoted);
512 if( p == "@" )
513 lay ~= "@" ~ eatId("after @", AllowQuoted);
514 else if( var.empty )
515 var = p;
516 else
517 throw genex!ParseException(pos, "one parameter has two names");
518 }
519 return new Parameter(var, lay);
520 }
521
522 private:
523 Lexer lex;
524 this(Lexer lex) { this.lex = lex; }
525
526 bool isNumber(string s)
527 {
528 return find!(`a<'0' || '9'<a`)(s).empty;
529 }
530
531 void eat(string kwd, lazy string msg)
532 {
533 if( !tryEat(kwd) )
534 if( lex.empty )
535 throw genex!UnexpectedEOF(
536 currentPosition(), sprintf!"%s is expected %s but not found"(kwd,msg));
537 else
538 throw genex!ParseException(
539 currentPosition(), sprintf!"%s is expected for %s but not found"(kwd,msg));
540 }
541
542 bool tryEat(string kwd)
543 {
544 if( lex.empty || lex.front.quoted || lex.front.str!=kwd )
545 return false;
546 lex.popFront;
547 return true;
548 }
549
550 enum {AllowQuoted=true, DisallowQuoted=false};
551 string eatId(lazy string msg, bool aq=DisallowQuoted)
552 {
553 if( lex.empty )
554 throw genex!UnexpectedEOF(currentPosition(), "identifier is expected but not found "~msg);
555 if( !aq && lex.front.quoted )
556 throw genex!ParseException(currentPosition(), "identifier is expected but not found "~msg);
557 scope(exit) lex.popFront;
558 return lex.front.str;
559 }
560
561 AST doNothingExpression()
562 {
563 return new Str(currentPosition(), "(empty function body)");
564 }
565
566 immutable(LexPosition) currentPosition()
567 {
568 return lex.empty ? null : lex.front.pos;
569 }
570 }
571
572 unittest
573 {
574 mixin EasyAST;
575
576 assert_eq(parseString(`123`), intl(123));
577 assert_eq(parseString(`"foo"`), strl("foo"));
578 assert_eq(parseString(`fun(){1}`), fun([],intl(1)));
579 assert_eq(parseString(`fun(x){1}`), fun(["x"],intl(1)));
580 assert_eq(parseString("\u03BB(){1}"), fun([],intl(1)));
581 assert_eq(parseString("\u03BB(x){1}"), fun(["x"],intl(1)));
582 assert_eq(parseString(`1;2`), let("_","",intl(1),intl(2)));
583 assert_eq(parseString(`1;2;`), let("_","",intl(1),intl(2)));
584 assert_eq(parseString(`let x=1 in 2`), let("x","",intl(1),intl(2)));
585 assert_eq(parseString(`var x=1;2;`), let("x","",intl(1),intl(2)));
586 assert_eq(parseString(`def x=1`), let("x","",intl(1),var("x")));
587 assert_eq(parseString(`@val x=1;`), let("x","@val",intl(1),var("x")));
588 assert_eq(parseString(`@typ x="#int";`), let("x","@typ",strl("#int"),var("x")));
589 assert_eq(parseString(`f(1,2)`), call(var("f"),intl(1),intl(2)));
590 assert_eq(parseString(`if(1){2}`), call(var("if"),intl(1),fun([],intl(2)),fun([],strl("(empty function body)"))));
591 assert_eq(parseString(`if(1){2}else{3}`), call(var("if"),intl(1),fun([],intl(2)),fun([],intl(3))));
592 assert_eq(parseString(`if(1){}else{3}()()`),
593 call(call(call(var("if"),intl(1),fun([],strl("(empty function body)")),fun([],intl(3))))));
594 assert_eq(parseString(`1+2*3`), call(var("+"),intl(1),call(var("*"),intl(2),intl(3))));
595 assert_eq(parseString(`(1+2)*3`), call(var("*"),call(var("+"),intl(1),intl(2)),intl(3)));
596 assert_eq(parseString(`1*(2+3)`), call(var("*"),intl(1),call(var("+"),intl(2),intl(3))));
597 assert_eq(parseString(`1*2+3`), call(var("+"),call(var("*"),intl(1),intl(2)),intl(3)));
598 assert_eq(parseString(`@x(1)`), lay("@x", intl(1)));
599 assert_eq(parseString(`fun(x @v @t, y, z @t){}`),
600 funp([param("x",["@v","@t"]), param("y",[]), param("z",["@t"])], strl("(empty function body)")));
601
602 assert_eq(parseString(`
603 let x = 100; #comment
604 let y = 200; #comment!!!!!
605 x+y
606 `),
607 let("x", "", intl(100), let("y", "", intl(200), call(var("+"), var("x"), var("y"))))
608 );
609
610 assert_eq(parseString(`
611 var fac = fun(x){ if(x <= 1) {1} else {x*fac(x-1)} };
612 fac(10)
613 `),
614 let("fac", "", fun(["x"],
615 call(var("if"),
616 call(var("<="), var("x"), intl(1)),
617 fun([], intl(1)),
618 fun([], call(var("*"), var("x"), call(var("fac"),call(var("-"),var("x"),intl(1)))))
619 )),
620 call(var("fac"),intl(10))
621 )
622 );
623 }
624
625 unittest
626 {
627 assert_throw!UnexpectedEOF(parseString(`1+`));
628 assert_throw!ParseException(parseString(`1+2}`));
629 assert_throw!UnexpectedEOF(parseString(`let "x"`));
630 assert_throw!UnexpectedEOF(parseString(`var`));
631 assert_throw!ParseException(parseString(`@val x ==`));
632 assert_throw!ParseException(parseString(`if(){1}`));
633 assert_throw!UnexpectedEOF(parseString(`f(`));
634 }
635
636 unittest
637 {
638 mixin EasyAST;
639 assert_eq(parseString(`def foo(x) { x+1 }; foo`),
640 let("foo", "",
641 fun(["x"], call(var("+"), var("x"), intl(1))),
642 var("foo"))
643 );
644
645 assert_eq(parseString(`@@type ( x ) { x }`),
646 let("@type", SystemLayer, fun(["x"], var("x")), lay(SystemLayer, var("@type"))) );
647
648 assert_eq(parseString(`{}`), call(var("{}")));
649 assert_eq(parseString(`{foo:1,"bar":2}`),
650 call(var(".="), call(var(".="), call(var("{}")), strl("foo"), intl(1)), strl("bar"), intl(2)));
651 assert_eq(parseString(`{}.foo`), call(var("."),call(var("{}")),strl("foo")));
652 assert_eq(parseString(`{}.?foo`), call(var(".?"),call(var("{}")),strl("foo")));
653 assert_eq(parseString(`x{y:1}`), call(var(".="),var("x"),strl("y"),intl(1)));
654 }
655
656 unittest
657 {
658 assert_nothrow(parseString(`
659 case( 1 )
660 when(x){1}
661 `));
662 assert_nothrow(parseString(`
663 case( 1 )
664 when({aaaa:_}){1}
665 `));
666 assert_nothrow(parseString(`
667 case( 1 )
668 when({aaaa:@value(x)}){1}
669 when({aaaa:{bbb:_}, ccc:123}){1}
670 `));
671 }