[antlr-interest] writing an interpreter

Bryan Ewbank ewbank at gmail.com
Sat Mar 25 07:22:27 PST 2006


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"
            )
        )
    ;

This assumes that <exprbool> evaluates a boolean expression and returns
true/false.  In other words, it has this ANTLR signature:

    exprbool
    returns [bool result = false]
    :
        ... ... ...
    ;

WHILE follows from IF; tracking the current state of the expression is left as
an exercise for the user :-)

Note that the same structure can be used to short-circuit &&, || operators, and
control selective evaluation of the ternary ?: operator.

- Bryan


More information about the antlr-interest mailing list