Created
August 7, 2011 12:27
-
-
Save zaphod42/1130334 to your computer and use it in GitHub Desktop.
Perl 6 expression parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| grammar Expr { | |
| token number { \d+ {*} } | |
| token operator { <op> {*} } | |
| proto token op { <...> } | |
| token op:sym<+> { <sym> } | |
| token op:sym<-> { <sym> } | |
| token op:sym<*> { <sym> } | |
| token op:sym</> { <sym> } | |
| rule expr { <number> [ <operator> <expr> ]? {*} } | |
| rule TOP { ^<expr>$ } | |
| } | |
| class ExprEval { | |
| has %.ops = { | |
| '+' => &infix:<+>, | |
| '-' => &infix:<->, | |
| '*' => &infix:<*>, | |
| '/' => &infix:</>, | |
| }; | |
| method expr($/) { | |
| if $/<operator> { | |
| my $op = $/<operator>[0].ast; | |
| make $op($/<number>.ast, $/<expr>[0].ast); | |
| } else { | |
| make $/<number>.ast; | |
| } | |
| } | |
| method TOP($/) { make $/<expr>.ast } | |
| method number($/) { make +$/ } | |
| method operator($/) { make %.ops{~$/<op><sym>} } | |
| } | |
| my $parse = Expr.parse("3 + 1 + 2", :actions(ExprEval.new)) || "unparsable"; | |
| say $parse.ast; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment