Parsing: The Problem of Finding a DerivationTopGenerating Code for expressions used as conditions (cont.)Generating Code for REAL Control Structures

Generating Code for REAL Control Structures

  1. Now that we know how to handle conditionals, we can consider the control structures in which they are used.
  2. Just as it was helpful to pass a branch target as a parameter to genCondExpr, we can generate better code for control structures if we branch targets as inherited semantic information to our code generation routines for statements. In particular, we must pass each statement a label for the statement that follows it, sometimes called its continuation.
  3. Notice that it is not just the if statement routine that expects "nextlabel" as a parameter. Even the generic "genstmt" expects this parameter! This is because genstmt may end up finding that it was asked to process an if statement (or a while loop) which will actually use "nextlabel" as the target of a branch.

    Then again, it may find out that it was called for an assignment statement and not use "nextlabel" at all.

  4. To make this work, you will have to place a label after each statement in a statement list (except the last) so that you have something to pass to "genstmt". That is, your code to generate a statement list will have a loop that runs through the list of statements generating code for them. As it does this, it will have to generate a label to place between each pair so that it can pass that label as the nextlabel for the statement that precedes it.
  5. To keep the code you generate more readable, you might want to store a flag in each codelabel indicating whether it was used. Then, when asked to place the label, only place it in the output if it was actually used.

    Beware that the label placed at the start of a while loop body will not be used until after it has been "placed".


Computer Science 434
Department of Computer Science
Williams College

Parsing: The Problem of Finding a DerivationTopGenerating Code for expressions used as conditions (cont.)Generating Code for REAL Control Structures