develooper Front page | perl.perl6.users | Postings from August 2018

parsing in different modes

Thread Next
From:
Theo van den Heuvel
Date:
August 1, 2018 14:41
Subject:
parsing in different modes
Message ID:
2edb7ba1448a30d26c28eb9c2c6b842f@heuvelhlt.nl


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

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About