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
,a
will be theID
andb.c.d.e
the recursive call tofunction
:resulting in the fact that
b.c.d.e
will havea
as its child. When thenb
becomes theID
, it too is added as a child next toa
. In your case,a
should 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
last
node as the root in your rewrite rule:and then collect all possible preceding nodes (
children
) in aList
using the+=
operator:and use a custom member-method in the parser to "inject" these
children
into 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: