CD9
CD9
PRECEDENCE FUNCTIONS
• Create symbols fa and ga for each a ε T that is a terminal or $.
• Partition the created symbols into as many groups as possible, in such a
way that if a ֹ═ b, then fa and gb are in the same group.
fa
gb
Compiler
• Create a directed graph whose nodes are the groups found in previous
step. For any a and b, if a <. b, place an edge from the group of gb to
the group of fa. If a .> b, place an edge from the group of fa to that
of gb.
fa gb fa gb
a .>b a <. b
Compiler
• For all the terminals a ε T in a given Grammar,
make two functions fa & ga.
• Let a , b ε T , then if..
a ֹ═ b → f(a) = g(b)
a ·> b → f(a) > g(b)
a <· b → f(a) < g(b)
PRECEDENCE TABLE
Consider the Grammar : E + E | E * E | E | id
Id * + $
id ·> ·> ·>
f* g*
f+ g+
f$ g$
fid gid =5
f* g*
f+ g+
f$ g$
fid gid
f* = 4 g*
f+ g+
f$ g$
fid gid
f* g*
f+ = 2 g+
f$ g$
Compiler
id * + $
Similarly by observing longest
path from each node...
PRECEDENCE FUNCTION
TABLE is hence given as.. f 4 4 2 0
g 5 3 1 0
Compiler
Eliminating Left Recursion
Applying the transformation to the Grammar, we get:
Expr Term Expr'
Expr' +Term Expr' | – Term Expr' |
Term Factor Term'
Term' *Factor Term' | / Factor Term' |
(Goal Expr and Factor number | id
Example
Goal Expr Term Factor * Term
Expr Term + Expr | Factor / Term
| Term – Expr | Factor
| Term Factor number
| id
We have a problem with the different rules for Expr as well as those for Term. In both
cases, the first symbol of the right-hand side is the same (Term and Factor, respectively).
E.g.:
FIRST(Term)=FIRST(Term)FIRST(Term)={number, id}.
FIRST(Factor)=FIRST(Factor)FIRST(Factor)={number, id}.
Applying left factoring:
Expr Term Expr´ FIRST(+)={+}; FIRST(–)={–}; FIRST()={};
Expr´ + Expr | – Expr | FIRST(–) FIRST(+) FIRST()= =
Term Factor Term´ FIRST(*)={*}; FIRST(/)={/}; FIRST()={};
Term´ * Term | / Term | FIRST(*) FIRST(/) FIRST()= =
14
Compiler