Skip to content

Instantly share code, notes, and snippets.

@zencd
Last active September 1, 2019 18:07
Show Gist options
  • Save zencd/0eb1714f0f3ea143f6eab861cc0516f0 to your computer and use it in GitHub Desktop.
Save zencd/0eb1714f0f3ea143f6eab861cc0516f0 to your computer and use it in GitHub Desktop.
Print ANTLR4 tree (Kotlin)
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