Top Down Parsing - Part I Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University.

Slides:



Advertisements
Similar presentations
Parsing V: Bottom-up Parsing
Advertisements

Parsing II : Top-down Parsing
1 Parsing The scanner recognizes words The parser recognizes syntactic units Parser operations: Check and verify syntax based on specified syntax rules.
By Neng-Fa Zhou Syntax Analysis lexical analyzer syntax analyzer semantic analyzer source program tokens parse tree parser tree.
Parsing III (Eliminating left recursion, recursive descent parsing)
ISBN Chapter 4 Lexical and Syntax Analysis The Parsing Problem Recursive-Descent Parsing.
1 Predictive parsing Recall the main idea of top-down parsing: Start at the root, grow towards leaves Pick a production and try to match input May need.
Parsing V Introduction to LR(1) Parsers. from Cooper & Torczon2 LR(1) Parsers LR(1) parsers are table-driven, shift-reduce parsers that use a limited.
Parsing — Part II (Ambiguity, Top-down parsing, Left-recursion Removal)
1 The Parser Its job: –Check and verify syntax based on specified syntax rules –Report errors –Build IR Good news –the process can be automated.
Table-driven parsing Parsing performed by a finite state machine. Parsing algorithm is language-independent. FSM driven by table (s) generated automatically.
1 CIS 461 Compiler Design & Construction Fall 2012 slides derived from Tevfik Bultan, Keith Cooper, and Linda Torczon Lecture-Module #12 Parsing 4.
Parsing II : Top-down Parsing Lecture 7 CS 4318/5331 Apan Qasem Texas State University Spring 2015 *some slides adopted from Cooper and Torczon.
MIT Top-Down Parsing Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology.
Compiler Construction Parsing Part I
CSC3315 (Spring 2009)1 CSC 3315 Lexical and Syntax Analysis Hamid Harroud School of Science and Engineering, Akhawayn University
Parsing IV Bottom-up Parsing Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University.
LR(1) Parsers Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit.
Syntax and Semantics Structure of programming languages.
Parsing Chapter 4 Parsing2 Outline Top-down v.s. Bottom-up Top-down parsing Recursive-descent parsing LL(1) parsing LL(1) parsing algorithm First.
Review: –How do we define a grammar (what are the components in a grammar)? –What is a context free grammar? –What is the language defined by a grammar?
BİL 744 Derleyici Gerçekleştirimi (Compiler Design)1 Syntax Analyzer Syntax Analyzer creates the syntactic structure of the given source program. This.
Introduction to Parsing Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University.
Introduction to Parsing Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University.
Introduction to Parsing Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University.
Parsing III (Top-down parsing: recursive descent & LL(1) )
-Mandakinee Singh (11CS10026).  What is parsing? ◦ Discovering the derivation of a string: If one exists. ◦ Harder than generating strings.  Two major.
Profs. Necula CS 164 Lecture Top-Down Parsing ICOM 4036 Lecture 5.
Lesson 3 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
Syntax and Semantics Structure of programming languages.
Left Recursion Lecture 7 Fri, Feb 4, 2005.
Parsing III (Top-down parsing: recursive descent & LL(1) ) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students.
Comp 311 Principles of Programming Languages Lecture 3 Parsing Corky Cartwright August 28, 2009.
Bottom-up Parsing, Part I Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University.
Parsing — Part II (Top-down parsing, left-recursion removal) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students.
Top-down Parsing lecture slides from C OMP 412 Rice University Houston, Texas, Fall 2001.
Parsing — Part II (Top-down parsing, left-recursion removal) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students.
Top-down Parsing Recursive Descent & LL(1) Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412.
Top-Down Parsing CS 671 January 29, CS 671 – Spring Where Are We? Source code: if (b==0) a = “Hi”; Token Stream: if (b == 0) a = “Hi”; Abstract.
1 CIS 461 Compiler Design and Construction Fall 2012 slides derived from Tevfik Bultan, Keith Cooper, and Linda Torczon Lecture-Module #8 Parsing Techniques.
1 Context free grammars  Terminals  Nonterminals  Start symbol  productions E --> E + T E --> E – T E --> T T --> T * F T --> T / F T --> F F --> (F)
Top-down Parsing. 2 Parsing Techniques Top-down parsers (LL(1), recursive descent) Start at the root of the parse tree and grow toward leaves Pick a production.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Top-Down Parsing.
CS 330 Programming Languages 09 / 25 / 2007 Instructor: Michael Eckmann.
COMP 3438 – Part II-Lecture 5 Syntax Analysis II Dr. Zili Shao Department of Computing The Hong Kong Polytechnic Univ.
1 CMPSC 160 Translation of Programming Languages Fall 2002 slides derived from Tevfik Bultan, Keith Cooper, and Linda Torczon Lecture-Module #6 Parsing.
Parsing III (Top-down parsing: recursive descent & LL(1) )
Parsing V LR(1) Parsers. LR(1) Parsers LR(1) parsers are table-driven, shift-reduce parsers that use a limited right context (1 token) for handle recognition.
Spring 16 CSCI 4430, A Milanova 1 Announcements HW1 due on Monday February 8 th Name and date your submission Submit electronically in Homework Server.
WELCOME TO A JOURNEY TO CS419 Dr. Hussien Sharaf Dr. Mohammad Nassef Department of Computer Science, Faculty of Computers and Information, Cairo University.
Comp 411 Principles of Programming Languages Lecture 3 Parsing
Compiler Construction Parsing Part I
Parsing — Part II (Top-down parsing, left-recursion removal)
Parsing III (Top-down parsing: recursive descent & LL(1) )
Programming Languages Translator
Parsing IV Bottom-up Parsing
Table-driven parsing Parsing performed by a finite state machine.
Parsing — Part II (Top-down parsing, left-recursion removal)
4 (c) parsing.
Parsing Techniques.
Top-Down Parsing CS 671 January 29, 2008.
Lecture 8 Bottom Up Parsing
Lecture 7: Introduction to Parsing (Syntax Analysis)
Lecture 8: Top-Down Parsing
Parsing IV Bottom-up Parsing
Introduction to Parsing
Introduction to Parsing
Parsing — Part II (Top-down parsing, left-recursion removal)
Compiler Construction
Presentation transcript:

