Hi all,

My attempt at a solution below does not work. In larger examples the decr gets called before the actions within Sum are processed. Maybe my hunch that this would cause time order problems was correct. I need to do some more researching. I'll post my findings.

best wishes,


Theo van den Heuvel

Theo van den Heuvel schreef op 2018-08-02 14:58:
Hi Laurent,

Here I set my example up along the lines of your second suggestion.

grammar Sum {
  token TOP { ^ <Sum> $ }
  rule Sum { <Expr>+ % <op> }
  rule Expr { <num> | { self.incr } '[' ~ ']'  <Sum> { self.decr } }
  token op { <[-+]> }
  token num { \d+ }
  token flag { <?> }
  method incr { self.actions.incr }
  method decr { self.actions.decr }
}
class Act {
  has Int $.nest;
  method num ($/) { say ">>> $/ at nesting level $!nest" }
  method incr { $!nest++ }
  method decr { $!nest-- }
}

This works nicely and fulfils my requirements.

Thanks,
Theo

Laurent Rosenfeld schreef op 2018-08-01 23:00:
Hi Theo,

You probably cannot use a grammar rule to change a dynamic variable
(unless you include some action code into the rule), I agree, but I
think you can use an action method attached to a rule to do it. I have
actually done it recently in a real $work grammar that I intend to
present at The Perl Conference in Glasgow in two weeks from now. Your
use case and mine are admittedly very different, but it seems to me
that they are syntactically very similar.

As an alternative, you could use an action object with an attribute (a
mutable attribute, _is rw_) for the mode. Basically, you instantiate
an object of the actions class (with the desired attribute set to the
proper initial mode at object creation), and then pass the object
instead of the class to the grammar when calling the _parse_ method.
It should be easy then to modify the attribute as needed. This is
perhaps slightly cleaner than using a dynamic variable.

I hope this helps.
Laurent.
...

Reply via email to