## 10.10. ` `An Unambiguous Grammar for Expressions

It is possible to write a grammar for arithmetic expressions that

1. is unambiguous.
2. enforces the precedence of * and / over + and -.
3. enforces left associativity.

Here is one such grammar:

1. <Sum>: <Sum> + <Product> | <Sum> - <Product> | <Product>
2. <Product>: <Product> * <N> | <Product> / <N> | <N>
3. <N>: ( <Sum> ) | number

If we attempt to build a parse tree for number + number * number,
we see there is only one such tree:

The only parse tree is:

This parse tree correctly represents left associativity by using
recursion on the left. If we rewrote the grammar to use recursion
on the right, we would represent right associativity.` `

Our grammar also correctly represents precedence levels
by introducing a new non-terminal symbol for each precedence level.` `
According to our grammar, expressions consist of the sum or
difference of terms (or a single term), where a term consists
of the product or division of factors (or a single factor),
and a factor is a nested expression or a number.` `
Add the power functionality to the grammar.` `

Here is the grammar:

1. <Sum>: <Sum> + <Product> (1)
| <Sum> - <Product> (2)
| <Product> (3)
2. <Product>: <Product> * <Pow> (4)
| <Product> / <Pow> (5)
| <Pow> (6)
3. <Pow>: <N> ^ <Pow> (7)
| <N> (8)
4. <N>: ( <Sum> ) (9)
| number (10)

What is the problem with the following grammar?` `

1. <Sum>: <Sum> + <Product> (1)
| <Sum> - <Product> (2)
| <Product> (3)
2. <Product>: <Product> * <Pow> (4)
| <Product> / <Pow> (5)
| <Pow> (6)
3. <Pow>: <Pow> ^ <N> (7)
| <N> (8)
4. <N>: ( <Sum> ) (9)
| number (10)

Created by *unroff & hp-tools.*
© by Hans-Peter Bischof. All Rights Reserved (1998).
Last modified: 27/July/98 (12:14)