[antlr-interest] Interpreting IF statements in ANTLR

ZelluX zellux at gmail.com
Thu Jul 8 01:38:32 PDT 2010


I'm implementing a BASIC-like language, the syntax of if statements is
almost the same to BASIC:

    IF a == b THEN
        PRINT "EQUAL"
    ELSE
        PRINT "UNEQUAL"
    ENDIF

I have write a grammar file to parse and a tree walker to interpreter the
language:

    [Expr.g]
    options {
        language=Python;
        output=AST;
        ASTLabelType=CommonTree;
    }

    tokens {
        BLOCK;
    }

    block
        : stmt* -> ^(BLOCK stmt*)
        ;

    if_stmt
        : 'IF' c=expr 'THEN' t=block ('ELSE' f=block)? 'ENDIF'
            -> ^('IF' $c $t+ ^('ELSE' $f+))
        ;

In the AST walker:

    [Walker.g]
    options {
        language=Python;
        tokenVocab=Expr;
        ASTLabelType=CommonTree;
    }

    block
        : ^(BLOCK stmt*)
        ;

    stmt
        : ...
        | 'IF' expr t=stmt* 'ELSE' f=stmt*
             {}

Now I can correctly generate AST for my language, but I don't know how to
handle branch statement. To be more exactly, if the *expr* in if statement
is true, how can I avoid evaluation of the ELSE statement? Thanks

-- 
Best regards,
Wang Yuanxuan
Parallel Processing Institute, Fudan University


More information about the antlr-interest mailing list