SlideShare a Scribd company logo
1 of 15
Ambiguous vs Unambiguous Grammar :
The grammars which have more than one derivation tree or parse tree are
ambiguous grammars. These grammar is not parsed by any parsers.
Example-
1. Consider the production shown below –
S->aSbS | bSaS | ∈
Say, we want to generate the string “abab” from the above grammar. We can
observe that the given string can be derived using two parse trees. So, the above
grammar is ambiguous.
The grammars which have only one derivation tree or parse tree are called
unambiguous grammars.
2. Consider the productions shown below –
S -> AB
A -> Aa | a
B -> b
For the string “aab” we have only one Parse Tree for the above grammar as shown
below.
It is important to note that there are no direct algorithms to find whether grammar
is ambiguous or not. We need to build the parse tree for a given input string that
belongs to the language produced by the grammar and then decide whether the
grammar is ambiguous or unambiguous based on the number of parse trees
obtained as discussed above.
Note – The string has to be chosen carefully because there may be some strings
available in the language produced by the unambiguous grammar which has only
one parse tree.
Converting Ambiguous Grammar Into Unambiguous
Grammar
 Causes such as left recursion, common prefixes etc makes the grammar
ambiguous.
 The removal of these causes may convert the grammar into unambiguous
grammar.
 However, it is not always compulsory.
NOTE: It is not always possible to convert an ambiguous grammar into an unambiguous grammar.
Removing Ambiguity By Precedence & Associativity
Rules-
An ambiguous grammar may be converted into an unambiguous grammar by
implementing-
 Precedence Constraints
 Associativity Constraints
These constraints are implemented using the following rules-
Rule-01:
The precedence constraint is implemented using the following rules-
 The level at which the production is present defines the priority of the operator
contained in it.
 The higher the level of the production, the lower the priority of operator.
 The lower the level of the production, the higher the priority of operator.
Rule-02:
The associativity constraint is implemented using the following rules
 If the operator is left associative, induce left recursion in its production.
 If the operator is right associative, induce right recursion in its production.
We can remove ambiguity solely on the basis of the following two properties
1. Precedence –
If different operators are used, we will consider the precedence of the operators.
The three important characteristics are :
1. The level at which the production is present denotes the priority of the
operator used.
2. The production at higher levels will have operators with less priority. In
the parse tree, the nodes which are at top levels or close to the root node
will contain the lower priority operators.
3. The production at lower levels will have operators with higher priority. In
the parse tree, the nodes which are at lower levels or close to the leaf
nodes will contain the higher priority operators.
2. Associativity –
If the same precedence operators are in production, then we will have to consider
the associativity.
 If the associativity is left to right, then we have to prompt a left recursion
in the production. The parse tree will also be left recursive and grow on
the left side.
+, -, *, / are left associative operators.
 If the associativity is right to left, then we have to prompt the right
recursion in the productions. The parse tree will also be right recursive
and grow on the right side.
^ is a right associative operator.
Operator Precedence in C
Operator precedence determines which operation is performed first in an
expression with more than one operator with different precedence.
Example of Operator Precedence
Let’s try to evaluate the following expression,
10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the
given table, the * has higher precedence than + so, the first evaluation will be
10 + (20 * 30)
After evaluating the higher precedence operator, the expression is
10 + 600
Now, the + operator will be evaluated.
610
Operator Associativity
Operators Associativity is used when two operators of the same precedence appear in
an expression. Associativity can be either from Left to Right or Right to Left.
Example of Operator Associativity
Let’s evaluate the following expression,
100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so the order of
evaluation will be decided by associativity.
According to the given table, the associativity of the multiplicative operators is from Left
to Right. So,
(100 / 5) % 2
After evaluation, the expression will be
20 % 2
Now, the % operator will be evaluated.
0
PROBLEMS BASED ON CONVERSION INTO
UNAMBIGUOUS GRAMMAR-
Problem-01:
Convert the following ambiguous grammar into unambiguous grammar-
R → R + R / R . R / R* / a / b
where * is kleen closure and . is concatenation.
Solution-
To convert the given grammar into its corresponding unambiguous grammar, we
implement the precedence and associativity constraints.
We have-
 Given grammar consists of the following operators-
+ , . , *
 Given grammar consists of the following operands-
a , b
The priority order is-
(a , b) > * > . > +
where-
 . operator is left associative
 + operator is left associative
Using the precedence and associativity rules, we write the corresponding unambiguous
grammar as-
E → E + T / T
T → T . F / F
F → F* / G
G → a / b
Unambiguous Grammar
OR
E → E + T / T
T → T . F / F
F → F* / a / b
Unambiguous Grammar
Problem-02:
Convert the following ambiguous grammar into unambiguous grammar-
bexp → bexp or bexp / bexp and bexp / not bexp / T / F
where bexp represents Boolean expression, T represents True and F represents False.
Solution-
To convert the given grammar into its corresponding unambiguous grammar, we
implement the precedence and associativity constraints.
We have-
 Given grammar consists of the following operators-
or , and , not
 Given grammar consists of the following operands-
T , F
The priority order is-
(T , F) > not > and > or
where-
 and operator is left associative
 or operator is left associative
Using the precedence and associativity rules, we write the corresponding unambiguous
grammar as-
bexp → bexp or M / M
M → M and N / N
N → not N / G
G → T / F
Unambiguous Grammar
OR
bexp → bexp or M / M
M → M and N / N
N → not N / T / F
Unambiguous Grammar
Removal of Ambiguity :
Example 1 – Consider the ambiguous grammar
E -> E-E | id
The language in the grammar will contain { id, id-id, id-id-id, ….}
Say, we want to derive the string id-id-id. Let’s consider a single value of id=3 to get
more insights. The result should be :
3-3-3 =-3
Since the same priority operators, we need to consider associativity which is left to
right.
Parse Tree – The parse tree which grows on the left side of the root will be the
correct parse tree in order to make the grammar unambiguous.
So, to make the above grammar unambiguous, simply make the grammar Left
Recursive by replacing the left most non-terminal E in the right side of the
production with another random variable, say P. The grammar becomes :
E -> E – P | P
P -> id
The above grammar is now unambiguous and will contain only one Parse Tree for
the above expression as shown below –
–
Similarly, the unambiguous grammar for the expression : 2^3^2 will be –
E -> P ^ E | P // Right Recursive as ^ is right associative.
P -> id
Example 2 – Consider the grammar shown below, which has two different
operators :
E -> E + E | E * E | id
Clearly, the above grammar is ambiguous as we can draw two parse trees for the
string “id+id*id” as shown below. Consider the expression :
3 + 2 * 5 // “*” has more priority than “+”
The correct answer is : (3+(2*5))=13
The “+” having the least priority has to be at the upper level and has to wait for the
result produced by the “*” operator which is at the lower level. So, the first parse
tree is the correct one and gives the same result as expected.
The unambiguous grammar will contain the productions having the highest priority
operator (“*” in the example) at the lower level and vice versa. The associativity of
both the operators are Left to Right. So, the unambiguous grammar has to be left
recursive. The grammar will be :
E -> E + P // + is at higher level and left associative
E -> P
P -> P * Q // * is at lower level and left associative
P -> Q
Q -> id
(or)
E -> E + P | P
P -> P * Q | Q
Q -> id
E is used for doing addition operations and P is used to perform multiplication
operations. They are independent and will maintain the precedence order in the
parse tree.
The parse tree for the string ” id+id*id+id ” will be –
Note : It is very important to note that while converting an ambiguous grammar to
an unambiguous grammar, we shouldn’t change the original language provided by
the ambiguous grammar. So, the non-terminals in the ambiguous grammar have to
be replaced with other variables in such a way that we get the same language as it
was derived before and also maintain the precedence and associativity rule
simultaneously.
This is the reason we wrote the production E -> P and P -> Q and Q -> id after
replacing them in the above example, because the language contains the strings {
id, id+id } as well.
Similarly, the unambiguous grammar for an expression having the operators -,*,^ is
:
E -> E – P | P // Minus operator is at higher level due to least priority and
left associative.
P -> P * Q | Q // Multiplication operator has more priority than – and lesser
than ^ and left associative.
Q -> R ^ Q | R // Exponent operator is at lower level due to highest priority
and right associative.
R -> id
Also, there are some ambiguous grammars which can’t be converted into
unambiguous grammars.
Eliminating the ambiguity in CFG grammar:
Ambiguity from all grammar cannot be eliminated. No direct and official algorithm can
determine whether the given grammar is ambiguous. We need to check by building
all the possible parse trees. We can use Precedence and Associativity to remove the
ambiguity from some grammar.
Let us take an example:
Grammar:
1. X -> X - X
2. X -> var/const
Here var can be any variable, and const can be any constant value. A string a - b - c
has two leftmost derivations:
1. X -> X - X
2. X - X - X
3. var - var - var
4. a - b - c
1. X -> X - X
2. var - X - X
3. a - var - var
4. a - b - c
For example, if we take the values a = 2, b = 3 and c = 4:
a - b - c = 2 - 3 - 4 = -5
In the first derivation tree, according to the order of substitution, the expression will
be evaluated as:
(a - b) - c = (2 - 3) - 4 = -1 -4 = -5
In the second derivation tree: a - (b - c) = 2 - (3 - 4) = 2 - -1 = 3
Observe that both parse trees aren't giving the same value. They have different
meanings. In the above example, the first derivation tree is the correct parse tree for
grammar.
(a - b) - c. Here there are two same operators in the expression. According to
mathematical rules, the expression must be evaluated based on the associativity of the
operator used. In the above example, the operator is -, which gives left-to-right
associativity. Hence, the first derivation tree is the correct parse tree.
So, for the left to right-associative operators, the parse tree has to be left associative-
The Non-terminals on the left sub-tree must be derived first and then the right sub-
tree.
Note: For the right-to-left associative operators like ^, the grammar has to be made
right-associative because, for these expressions, the order of evaluation must be
from right to left.
Now, let us convert the grammar into unambiguous grammar:
1. X -> X - X
2. X -> var/const
We need to make the grammar left-recursive. We need to place a random non-
terminal in place of the right Non-terminal:
1. X -> X - P/P
2. P -> var/ const
Now, for the string a - b - c:
1. X -> X - P
2. X - X - P
3. P - P - var
4. var - var - var
Now, what if the grammar is:
1. E -> E + E
2. E -> E * E
3. E -> id
This grammar will give two leftmost derivation trees for the string, id + id * id*.
We can't use associativity here as there are two different operators, + and *. Hence, we
need to use "Precedence".
In the string:
1. id + id * id:
The order of evaluation must be: id + (id * id) as * has more precedence than +. The
operator with the highest priority must be evaluated first. Hence, the operators with
high priority are to be arranged in the lower levels of the parse tree.
If id = 2:
If + id * id = 2 + 2 * 2 = 6
For the first derivation tree:
id + (id * id) = 2 + (2 * 2) = 2 + 4 = 6
For the second derivation tree:
(id + id) * id = (2 + 2) * 2 = 4*2 = 8
Hence, the first derivation tree is the correct parse tree.
Converting into unambiguous grammar:
We should write the grammar so that all the highest priority operators stay in lower
levels. Every production should follow a recursion based on the associativity of the
operator used.
o +, -, *, / are left associative operators. Hence, the productions using these operators
must follow left recursion
o ^ and = are right-associative operators. Hence, the productions using these operators
must follow the right recursion.
Given grammar:
1. E -> E + E
2. E -> E * E
3. E -> id
Precedence: * has the highest priority than +. Hence, it should be at a lower level. So,
we need to start with +
Associativity: + and * both are left associative
1. E -> E + P/P
2. P -> P*Q/Q
3. Q -> id
Parse tree:
Now, finally, let us take another example:
1. E -> E + E/E * E/ E^E/id
First, determine whether the given grammar is ambiguous.
Given a string id + id * id ^ id
E -> E + E
id + E * E
id + id * E
id + id * E^E
id + id * id ^ id
E -> E * E
E + E * E
id + E * E
id + id * E ^ E
id + id * id ^ id
More than one left most derivation trees.
Operators: +, * and ^
Precedence: ^ > * > +
Associativity:
+, * -> left to right
^ -> right to left
o We need to arrange the grammar so that the production with ^ and * are in the lower
levels of the parse tree, and every production must follow the associativity of its
operator.
Grammar:
E -> E + P/P
P -> P * Q/Q
Q -> R ^ Q/R (Right associative)
R -> id
Parse Tree:
Evaluation:
If id = 2: id + id * id ^ id = 2 + 2 * 22
= 2 + 2 * 4 = 16.

