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