Is the following even possible? I want to “reverse” the input given to antlr and make each token a child of the previous one.
So, for the input (Assume each token is separated by the ‘.’ char) :
Stack.Overflow.Horse
I would like my grammar to produce the following AST:
Horse
|---Overflow
|---Stack
So far, I’ve managed to reverse the nodes, but I’m unable to make them children of each other:
function
: ID PERIOD function
-> function ID
| ID
;
ID : 'a'..'z'*
;
I don’t think there’s an easy way to do that. You could make your rule like this:
but that only makes the last node the root and all other nodes its children. For example, the following source:
will result in the following tree:
I can’t see an easy fix since when you first parse
a.b.c.d.e,awill be theIDandb.c.d.ethe recursive call tofunction:resulting in the fact that
b.c.d.ewill haveaas its child. When thenbbecomes theID, it too is added as a child next toa. In your case,ashould be removed as a child and then added to the list ofb‘s children. But AFAIK, that is not possible in ANLTR (at least, not in a clean way inside the grammar).EDIT
Okay, as a work-around I had something elegant in mind, but that didn’t work as I had hoped. So, as a less elegant solution, you could match the
lastnode as the root in your rewrite rule:and then collect all possible preceding nodes (
children) in aListusing the+=operator:and use a custom member-method in the parser to “inject” these
childreninto the root of your tree (going from right to left in yourList!):A little demo:
And a little test class:
which will produce an AST that looks like:
For the input string: