Putting Extended Nodes in an AST

 

<< skipping higher level productions >>

 

expr : term ( (EQ^ | NEQ^) term)*

;

term : factor ((PLUS^ | MINUS^) factor)*

;

factor: primary ((TIMES^ | DIVIDE^) primary)*

;

primary : MINUS^ (primary)

| LPAREN! expr RPAREN!

| id

| constant

;

id :! i:ID

{MyAST t= new MyAST();

t.initialize(i);

t.setExprType(0);

#id = t;

}

;

constant :! n:NUM

{MyAST t= new MyAST();

t.initialize(n);

t.setExprType(1);

#constant = t;

}

;

 


 

Implementing MyAST

 

import antlr.CommonAST;

public class MyAST extends CommonAST {

int ExprType=0;

public void setExprType (int i) {

ExprType = i;

}

public int getExprType () {

return ExprType;

}

public String toString () {

return getText()+"/"+(new Integer(ExprType)).toString();

}

}

 


 

The result:

$ cat test1

begin

a := b + 2;

d := e+3*g;

end

$ java Main <test1

( block ( := a/0 ( + b/0 2/1 ) ) ( := d/0 ( + e/0 ( * 3/1 g/0 ) ) ) )