
+ - * / function callsvar = expr; if (expr rel expr) stat else stat
while (expr rel expr) stat
Need as built-in because we don't have closures
funName(param 1, param2, ...) {
var varName1;
var varName2;
...
stat1
stat2
...
return expr;
}
main() {
print(fac(3));
return 0;
}
fac(n) {
var f;
var i;
f = 1;
i = 1;
while (i <= n) {
f = f * i;
i = i + 1;
}
return f;
}
mainprint is a special function that prints an integerpublic static void main(String[]) calls main()print method is always added+ / \ 3 * / \ 4 5
case Operator(left, right, op) => {
codeof(left)
codeof(right)
il.append(InstructionFactory.createBinaryOperation(op, Type.INT))
}
iconst 3 iconst 4 iconst 5 imul iadd
iconstiloadmg.getLocalVariables().find(_.getName() == name) match { case Some(v) =>
il.append(InstructionFactory.createLoad(v.getType, v.getIndex))
}
args.foreach(codeof _) il.append(factory.createInvoke(className, f.name, Type.INT, f.params.map(x => Type.INT).toArray, // return type, param types Constants.INVOKESTATIC))
printIfStat(BoolOp(expr1, expr2, rel), body1, optBody2) becomes
expr1 expr2 isub if !rel goto :label1 body1 goto :label2 :label1 nop body2 :label2 nop
codeof(expr1)
codeof(expr2)
il.append(InstructionFactory.createBinaryOperation("-", Type.INT))
val instr1 = InstructionFactory.createBranchInstruction(notrel2op(rel), null)
il.append(instr1)
...
instr1.setTarget(il.append(InstructionConstants.NOP))
val notrel2op = Map(">=" -> Constants.IFLT, ">" -> Constants.IFLE,
"<=" -> Constants.IFGT, "<" -> Constants.IFGE,
"!=" -> Constants.IFEQ, "==" -> Constants.IFNE)
WhileStat(BoolOp(expr1, expr2, rel), body) becomes
:label1 nop expr1 expr2 isub if !rel goto :label2 body goto :label1 :label2 nop
val loc = il.append(InstructionConstants.NOP)
codeof(expr1)
codeof(expr2)
il.append(InstructionFactory.createBinaryOperation("-", Type.INT))
val instr = InstructionFactory.createBranchInstruction(notrel2op(rel), null)
il.append(instr)
codeofBlock(body)
il.append(InstructionFactory.createBranchInstruction(Constants.GOTO, loc))
instr.setTarget(il.append(InstructionConstants.NOP))

sbt eclipse in the sl3 directory and import the project.javap -c. How many functions are in the class file? while loop?if statement?stat ::= "if" "(" expr ")" stat ( "else" stat )? | expr ";"
is ambiguous. There are two possible parse trees for if (c1) if (c2) e1 else e2. What are these parse trees?
if and while statements contain identical code for generating the branch condition. What is that code?codeofBoolOp that generates this code and deals with the fact that you need to set the branch target later. What is your function?for loopfor loop to SL3, like this:
fac(n) {
var f;
var i;
f = 1;
for (i = 1; i <= n; i = i + 1)
f = f * i;
return f;
}
What change is required in the grammar?
while statement, followed by the code of the last statement. What change did you need to make in the SL3 compiler?fac function above?