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