SlideShare a Scribd company logo
1 of 24
Download to read offline
Derivation and Ambiguity
1
Course Name: Compiler Design
Course Code: CSE331
Level:3, Term:3
Department of Computer Science and Engineering
Daffodil International University
Derivation
A derivation is basically a sequence of production rules, in order to get the
input string. During parsing, we take two decisions for some sentential form
of input:
• Deciding the non-terminal which is to be replaced.
• Deciding the production rule, by which, the non-terminal will be replaced.
• To decide which non-terminal to be replaced with production rule, we can
have two options.
2
Derivation Types
• Left-most Derivation
If the sentential form of an input is scanned and replaced from left to
right, it is called left-most derivation. The sentential form derived by the left-
most derivation is called the left-sentential form.
• Right-most Derivation
If we scan and replace the input with production rules, from right to
left, it is known as right-most derivation. The sentential form derived from the
right-most derivation is called the right-sentential form.
3
4
• Production rules:
E → E + E
E → E * E
E → id
The left-most derivation is:
E → E * E
E → E + E * E
E → id + E * E
E → id + id * E
E → id + id * id
The right-most derivation is:
E → E + E
E → E + E * E
E → E + E * id
E → E + id * id
E → id + id * id
Input string: id + id * id
Example
Parse Tree
• A parse tree is a graphical depiction of a derivation.
• It is convenient to see how strings are derived from the start symbol.
• The start symbol of the derivation becomes the root of the parse tree.
5
Constructing the Parse Tree
6
• Step 1:
E → E * E
Step 2:
E → E + E * E
• Step 3:
E → id + E * E
Constructing the Parse Tree …
Step 4:
E → id + id * E
7
• In a parse tree:
-All leaf nodes are terminals.
-All interior nodes are non-terminals.
-In-order traversal gives original input string
Step 5:
E → id + id * id
Constructing the Parse Tree …
8
Ambiguity
• A grammar G is said to be ambiguous if it has more than one parse tree (left or right
derivation) for at least one string.
Example: E → E + E
E → E – E
E → id
For the string id + id – id, the above grammar generates two parse trees:
9
• Parsing that we have seen so far.
Top-Down Parsing
10
• Parsing is the process of determining if a string of tokens can be generated by a
grammar.
• For any context-free grammar there is a parser that takes at most Ο(n3) time to
parse a string of n tokens.
• Top-down parsers build parse trees from the top (root) to the bottom (leaves).
• Two top-down parsing are to be discussed:
o Recursive Descent Parsing
o Predictive Parsing An efficient non-backtracking parsing called for LL(1)
grammars.
Top-Down Parsing
11
Consider the grammar
S → cAd
A → ab | a
Input string w = cad
To construct a parse tree for this string using top-down approach,
initially create a tree consisting of a single node labeled S.
Example of Top-Down Parsing
12
Example of Top-Down Parsing
S → cAd
A → ab | a
Input string w = cad
13
Procedure of Top-down Parsing
• An input pointer points to c, the first symbol of w.
• Then use the first production for S to expand the tree and obtain the tree.
• The leftmost leaf, labeled c, matches the first symbol of w.
• Next input pointer to a, the second symbol of w.
• Consider the next leaf, labeled A.
• Expand A using the first alternative for A to obtain the tree.
14
• Now have a match for the second input symbol. Then advance to the next
input pointer d, the third input symbol and compare d against the next leaf,
labeled b. Since b does not match d, report failure and go back to A to see
whether there is another alternative. (Backtracking takes place).
• If there is another alternative for A, substitute and compare the input symbol
with leaf.
• Repeat the step for all the alternatives of A to find a match using backtracking.
If match found, then the string is accepted by the grammar. Else report failure.
• A left-recursive grammar can cause a recursive-descent parser, even one with
backtracking, to go into an infinite loop.
• As discussed above, an easy way to implement a recursive descent parsing with
backtracking is to create a procedure for each non-terminals.
Procedure of Top-down Parsing
15
Transition Diagram for Predictive Parsers
16
Example: Build the parse tree for the arithmetic expression 4 + 2 * 3 using the expression grammar:
E → E + T | E - T | T
T → T * F | F
F → a | ( E )
where a represents an operand of some type, be it a number or variable. The trees are grouped by height.
17
E → E + T | E - T | T
T → T * F | F
F → a | ( E )
18
Grammer:
E → E+E | a
E ⇒ E+Ě
⇒ Ě+E+E
⇒ a+Ě+E
⇒ a+a+Ě
⇒ a+a+a
19
Derivation:
Example: Build the parse tree for the arithmetic expression “a+a+a” using the
expression grammar:
E → E+E | a
20
Consider again, the grammar specifying only addition in expression:
E → E+E | a
E ⇒ Ě+E
⇒ Ě+E+E
⇒ a+Ě+E
⇒ a+a+Ě
⇒ a+a+a
E ⇒ E+Ě
⇒ E+E+Ě
⇒ E+Ě+a
⇒ Ě+a+a
⇒ a+a+a
AMBIGUOUS
21
Left Most Derivation(LMD):
Right Most Derivation(LMD):
The grammar is: S ⇾ S S | (S) | ε
Consider the string "()()"
S ⇒ Š S
⇒ ( S ̌) S
⇒ ( ) Š
⇒ ( ) ( S ̌)
⇒ ( ) ( )
S ⇒ S Š
⇒ S ̌( S )
⇒ ( S ) ( Š )
⇒ ( Š ) ( )
⇒ ( ) ( )
NOT AMBIGUOUS
22
UNAMBIGUOUS
The grammar is: S ⇾ S S | (S) | ε
Consider the string "(())()"
S ⇒ ŠS
⇒ (Š)S
⇒ ((Š))S
⇒ (())Š
⇒ (())(Š)
⇒ (())()
S ⇒ ŠS
⇒ SŠS
⇒ S(Š)S
⇒ S((Š))S
⇒ S(())Š
⇒ S(())(Š)
⇒ Š(())()
⇒ (())()
AMBIGUOUS
23
24
THANK YOU

