Search code examples
compiler-construction

Backpatching Intermediate Code Generation For Boolean Expressions


I´m studying the Dragon Book to create an intermediate code generator for my DECAF compiler.

I´m reading the backpatching method, which suggest the following translation of boolean expressions:

enter image description here

I find everything very clear. However, when implementing my translator based on the book I´ve found a problem when having if statements such as:

boolean a = false;
if(a){
    x= 0;
}

The problem I have is that I don´t know how to manage variables in a boolean expression where there is no operand. When I have things like:

if(x>200){
   ....
}

The translation works fine. Can anyone tell what to do in the case I have a single variable as a control-flow boolean expression?


Solution

  • You need to emit some sort of test-and-jump operator. For example, you could pretend that if(a) were the same as if(a!=0) (with appropriate type safety, but still assuming that in your VM boolean false is 0) and proceed in a fashion similar to the E1 relop E2 case. (Here E1 would be the expression and E2 a literal 0.)

    The Dragon book example doesn't contemplate boolean variables; note that it effectively constant-folds true and false. That's probably effective for didactic purposes; in a real programming language, boolean types would have to have some kind of integer representation, and boolean variables would need to be tested appropriately.