in reply to Re: P6: Beginning grammar
in thread P6: Beginning grammar
( Moritz: Thanks. Thursday, I grabbed a copy of the book and moved to the latest rakudo release. I didn't find the .perl method yet; so I'll just salivate for a while more. I will look again at the book--that was helpful. )
This is going slow as I have little time (and lots of ignorance) but I will keep scratching away.
Ok, I have retrenched. I grabbed Rakudo's/Pug's spectest and found some grammars that compile out of the box. The above is built up from t/spec/S05-grammarr/action-stubs.t . (Running spectest was less onerous than I expected.)#!/home/rir/rakudo/parrot_install/bin/perl6 { grammar Calc { token TOP { <expression> } rule expression { <lhs> <op> <rhs> } token lhs { <numeric> } token rhs { <numeric> } token numeric { \d+[\.\d*]? } token op { '-' | '+' | '*' | '/' | 'x' } } class Calc::Actions { method TOP($/) { make $<expression>.ast } method expression($/) { make eval "$/<lhs> $/<op>.ast() $/<rhs +>" } method lhs($/) { make $/ } method rhs($/) { make $/ } method numeric($/) { make $/ } method op($/) { if ( $/ eq 'x') { make '*'; } else {make $/; } + } } my $m = Calc.parse( "8.8 x 5.0 - 2", :actions( Calc::Actions)); die "dying no match" unless $m; say "$m<expression> = $m.ast()"; }
The above is meant to model a cheap calculator.
Questions:
- Is the string eval reasonable here?
-
Can the expression rule be handled without the separate
naming of the lhs and rhs? Is there a way to
access each numeric in something like:
rule expression { <numeric> <op> <numeric> }
-
The above can easily be extended by changing the rhs token
line to
But this destroys the calculator's left associativity and equal precedence. I suppose this could be addressed by changing the rule expression line to:token rhs { <numeric> | <expression> }
but I'm getting lost here.rule expression { <lhs> ( <op> <rhs> )+ }
Be well,
rir
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: P6: Beginning grammar
by moritz (Cardinal) on Jun 08, 2010 at 06:47 UTC |
In Section
Seekers of Perl Wisdom