More Related Content

What's hot

Operator Precedence Grammar
Operator Precedence GrammarOperator Precedence Grammar
Operator Precedence GrammarHarisonFekadu
 
Chapter 5 -Syntax Directed Translation - Copy.ppt
Chapter 5 -Syntax Directed Translation - Copy.pptChapter 5 -Syntax Directed Translation - Copy.ppt
Chapter 5 -Syntax Directed Translation - Copy.pptFamiDan
 
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...movocode
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up ParsingGerwin Ocsena
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In JavaMD SALEEM QAISAR
 
CONTEXT FREE GRAMMAR
CONTEXT FREE GRAMMAR CONTEXT FREE GRAMMAR
CONTEXT FREE GRAMMAR Zahid Parvez
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & DeletionAfaq Mansoor Khan
 
Applications of stack
Applications of stackApplications of stack
Applications of stackeShikshak
 
Regular expression to NFA (Nondeterministic Finite Automata)
Regular expression to NFA (Nondeterministic Finite Automata)Regular expression to NFA (Nondeterministic Finite Automata)
Regular expression to NFA (Nondeterministic Finite Automata)Niloy Biswas
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Iffat Anjum
 
Expression evaluation
Expression evaluationExpression evaluation
Expression evaluationJeeSa Sultana
 

