Operator precedence, associativity, ambiguity Dangling else problem
Syntax diagrams
Where Syntax Meets Semantics
Lecture 3 Grammars and Parse Trees
Grammars and Parse Trees
Need some semantics with our syntax
1
Three “Equivalent” Grammars
Lecture 3 Formal Grammars and Parse Trees
CS631 Fall 2000
2
Why Parse Trees Matter
-
-
::= 1 | 2 | 3 | - ::= - | ::= 1 | 2 | 3
3 -
::= - | ::= 1 | 2 | 3
2
CS631 Fall 2000
3
Concepts
2
Lecture 3 Formal Grammars and Parse Trees
CS631 Fall 2000
4
Working Grammar
We want the structure of the parse tree to correspond to the semantics of the string it generates. This makes grammar design much harder: we’re interested in the structure of each parse tree, not just in the generated string. “Where syntax meets semantics”
Lecture 3 Formal Grammars and Parse Trees
3 Both grammars generate the string 3-2-1, but the parse tree on the left corresponds to the computation 3 - (2 - 1) = 2, while the one on the right corresponds to (3 - 2) - 1 = 0.
These grammars all define the same language: the language of strings that contain one or more 1’s, 2’s and/or 3’s separated by minus signs. But... Lecture 3 Formal Grammars and Parse Trees
1
- 1
CS631 Fall 2000
::= * | + | () |a|b|c This generates a language of arithmetic expressions using parentheses, the operators + and *, and the variables a, b and c.
5
Lecture 3 Formal Grammars and Parse Trees
CS631 Fall 2000
6
1
Issue #1: Precedence
Our grammar generates this tree for a+b*c. In this tree, the addition is performed before the multiplication, which is not the usual convention for operator precedence.
* + a
Operator Precedence
c
b
Applies when the order of evaluation is not completely decided by parentheses. Each operator has a precedence level, and those with higher precedence are performed before those with lower precedence. Most languages put * at a higher precedence level than +, so that a+b*c = a+(b*c)
Note: G4 is also an ambiguous grammar--this is not the only parse tree for a+b*c. Lecture 3 Formal Grammars and Parse Trees