More Related Content

What's hot (20)

Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Run time storage
Run time storageRun time storage
Run time storage
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
 
Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler design
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time Environments
 
Parsing
ParsingParsing
Parsing
 
Principle source of optimazation
Principle source of optimazationPrinciple source of optimazation
Principle source of optimazation
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
 
COMPILER DESIGN
COMPILER DESIGNCOMPILER DESIGN
COMPILER DESIGN
 
Bootstrapping in Compiler
Bootstrapping in CompilerBootstrapping in Compiler
Bootstrapping in Compiler
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Types of Parser
Types of ParserTypes of Parser
Types of Parser
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 
Parsing
ParsingParsing
Parsing
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
Code generation
Code generationCode generation
Code generation
 

Similar to Derivation and Ambiguity in Compiler Design

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 parsering and bottom up parsering.pptx
Top down parsering and bottom up parsering.pptxTop down parsering and bottom up parsering.pptx
Top down parsering and bottom up parsering.pptxLaibaFaisal3
 
Chapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materialsChapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materialsgadisaAdamu
 
Theory of automata and formal language lab manual
Theory of automata and formal language lab manualTheory of automata and formal language lab manual
Theory of automata and formal language lab manualNitesh Dubey
 
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
 
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
 
Ll(1) Parser in Compilers
Ll(1) Parser in CompilersLl(1) Parser in Compilers
Ll(1) Parser in CompilersMahbubur Rahman
 
Chapter3pptx__2021_12_23_22_52_54.pptx
Chapter3pptx__2021_12_23_22_52_54.pptxChapter3pptx__2021_12_23_22_52_54.pptx
Chapter3pptx__2021_12_23_22_52_54.pptxDrIsikoIsaac
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTanzeela_Hussain
 
LEC 7-DS ALGO(expression and huffman).pdf
LEC 7-DS  ALGO(expression and huffman).pdfLEC 7-DS  ALGO(expression and huffman).pdf
LEC 7-DS ALGO(expression and huffman).pdfMuhammadUmerIhtisham
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler DesignShine Raj
 
Ch3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptxCh3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptxTameneTamire
 
Syntax Analysis.pptx
Syntax Analysis.pptxSyntax Analysis.pptx
Syntax Analysis.pptxAshaS74
 

Similar to Derivation and Ambiguity in Compiler Design (20)

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-...
 
3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx
 
Top down parsering and bottom up parsering.pptx
Top down parsering and bottom up parsering.pptxTop down parsering and bottom up parsering.pptx
Top down parsering and bottom up parsering.pptx
 
Chapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materialsChapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materials
 
Ch2 (1).ppt
Ch2 (1).pptCh2 (1).ppt
Ch2 (1).ppt
 
Theory of automata and formal language lab manual
Theory of automata and formal language lab manualTheory of automata and formal language lab manual
Theory of automata and formal language lab manual
 
Ch06
Ch06Ch06
Ch06
 
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
 
Lexical 2
Lexical 2Lexical 2
Lexical 2
 
LECTURE-1 (1).pptx
LECTURE-1 (1).pptxLECTURE-1 (1).pptx
LECTURE-1 (1).pptx
 
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...
 
Ll(1) Parser in Compilers
Ll(1) Parser in CompilersLl(1) Parser in Compilers
Ll(1) Parser in Compilers
 
Chapter3pptx__2021_12_23_22_52_54.pptx
Chapter3pptx__2021_12_23_22_52_54.pptxChapter3pptx__2021_12_23_22_52_54.pptx
Chapter3pptx__2021_12_23_22_52_54.pptx
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
 
Assignment10
Assignment10Assignment10
Assignment10
 
LEC 7-DS ALGO(expression and huffman).pdf
LEC 7-DS  ALGO(expression and huffman).pdfLEC 7-DS  ALGO(expression and huffman).pdf
LEC 7-DS ALGO(expression and huffman).pdf
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
 
Ch3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptxCh3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptx
 
Syntax Analysis.pptx
Syntax Analysis.pptxSyntax Analysis.pptx
Syntax Analysis.pptx
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
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
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
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
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.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
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
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
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
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
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Derivation and Ambiguity in Compiler Design

  • 1. Derivation and Ambiguity 1 Course Name: Compiler Design Course Code: CSE331 Level:3, Term:3 Department of Computer Science and Engineering Daffodil International University
  • 2. Derivation A derivation is basically a sequence of production rules, in order to get the input string. During parsing, we take two decisions for some sentential form of input: • Deciding the non-terminal which is to be replaced. • Deciding the production rule, by which, the non-terminal will be replaced. • To decide which non-terminal to be replaced with production rule, we can have two options. 2
  • 3. Derivation Types • Left-most Derivation If the sentential form of an input is scanned and replaced from left to right, it is called left-most derivation. The sentential form derived by the left- most derivation is called the left-sentential form. • Right-most Derivation If we scan and replace the input with production rules, from right to left, it is known as right-most derivation. The sentential form derived from the right-most derivation is called the right-sentential form. 3
  • 4. 4 • Production rules: E → E + E E → E * E E → id The left-most derivation is: E → E * E E → E + E * E E → id + E * E E → id + id * E E → id + id * id The right-most derivation is: E → E + E E → E + E * E E → E + E * id E → E + id * id E → id + id * id Input string: id + id * id Example
  • 5. Parse Tree • A parse tree is a graphical depiction of a derivation. • It is convenient to see how strings are derived from the start symbol. • The start symbol of the derivation becomes the root of the parse tree. 5
  • 6. Constructing the Parse Tree 6 • Step 1: E → E * E Step 2: E → E + E * E
  • 7. • Step 3: E → id + E * E Constructing the Parse Tree … Step 4: E → id + id * E 7
  • 8. • In a parse tree: -All leaf nodes are terminals. -All interior nodes are non-terminals. -In-order traversal gives original input string Step 5: E → id + id * id Constructing the Parse Tree … 8
  • 9. Ambiguity • A grammar G is said to be ambiguous if it has more than one parse tree (left or right derivation) for at least one string. Example: E → E + E E → E – E E → id For the string id + id – id, the above grammar generates two parse trees: 9
  • 10. • Parsing that we have seen so far. Top-Down Parsing 10
  • 11. • Parsing is the process of determining if a string of tokens can be generated by a grammar. • For any context-free grammar there is a parser that takes at most Ο(n3) time to parse a string of n tokens. • Top-down parsers build parse trees from the top (root) to the bottom (leaves). • Two top-down parsing are to be discussed: o Recursive Descent Parsing o Predictive Parsing An efficient non-backtracking parsing called for LL(1) grammars. Top-Down Parsing 11
  • 12. Consider the grammar S → cAd A → ab | a Input string w = cad To construct a parse tree for this string using top-down approach, initially create a tree consisting of a single node labeled S. Example of Top-Down Parsing 12
  • 13. Example of Top-Down Parsing S → cAd A → ab | a Input string w = cad 13
  • 14. Procedure of Top-down Parsing • An input pointer points to c, the first symbol of w. • Then use the first production for S to expand the tree and obtain the tree. • The leftmost leaf, labeled c, matches the first symbol of w. • Next input pointer to a, the second symbol of w. • Consider the next leaf, labeled A. • Expand A using the first alternative for A to obtain the tree. 14
  • 15. • Now have a match for the second input symbol. Then advance to the next input pointer d, the third input symbol and compare d against the next leaf, labeled b. Since b does not match d, report failure and go back to A to see whether there is another alternative. (Backtracking takes place). • If there is another alternative for A, substitute and compare the input symbol with leaf. • Repeat the step for all the alternatives of A to find a match using backtracking. If match found, then the string is accepted by the grammar. Else report failure. • A left-recursive grammar can cause a recursive-descent parser, even one with backtracking, to go into an infinite loop. • As discussed above, an easy way to implement a recursive descent parsing with backtracking is to create a procedure for each non-terminals. Procedure of Top-down Parsing 15
  • 16. Transition Diagram for Predictive Parsers 16
  • 17. Example: Build the parse tree for the arithmetic expression 4 + 2 * 3 using the expression grammar: E → E + T | E - T | T T → T * F | F F → a | ( E ) where a represents an operand of some type, be it a number or variable. The trees are grouped by height. 17
  • 18. E → E + T | E - T | T T → T * F | F F → a | ( E ) 18
  • 19. Grammer: E → E+E | a E ⇒ E+Ě ⇒ Ě+E+E ⇒ a+Ě+E ⇒ a+a+Ě ⇒ a+a+a 19 Derivation:
  • 20. Example: Build the parse tree for the arithmetic expression “a+a+a” using the expression grammar: E → E+E | a 20
  • 21. Consider again, the grammar specifying only addition in expression: E → E+E | a E ⇒ Ě+E ⇒ Ě+E+E ⇒ a+Ě+E ⇒ a+a+Ě ⇒ a+a+a E ⇒ E+Ě ⇒ E+E+Ě ⇒ E+Ě+a ⇒ Ě+a+a ⇒ a+a+a AMBIGUOUS 21 Left Most Derivation(LMD): Right Most Derivation(LMD):
  • 22. The grammar is: S ⇾ S S | (S) | ε Consider the string "()()" S ⇒ Š S ⇒ ( S ̌) S ⇒ ( ) Š ⇒ ( ) ( S ̌) ⇒ ( ) ( ) S ⇒ S Š ⇒ S ̌( S ) ⇒ ( S ) ( Š ) ⇒ ( Š ) ( ) ⇒ ( ) ( ) NOT AMBIGUOUS 22 UNAMBIGUOUS
  • 23. The grammar is: S ⇾ S S | (S) | ε Consider the string "(())()" S ⇒ ŠS ⇒ (Š)S ⇒ ((Š))S ⇒ (())Š ⇒ (())(Š) ⇒ (())() S ⇒ ŠS ⇒ SŠS ⇒ S(Š)S ⇒ S((Š))S ⇒ S(())Š ⇒ S(())(Š) ⇒ Š(())() ⇒ (())() AMBIGUOUS 23