How do I debug a tree grammar using AntlrWorks?
In order to debug a tree grammar the input must be an AST.
Presently the only way to gain access to AST input is through creating a parser that provides "remote debugging".
See How do I set up remote debugging anyway?.
It is necessary to first build an AST that will serve as input to the tree grammar parser.
This parser (sample.g) will not be a debug parser and must not be generated with the -debug option. Only the tree grammar (sampleWalker.g) source should be generated with the -debug option
grammar sample; example : 'SOME TEXT TO PARSE';
tree grammar sampleWalker; example : 'SOME TEXT TO PARSE';
public class remoteAstDebugging { public static void main(String[] args) throws Exception { CommonTokenStream tokens = new CommonTokenStream(); { ANTLRInputStream input = new ANTLRInputStream( System.in ); sampleLexer lexer = new sampleLexer(input); tokens.setTokenSource(lexer); } CommonTreeNodeStream nodes; { sampleParser parser = new sampleParser(tokens); sampleParser.example_return example = parser.example(); CommonTree tree = (CommonTree)example.getTree(); nodes = new CommonTreeNodeStream(tree); } { sampleWalker walker = new sampleWalker(nodes); // remove these lines if not using templates FileReader groupFileReader = new FileReader("cpp.stg"); StringTemplateGroup templates = new StringTemplateGroup( groupFileReader ); groupFileReader.close(); walker.setTemplateLib(templates); sampleWalker.example_return example = walker.example(); System.out.println(example.toString()); } System.exit(0); } }
This program blocks when
sampleWalker.example_return example = walker.example();
is executed, waiting for a remote process to connect. From within ANTLRWorks open sampleWalker.g and select "Debugger -> Debug Remote", using the default host and port, localhost:49153. This allows ANTLRWorks to take control of the remote parsing operation.