Compiling 3

SL4

SL4 Functions

SL4 Example Program

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;
}

SL4 Compiler

Compiling Arithmetic Expressions

Compiling Expressions

Compiling Branches

Compiling Loops

What Did We Achieve?

Lab

???

Step 1: Try the Compiler

  1. In Eclipse, make a Scala project Lab18
  2. Add SL4.scala
  3. Start the program and paste in the factorial program from slide 4. Hit Ctrl+D/Ctrl+Z. What happens?
  4. Where is the compiled program?
  5. What happens when you run it?
  6. Run javap -c. How many functions are in the class file?
  7. What code is generated for the while loop?

Step 2: Rewrite Factorial

  1. Rewrite the factorial program to be recursive, not iterative. What is your code?
  2. What happens when you compile and run it?
  3. What code is generated for the if statement?

Step 3: Improve the Compiler

  1. The parts of the compiler that generate code for if and while statements contain identical code for generating the branch condition. What is that code?
  2. Make a separate function codeofBoolOp that generates this code and deals with the fact that you need to set the branch target later. What is your function?
  3. Try your changed compiler with the programs in step 1 and 2 to make sure that it still works.

Step 4: The if/if/else ambiguity

  1. The grammar
    stat ::= "if" "(" expr ")" stat ( "else" stat )? | expr ";"

    is ambiguous. There are two possible parse trees for if (c1) e1 if(c2) e2 else e3. What are these parse trees?

  2. In Java, which of them is actually being used?
  3. In SL4, which of them is actually being used?