1. CSE340 - Principles of
Programming Languages
Lecture 09:
Grammars 1
Javier Gonzalez-Sanchez
javiergs@asu.edu
BYENG M1-38
Office Hours: By appointment
2. Javier Gonzalez-Sanchez | CSE340 | Summer 2015 | 2
Ambiguity
• A grammar is said to be ambiguous if there is at
least one string with two or more parse trees.
• Note that ambiguity is a property of grammars, not
languages.
4. Javier Gonzalez-Sanchez | CSE340 | Summer 2015 | 4
Solution
• If a grammar can be made unambiguous at all, it is
usually made unambiguous through layering.
• Have exactly one way to build each piece of the
string.
• Have exactly one way of combining pieces back
together.
• Recursive constructions
7. Javier Gonzalez-Sanchez | CSE340 | Summer 2015 | 7
Exercise
Provide a Grammar that is Not ambiguous
for arithmetic expressions
10 * 20 + 15
Precedence of operators and Associativity
þ (10 * 20) + 15
ý 10 * (20 + 15)
8. Javier Gonzalez-Sanchez | CSE340 | Summer 2015 | 8
Exercise | Precedence
New Grammar:
<E> à <__> + <__>
< > à <__> - <__>
< > à <__> * <__>
< > à <__> / <__>
< > à - <__>
Original Grammar:
E à E OP E
E à integer
OPà + | - | * | /
19. Javier Gonzalez-Sanchez | CSE340 | Summer 2015 | 19
Exercise 2
Include rules to accept variables names (identifiers) in
expressions. The grammar should accept as correct the
following expressions:
A * 20 + time
(x * y) + 15
10 * (ASU + cse340)
(10) * (20) + (15)
(hello * world + Arizona)
10 * (counter) + 15
21. Javier Gonzalez-Sanchez | CSE340 | Summer 2015 | 21
Exercise 3
Provide a Grammar that is
Not ambiguous
with Precedence of operators and Associativity for this:
10 + 20 > 15 & -10 != 1 | 20 / ( 10 + 1) < 5
27. CSE340 - Principles of Programming Languages
Javier Gonzalez-Sanchez
javiergs@asu.edu
Summer 2015
Disclaimer. These slides can only be used as study material for the class CSE340 at ASU. They cannot be distributed or used for another purpose.