Say I have the following Java API that all packages up as blocks.jar
:
public class Block {
private Sting name;
private int xCoord;
private int yCoord;
// Getters, setters, ctors, etc.
public void setCoords(int x, int y) {
setXCoord(x);
setYCoord(y);
}
}
public BlockController {
public static moveBlock(Block block, int newXCoord, int newYCoord) {
block.setCooords(newXCoord, newYCoord);
}
public static stackBlocks(Block under, Block onTop) {
// Stack "onTop" on top of "under".
// Don't worry about the math here, this is just for an example.
onTop.setCoords(under.getXCoord() + onTop.getXCoord(), under.getYCoord());
}
}
Again, don't worry about the math and the fact that (x,y) coordinates don't accurately represent blocks in 3D space. The point is that we have Java code, compiled as a JAR, that performs operations on blocks. I now want to build a lightweight scripting language that allows a non-programmer to invoke the various block API methods and manipulate blocks, and I want to implement its interpreter with ANTLR (latest version is 4.3).
The scripting language, we'll call it BlockSpeak, might look like this:
block A at (0, 10) # Create block "A" at coordinates (0, 10)
block B at (0, 20) # Create block "B" at coordinates (0, 20)
stack A on B # Stack block A on top of block B
This might be equivalent to the following Java code:
Block A, B;
A = new Block(0, 10);
B = new Block(0, 20);
BlockController.stackBlocks(B, A);
So the idea is that the ANTLR-generated interpreter would take a *.blockspeak
script as input, and use the commands in this script to invoke blocks.jar
API operations. I read the excellent Simple Example which creates a simple calculator using ANTLR. However in that link, there is an ExpParser class with an eval()
method:
ExpParser parser = new ExpParser(tokens);
parser.eval();
The problem here is that, in the case of the calculator, the tokens
represent a mathematical expression to evaluate, and eval()
returns the evaluation of the expression. In the case of an interpreter, the tokens
would represent my BlockSpeak script, but calling eval()
shouldn't evaluate anything, it should know how to map the various BlockSpeak commands to Java code:
BlockSpeak Command: Java code:
==========================================
block A at (0, 10) ==> Block A = new Block(0, 10);
block B at (0, 20) ==> Block B = new Block(0, 20);
stack A on B ==> BlockController.stackBlocks(B, A);
So my question is, where do I perform this "mapping"? In other words, how do I instruct ANTLR to call various pieces of code (packaged inside blocks.jar
) when it encounters particular grammars in the BlockSpeak script? More importantly, can someone give me a pseudo-code example?