Compiler Lecture 6
Compiler Lecture 6
exp op exp
number + number
2 exp 3 op 4 exp
number + number
4 exp 3 op 2 exp
Right-most
( 5 exp ) * number Derivation
8 exp 7 op 6 exp
number – number
Sahar Selim CSCI415 | Compiler Design Lecture 6: Syntax Analysis II 14
Parse Trees:
int * ( int + int)
Ambiguous Grammar
exp op exp
number * number
(3) (4)
Sahar Selim CSCI415 | Compiler Design Lecture 6: Syntax Analysis II 36
Why Abstract Syntax-Tree ?
The principle of syntax-directed translation
The meaning, or semantics, of the string 3+4 should be directly
related to its syntactic structure as represented by the parse tree.
In this case, the parse tree should imply that the value 3 and
the value 4 are to be added.
A much simpler way to represent this same information,
namely, as the tree
+
3 4
- 42
34 3
The parentheses tokens have actually disappeared
still represents precisely the semantic content of
subtracting 3 from 34, and then multiplying by 42
if-stmt
0 other other
Sahar Selim CSCI415 | Compiler Design Lecture 6: Syntax Analysis II 40
Example 2
Using another grammar of if-statement
other
Sahar Selim CSCI415 | Compiler Design Lecture 6: Syntax Analysis II 42
Example 3
The grammar of a sequence of statements
separated by semicolons:
stmt ; stmt-sequence
s stmt ; stmt-sequence
s stmt
s
Sahar Selim CSCI415 | Compiler Design Lecture 6: Syntax Analysis II 44
Example 3
s ;
s s
s s s
Ambiguous Grammar
exp exp
_ exp op exp
* number
exp op exp number
number * number
number - number
- 42
34 3 AND
-
34 *
3 42
• The precedence cascades cause the parse trees to become much more complex
• The syntax trees, however, are not affected
Sahar Selim CSCI415 | Compiler Design Lecture 6: Syntax Analysis II 67
4 The dangling else
problem
S ⟹ aAb ( ∵ S → aAb)
⟹ abSb (∵ A → bS)
⟹ abab (∵ S → a)
E → E + T | T E → E + T | T
T → T . F | F OR T → T . F | F
F → F * F | G F → F * F | a | b
G → a | b
https://youtu.be/9vmhcBpZDcE