1tree grammar Simplifier; 2options { 3 tokenVocab=Poly; 4 language=ObjC; 5 ASTLabelType=CommonTree; 6 output=AST; 7 backtrack=true; 8// rewrite=true; // works either in rewrite or normal mode 9} 10 11/** Match some common patterns that we can reduce via identity 12 * definitions. Since this is only run once, it will not be 13 * perfect. We'd need to run the tree into this until nothing 14 * changed to make it correct. 15 */ 16poly: ^('+' a=INT b=INT) -> INT[[NSString stringWithFormat:@"\%d", ($a.int+$b.int)\]] 17 18 | ^('+' ^('+' a=INT p=poly) b=INT) 19 -> ^('+' $p INT[[NSString stringWithFormat:@"\%d", ($a.int+$b.int)\]]) 20 21 | ^('+' ^('+' p=poly a=INT) b=INT) 22 -> ^('+' $p INT[[NSString stringWithFormat:@"\%d", ($a.int+$b.int)\]]) 23 24 | ^('+' p=poly q=poly)-> { [[$p.tree toStringTree] isEqualToString:@"0"] }? $q 25 -> { [[$q.tree toStringTree] isEqualToString:@"0"] }? $p 26 -> ^('+' $p $q) 27 28 | ^(MULT INT poly) -> {$INT.int==1}? poly 29 -> ^(MULT INT poly) 30 31 | ^('^' ID e=INT) -> {$e.int==1}? ID 32 -> {$e.int==0}? INT[@"1"] 33 -> ^('^' ID INT) 34 35 | INT 36 | ID 37 ; 38