Handout 11 CFG
Handout 11 CFG
– S → aS
– S → bb
Context Free Grammars
• CFG For L = {anbn n 0 1 2 3 4 …}
– S → aSb
– S→Λ
– S → ab
• CFG For EQUAL
– S → aB
– S → bA
– A→a
– A → aS
– A → bAA
– B→b
– B → bS
– B → aBB
Context Free Grammars
• CFG For EQUAL
– S → aB
– S → bA
– A→a
– A → aS
– A → bAA
– B→b
– B → bS
– B → aBB
• Can be compactly written as
S → aB | bA <S> ::= a<B> | b<A>
A → a | aS | bAA <A >::= a | a<S> | b<A><A>
B → b | bS | Abb <B> ::= b | b<S> | <A>bb
Context Free Grammars
• CFG For identifier
– IDENTIFIER → ALPHA /ALPHANUMERIC
– ALPHA → A|B|….|Z|a|b|c….|z
NUMERIC ALPHANUMERIC | Λ
– NUMERIC → 0|1|2…|9
Context Free Grammars
• CFG For arithmetic expressions
– <expression> <expression> + <expression>
– <expression> <expression> * <expression>
– <expression> <expression> - <expression>
– <expression> <expression> + <expression>
– <expression> (<expression>)
– <expression> <number>
Context Free Grammars
• Derivation or Generation
• S → abS | Λ
• S abS
ababS
abababS
ababab
abab
Parse Trees
• A tree format used for the derivation of a string from
the CFG
• Parse tree, Syntax tree, Generation tree, Production
tree, Derivation tree
• Start symbol of the CFG at root
• Non terminals are represented as nodes
• Terminals as leaves
• Every next level of tree is a derivation from a
production of CFG
• The yield of a parse tree is a terminal string held at all
the leaves
Parse Trees
• Examples
– S → abS | Λ
– Derivation of abababab
a b S
a b S
a b S
a b Λ
Derivation
• Left Most Derivation
– If a word w is generated by a CFG by a certain derivation and
at each step in the derivation a rule of production is applied to
the leftmost nonterminal in the working string then this
derivation is called a leftmost derivation
• Right Most Derivation
– If a word w is generated by a CFG by a certain derivation and
at each step in the derivation a rule of production is applied to
the rightmost nonterminal in the working string then this
derivation is called a rightmost derivation
Ambiguity
• A CFG is called ambiguous if for at least one
word in the language that it generated, there
are two possible derivations of the word that
corresponds to different syntax trees.
S S S S
a a
S S S a S a
a S S a a S S a
a a a a
• S → aS | a