Skip to content

Instantly share code, notes, and snippets.

Created September 10, 2010 01:11
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 anonymous/572880 to your computer and use it in GitHub Desktop.
Save anonymous/572880 to your computer and use it in GitHub Desktop.
pmichaud@orange:~/nqp-rx$ cat json.nqp
#! nqp
INIT {
pir::load_bytecode('P6Regex.pbc');
}
grammar JSON::Grammar is HLL::Grammar {
rule TOP { <value> }
proto token value { <...> }
token value:sym<string> { <string> }
token value:sym<number> {
'-'?
[ <[1..9]> <[0..9]>+ | <[0..9]> ]
[ '.' <[0..9]>+ ]?
[ <[Ee]> <[+\-]>? <[0..9]>+ ]?
}
rule value:sym<array> {
'[' [ <value> ** ',' ]? ']'
}
rule value:sym<object> {
'{'
[ [ <string> ':' <value> ] ** ',' ]?
'}'
}
token string {
<?["]> <quote_EXPR: ':qq'>
}
}
class JSON::Actions is HLL::Actions {
method TOP($/) {
make PAST::Block.new($<value>.ast, :node($/));
};
method value:sym<string>($/) { make $<string>.ast; }
method value:sym<number>($/) { make +$/; }
method value:sym<array>($/) {
my $past := PAST::Op.new(:pasttype<list>, :node($/));
if $<value> {
for $<value> { $past.push($_.ast); }
}
make $past;
}
method value:sym<object>($/) {
my $past := PAST::Stmts.new( :node($/) );
my $hashname := PAST::Compiler.unique('hash');
my $hash := PAST::Var.new( :scope<register>, :name($hashname),
:viviself('Hash'), :isdecl );
my $hashreg := PAST::Var.new( :scope<register>, :name($hashname) );
$past.'push'($hash);
# loop through all string/value pairs, add set opcodes for each pair.
my $n := 0;
while $n < +$<string> {
$past.'push'(PAST::Op.new( :pirop<set__vQ~*>, $hashreg,
$<string>[$n].ast, $<value>[$n].ast ) );
$n++;
}
# return the Hash as the result of this node
$past.'push'($hashreg);
make $past;
}
method string($/) { make $<quote_EXPR>.ast; }
}
class JSON::Compiler is HLL::Compiler {
INIT {
JSON::Compiler.language('json');
JSON::Compiler.parsegrammar(JSON::Grammar);
JSON::Compiler.parseactions(JSON::Actions);
}
our sub MAIN() is pirflags<:main> {
my @ARGS := (pir::getinterp__P)[2];
JSON::Compiler.command_line(@ARGS);
}
}
pmichaud@orange:~/nqp-rx$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment