Skip to content

Instantly share code, notes, and snippets.

@zaphod42
Created August 7, 2011 15:24
Show Gist options
  • Select an option

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

Select an option

Save zaphod42/1130455 to your computer and use it in GitHub Desktop.
Simple S-Expr to Perl 6 compiler
grammar Scheme {
rule TOP { ^ <program> $ {*} }
rule program { <s_expression>* {*} }
rule s_expression {
<number>
| <ident>
| <cons_list>
{*}
}
rule cons_list { '(' ~ ')' <s_expression>* {*} }
token number { \d+ {*} }
}
class Scheme2Perl {
method TOP($/) { make $/<program>.ast }
method program($/) { make $/<s_expression>>>.ast.map({ $_('$') }).join(";
\n") }
method s_expression($/) {
my $expression = [//] $/<number ident cons_list>;
make $expression.ast;
}
method cons_list($/) {
my @expressions = $/<s_expression>>>.ast;
if @expressions {
my $func = @expressions.shift;
make -> $sigil {
"-> \{ { $func('&') } \}()( { @expressions.map({ $_('$') }).j
oin(', ') } )"
}
} else {
make -> $sigil { "()" }
}
}
method number($/) { make -> $sigil { +$/ } }
method ident($/) { make -> $sigil { "$sigil$/" }; }
}
say Scheme.parse('(say 1)', :actions(Scheme2Perl.new)).ast;
eval Scheme.parse('(say 1)', :actions(Scheme2Perl.new)).ast;
my $a = 2;
eval Scheme.parse('(say a)', :actions(Scheme2Perl.new)).ast;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment