Skip to content

Instantly share code, notes, and snippets.

@zaphod42
Created August 7, 2011 12:27
Show Gist options
  • Select an option

  • Save zaphod42/1130334 to your computer and use it in GitHub Desktop.

Select an option

Save zaphod42/1130334 to your computer and use it in GitHub Desktop.
Perl 6 expression parser
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