I’m trying to figure out where to start with this project. Perhaps someone can steer me in the right direction.
I am given a small language that I must write an interpreter for. The language consists of either an expression in parentheses:
(integer integer operator)
or an arithmetic IF statement made up of expressions in the form:
IF exp1 exp2 exp3 exp4
where exp2 is returned if exp1 is negative,
exp3 is returned if exp1 is zero,
and exp4 is returned if exp1 is positive.
The operator is either + or x (for addition and multiplication respectively).
I have to implement a scanner/parser together, then the interpreter that will output the result. The interpreter part will not be difficult, but I’m having trouble figuring out how to start the scanning/parsing process.
I have started by using Java, and have a Scanner object collect the input and store it in a string. Then I split the String into a String array using nothing as the delimiter (so that each single character, symbol, space, etc. is stored in its own index of a string). This may not be the best way to do this, as I cannot figure out where to go from here. The part I cannot grasp is how to return errors if this syntax isn’t followed, or how to detect the parenthesis and/or IF and etc.
Here’s the snippet of code that I described in the last paragraph:
public void run() {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String sLine = sc.nextLine();
String[] scanned = sLine.split("");
Input examples:
(7 2 +)
Output: 9
IF (2 -2 +) (5 2 +) (5 -2 x) (5 2 x)
Output: -10
If anybody has a good direction for me to take, please share. 🙂
I think using ANTLR, JavaCC, SampleCC or other parser generator tools would be using a sledgehammer to crack a nut. if there is no recursion in grammar definition just a few methods would be sufficient. the following code gives a basic idea (it may not compile or work, I wrote it from scratch as an illustration how to start):