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, LiftLayer, e, Body());
106 else
107 return new Let(pos, var, LiftLayer, e,
108 new Lay(pos, LiftLayer, 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 if( layer.empty )
127 return new Let(pos, var, layer, e, new Var(varpos, var));
128 else if( isMacroLayer(layer) )
129 return new Let(pos, var, layer, e, new Str(varpos, "(macro definition)"));
130 else
131 return new Let(pos, var, layer, e, new Lay(varpos, layer, new Var(varpos, var)));
132 }
133 }
134 }
135
136 AST TopLevelExpression()
137 {
138 /// TopLevelExpression ::= Expression ([";"|"in"] Body?)?
139
140 auto pos = currentPosition();
141 auto e = E(0);
142 if( moreDeclarationExists() )
143 return new Let(pos, "_", "", e, Body());
144 else
145 return e;
146 }
147
148 private bool moreDeclarationExists()
149 {
150 return (tryEat(";") || tryEat("in")) && !closingBracket();
151 }
152
153 private bool closingBracket()
154 {
155 return lex.empty || !lex.front.quoted && ["}",")","]",","].canFind(lex.front.str);
156 }
157
158 // [TODO] make this customizable from program
159 private static string[][] operator_perferences = [
160 ["||"],
161 ["&&"],
162 ["!="],
163 ["=="],
164 ["<","<=",">",">="],
165 ["|"],
166 ["^"],
167 ["&"],
168 ["<<", ">>", "<<<", ">>>"],
169 ["+","-"],
170 ["~"],
171 ["*","/","%"],
172 ["^^","**"],
173 [".",".?"]
174 ];
175
176 AST E(size_t level)
177 {
178 /// Expression ::= (Binary left-associative operators over) Funcall
179
180 AST rec(AST lhs)
181 {
182 if( closingBracket() )
183 return lhs;
184
185 auto pos = currentPosition();
186 foreach(op; operator_perferences[level])
187 if( tryEat(op) )
188 if( op[0]=='.' )
189 return rec(
190 new App(lhs.pos, new Var(pos, op), lhs, parseId()));
191 else
192 return rec(
193 new App(lhs.pos, new Var(pos, op), lhs, E(level+1)));
194 return lhs;
195 }
196
197 if( operator_perferences.length <= level )
198 return Funcall();
199 else
200 return rec(E(level+1));
201 }
202
203 AST Funcall()
204 {
205 /// Funcall ::= BaseExpression ["(" Expression%"," ")" | "{" ENTRIES "}"]*
206
207 auto e = BaseExpression();
208 for(;;)
209 if( tryEat("(") )
210 {
211 auto pos = currentPosition();
212 AST[] args;
213 while( !tryEat(")") ) {
214 if( lex.empty )
215 throw genex!UnexpectedEOF(pos, "closing ')' for arguments not found");
216 args ~= E(0);
217 if( !tryEat(",") ) {
218 eat(")", "after function parameters");
219 break;
220 }
221 }
222 e = new App(e.pos, e, args);
223 }
224 else if( tryEat("{") )
225 {
226 e = parseTableSetAfterBrace(e);
227 }
228 else
229 break;
230 return e;
231 }
232
233 AST parseTableSetAfterBrace(AST e)
234 {
235 /// TableSet ::= "{" (ID ":" E) % "," "}"
236
237 if( tryEat("}") )
238 return e;
239 auto pos = currentPosition();
240 for(;;)
241 {
242 string key = eatId("for table key", AllowQuoted);
243 eat(":", "after table key");
244 AST val = E(0);
245 e = new App(pos, new Var(pos,".="),
246 e, new Str(pos,key), val);
247 if( !tryEat(",") )
248 {
249 eat("}", "for the end of table literal");
250 break;
251 }
252 }
253 return e;
254 }
255
256 AST BaseExpression()
257 {
258 if( lex.empty )
259 throw genex!UnexpectedEOF(currentPosition(), "Reached EOF when tried to parse an expression");
260
261 auto pos = currentPosition();
262 if( lex.front.quoted )
263 {
264 scope(exit) lex.popFront;
265 return new Str(pos, lex.front.str);
266 }
267 if( isNumber(lex.front.str) )
268 {
269 scope(exit) lex.popFront;
270 return new Int(pos, BigInt(cast(string)lex.front.str));
271 }
272 if( tryEat("@") )
273 {
274 auto lay = "@"~eatId("for layer ID");
275 eat("(", "for layered execution");
276 auto e = Body();
277 eat(")", "after "~lay~"(...");
278 return new Lay(pos, lay, e);
279 }
280 if( tryEat("(") )
281 {
282 auto e = Body();
283 eat(")", "after parenthesized expression");
284 return e;
285 }
286 if( tryEat("{") )
287 {
288 AST e = new App(pos, new Var(pos,"{}"));
289 return parseTableSetAfterBrace(e);
290 }
291 if( tryEat("if") )
292 {
293 return parseIfAfterIf(pos);
294 }
295 if( tryEat("case") )
296 {
297 return parsePatternMatch(pos);
298 }
299 if( tryEat("fun") || tryEat("\u03BB") ) // lambda!!
300 {
301 eat("(", "after fun");
302 return parseLambdaAfterOpenParen(pos);
303 }
304 scope(exit) lex.popFront;
305 return new Var(pos, lex.front.str);
306 }
307
308 AST parseIfAfterIf(LexPosition pos)
309 {
310 auto cond = E(0);
311 auto thenPos = currentPosition();
312 if(!tryEat(":")) {
313 eat("then", "after if condition");
314 tryEat(":");
315 }
316 AST th = E(0);
317 auto el = doNothingExpression();
318 auto elsePos = currentPosition();
319 if( tryEat("else") ) {
320 tryEat(":");
321 el = E(0);
322 }
323 return new App(pos, new Var(pos,"if"), cond, new Fun(thenPos,[],th), new Fun(elsePos,[],el));
324 }
325
326 AST parsePatternMatch(LexPosition pos)
327 {
328 // case pmExpr CASES
329 //==>
330 // let pmVar = pmExpr in (... let pmTryFirst = ... in pmTryFirst())
331 AST pmExpr = E(0);
332 string pmVar = freshVarName();
333 string pmTryFirst = freshVarName();
334 AST pmBody = parsePatternMatchCases(pos, pmVar, pmTryFirst,
335 new App(pos, new Var(pos, pmTryFirst)));
336 return new Let(pos, pmVar, [], pmExpr, pmBody);
337 }
338
339 AST parsePatternMatchCases(LexPosition casePos, string pmVar, string tryThisBranchVar, AST thenDoThis)
340 {
341 // when pat: cBody
342 //==>
343 // ... let failBranchVar = ... in
344 // let tryThisBranchVar = fun(){ if(test){cBody}else{failBranchVar()} } in thenDoThis
345 if( tryEat("when") )
346 {
347 auto pos = currentPosition();
348 string failBranchVar = freshVarName();
349
350 auto pr = parsePattern();
351 eat(":", "after when pattern");
352 AST cBody = E(0);
353 AST judgement = new App(pos, new Var(pos, "if"),
354 ppTest(pmVar, pr), new Fun(pos,[],ppBind(pmVar, pr, cBody)),
355 new Var(pos, failBranchVar));
356 return parsePatternMatchCases(casePos, pmVar, failBranchVar,
357 new Let(pos, tryThisBranchVar, [],
358 new Fun(pos,[],judgement), thenDoThis)
359 );
360 }
361 else
362 {
363 AST doNothing = new Fun(casePos,[],
364 new Str(casePos, sprintf!"(pattern match failure:%s)"(casePos)));
365 return new Let(casePos, tryThisBranchVar, [], doNothing, thenDoThis);
366 }
367 }
368
369 // hageshiku tenuki
370 abstract class SinglePattern
371 {
372 string[] path;
373 mixin SimpleClass;
374 private AST access(string pmVar, string[] path) {
375 auto pos = currentPosition();
376 AST e = new Var(pos, pmVar);
377 foreach(p; path)
378 e = new App(pos, new Var(pos, "."), e, new Str(pos, p));
379 return e;
380 }
381 private AST has(AST e, string k) {
382 auto pos = currentPosition();
383 return opAndAnd(
384 new App(pos, new Var(pos, "_istable"), e),
385 new App(pos, new Var(pos, ".?"), e, new Str(pos, k))
386 );
387 }
388 private AST opAndAnd(AST a, AST b) {
389 if( a is null ) return b;
390 if( b is null ) return a;
391 auto pos = currentPosition();
392 return new App(pos,
393 new Var(pos, "if"),
394 a,
395 new Fun(pos, [], b),
396 new Fun(pos, [], new Int(pos, 0))
397 );
398 }
399 AST ppTest(string pmVar) {
400 AST c = null;
401 for(int i=0; i<path.length; ++i)
402 c = opAndAnd(c, has(access(pmVar,path[0..i]), path[i]));
403 return c;
404 }
405 AST ppBind(string pmVar, AST thenDoThis) { return thenDoThis; }
406 }
407 class WildPattern : SinglePattern
408 {
409 mixin SimpleClass;
410 }
411 class VarPattern : SinglePattern
412 {
413 string name;
414 mixin SimpleClass;
415 AST ppBind(string pmVar, AST thenDoThis) {
416 auto pos = currentPosition();
417 return new Let(pos, name, [], access(pmVar,path), thenDoThis);
418 }
419 }
420 class ConstantPattern : SinglePattern
421 {
422 AST e;
423 mixin SimpleClass;
424 AST ppTest(string pmVar) {
425 auto pos = currentPosition();
426 return opAndAnd( super.ppTest(pmVar),
427 new App(pos, new Var(pos,"=="), access(pmVar,path), e)
428 );
429 }
430 }
431
432 SinglePattern[] parsePattern(string[] path = null)
433 {
434 SinglePattern[] result;
435 if( tryEat("{") )
436 {
437 if( !tryEat("}") ) {
438 do {
439 string key = eatId("in table pattern", AllowQuoted);
440 eat(":", "after field-id in table pattern");
441 result ~= parsePattern(path ~ key);
442 } while( tryEat(",") );
443 eat("}", "at the end of table pattern");
444 }
445 }
446 else
447 {
448 AST e = E(0);
449 if(auto ev = cast(Var)e)
450 if(ev.name == "_")
451 result ~= new WildPattern(path);
452 else
453 result ~= new VarPattern(path, ev.name);
454 else
455 result ~= new ConstantPattern(path, e);
456 }
457 return result;
458 }
459
460 AST ppTest(string pmVar, SinglePattern[] pats)
461 {
462 auto pos = currentPosition();
463 AST cond = null;
464 foreach(p; pats) {
465 AST c2 = p.ppTest(pmVar);
466 if( c2 !is null )
467 cond = cond is null ? c2
468 : new App(pos, new Var(pos,"&&"), cond, c2);
469 }
470 return cond is null ? new Int(currentPosition(), 1) : cond;
471 }
472
473 AST ppBind(string pmVar, SinglePattern[] pats, AST thenDoThis)
474 {
475 foreach(p; pats)
476 thenDoThis = p.ppBind(pmVar, thenDoThis);
477 return thenDoThis;
478 }
479
480 AST parseId()
481 {
482 scope(exit) lex.popFront;
483 return new Str(currentPosition(), lex.front.str);
484 }
485
486 AST parseLambdaAfterOpenParen(LexPosition pos)
487 {
488 Parameter[] params;
489 while( !tryEat(")") )
490 {
491 params ~= parseParam();
492 if( !tryEat(",") ) {
493 eat(")", "after function parameters");
494 break;
495 }
496 }
497 eat("{", "after function parameters");
498 auto funbody = Body();
499 eat("}", "after function body");
500 return new Fun(pos, params, funbody);
501 }
502
503 Parameter parseParam()
504 {
505 string var;
506 string[] lay;
507 while( !closingBracket() && !lex.empty && lex.front.str!="," )
508 {
509 auto pos = currentPosition();
510 string p = eatId("for function parameter", AllowQuoted);
511 if( p == "@" )
512 lay ~= "@" ~ eatId("after @", AllowQuoted);
513 else if( var.empty )
514 var = p;
515 else
516 throw genex!ParseException(pos, "one parameter has two names");
517 }
518 return new Parameter(var, lay);
519 }
520
521 private:
522 Lexer lex;
523 this(Lexer lex) { this.lex = lex; }
524
525 bool isNumber(string s)
526 {
527 return find!(`a<'0' || '9'<a`)(s).empty;
528 }
529
530 void eat(string kwd, lazy string msg)
531 {
532 if( !tryEat(kwd) )
533 if( lex.empty )
534 throw genex!UnexpectedEOF(
535 currentPosition(), sprintf!"%s is expected %s but not found"(kwd,msg));
536 else
537 throw genex!ParseException(
538 currentPosition(), sprintf!"%s is expected for %s but not found"(kwd,msg));
539 }
540
541 bool tryEat(string kwd)
542 {
543 if( lex.empty || lex.front.quoted || lex.front.str!=kwd )
544 return false;
545 lex.popFront;
546 return true;
547 }
548
549 enum {AllowQuoted=true, DisallowQuoted=false};
550 string eatId(lazy string msg, bool aq=DisallowQuoted)
551 {
552 if( lex.empty )
553 throw genex!UnexpectedEOF(currentPosition(), "identifier is expected but not found "~msg);
554 if( !aq && lex.front.quoted )
555 throw genex!ParseException(currentPosition(), "identifier is expected but not found "~msg);
556 scope(exit) lex.popFront;
557 return lex.front.str;
558 }
559
560 AST doNothingExpression()
561 {
562 return new Str(currentPosition(), "(empty function body)");
563 }
564
565 LexPosition currentPosition()
566 {
567 return lex.empty ? new LexPosition("EOF",0,0) : lex.front.pos;
568 }
569 }
570
571 unittest
572 {
573 mixin EasyAST;
574
575 assert_eq(parseString(`123`), intl(123));
576 assert_eq(parseString(`"foo"`), strl("foo"));
577 assert_eq(parseString(`fun(){1}`), fun([],intl(1)));
578 assert_eq(parseString(`fun(x){1}`), fun(["x"],intl(1)));
579 assert_eq(parseString("\u03BB(){1}"), fun([],intl(1)));
580 assert_eq(parseString("\u03BB(x,y){1}"), fun(["x","y"],intl(1)));
581 assert_eq(parseString(`1;2`), let("_","",intl(1),intl(2)));
582 assert_eq(parseString(`1;2;`), let("_","",intl(1),intl(2)));
583 assert_eq(parseString(`let x=1 in 2`), let("x","",intl(1),intl(2)));
584 assert_eq(parseString(`var x=1;2;`), let("x","",intl(1),intl(2)));
585 assert_eq(parseString(`def x=1`), let("x","",intl(1),var("x")));
586 assert_eq(parseString(`@val x=1;`), let("x","@val",intl(1),lay("@val",var("x"))));
587 assert_eq(parseString(`@typ x="#int";`), let("x","@typ",strl("#int"),lay("@typ",var("x"))));
588 assert_eq(parseString(`@macro x=1`), let("x","@macro",intl(1),strl("(macro definition)")));
589 assert_eq(parseString(`f(1,2)`), call(var("f"),intl(1),intl(2)));
590 assert_eq(parseString(`if 1 then 2`), call(var("if"),intl(1),fun([],intl(2)),fun([],strl("(empty function body)"))));
591 assert_eq(parseString(`if 1 then: 2 else(3)`), call(var("if"),intl(1),fun([],intl(2)),fun([],intl(3))));
592 assert_eq(parseString(`(if 1 then () 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) then 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", LiftLayer, fun(["x"], var("x")), lay(LiftLayer, 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 }