Using Parboiled to generate an AST (Java)

1.6k Views Asked by At

I have created a PEG using the Parboiled library for Java.
I based it off of this example.

It works fine, but now I need to actually create the AST.

My question is how do I do this using the library?

After looking around on Google for a bit and looking at the examples on the Github, I see that you are intended to use push, pop, swap, etc. to create the AST but I am having trouble figuring out how to do this with my parser. My parser is similar enough to the Java one that if you can help me understand how it would work for the Java one, I could adapt it to mine.

1

There are 1 best solutions below

0
On

Basically PEG parser keeps a stack with values, you can push and pop values as you are matching the input. You will push the values (AST nodes) on the stack and when the parsing finish you get the root node of your AST from the parser.

Check https://github.com/sirthias/parboiled/blob/master/examples-java/src/main/java/org/parboiled/examples/calculators/CalculatorParser4.java as an example how to use push and pop .

Check also (quite nice!) documentation of Parboiled project. Here is part specific for AST creation https://github.com/sirthias/parboiled/wiki/Working-with-the-Value-Stack