tags:

views:

67

answers:

1

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

+1  A: 

If you're using Python, then you should be able to use lambda expressions -- instead returning a value in parser actions, you can return a lambda expression and evaluate it only when neccessary.

Aivar
It is really a simple and clear way to do this, many thanks.
ZelluX