CS 152 - Lecture 24

Cover page image

Cay S. Horstmann

Compiling 3

SL3

SL3 Functions

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

SL3 Compiler

Compiling Arithmetic Expressions

Compiling Expressions

Compiling Branches

Compiling Loops

What Did We Achieve?

What Else Did We Achieve in this Course?

Lab

???

Step 1: Try the Compiler

  1. Download and unzip the SBT project in sl3.zip
  2. If you use Eclipse, run sbt eclipse in the sl3 directory and import the project.
  3. Start the program and paste in the factorial program from slide 5. 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?
  8. How did Eclipse know where to find the BCEL library?

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: 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) if (c2) e1 else e2. What are these parse trees?

  2. In Scala, which of them is actually being used?
  3. In SL3, which of them is actually being used?

Step 4: 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 5: A for loop

  1. Add a C style for 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?

  2. Add a class for the AST. What is your class?
  3. Generate code: First the code in the first statement, then the same code as for a while statement, followed by the code of the last statement. What change did you need to make in the SL3 compiler?
  4. What code is generated for the fac function above?