What's hot (20)

Circular queues
Circular queuesCircular queues
Circular queues
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Module 11
Module 11Module 11
Module 11
 
Operator Precedence Grammar
Operator Precedence GrammarOperator Precedence Grammar
Operator Precedence Grammar
 
Chapter 5 -Syntax Directed Translation - Copy.ppt
Chapter 5 -Syntax Directed Translation - Copy.pptChapter 5 -Syntax Directed Translation - Copy.ppt
Chapter 5 -Syntax Directed Translation - Copy.ppt
 
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
 
LL(1) parsing
LL(1) parsingLL(1) parsing
LL(1) parsing
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 
CONTEXT FREE GRAMMAR
CONTEXT FREE GRAMMAR CONTEXT FREE GRAMMAR
CONTEXT FREE GRAMMAR
 
Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Context free grammar
Context free grammar Context free grammar
Context free grammar
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Regular expression to NFA (Nondeterministic Finite Automata)
Regular expression to NFA (Nondeterministic Finite Automata)Regular expression to NFA (Nondeterministic Finite Automata)
Regular expression to NFA (Nondeterministic Finite Automata)
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2
 
Expression evaluation
Expression evaluationExpression evaluation
Expression evaluation
 

Similar to 9-Removal of ambiguity, precedence and associativity-26-05-2023.docx

Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsingsanchi29
 
11 EXPRESSIONS.pptx
11 EXPRESSIONS.pptx11 EXPRESSIONS.pptx
11 EXPRESSIONS.pptxRodmanCajes
 
Introduction to Python Values, Variables Data Types Chapter 2
Introduction to Python  Values, Variables Data Types Chapter 2Introduction to Python  Values, Variables Data Types Chapter 2
Introduction to Python Values, Variables Data Types Chapter 2Raza Ul Mustafa
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxabhi353063
 
Chapter 3.3
Chapter 3.3Chapter 3.3
Chapter 3.3sotlsoc
 
E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2Mukund Trivedi
 
E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)Mukund Trivedi
 
E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)Mukund Trivedi
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack LavanyaJ28
 
Operator precedence and associativity
Operator precedence and associativityOperator precedence and associativity
Operator precedence and associativityDr.Sandhiya Ravi
 
Operator precedence and associativity
Operator precedence and associativityOperator precedence and associativity
Operator precedence and associativityDr.Sandhiya Ravi
 
C operators
C operatorsC operators
C operatorsGPERI
 
Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.LamiyQurbanlKomptert
 

Similar to 9-Removal of ambiguity, precedence and associativity-26-05-2023.docx (20)

Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
 
C# operators
C# operatorsC# operators
C# operators
 
11 EXPRESSIONS.pptx
11 EXPRESSIONS.pptx11 EXPRESSIONS.pptx
11 EXPRESSIONS.pptx
 
Introduction to Python Values, Variables Data Types Chapter 2
Introduction to Python  Values, Variables Data Types Chapter 2Introduction to Python  Values, Variables Data Types Chapter 2
Introduction to Python Values, Variables Data Types Chapter 2
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
c programming2.pptx
c programming2.pptxc programming2.pptx
c programming2.pptx
 
operator
operatoroperator
operator
 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
 
Chapter 3.3
Chapter 3.3Chapter 3.3
Chapter 3.3
 
E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2E212d9a797dbms chapter3 b.sc2
E212d9a797dbms chapter3 b.sc2
 
E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)E212d9a797dbms chapter3 b.sc2 (2)
E212d9a797dbms chapter3 b.sc2 (2)
 
