Tutorial 2 Discussion Document - Batch 04
Tutorial 2 Discussion Document - Batch 04
Ambiguous Grammar:
S→E
E → E + E | E * E | (E) | id
The string id + id * id
S S
E E
E * E
E + E
E + E id
id E * E
id id
id id
The parser will read the first parse tree with * taking higher priority followed by + which is the right
semantics of the string or token id + id * id as it follows the hierarchy of operators.
The parser will read the second parse tree with + taking higher priority followed by * which is not the
correct semantics as it does not follow the hierarchy of operators.
In the above example it means that the string id + id * id has two different meaning, and the parser will
not be able to distinguish which meaning is correct or to follow.
If a valid string in a grammar has more then one derivation tree, then the given grammar is ambiguous.
When we write grammar for programming languages, the grammar must be unambiguous. The parser
or the compiler will not be able to handle ambiguity.
Questions
1. Let G be the grammar
S → aS | Sb | ab | SS
(a) Using this grammar, produce two leftmost derivations of the string ”aaabbb”.
S => aS => aaS => aaSb => aaSbb => aaabbb
S => Sb => aSb => aaSb =>aaSbb => aaabbb
(b) Build the parse trees for the derivations from part (a).
S S
S b
a S
a S a S
S b
a S
S b
S b
a b
a b
(c) Give a regular expression for L(G). Discuss your answer and how it relates to ambiguity.
Answer this question as part of your assignment 1, tutorial 2.
(a) Using this grammar, produce two leftmost derivations of the string ”aaaabb”.
Please do this as part of learning at home. No need to submit as part of Assignment 1.
(b) Build the parse trees for the derivations from part (a).
Please do this as part of learning at home. No need to submit as part of Assignment 1.
(c) Give a regular expression for L(G).
Answer this question as part of your assignment 1, tutorial 2.
Use leftmost or rightmost derivation to construct a parse tree, on the following strings:
(a) “aacabdbb”
(b) “aaaaabbbbb” See if any of the above strings can be derived by more than one parse tree.