I am designing a declarative language. In my language are definitions of “nodes” that can be reused later. Think of them like prototypes or templates. You can create copies of them as needed. I have a version of the interpreter that generates the appropriate Java objects during the definition phase. Up until recently I have been using a deep copy library to create copies of the Java representation of the nodes to create instances of the node. Due to the limitations of most of the deep copying libraries I have found and my lack of desire to write a copy constructor for every object in my system, I want to take a different approach. Part of my language specifies GUI Java Swing objects which cause issues with the deep copy libraries.
Is there a way I can save the AST subgraph for my object declaration and reprocess it when I want to create an instance of the node? I am asking the question in terms of ANTLR ASTs, but if you have a language implementation advice I welcome that too.
In an ANTLR parser/lexer grammar, you have access to a
$ruleName.tree. This rule attribute is the reference to AST subtree generated during parsing. Using the@afterfield and the@membersfield, you can store the subtree. Let me show you.below in your grammar
This will create a list of all the ruleName AST subtrees. These trees can be turned into CommonTreeNodeStream and used with your tree grammar code.
See this question for more info on returning data from an ANTLR grammar rule.
This will allow you to create node instances by reprocessing saved AST subgraphs. You can create the TreeNodeStream and call the walker whenever you need to create an instance.