E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)E212d9a797dbms chapter3 b.sc2 (1)
E212d9a797dbms chapter3 b.sc2 (1)
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack
 
Operator precedence and associativity
Operator precedence and associativityOperator precedence and associativity
Operator precedence and associativity
 
Operator precedence and associativity
Operator precedence and associativityOperator precedence and associativity
Operator precedence and associativity
 
C operators
C operatorsC operators
C operators
 
Mycasestudy
MycasestudyMycasestudy
Mycasestudy
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.
 

More from venkatapranaykumarGa

5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptxvenkatapranaykumarGa
 
10-SLR parser practice problems-02-06-2023.pptx
10-SLR parser practice problems-02-06-2023.pptx10-SLR parser practice problems-02-06-2023.pptx
10-SLR parser practice problems-02-06-2023.pptxvenkatapranaykumarGa
 
13-Applications of Syntax Directed Translation - Syntax Directed Translation ...
13-Applications of Syntax Directed Translation - Syntax Directed Translation ...13-Applications of Syntax Directed Translation - Syntax Directed Translation ...
13-Applications of Syntax Directed Translation - Syntax Directed Translation ...venkatapranaykumarGa
 
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.pptvenkatapranaykumarGa
 
15-CAT-2 answer key discussion-04-07-2023.pdf
15-CAT-2 answer key discussion-04-07-2023.pdf15-CAT-2 answer key discussion-04-07-2023.pdf
15-CAT-2 answer key discussion-04-07-2023.pdfvenkatapranaykumarGa
 
11-SLR input string parsing, CLR introduction-06-06-2023.docx
11-SLR input string parsing, CLR introduction-06-06-2023.docx11-SLR input string parsing, CLR introduction-06-06-2023.docx
11-SLR input string parsing, CLR introduction-06-06-2023.docxvenkatapranaykumarGa
 
8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docxvenkatapranaykumarGa
 
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...venkatapranaykumarGa
 
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...venkatapranaykumarGa
 
6-Practice Problems - LL(1) parser-16-05-2023.pptx
6-Practice Problems - LL(1) parser-16-05-2023.pptx6-Practice Problems - LL(1) parser-16-05-2023.pptx
6-Practice Problems - LL(1) parser-16-05-2023.pptxvenkatapranaykumarGa
 
1-Phases of compiler-26-04-2023.pptx
1-Phases of compiler-26-04-2023.pptx1-Phases of compiler-26-04-2023.pptx
1-Phases of compiler-26-04-2023.pptxvenkatapranaykumarGa
 
7-Operator Precedence Parser-23-05-2023.pptx
7-Operator Precedence Parser-23-05-2023.pptx7-Operator Precedence Parser-23-05-2023.pptx
7-Operator Precedence Parser-23-05-2023.pptxvenkatapranaykumarGa
 
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docxvenkatapranaykumarGa
 

More from venkatapranaykumarGa (14)

9-Query Processing-05-06-2023.PPT
9-Query Processing-05-06-2023.PPT9-Query Processing-05-06-2023.PPT
9-Query Processing-05-06-2023.PPT
 
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
 
10-SLR parser practice problems-02-06-2023.pptx
10-SLR parser practice problems-02-06-2023.pptx10-SLR parser practice problems-02-06-2023.pptx
10-SLR parser practice problems-02-06-2023.pptx
 
13-Applications of Syntax Directed Translation - Syntax Directed Translation ...
13-Applications of Syntax Directed Translation - Syntax Directed Translation ...13-Applications of Syntax Directed Translation - Syntax Directed Translation ...
13-Applications of Syntax Directed Translation - Syntax Directed Translation ...
 
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
 
15-CAT-2 answer key discussion-04-07-2023.pdf
15-CAT-2 answer key discussion-04-07-2023.pdf15-CAT-2 answer key discussion-04-07-2023.pdf
15-CAT-2 answer key discussion-04-07-2023.pdf
 
11-SLR input string parsing, CLR introduction-06-06-2023.docx
11-SLR input string parsing, CLR introduction-06-06-2023.docx11-SLR input string parsing, CLR introduction-06-06-2023.docx
11-SLR input string parsing, CLR introduction-06-06-2023.docx
 
8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx
 
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
14-Intermediate code generation - Variants of Syntax trees - Three Address Co...
 
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
4-Regular expression to Deterministic Finite Automata (Direct method)-05-05-2...
 
