Skip to content

Instantly share code, notes, and snippets.

@ashleydev
Forked from anonymous/gist:452999
Created June 25, 2010 17:55
Show Gist options
  • Save ashleydev/453195 to your computer and use it in GitHub Desktop.
Save ashleydev/453195 to your computer and use it in GitHub Desktop.
how to write a compiler in 20 lines of code
pmichaud@plum:~/rakudo$ cat x
grammar Expr {
rule TOP { <expr> }
rule expr { <integer> <addop> <integer> };
token addop { '+' | '-' }
token integer { \d+ }
}
class ExprActions {
method TOP($/) { make $<expr>.ast }
method expr($/) {
my $a = $<integer>[0].ast;
my $b = $<integer>[1].ast;
make $<addop> eq '+' ?? $a + $b !! $a - $b;
}
method integer($/) { make +$/; }
}
my $match = Expr.parse("3+4", :actions(ExprActions));
say $match.ast;
pmichaud@plum:~/rakudo$ ./perl6 x
7
pmichaud@plum:~/rakudo$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment