I would really appreciate if someone could give me advice,or point me to tutorial, or sample implementation, anything that could help me implement basic goto statement in ANTLR?
Thanks for any help
edit. ver2 of question:
Say I have this tree structure:
(BLOCK (PRINT 1) (PRINT 2) (PRINT 3) (PRINT 4) )
Now, I’m interested to know is there a way to
select, say, node (PRINT 2) and all nodes that follow
that node ((PRINT 2) (PRINT 3) (PRINT 4)) ?
I’m asking this because I’m trying to implement
basic goto mechanism.
I have print statement like this:
i=LABEL print
{interpreter.store($i.text, $print.tree);} //stores in hash table
-> print
However $print.tree just ignores later nodes,
so in input:
label: print 1
print 2
goto label
would print 121!
(What I would like is infinite loop 1212…)
I’ve also tried taking token
address of print statement with
getTokenStartIndex() and setting
roots node with setTokenStartIndex
but that just looped whatever was first node over and over.
My question is, how does one implement goto statement in antlr ?
Maybe my approach is wrong, as I have overlooked something?
I would really appreciate any help.
ps. even more detail, it is related to pattern 25 – Language Implementation patterns, I’m trying to add on to examples from that pattern.
Also, I’ve searched quite a bit on the web, looks like it is very hard to find goto example
Note that it isn’t ANTLR that implements this. With ANTLR you merely describe the language you want to parse to get a lexer, parser and possibly a tree-walker. After that, it’s up to you to manipulate the tree and evaluate it.
Here’s a possible way. Please don’t look too closely at the code. It’s a quick hack: there’s a bit of code-duplication and I’m am passing package protected variables around which isn’t as it should be done. The grammar also dictates you to start your input source with a
label, but this is just a small demo of how you could solve it.You need the following files:
Goto.g– the combined grammar fileGotoWalker.g– the tree walker grammar fileMain.java– the main class including the Node-model classes of the languagetest.goto– the test input source fileantlr-3.3.jar– the ANTLR JAR (could also be another 3.x version)Goto.g
GotoWalker.g
Main.java
test.goto
To run the demo, do the following:
*nix/MacOS
or:
Windows
which will print:
Note that the 2 and 3 are repeated until you terminate the app manually.