0
votes

I need to implement generics with Antlr4. In order to do this, I need to be able to take a class and, as it is used, dynamically generate code for it like a macro, tokenize that code, generate a tree, and then add that new tree to my original parse tree.

I saw these two classes

http://www.antlr.org/api/JavaTool/org/antlr/v4/runtime/RuleContext.html

http://www.antlr.org/api/JavaTool/org/antlr/v4/runtime/ParserRuleContext.html

However, I'm not sure what they actually do, nor am I sure how to use the constructor.

ParserRuleContext(ParserRuleContext parent, int invokingStateNumber)

RuleContext(RuleContext parent, int invokingState)

Specifically, are these the classes that will represent the new tree, and what should I pass into invokingState/invokingStateNumber?

1
Generally, Antlr4 does not support direct modification of the parse tree. Might be better to back up a step and ask the question of where and how generics can be implemented given more specifics about what you are trying to do.GRosenberg
Sadly, there is no way to implement generics except by this method. Guess I'll dive into the constructor and try to figure out what that int argument does >: o.nestharus

1 Answers

0
votes

Apparently it is as easy as this

When walking the first tree, it correctly displays information from both files.

    public class Program
    {
            private static ParserRuleContext getTree(String file) throws Exception
            {
                    InputStream input = new FileInputStream(file);
                    Reader reader = new InputStreamReader(input);
                    ANTLRInputStream inputStream = new ANTLRInputStream(reader);

                    JavaLexer lexer = new JavaLexer(inputStream);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    JavaParser parser = new JavaParser(tokens);
                    ParserRuleContext tree = parser.compilationUnit(); // parse

                    return tree;
            }

            public static void main(String args[]) throws Exception
            {
                    ParserRuleContext tree1 = getTree("E:\\Users\\nessy\\IdeaProjects\\AntlrTest\\src\\in1.java");
                    ParserRuleContext tree2 = getTree("E:\\Users\\nessy\\IdeaProjects\\AntlrTest\\src\\in2.java");

                    tree1.addChild(tree2);

                    ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker
                    JavaWalker extractor = new JavaWalker();
                    walker.walk(extractor, tree1); // initiate walk of tree with listener
            }
    }