[antlr-interest] flat AST tree

Torsten Curdt tcurdt at vafer.org
Sat Aug 23 20:13:03 PDT 2008


I am a little confused. Here a quick snipped from my grammar

	grammar test;

	options {
		output=AST;
		ASTLabelType=CommonTree;
	}

	file
	    : classDeclaration+
	    ;

	classDeclaration
	    : 'class' Identifier ( 'extends' identifierList)? classBody
	    ;

	classBody
	    : '{' attributeDeclaration+ '}'
	    ;

When I now look at the AST it appears to be totally flat

         testParser g = new testParser(tokens);

         try {
         	
         	testParser.file_return r = g.file();

         	Tree tree = (Tree)r.getTree();

         	int c = tree.getChildCount();
         	for(int i=0;i<c;i++) {
         		CommonTree child = (CommonTree) tree.getChild(i);
         		System.out.println(i + ":" + child.toString() + "(" +  
child.getChildCount() + ")");
         	}

Not a single child has further sub-childs. OK ...turns out I need to  
use rewriting for this

  classDeclaration : 'class' Identifier ( 'extends' identifierList)?  
classBody -> ^('class' Identifier ( 'extends' identifierList)?  
classBody) ;

But that totally blows up the grammar. Why isn't it just the same  
hierarchy as the input tree?

What am I missing here? IIRC that was the default in antlr2 ...no?

cheers
--
Torsten


More information about the antlr-interest mailing list