问题
I have successfully built a parser/lexer that creates an AST for my language. Yeah!! I am now onto the "interpreter" stage. I say interpreter in quotes because the language is declarative as isn't really being executed like a procedural language might. It is being translated into Java objects that are used later on in the run of my application.
As I am walking my AST I need to translate the tree nodes into Java objects. These Java objects are used else where in my program. I understand how to create actions to cause the Java objects to be created, but how do I get the result of the actions back into my main program?
Do I use the @members{} tag and write my getter methods in there?
回答1:
Do I use the @members{} tag and write my getter methods in there?
Yes, that is an option. However, (tree) grammar rules can return your custom objects so that when you invoke the entry point of your tree walker (or parser), this custom object is returned:
grammar
tree grammar YourTreeWalker;
...
walk returns [CustomObject obj]
: ...
{
$obj = ...
}
;
...
elsewhere in your code
...
YourTreeWalker walker = new YourTreeWalker(...);
CustomObject obj = walker.walk();
来源:https://stackoverflow.com/questions/11909007/how-can-i-get-information-out-of-a-tree-parser-using-the-antlr-tree-grammar-synt