



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




The derivations can be represented in a tree-like fashion. The interior nodes contain the non-terminals used during the derivation
These two derivations point out a problem with the grammar. It has no notion of precedence , or implied order of evaluation. The normal arithmetic rules say that multiplication has higher precedence than subtraction. To add precedence, create a non-
terminal for each level of precedence. Isolate corresponding part of grammar to force parser to recognize high precedence sub-expressions first. Here is the revised grammar:
This grammar is larger and requires more rewriting to reach some of the terminal symbols. But it encodes expected precedence. Let’s see how it parses
x – 2 * y
Rule Sentential Form
This produces same parse tree under leftmost and rightmost derivations
9 | Id
8 factor? number
7 | factor
6 | term / factor
5 term?^ term^ ∗^ factor
4 | term
3 | expr – term
2 expr? expr + term
1 Goal? expr
level two
level one
The convention in most programming languages is to match the else with the most recent if.
Production 1, then Production 2: if E 1 then if E 2 then S 1 else S 2
Production 2, then Production 1: if E 1 then if E 2 then S 1 else S 2
We can rewrite grammar to avoid generating the problem and match each else to innermost unmatched if:
1. Stmt? If E then Stmt 2. | If E then WithElse else Stmt 3. | _Assignment
Let derive the following using the rewritten grammar:
if E 1 then if E 2 then A 1 else A 2
We have been using the term context- free without explaining why such rules are in fact “free of context”. The simple reason is that non-terminals appear by themselves to the left of the arrow in context-free rules:
A? α
The rule A? α says that A may be replaced by α anywhere , regardless of where A occurs. On the other hand, we could define a context as pair of strings β , γ , such that a rule would apply only if β occurs before and γ occurs after the non-terminal A. We would write this as β A γ? β α γ
This binds the else controlling A 2 to inner if
Stmt
then
else
if Expr Stmt
if Expr then Withelse Stmt