Chapter 5:Semantic Analysis

Type checking for statements

. Statements typically do not have values. Special basic type void can be assigned to them.

S id := E S.Type = if id.type == E.type
 

then void

 

else type_error

S if E then S1 S.Type = if E.type == boolean
 

then S1.type

 

else type_error

S while E do S1

S.Type = if E.type == boolean

 
then S1.type
 

else type_error

S S1 ; S2

S.Type = if S1.type == void

 

and S2.type == void

 
then void
 
else type_error
 
 

Since statements do not have values, the special basic type void is assigned to them, but if an error is detected within a statement, the type assigned to the statement is type_error . The statements considered below are assignment, conditional, and while statements. Sequences of statements are separated by semi-colons. The productions given below can be combined with those given before if we change the production for a complete program to P -> D; S. The program now consists of declarations followed by statements.

Rules for checking statements are given below.

1. S id := E { S.type := if id . type == E.type then void else type_error }

This rule checks that the left and right sides of an assignment statement have the same type.

2. S if E then S1 { S.type := if E.type == boolean then S1.type else type_error }

This rule specifies that the expressions in an if -then statement must have the type boolean .

3. S while E do S1 { S.type := if E.type == boolean then S1.type else type_error }

This rule specifies that the expression in a while statement must have the type boolean .

4. S S1; S2 { S.type := if S1.type == void and S2.type == void then void else type_error }

Errors are propagated by this last rule because a sequence of statements has type void only if each sub-statement has type void .