Act CH 3
Act CH 3
Chapter 3
CFGs AND PUSH-DOWN AUTOMATA
CFGs 2
Context-Free Grammars:
are notations used for describing context-free languages and
recursions.
This CFGs can be defined using an extension of -NFA with stack
called push-down automata.
CFGs has been used in compiled design to impose the syntax of a
programming language.
CFGs explained by quadruples
V, is a finite set of non-terminals (like states)፣ T, is a finite set of terminal (like
inputs)
P, is a finite set of production rules and S, is a start symbol which is an element
of N and represent the language to be defined.
A production rule is of the form A where, {V ∪ T}* and A V
… 3
Given a grammar G:
T→R
T → aTc
R→
R → RbR
generate a parse tree for the strings aabbbcc and abbc.
Ambiguity in CFGs 10
A CFG is ambiguous:
if there exists at least one string w in T*, for which we can find
more than one possible parse trees that yields w.
A CFG is unambiguous:
If a string has at most one parse tree in a gramma that yields w.
Example: show a grammar G:
E E*E E-E E+E E/E
E (E)
E id , is ambiguous grammar taking a string id + id * id.
… 11
Ambiguous grammars:
are defective to impose the structural definition on a program.
Therefor, its important to know the causes of ambiguity in a
grammar and
Convert ambiguous grammars into unambiguous one’s.
First, how do we know if a grammar is ambiguous?
Determining ambiguity is undecidable.
Which means there is no theorem, proof or algorithm to be used for determining
whether a grammar is ambiguous or not.
Although, it possible to find a string and show that the string have two
different parse trees generated.
Operator precedence and associativity 12
The general rule is, "Match each else with the closest unmatched then."
… 14
Every regular grammar can be converted into finite automata and vise-
versa.
FSA to regular grammar 17
2. Regular grammar G:
S a | aA | bB |
A aA | aS
B cS |
Normal forms of CFGs 21
2. Phase two: drive G’’ from G’, such that each symbols appears in a sentential
form.
A. Include start symbol in Y1 and initialize i=1.
B. Include all symbols Yi+1, that can be derived from Y1 and all production rules applied.
C. Increment i and repeat step-2 until yi+1 =Yi
… 23
A aA| A aAA|
B bB| B bBB|
Eliminating unit-productions 25
A PDA
Example:
1. Design a PDA for the language 0n1n ,n1 and 0n12n ,n1.
2. Design a PDA for the language wwR for w is in ={0,1}
CFG to PDA 34
Example:
1. Convert the CFG given below into equivalent PDA.
1. G:
2. G:
3. G:
Applications of CFGs 36