Compiler Lecture 4
Compiler Lecture 4
Objective:
• To explain the Context Free Grammar (CFG) with example.
• To demonstrate derivation or derivation tree from a CFG
• To elaborate ambiguity and ambiguous grammar.
• To explain associativity and precedence of operator
Outcome:
• After this lecture the student will able to demonstrate CFG
• Student will be capable of derivation from CFG
• Student will be able to differentiate if a grammar is ambiguous or not.
• After this lecture student will learn associativity and precedence of operator
Context-free grammar
One can provide a formal definition of a context free grammar. It is a 4-tuple (V, Σ, S, P)
where:
• V is a finite set of variables;
• Σ is a finite alphabet of terminals;
• S is the start variable; and
• P is the finite set of productions. Each production has the form V → (V ∪ Σ) ∗
• A grammar derives strings by beginning with the start symbol and repeatedly
replacing a nonterminal by the body of a production for that nonterminal.
• The terminal strings that can be derived from the start symbol form the language
defined by the grammar.
Derivation
S → 0S1
S→ε
S → NP VP
NP → the N
VP → V NP
V → sings | eats
N → cat | song | canary
This generates “the canary sings the song”, but also “the song eats the cat”.
This CFG generates all “legal” sentences, not just meaningful ones.
Parse Trees and Ambiguity
• A parse tree pictorially shows how the start symbol of a grammar derives a
string in the language. If nonterminal A has a production A -> XYZ, then a
parse tree may have an interior node labeled A with three children labeled X,
Y, and Z, from left to right.
• A grammar can have more than one parse tree generating a given string
of terminals. Such a grammar is said to be ambiguous.
Derivation
string ->string + string | string - string | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Check if the given grammar G is ambiguous or not.
S → aSb | SS
S→ε
For the string "aabb" the above grammar can generate two parse trees
Since there are two parse trees for a single string "aabb", the grammar G is ambiguous.
Associativity of operators
left-associative
1. Compilers-Principles, techniques and tools (2nd Edition) V. Aho, Sethi and D. Ullman
References/ Books