Type conversion within assignments
E E1 + E2
E.place= newtmp;
if E1 .type = integer and E2 .type = integer
then emit(E.place ':=' E 1 .place 'int+' E 2 .place);
E.type = integer;
.
similar code if both E1 .type and E2 .type are real
.
else if E 1 .type = int and E2 .type = real
then
u = newtmp;
emit(u ':=' inttoreal E 1 .place);
emit(E.place ':=' u 'real+' E2 .place);
E.type = real;
.
similar code if E1 .type is real and E2 .type is integer
When a compiler encounters mixed type operations it either rejects certain mixed type operations or generates coercion instructions for them.
Semantic action for E -> E1+ E2:
E.place= newtmp;
if E1.type = integer and E2.type = integer
then emit(E.place ':=' E1.place 'int+' E2.place);
E.type = integer;
..
similar code if both E1.type and E2.type are real
.
else if E1.type = int and E2.type = real
then
u = newtmp;
emit(u ':=' inttoreal E1.place);
emit(E.place ':=' u 'real+' E2.place);
E.type = real;
.
similar code if E1.type is real and E2.type is integer
The three address statement of the form u ':=' inttoreal E1.place denotes conversion of an integer to real. int+ denotes integer addition and real+ denotes real addition.
Code generation is done along with type checking and if type resolution can be done in a single pass no intermediate representation like an abstract syntax tree would be required.
|