antlr4/java: pretty print parse tree to stdout

前端 未结 4 1537
抹茶落季
抹茶落季 2021-02-06 04:14

Beginners question: how do I print a readable version of the parse tree to stdout?

CharStream input = CharStreams.fromFileName(\"testdata/test.txt\");
MyLexer le         


        
4条回答
  •  青春惊慌失措
    2021-02-06 04:37

    If you like to use regex only for what it's really for, you can always print a tree by yourself:

    import org.antlr.v4.runtime.Parser;
    import org.antlr.v4.runtime.ParserRuleContext;
    import org.antlr.v4.runtime.tree.ParseTree;
    import org.antlr.v4.runtime.tree.Trees;
    
    public static String printSyntaxTree(Parser parser, ParseTree root) {
        StringBuilder buf = new StringBuilder();
        recursive(root, buf, 0, Arrays.asList(parser.getRuleNames()));
        return buf.toString();
    }
    
    private static void recursive(ParseTree aRoot, StringBuilder buf, int offset, List ruleNames) {
        for (int i = 0; i < offset; i++) {
            buf.append("  ");
        }
        buf.append(Trees.getNodeText(aRoot, ruleNames)).append("\n");
        if (aRoot instanceof ParserRuleContext) {
            ParserRuleContext prc = (ParserRuleContext) aRoot;
            if (prc.children != null) {
                for (ParseTree child : prc.children) {
                    recursive(child, buf, offset + 1, ruleNames);
                }
            }
        }
    }
    

    Usage:

    ParseTree root = parser.yourOwnRule();
    System.out.println(printSyntaxTree(parser, root));
    

提交回复
热议问题