[antlr-interest] How to implement an IF
ugol
ugo.landini at gmail.com
Mon Dec 4 08:34:06 PST 2006
Hi, I am a complete newbie of ANTLR. I am using the 3.0b5 release and
I am trying to adapt the example found here:
http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator
I want to add to the expression evaluation a conditional expression:
f.e.
if (x>10) x=y
I think I have correctly built the lexer and parser stuff, but I can't
figure out how to check the condition and then act. My tree stuff
parse the condition, no matter if the condition is true or false. I am
probably missing something here.
I have a IF node with a condition and an expression, but don't know
how to say this:
if ($cond.value() assign.??? )
I was thinking to set some sort of variable and then check it, but I
don't know if this is the right way to do it, and the v3examples
didn't help.
TIA,
uL
Attached two fragments of Cond.g and Eval.g
grammar Cond;
options {
output=AST;
ASTLabelType=CommonTree; // type of $stat.tree ref etc...
}
prog
: ( stat {System.out.println($stat.tree.toStringTree());} )+ ;
stat
: IF LPAREN condition RPAREN assign NEWLINE -> ^(IF condition assign)
| assign NEWLINE -> assign
| expr NEWLINE -> expr
| NEWLINE ->
;
assign
: VAR ASSIGN expr -> ^(ASSIGN VAR expr)
;
[cut]
tree grammar Eval;
options {
tokenVocab=Cond;
ASTLabelType=CommonTree;
}
@header {
import java.util.HashMap;
}
@members {
}
prog: stat+ ;
stat: expr
{System.out.println($expr.value);}
| ^(ASSIGN VAR expr)
{Memory.put($VAR.text, new Integer($expr.value));}
| ^(IF condition assign)
{if ($condition.value) // how to reference the assign part here?} ;
condition returns [boolean value]
: ^(EQUALS a=expr b=expr) {$value = (a == b);}
;
More information about the antlr-interest
mailing list