Is anyone aware of tutorials for walking ANTLR-generated ASTs in C#? The closest I was able to find is this, but it’s not terribly helpful.
My goal is to walk through trees that I’m generating based on a domain-specific language that I’m working on, and to use the trees to output generated C# code.
A Java-based tutorial would be helpful, too — anything that provides clear examples of how to traverse ANTLR ASTs.
I managed to figure this out by adapting the example at the end of Manuel Abadia’s article.
Here’s my version, which I happen to be using to convert parsed code to C#.
These are the steps:
CommonTree.To get the literal text of a node, use
node.Text.To get the token name of a node, use
node.Token.Text.Note that
node.Token.Textwill only give you the actual name of your token if it’s an imaginary token with no corresponding string. If it’s a real token, thennode.Token.Textwill return its string.For example, if you had the following in your grammar:
Then you’ll get
"PROGRAM","FUNCDEC","==", and"="from the corresponding accesses ofnode.Token.Text.You can see part of my example below, or you can browse the full version.