Lecture 4 - Context-Free Grammars
Lecture 4 - Context-Free Grammars
Lecture 4
Sections 4.1 - 4.2
Associate Professor
Dept of Computer Science and Engineering
University of Chittaong, Bangladesh
Email: [email protected]
The Phases of Compilation
Source Program
id1 +
id2 *
id3 num
1 Context-Free Grammars
Parse Trees
Leftmost and Rightmost Derivations
2 Ambiguity
Outline
1 Context-Free Grammars
Parse Trees
Leftmost and Rightmost Derivations
2 Ambiguity
Context-Free Grammars,
uses special notation (BNF – Backus Naur Form),
consist of set of rules (productions).
Example:
Corresponds to a rule:
Context-Free Grammars
Example
Example (Context-free grammar)
Let the terminals be the tokens
{+, *, (, ), id}.
E→E + E
E→E ∗ E
E→(E)
E → id
Example
Context-free grammars
We can use the grammar to derive strings of terminals if we
Begin with the start symbol.
Repeatedly replace a nonterminal with the body of a production of
which that nonterminal is the head, until the resulting string
consists only of terminals.
Example
Example
E → E + E | E ∗ E | ( E ) | id
Outline
1 Context-Free Grammars
Parse Trees
Leftmost and Rightmost Derivations
2 Ambiguity
Parse Trees
Example
Example
E * E
( E ) id
E + E
id id
Example
+ id
id id
Outline
1 Context-Free Grammars
Parse Trees
Leftmost and Rightmost Derivations
2 Ambiguity
Example
E → E + E | E ∗ E | ( E ) | id
Outline
1 Context-Free Grammars
Parse Trees
Leftmost and Rightmost Derivations
2 Ambiguity
Ambiguity
E → E + E | E ∗ E | ( E ) | id
Ambiguity
Example
E→E+T |T
T →T *F |F
F → ( E ) | id
Example
E→E+T |T
T →T *F |F
F → ( E ) | id