Skip to content

Instantly share code, notes, and snippets.

@pmichaud
Created August 27, 2012 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmichaud/3490798 to your computer and use it in GitHub Desktop.
Save pmichaud/3490798 to your computer and use it in GitHub Desktop.
a sample nqp compiler
use NQPHLL;
grammar Calc::Grammar is HLL::Grammar {
token TOP { ^ <statement> $ }
rule statement { <term> [ <addop> <term> ]* }
rule term { <value> [ <mulop> <value> ]* }
token value { \d+ }
token addop { '+' | '-' }
token mulop { '*' | '/' }
}
class Calc::Actions is HLL::Actions {
method TOP($/) {
make QAST::CompUnit.new(
QAST::Block.new( $<statement>.ast )
);
}
method statement($/) {
make QAST::Op.new(
:op($<addop> eq '+'
?? 'add_i'
!! 'sub_i'
),
$<value>[0].ast,
$<value>[1].ast
);
}
method value($/) {
make QAST::IVal.new( :value( +$/ ) );
}
}
class Calc::Compiler is HLL::Compiler { }
sub MAIN(*@ARGS) {
my $calc := Calc::Compiler.new();
$calc.language('calc');
$calc.parsegrammar(Calc::Grammar);
$calc.parseactions(Calc::Actions);
$calc.command_line(@ARGS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment