in reply to Macros in a RecDescent grammar

You can edit $text in a rule to achieve a "pass-and-a-half" parsing. When you recognize a macrodef, store the key into a hash, with the value being the replacement string. Then, whenever you are looking for an identifier, also look first to see if it's one of the keys, and if so, prepend $text with the corresponding value and accept it.

I've been thinking about writing a column on that, but haven't finished. I saw a good example of that in theDamian's class notes though.

-- Randal L. Schwartz, Perl hacker


update: The file demo_cpp.pl in the Parse::RecDescent distro has a good example of mangling $text.

Replies are listed 'Best First'.
Re: •Re: Macros in a RecDescent grammar
by mush4brains (Acolyte) on Jun 21, 2002 at 21:51 UTC
    I'm currently doing something like that, though I'm not actually updating $text:
    macro: identifier ":" expr { if (defined $_macro{$item[2]->getVal()}) { # ERROR -- duplicate macro definitions } else { $_macro{$item[2]->getVal()} = $item[4]; $return = $item[2]; } }
    Rather than update $text, I build my op-tree branch directly from expr. (And it's working so far...)
    Adding arg's to this seems harder, since the instantiation-points can be many subrules deeper.
    - Jim
Re^2: Macros in a RecDescent grammar
by Aristotle (Chancellor) on Jun 22, 2002 at 16:12 UTC
    Macros will have to be defined prior to use then though, unless I'm a mile off on how this'd work. (Not that that's bad, but it would differ from a two pass compiler in this respect and might be a point to consider.)

    Makeshifts last the longest.

Re: •Re: Macros in a RecDescent grammar
by mush4brains (Acolyte) on Jun 21, 2002 at 22:18 UTC
    (Merlyn, I look forward to seeing your column on this, by the way. - Jim)