[antlr-interest] Example code with multiple AST passes?

Bryan Ewbank ewbank at gmail.com
Mon Jun 20 09:57:00 PDT 2005


Thank you, Don.  That's a very interesting solution to a problem that
I've been encountering as I have more and more passes, especially when
I need to add a new token to *every* pass.  *Groan*.

I think I see construction of an actions object that is passed to the
grammar, but that starts to smell more and more like visitor pattern
(turned inside out, perhaps).

Using an "action object" per pass, rather than a complete *.g, would
allow that object to be passed to the constructor for the more generic
tree parser.
Hmm.  Sounds like quite a bit less duplicate code, as well as
splitting "tree goo" from "action foo".

> I just maintain a pass count so the actions know what pass is current.  In
> the .g file:
> 
> class MyTreeParser;
> 
> {
> public:
> 
>    MyTreeParser( void )
>    {
>       m_pass = 0;
>    }
>   
> private:
> 
>    int m_pass;
>   
>    const bool pass( const int passNum ) const
>    {
>       return m_pass == passNum;
>    }
> }
> 
> And in your top level rule:
> 
> topLevelRule : { m_pass++; } ( secondLevelRules )*;
> 
> If you don't have a simple top-level rule in your tree parser, just create
> one that does nothing but increment the pass count, then calls your existing
> top-level rule.
> 
> Now, in all of your actions you'll have to do something like this:
> 
> foo : bar
> {
>   if ( pass( 1 ) )
>   {
>      ...
>   }
>   else if ( pass ( 2 ) )
>   {
>      ...
>   }
> }


More information about the antlr-interest mailing list