tree grammar Optimizer; options { language = Java; output = AST; tokenVocab = Arith; ASTLabelType = CommonTree; } @header{ package de.hshn.se.akse.ss09.parser; } //a program consists of zero or more statements program : statement*; //a statement can either be an assignment or an I/O Operation statement : ^(ASSIGN ID expr) | ^(READ ID) | ^(WRITE expr) ; /* All of the expression rules from the parser grammar collapse into a single recursive rule in the tree grammar. The parser constructs ASTs for expressions that encode the order of operations by their very structure. The tree grammar does not need to repeat the multilevel expression grammar pattern used by parser grammars to deal with different levels of precedence. -- ANTLR The Definitive Reference p.202 */ expr : ^(ADD a=expr b=expr) //-> {$a.tree.toStringTree().equals("0")}? $a //-> {$b.tree.toStringTree().equals("0")}? $b //-> ^(ADD $a $b) -> $a | ^(MINUS a=expr b=expr) -> {$b.tree.toStringTree().equals("0")}? $a -> ^(MINUS $a $b) | ^(MULT a=expr b=expr) -> {$a.tree.toStringTree().equals("1")}? $a -> {$b.tree.toStringTree().equals("1")}? $b -> ^(MULT $a $b) | ^(DIV a=expr b=expr) -> {$a.tree.toStringTree().equals("0")}? $a -> {$b.tree.toStringTree().equals("1")}? $a -> ^(DIV $a $b) | ID -> ID | INT -> INT | FLOAT -> FLOAT | ZERO -> ZERO ;