Top Down Parsing - Part I Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit permission to make copies of these materials for their personal use. Faculty from other educational institutions may use these materials for nonprofit educational purposes, provided this copyright notice is preserved. COMP 412 FALL 2010

Comp 412, Fall Parsing Techniques Top-down parsers (LL(1), recursive descent) Start at the root of the parse tree and grow toward leaves Pick a production & try to match the input Bad “pick”  may need to backtrack Some grammars are backtrack-free (predictive parsing) Bottom-up parsers (LR(1), operator precedence) Start at the leaves and grow toward root As input is consumed, encode possibilities in an internal state Start in a state valid for legal first tokens Bottom-up parsers handle a large class of grammars

Comp 412, Fall A top-down parser starts with the root of the parse tree The root node is labeled with the goal symbol of the grammar Top-down parsing algorithm: Construct the root node of the parse tree Repeat until lower fringe of the parse tree matches the input string 1At a node labeled A, select a production with A on its lhs and, for each symbol on its rhs, construct the appropriate child 2When a terminal symbol is added to the fringe and it doesn’t match the fringe, backtrack 3Find the next node to be expanded (label  NT) The key is picking the right production in step 1 —That choice should be guided by the input string Top-down Parsing

Comp 412, Fall Remember the expression grammar? And the input x – 2 * y We will call this version “the classic expression grammar” —from last lecture 0Goal  Expr 1  Expr + Term 2|Expr - Term 3|Term 4  Term * Factor 5|Term / Factor 6|Factor 7  ( Expr ) 8|number 9|id

Let’s try x – 2 * y : Comp 412, Fall RuleSentential FormInput —Goal  x - 2 * y Example Goal  is the position in the input buffer

Let’s try x – 2 * y : Comp 412, Fall RuleSentential FormInput —Goal  x - 2 * y 0Expr  x - 2 * y 1Expr +Term  x - 2 * y 3Term +Term  x - 2 * y 6Factor +Term  x - 2 * y 9 +Term  x - 2 * y  +Termx  - 2 * y Example Goal Expr Term + Expr Term Fact. This worked well, except that “–” doesn’t match “+” The parser must backtrack to here  is the position in the input buffer

Comp 412, Fall Example Continuing with x – 2 * y : Goal Expr Term – Expr Term Fact.  Now, we need to expand Term - the last NT on the fringe RuleSentential FormInput —Goal  x - 2 * y 0Expr  x - 2 * y 2Expr -Term  x - 2 * y 3Term -Term  x - 2 * y 6Factor -Term  x - 2 * y 9 - Term  x - 2 * y  -Term x  - 2 * y  -Termx -  2 * y Now, “-” and “-” match Now we can expand Term to match “2”

Comp 412, Fall Where are we? “2” matches “2” We have more input, but no NT s left to expand The expansion terminated too soon  Need to backtrack Example Trying to match the “2” in x – 2 * y : Goal Expr Term - Expr Term Fact. Fact. RuleSentential FormInput  - Term x -  2 * y 6 - Factor x -  2 * y 8 - x -  2 * y  - x - 2  * y

Comp 412, Fall Example Trying again with “2” in x – 2 * y : Goal Expr Term – Expr Term Fact. Fact. Term Fact. * This time, we matched & consumed all the input  Success! RuleSentential FormInput  - Term x -  2 * y 4 - Term * Factor x -  2 * y 6 - Factor * Factor x -  2 * y 8 - * Factor x -  2 * y  - * Factor x - 2  * y  - * Factor x - 2 *  y 9 - * x - 2 *  y  - * x - 2 * y  The Point: The parser must make the right choice when it expands a NT. Wrong choices lead to wasted effort.

Comp 412, Fall Other choices for expansion are possible This expansion doesn’t terminate Wrong choice of expansion leads to non-termination Non-termination is a bad property for a parser to have Parser must make the right choice Another possible parse RuleSentential FormInput —Goal  x - 2 * y 0Expr  x - 2 * y 1Expr +Term  x - 2 * y 1Expr + Term +Term  x - 2 * y 1Expr + Term +Term + Term  x - 2 * y 1And so on ….  x - 2 * y Consumes no input!

Comp 412, Fall Left Recursion Top-down parsers cannot handle left-recursive grammars Formally, A grammar is left recursive if  A  NT such that  a derivation A  + A , for some string   (NT  T ) + Our classic expression grammar is left recursive This can lead to non-termination in a top-down parser In a top-down parser, any recursion must be right recursion We would like to convert the left recursion to right recursion Non-termination is always a bad property in a compiler

Comp 412, Fall Eliminating Left Recursion To remove left recursion, we can transform the grammar Consider a grammar fragment of the form Fee  Fee  |  where neither  nor  start with Fee We can rewrite this fragment as Fee   Fie Fie   Fie |  where Fie is a new non-terminal The new grammar defines the same language as the old grammar, using only right recursion. Added a reference to the empty string

Comp 412, Fall Eliminating Left Recursion Expr  Expr + Term |Expr - Term |Term  Term * Factor | |Factor Expr  Term Expr’ Expr’  + Term Expr’ |- Term Expr’ |  Term  Factor Term’ Term’  * Factor Term’ |/ Factor Term’ |  The expression grammar contains two cases of left recursion Applying the transformation yields These fragments use only right recursion Right recursion often means right associativity. In this case, the grammar does not display any particular associative bias.

Comp 412, Fall Eliminating Left Recursion Substituting them back into the grammar yields This grammar is correct, if somewhat non-intuitive. It is left associative, as was the original ⇒ The naïve transformation yields a right recursive grammar, which changes the implicit associativity A top-down parser will terminate using it. A top-down parser may need to backtrack with it. 0Goal  Expr 1  Term Expr’ 2Expr’  + Term Expr’ 3|- Term Expr’ 4|  5Term  Factor Term’ 6Term’  * Factor Term’ 7|/ Factor Term’ 8|  9Factor  ( Expr ) 10|number 11|id

Comp 412, Fall Eliminating Left Recursion The transformation eliminates immediate left recursion What about more general, indirect left recursion ? The general algorithm: arrange the NTs into some order A 1, A 2, …, A n for i  1 to n for s  1 to i – 1 replace each production A i  A s  with A i   1  2  k , where A s   1  2  k are all the current productions for A s eliminate any immediate left recursion on A i using the direct transformation This assumes that the initial grammar has no cycles (A i  + A i ), and no epsilon productions And back Must start with 1 to ensure that A 1  A 1  is transformed

Comp 412, Fall Eliminating Left Recursion How does this algorithm work? 1. Impose arbitrary order on the non-terminals 2. Outer loop cycles through NT in order 3. Inner loop ensures that a production expanding A i has no non-terminal A s in its rhs, for s < i 4. Last step in outer loop converts any direct recursion on A i to right recursion using the transformation showed earlier 5. New non-terminals are added at the end of the order & have no left recursion At the start of the i th outer loop iteration For all k < i, no production that expands A k contains a non-terminal A s in its rhs, for s < k

Order of symbols: G, E, T Comp 412, Fall Example 1. A i = G G  E E  E + T E  T T  E * T T  id 2. A i = E G  E E  T E' E'  + T E' E'   T  E * T T  id 3. A i = T, A s = E G  E E  T E' E'  + T E' E'   T  T E' * T T  id Go to Algorithm 4. A i = T G  E E  T E' E'  + T E' E'   T  id T' T'  E ' * T T' T'  

