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