6-Practice Problems - LL(1) parser-16-05-2023.pptx
6-Practice Problems - LL(1) parser-16-05-2023.pptx6-Practice Problems - LL(1) parser-16-05-2023.pptx
6-Practice Problems - LL(1) parser-16-05-2023.pptx
 
1-Phases of compiler-26-04-2023.pptx
1-Phases of compiler-26-04-2023.pptx1-Phases of compiler-26-04-2023.pptx
1-Phases of compiler-26-04-2023.pptx
 
7-Operator Precedence Parser-23-05-2023.pptx
7-Operator Precedence Parser-23-05-2023.pptx7-Operator Precedence Parser-23-05-2023.pptx
7-Operator Precedence Parser-23-05-2023.pptx
 
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
 

Recently uploaded

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

9-Removal of ambiguity, precedence and associativity-26-05-2023.docx

  • 1. Ambiguous vs Unambiguous Grammar : The grammars which have more than one derivation tree or parse tree are ambiguous grammars. These grammar is not parsed by any parsers. Example- 1. Consider the production shown below – S->aSbS | bSaS | ∈ Say, we want to generate the string “abab” from the above grammar. We can observe that the given string can be derived using two parse trees. So, the above grammar is ambiguous. The grammars which have only one derivation tree or parse tree are called unambiguous grammars. 2. Consider the productions shown below – S -> AB A -> Aa | a B -> b For the string “aab” we have only one Parse Tree for the above grammar as shown below. It is important to note that there are no direct algorithms to find whether grammar is ambiguous or not. We need to build the parse tree for a given input string that belongs to the language produced by the grammar and then decide whether the
  • 2. grammar is ambiguous or unambiguous based on the number of parse trees obtained as discussed above. Note – The string has to be chosen carefully because there may be some strings available in the language produced by the unambiguous grammar which has only one parse tree. Converting Ambiguous Grammar Into Unambiguous Grammar  Causes such as left recursion, common prefixes etc makes the grammar ambiguous.  The removal of these causes may convert the grammar into unambiguous grammar.  However, it is not always compulsory. NOTE: It is not always possible to convert an ambiguous grammar into an unambiguous grammar. Removing Ambiguity By Precedence & Associativity Rules- An ambiguous grammar may be converted into an unambiguous grammar by implementing-  Precedence Constraints  Associativity Constraints These constraints are implemented using the following rules- Rule-01: The precedence constraint is implemented using the following rules-  The level at which the production is present defines the priority of the operator contained in it.  The higher the level of the production, the lower the priority of operator.  The lower the level of the production, the higher the priority of operator. Rule-02:
  • 3. The associativity constraint is implemented using the following rules  If the operator is left associative, induce left recursion in its production.  If the operator is right associative, induce right recursion in its production. We can remove ambiguity solely on the basis of the following two properties 1. Precedence – If different operators are used, we will consider the precedence of the operators. The three important characteristics are : 1. The level at which the production is present denotes the priority of the operator used. 2. The production at higher levels will have operators with less priority. In the parse tree, the nodes which are at top levels or close to the root node will contain the lower priority operators. 3. The production at lower levels will have operators with higher priority. In the parse tree, the nodes which are at lower levels or close to the leaf nodes will contain the higher priority operators. 2. Associativity – If the same precedence operators are in production, then we will have to consider the associativity.  If the associativity is left to right, then we have to prompt a left recursion in the production. The parse tree will also be left recursive and grow on the left side. +, -, *, / are left associative operators.  If the associativity is right to left, then we have to prompt the right recursion in the productions. The parse tree will also be right recursive and grow on the right side. ^ is a right associative operator. Operator Precedence in C Operator precedence determines which operation is performed first in an expression with more than one operator with different precedence. Example of Operator Precedence Let’s try to evaluate the following expression, 10 + 20 * 30 The expression contains two operators, + (plus), and * (multiply). According to the given table, the * has higher precedence than + so, the first evaluation will be 10 + (20 * 30) After evaluating the higher precedence operator, the expression is 10 + 600 Now, the + operator will be evaluated. 610
  • 4. Operator Associativity Operators Associativity is used when two operators of the same precedence appear in an expression. Associativity can be either from Left to Right or Right to Left. Example of Operator Associativity Let’s evaluate the following expression, 100 / 5 % 2 Both / (division) and % (Modulus) operators have the same precedence, so the order of evaluation will be decided by associativity. According to the given table, the associativity of the multiplicative operators is from Left to Right. So, (100 / 5) % 2 After evaluation, the expression will be 20 % 2 Now, the % operator will be evaluated. 0 PROBLEMS BASED ON CONVERSION INTO UNAMBIGUOUS GRAMMAR- Problem-01: Convert the following ambiguous grammar into unambiguous grammar- R → R + R / R . R / R* / a / b where * is kleen closure and . is concatenation.
  • 5. Solution- To convert the given grammar into its corresponding unambiguous grammar, we implement the precedence and associativity constraints. We have-  Given grammar consists of the following operators- + , . , *  Given grammar consists of the following operands- a , b The priority order is- (a , b) > * > . > + where-  . operator is left associative  + operator is left associative Using the precedence and associativity rules, we write the corresponding unambiguous grammar as- E → E + T / T T → T . F / F F → F* / G G → a / b Unambiguous Grammar OR E → E + T / T T → T . F / F F → F* / a / b Unambiguous Grammar Problem-02: Convert the following ambiguous grammar into unambiguous grammar-
  • 6. bexp → bexp or bexp / bexp and bexp / not bexp / T / F where bexp represents Boolean expression, T represents True and F represents False. Solution- To convert the given grammar into its corresponding unambiguous grammar, we implement the precedence and associativity constraints. We have-  Given grammar consists of the following operators- or , and , not  Given grammar consists of the following operands- T , F The priority order is- (T , F) > not > and > or where-  and operator is left associative  or operator is left associative Using the precedence and associativity rules, we write the corresponding unambiguous grammar as- bexp → bexp or M / M M → M and N / N N → not N / G G → T / F Unambiguous Grammar OR bexp → bexp or M / M M → M and N / N N → not N / T / F Unambiguous Grammar
  • 7. Removal of Ambiguity : Example 1 – Consider the ambiguous grammar E -> E-E | id The language in the grammar will contain { id, id-id, id-id-id, ….} Say, we want to derive the string id-id-id. Let’s consider a single value of id=3 to get more insights. The result should be : 3-3-3 =-3 Since the same priority operators, we need to consider associativity which is left to right. Parse Tree – The parse tree which grows on the left side of the root will be the correct parse tree in order to make the grammar unambiguous. So, to make the above grammar unambiguous, simply make the grammar Left Recursive by replacing the left most non-terminal E in the right side of the production with another random variable, say P. The grammar becomes : E -> E – P | P P -> id The above grammar is now unambiguous and will contain only one Parse Tree for the above expression as shown below – –
  • 8. Similarly, the unambiguous grammar for the expression : 2^3^2 will be – E -> P ^ E | P // Right Recursive as ^ is right associative. P -> id Example 2 – Consider the grammar shown below, which has two different operators : E -> E + E | E * E | id Clearly, the above grammar is ambiguous as we can draw two parse trees for the string “id+id*id” as shown below. Consider the expression : 3 + 2 * 5 // “*” has more priority than “+” The correct answer is : (3+(2*5))=13 The “+” having the least priority has to be at the upper level and has to wait for the result produced by the “*” operator which is at the lower level. So, the first parse tree is the correct one and gives the same result as expected.
  • 9. The unambiguous grammar will contain the productions having the highest priority operator (“*” in the example) at the lower level and vice versa. The associativity of both the operators are Left to Right. So, the unambiguous grammar has to be left recursive. The grammar will be : E -> E + P // + is at higher level and left associative E -> P P -> P * Q // * is at lower level and left associative P -> Q Q -> id (or) E -> E + P | P P -> P * Q | Q Q -> id E is used for doing addition operations and P is used to perform multiplication operations. They are independent and will maintain the precedence order in the parse tree. The parse tree for the string ” id+id*id+id ” will be – Note : It is very important to note that while converting an ambiguous grammar to an unambiguous grammar, we shouldn’t change the original language provided by the ambiguous grammar. So, the non-terminals in the ambiguous grammar have to be replaced with other variables in such a way that we get the same language as it was derived before and also maintain the precedence and associativity rule simultaneously.
  • 10. This is the reason we wrote the production E -> P and P -> Q and Q -> id after replacing them in the above example, because the language contains the strings { id, id+id } as well. Similarly, the unambiguous grammar for an expression having the operators -,*,^ is : E -> E – P | P // Minus operator is at higher level due to least priority and left associative. P -> P * Q | Q // Multiplication operator has more priority than – and lesser than ^ and left associative. Q -> R ^ Q | R // Exponent operator is at lower level due to highest priority and right associative. R -> id Also, there are some ambiguous grammars which can’t be converted into unambiguous grammars. Eliminating the ambiguity in CFG grammar: Ambiguity from all grammar cannot be eliminated. No direct and official algorithm can determine whether the given grammar is ambiguous. We need to check by building all the possible parse trees. We can use Precedence and Associativity to remove the ambiguity from some grammar. Let us take an example: Grammar: 1. X -> X - X 2. X -> var/const Here var can be any variable, and const can be any constant value. A string a - b - c has two leftmost derivations: 1. X -> X - X 2. X - X - X 3. var - var - var 4. a - b - c
  • 11. 1. X -> X - X 2. var - X - X 3. a - var - var 4. a - b - c For example, if we take the values a = 2, b = 3 and c = 4: a - b - c = 2 - 3 - 4 = -5 In the first derivation tree, according to the order of substitution, the expression will be evaluated as: (a - b) - c = (2 - 3) - 4 = -1 -4 = -5 In the second derivation tree: a - (b - c) = 2 - (3 - 4) = 2 - -1 = 3 Observe that both parse trees aren't giving the same value. They have different meanings. In the above example, the first derivation tree is the correct parse tree for grammar.
  • 12. (a - b) - c. Here there are two same operators in the expression. According to mathematical rules, the expression must be evaluated based on the associativity of the operator used. In the above example, the operator is -, which gives left-to-right associativity. Hence, the first derivation tree is the correct parse tree. So, for the left to right-associative operators, the parse tree has to be left associative- The Non-terminals on the left sub-tree must be derived first and then the right sub- tree. Note: For the right-to-left associative operators like ^, the grammar has to be made right-associative because, for these expressions, the order of evaluation must be from right to left. Now, let us convert the grammar into unambiguous grammar: 1. X -> X - X 2. X -> var/const We need to make the grammar left-recursive. We need to place a random non- terminal in place of the right Non-terminal: 1. X -> X - P/P 2. P -> var/ const Now, for the string a - b - c: 1. X -> X - P 2. X - X - P 3. P - P - var 4. var - var - var Now, what if the grammar is:
  • 13. 1. E -> E + E 2. E -> E * E 3. E -> id This grammar will give two leftmost derivation trees for the string, id + id * id*. We can't use associativity here as there are two different operators, + and *. Hence, we need to use "Precedence". In the string: 1. id + id * id: The order of evaluation must be: id + (id * id) as * has more precedence than +. The operator with the highest priority must be evaluated first. Hence, the operators with high priority are to be arranged in the lower levels of the parse tree. If id = 2: If + id * id = 2 + 2 * 2 = 6 For the first derivation tree: id + (id * id) = 2 + (2 * 2) = 2 + 4 = 6 For the second derivation tree:
  • 14. (id + id) * id = (2 + 2) * 2 = 4*2 = 8 Hence, the first derivation tree is the correct parse tree. Converting into unambiguous grammar: We should write the grammar so that all the highest priority operators stay in lower levels. Every production should follow a recursion based on the associativity of the operator used. o +, -, *, / are left associative operators. Hence, the productions using these operators must follow left recursion o ^ and = are right-associative operators. Hence, the productions using these operators must follow the right recursion. Given grammar: 1. E -> E + E 2. E -> E * E 3. E -> id Precedence: * has the highest priority than +. Hence, it should be at a lower level. So, we need to start with + Associativity: + and * both are left associative 1. E -> E + P/P 2. P -> P*Q/Q 3. Q -> id Parse tree: Now, finally, let us take another example: 1. E -> E + E/E * E/ E^E/id First, determine whether the given grammar is ambiguous. Given a string id + id * id ^ id E -> E + E id + E * E id + id * E
  • 15. id + id * E^E id + id * id ^ id E -> E * E E + E * E id + E * E id + id * E ^ E id + id * id ^ id More than one left most derivation trees. Operators: +, * and ^ Precedence: ^ > * > + Associativity: +, * -> left to right ^ -> right to left o We need to arrange the grammar so that the production with ^ and * are in the lower levels of the parse tree, and every production must follow the associativity of its operator. Grammar: E -> E + P/P P -> P * Q/Q Q -> R ^ Q/R (Right associative) R -> id Parse Tree: Evaluation: If id = 2: id + id * id ^ id = 2 + 2 * 22 = 2 + 2 * 4 = 16.