Last active
September 1, 2019 18:07
-
-
Save zencd/0eb1714f0f3ea143f6eab861cc0516f0 to your computer and use it in GitHub Desktop.
Print ANTLR4 tree (Kotlin)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.antlr.v4.runtime.ParserRuleContext | |
import org.antlr.v4.runtime.tree.ParseTree | |
import org.antlr.v4.runtime.tree.TerminalNode | |
fun printSyntaxTree(root: ParserRuleContext): String { | |
fun recursive(aRoot: ParseTree, buf: StringBuilder, offset: Int) { | |
buf.append(" ".repeat(offset)) | |
if (aRoot is TerminalNode) { | |
buf.appendln("'${aRoot.text}'") | |
} else { | |
buf.appendln(aRoot.javaClass.simpleName) | |
} | |
if (aRoot is ParserRuleContext) { | |
if (aRoot.children != null) { | |
for (child in aRoot.children) { | |
recursive(child, buf, offset + 1) | |
} | |
} | |
} | |
} | |
val buf = StringBuilder() | |
recursive(root, buf, 0) | |
return buf.toString() | |
} | |
// Usage: | |
// ParseTree tree = parser.compilationUnit(); | |
// System.out.println(printSyntaxTree(tree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment