A simple example:
(grammar):
stat: ID '=' expr NEWLINE -> ^('=' ID expr)
expr: atom '+' atom -> ^(+ atom atom)
atom: INT | ID
...
(input text): a = 3 + 5
The corresponding CommonTree for ‘3 + 5’ contains a ‘+’ token and two children (3, 5).
At this point, what is the best way to recover the original input text that parsed into this tree (‘3 + 5’)?
I’ve got the text, position and the line number of individual tokens in the CommonTree object, so theoretically it’s possible to make sure only white space tokens are discarded and piece them together using this information, but it looks error prone.
Is there a better way to do this?
Better, I don’t know. There is another way, of course. You decide what’s better.
Another option would be to create a custom AST node class (and corresponding node-adapter) and add the matched text to this AST node during parsing. The trick here is to not use
skip(), which discards the token from the lexer, but to put it on theHIDDENchannel. This is effectively the same, however, the text these (hidden) tokens match are still available in the parser.A quick demo: put all these 3 file in a directory named
demo:demo/T.g
demo/XTree.java
demo/Main.java
You can run this demo by opening a shell and cd-ing to the directory that holds the
demodirectory and execute the following:which will produce the following output: