1

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)*  
Fiary
  • 203
  • 2
  • 11
  • 2
    http://vimeo.com/groups/29150/videos/sort:oldest You may watch through the steps, as the video clips are quite good. – Lex Li Feb 06 '12 at 09:10
  • 1
    Can you post the parser grammar and your attempt of the tree grammar? – Bart Kiers Feb 06 '12 at 09:23
  • @BartKiers,my grammar is very large ,it isn't appropriate to post it.I think I just want some general suggetion or instruction about how to write grammar that can traverse a tree. – Fiary Feb 06 '12 at 12:08
  • @BartKiers,thank you so much.But I am not able to access blogspot.Is there anywhere else that has similar content with your blog? – Fiary Feb 07 '12 at 09:14
  • @BartKiers,I've downloaded it.thank you again! – Fiary Feb 07 '12 at 12:25

0 Answers0