Skip to content

Instantly share code, notes, and snippets.

@ajs
Created June 21, 2012 15:50
Show Gist options
  • Save ajs/2966586 to your computer and use it in GitHub Desktop.
Save ajs/2966586 to your computer and use it in GitHub Desktop.
Actions and Grammars: a proposal for combining them
role EXPRish is Parser {}
grammar EXPR does EXPRish {
rule TOP { <expr> }
rule expr { <num> '+' <num> | <num> }
token num { (\d+) }
}
class EXPR::Actions does EXPRish {
action TOP { make $<expr>.ast }
action expr {
if $<num>.elems == 1 {
make $<num>[0].ast;
} else {
make { :op<+>, :lhs($<num>[0].ast), :rhs($<num>[1].ast) }
}
}
action num {
make { :literal, :integer, :value(+$0.Str) }
}
}
EXPR.parse("1 + 2", :actions(EXPR::Actions));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment