Have you considered subclassing your grammar? The child inherits the rules from the parent, and an override the changed methods. Or, the parent grammar could be rules-and-common-methods-only, and then have two child grammas for "inside parens" vs "outside parens."
Not sure the mechanics of implementing that. -y On Wed, Aug 1, 2018 at 7:41 AM, Theo van den Heuvel <vdheu...@heuvelhlt.nl> wrote: > > > Hi Perl6-people, > > I am looking for some inspiration. I am working with a grammar that I > would like to have operate in two different modes. > In both modes the rules are identical, but the methods should behave > differently. There are probably better ways to do this than I can think of > at this point. > > As an illustration (not the actual problem), say we want to proces > arithmetical expressions in two modes: normally we just copy the input, but > within a pair of braces we directly calculate the result. grammar actions > are easy to write per mode, but the combination is harder. > > In our example we would like to convert "{3 + 5} + {2 -1}" into "8 + 1". > In my original case the grammar is large. > > So far, I have considered the following ideas: > - using a parameter on the grammar rules > - meddling with the AST > - using a dynamic variable (but actions are performed later) > - using the actions method (I don't see how I could use that here) > > One way to get this done is by combining the first two ideas: > > grammar Sum { > token TOP { ^ <Sum: 0> $ } > rule Sum($p) { <Expr>+ % <op> <flag>**{$p}} > rule Expr { <num> | '[' ~ ']' <Sum: 1> } > token op { <[-+]> } > token num { \d+ } > token flag { <?> } > } > > The presence of the flag is the clue for the actions. > > This is less than satisfactory because we would have to pass on the > parameter to all non-terminals. > > Can anyone think of a better way to do this? > > thanks, > > -- > Theo van den Heuvel >