Comp 412, Fall Picking the “Right” Production If it picks the wrong production, a top-down parser may backtrack Alternative is to look ahead in input & use context to pick correctly How much lookahead is needed? In general, an arbitrarily large amount Use the Cocke-Younger, Kasami algorithm or Earley’s algorithm Fortunately, Large subclasses of CFGs can be parsed with limited lookahead Most programming language constructs fall in those subclasses Among the interesting subclasses are LL(1) and LR(1) grammars We will focus, for now, on LL(1) grammars & predictive parsing

Comp 412, Fall Predictive Parsing Basic idea Given A    , the parser should be able to choose between  &  F IRST sets For some rhs   G, define F IRST (  ) as the set of tokens that appear as the first symbol in some string that derives from  That is, x  F IRST (  ) iff   * x , for some  We will defer the problem of how to compute F IRST sets for the moment.

Comp 412, Fall Predictive Parsing Basic idea Given A    , the parser should be able to choose between  &  F IRST sets For some rhs   G, define F IRST (  ) as the set of tokens that appear as the first symbol in some string that derives from  That is, x  F IRST (  ) iff   * x , for some  The LL(1) Property If A   and A   both appear in the grammar, we would like F IRST (  )  F IRST (  ) =  This would allow the parser to make a correct choice with a lookahead of exactly one symbol ! This is almost correct See the next slide

Comp 412, Fall Predictive Parsing What about  -productions?  They complicate the definition of LL(1) If A   and A   and   F IRST (  ), then we need to ensure that F IRST (  ) is disjoint from F OLLOW (A), too, where F OLLOW (A) = the set of terminal symbols that can immediately follow A in a sentential form Define F IRST + (A  ) as F IRST (  )  F OLLOW (A), if   F IRST (  ) F IRST (  ), otherwise Then, a grammar is LL(1) iff A   and A   implies F IRST + (A  )  F IRST + (A  ) = 

Comp 412, Fall Predictive Parsing Given a grammar that has the LL(1) property Can write a simple routine to recognize each lhs Code is both simple & fast Consider A   1 |  2 |  3, with FIRST + (A  i )  FIRST + (A  j ) =  if i ≠ j /* find an A */ if (current_word  F IRST (A  1 )) find a  1 and return true else if (current_word  F IRST (A  2 )) find a  2 and return true else if (current_word  F IRST (A  3 )) find a  3 and return true else report an error and return false Of course, there is more detail to “find a  i ” ( p. 103 in EAC, 1 st Ed. ) Grammars with the LL(1) property are called predictive grammars because the parser can “predict” the correct expansion at each point in the parse. Parsers that capitalize on the LL(1) property are called predictive parsers. One kind of predictive parser is the recursive descent parser.

Comp 412, Fall Recursive Descent Parsing Recall the expression grammar, after transformation This produces a parser with six mutually recursive routines: Goal Expr EPrime Term TPrime Factor Each recognizes one NT or T The term descent refers to the direction in which the parse tree is built. 0Goal  Expr 1  Term Expr’ 2Expr’  + Term Expr’ 3|- Term Expr’ 4|  5Term  Factor Term’ 6Term’  * Factor Term’ 7|/ Factor Term’ 8|  9Factor  ( Expr ) 10|number 11|id

Comp 412, Fall Recursive Descent Parsing (Procedural) A couple of routines from the expression parser Goal( ) token  next_token( ); if (Expr( ) = true & token = EOF) then next compilation step; else report syntax error; return false; Expr( ) if (Term( ) = false) then return false; else return Eprime( ); Factor( ) if (token = Number) then token  next_token( ); return true; else if (token = Identifier) then token  next_token( ); return true; else if (token = Lparen) token  next_token( ); if (Expr( ) = true & token = Rparen) then token  next_token( ); return true; // fall out of if statement report syntax error; return false; looking for Number, Identifier, or “(“, found token instead, or failed to find Expr or “)” after “(” EPrime, Term, & TPrime follow the same basic lines (Figure 3.7, EAC)

Comp 412, Fall Extra Slides Start Here

Comp 412, Fall RuleSentential Form —Goal 0Expr 1Expr +Term 3Expr + 1Expr +Term + 3Expr + + 2Term Left Recursion Creates Left Associative Trees A Trivial Expression Grammar 0Goal  Expr 1  Expr + Term 2|Term 3  id Goal Expr Term + Expr Term Term + Expr Derivation of id + id +id Evaluates as (id + id) + id