Here is a solution to the expression code generation problem
from Assignment 5. The one posted earlier by David Cimbala is
incorrect. The code you need to write for Assignment 7 is not much
more than this.
- Professor Pingali
class Parser
{
private static CS211In fpe;
private static CS211Out outfile;
private String result;
// this is our recursive descent parsing routine
// the fpe is assumed to be correct, no error checking in this version
public static String evalFpe()
{ String code = "";
switch (fpe.peekAtKind()) {
case fpe.INTEGER: {
int num = fpe.getInt();
code = "PUSHIMM " + num + "\n"; // string concatenation
break;
}
case fpe.OPERATOR: {
char op = fpe.getOp(); // get the left parentheses
String arg1 = evalFpe(); // recursive call to deal with
// first argument
op = fpe.getOp(); // get the arithmetic operator
String arg2 = evalFpe(); // deal with second argument
char op2 = fpe.getOp(); // move past right parentheses
String arith = "";
switch (op) {
case '+': arith = "ADD " + "\n"; break;
case '-': arith = "SUB " + "\n"; break;
case '*': arith = "TIMES " + "\n"; break;
}
code = arg1 + arg2 + arith;
break;
}
}
return code;
}
public static void main(String[] args)
{
if (args.length == 1 )
fpe = new CS211In(args[0]); // cmd line entry
else {
System.out.println("Usage: Parser ");
return;
}
String result = evalFpe() + "STOP " + "\n"; // last SaM cmd
CS211Out outfile = new CS211Out("exp.sam");
outfile.println(result);
outfile.close();
}
}