[antlr-interest] writing an interpreter

Maciej Zawadziński mzawadzinski at gmail.com
Sat Mar 25 12:44:39 PST 2006


On 3/25/06, Bryan Ewbank <ewbank at gmail.com> wrote:
> On 3/25/06, Maciej Zawadziński <mzawadzinski at gmail.com> wrote:
> > I am gonna write an interpreter of simple language. I am thinking of
> > implementing it as a treewalker, but I encountered some problems with loops.
> >
> > How can I force ANTLR treewalker not to parse some nodes of tree? (e.g.
> > "body" of the if/while loop if the condition is not satisfied?)
>
> Assuming your if node looks like this:
>     #( IF e1 s1 s2 )
>         -- e1 is the expression to evaluate
>         -- s1 is the statement to evaluate if e1 is true
>         -- s2 is the statement to evaluate if e2 is false
>
> The ANTLR for driving evaluation is:
>
>     if_statement
>     { bool res; }
>     :
>         #( IF res=exprbool
>             ( {res == true}?  statement .   // i.e., skip "s2"
>             |                 . statement   // i.e., skip "s1"
>             )
>         )
>     ;
>

Thanks a lot! I am close to understanding antlr now ;)

But nothing comes so quickly. I had some problems with optional "else"
phrase, but I finally wrote something like this that works:

ifStatement { int e = 0; }:
  ( #("if" expr stmt "else") ) => #("if" e=expr ( {e == true}? stmt |
. "else" stmt ) )
 | ( #("if" expr stmt) ) => #("if" e=expr ( {e == true}? stmt | . ) )


It looks a bit ugly, is there a way to make it without syntactic predicates?

greets,

--
Maciej Zawadziński


More information about the antlr-interest mailing list