I have a grammar file that can generate ast. How can I write tree grammar
that can traverse the tree generated
?I have some examples from the Internet, but while I can understand them I don't know how to write them from scratch myself.For example:
ExprTree.g
stat: expr NEWLINE -> expr
| ID '=' expr NEWLINE -> ^('=' ID expr)
| NEWLINE ->
;
expr: multExpr (('+' ^|'-' ^) multExpr)* ;
multExpr: atom ('*' ^ atom)* ;
atom: INT
| ID
| '(' ! expr ')' !
;
ID : ('a'..'z'|'A'..'Z')+ ;
INT : '0'..'9'+ ;
NEWLINE: (('/r'? '/n')|';')+ ;
WS : (' '|'/t')+ { $channel = HIDDEN; } ;
ExprEval.g
stat: expr
| ^('=' ID expr) ;
expr
: ^('+' a=expr b=expr)
| ^('-' a=expr b=expr)
| ^('*' a=expr b=expr)
| ID
| INT
ExprTree.g is grammar that generate ast and ExprEval.g can traverse the tree.For rule expr in ExprEval.g,why not this:
expr: multExpr (('+' ^|'-' ^) multExpr)*