| Refresh | Home EGTry.com

runtime selection of tree structure


Give an input sequence:
OP DIGIT DIGIT ...
The first element is the operator id, 1 for plus, 2 for minus, 3 for multiplication and 4 for division.


Plus example

example sequence

1 5 6 7


Output

(PLUS 5 6 7)



Minus example

example sequence

2 5 6 7


Output

(MINUS 5 6 7)


tree construction antlr grammar

grammar TreeConstruct;
options 
{
  output=AST;
}

tokens 
{
PLUS;
MINUS;
MUL;
DIV;
}


prog 
@init 
{
 int opid=1;
}
:
   OP {opid=Integer.parseInt($OP.text);}  

   
   (DIGIT)+ 
   -> {opid==1}? ^(PLUS DIGIT+)
   -> {opid==2}? ^(MINUS DIGIT+)
   -> {opid==3}? ^(MUL DIGIT+)
   -> {opid==4}? ^(DIV DIGIT+)
   ->
   ;

OP: '1' .. '4';
DIGIT: '0' .. '9' ;


WS: (' '|'\r'|'\n') {$channel=HIDDEN;};