/ CASE STUDY
/ The Compiler
Here is the specification for translating statements:
The predicate Statement(Stmt) analyzes and translates statements. For each alternative of the abstract syntax, there is a separate rule.
As an example, consider the treatment of if-statements that are represented by
if(E, S1, S2, Pos)The code for this construct is
code for expression E FJP(L1) code for statement S1 JMP(L2) LAB(L1) code for statement S2 LAB(L2)where L1 and L2 are two unique labels. First, the expression is evaluated. If this yields false, the FJP instruction jumps to L2. Otherwise, the statement S1 is executed. After that, we jump over the code for S2. The code for S2 is preceded by a label S2, which is the target of FJP.
New labels are created by NewLabel. The predicate Expression not only generates codes for its argument E, but also computes the type T of E. In an if-statement this type must be bool. This is checked by CheckBool.
Hence, the rule for if is
'rule' Statement(if(E, S1, S2, Pos)) : Expression(E -> T) CheckBool(T, Pos) NewLabel(-> L1) NewLabel(-> L2) FJP(L1) Statement(S1) JMP(L2) LAB(L1) Statement(S2) LAB(L2)An assignment
assign(V, E, Pos)is compiled into code for the designator V and code for the expression E.
After evaluation of these code sequences, the stack top comprises the address given by V and the value of E. An instruction STI is used to store the value at the given address and to remove the two items from the stack. The types TV and TE of V and E must be equal and scalar. In addition, TV may be real and TE may be int. Then the STI must be preceeded by an FLT instruction. This check and the generation of FLT and STI are expressed by the predicate Assign.
The code for a procedure call is
MST(CurLev-Level) code for parameters JSR(Size, Start)where CurLev is the current nesting level and the procedure has been declared at level Level and with start label Start. The code for parameters is generated by ParamList.
Assign(LhsType, RhsType, Pos) checks whether a value of type RhsType can be assigned to a designator of type LhsType. If so, it emits the corresponding instruction(s).
The code for parameter passing is constructed by the predicate ParamList(Formals, Actuals -> Size) which processes the lists of formal and actual parameters in parallel.
A pair of formal and actual parameters is handled by Param(Formal, Actual, Pos).