[antlr-interest] CommonTree -> AST conversion ?
Sébastien Kirche
sebastien.kirche at gmail.com
Mon Apr 12 11:16:53 PDT 2010
Hi,
I am kinda new to antlr and I am working on a grammar fragment to familiar
myself with the antlr mechanics.
I have a parser grammar that is producing an AST (I have already read some
doc about the tree grammars, but in a first step i would like to manually
walk the tree to learn the basics) with the output=AST statement. The final
goal will be a spreadsheet-like language for a reporting application.
I would like to make some debugging tests using the ASTFrame but I did not
managed to provide the ASTFrame with a suitable AST / CommonAST so I print
it myselft for the moment.
Could someone correct my code or point me an example more complete that the
code snippet that is mentioned in the wiki ?
And could you point me some code for a custom tree walker ? I have read some
mentions about implementing a visitor pattern, it that the regular way ?
Thanks for your help.
public class TreeTester {
/**
* @param args
* @throws IOException
* @throws RecognitionException
*/
public static void main(String[] args) throws IOException,
RecognitionException {
if (args.length < 1){
System.out.println("Usage : TreeTester <fichier d'expressions>");
System.exit(1);
}
String filename = args[0];
File tstFile = new File(filename);
if (!tstFile.exists() || !tstFile.canRead()){
System.out.println(filename + " n'existe pas ou n'est pas accessible.");
System.exit(1);
}
plxLexer lexer = new plxLexer(new ANTLRFileStream(filename));
CommonTokenStream tokens = new CommonTokenStream(lexer);
plxParser parser = new plxParser(tokens);
plxParser.cell_return r = parser.cell();
CommonTree t = (CommonTree) r.getTree();
System.out.println(t.getChildCount());
for (int i=0; i< t.getChildCount(); i++){
System.out.print(plxParser.tokenNames[t.getChild(i).getType()] + " : ");
System.out.println(t.getChild(i).toStringTree());
}
printTree(t, 0);
// this does not work, as It cant cast CommonTree to CommonAST nor AST
// ASTFrame debugView = new ASTFrame("arbre", (CommonAST) t);
// debugView.setVisible(true);
}
public static void printTree(CommonTree t, int indent) {
if ( t != null ) {
StringBuffer sb = new StringBuffer(indent);
for ( int i = 0; i < indent; i++ )
sb = sb.append(" ");
for ( int i = 0; i < t.getChildCount(); i++ ) {
System.out.println(sb.toString() + t.getChild(i).toString());
printTree((CommonTree)t.getChild(i), indent+1);
}
}
}
}
--
Sébastien Kirche
More information about the antlr-interest
mailing list