Top-down Parsing lecture slides from C OMP 412 Rice University Houston, Texas, Fall 2001.

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.
Chap. 5, Top-Down Parsing J. H. Wang Mar. 29, 2011.
Top-Down Parsing.
By Neng-Fa Zhou Syntax Analysis lexical analyzer syntax analyzer semantic analyzer source program tokens parse tree parser tree.
Context-Free Grammars Lecture 7
3. Parsing Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
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)
Prof. Fateman CS 164 Lecture 91 Bottom-Up Parsing Lecture 9.
CS 330 Programming Languages 09 / 23 / 2008 Instructor: Michael Eckmann.
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.
(2.1) Grammars  Definitions  Grammars  Backus-Naur Form  Derivation – terminology – trees  Grammars and ambiguity  Simple example  Grammar hierarchies.
Compiler Construction Parsing Part I
CSC3315 (Spring 2009)1 CSC 3315 Lexical and Syntax Analysis Hamid Harroud School of Science and Engineering, Akhawayn University
1 Introduction to Parsing Lecture 5. 2 Outline Regular languages revisited Parser overview Context-free grammars (CFG’s) Derivations.
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.
Syntax and Semantics Structure of programming languages.
BİL 744 Derleyici Gerçekleştirimi (Compiler Design)1 Syntax Analyzer Syntax Analyzer creates the syntactic structure of the given source program. This.
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.
Syntax and Semantics Structure of programming languages.
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.
Parsing III (Top-down parsing: recursive descent & LL(1) ) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students.
COP4020 Programming Languages Parsing Prof. Xin Yuan.
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.
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.
CSE 5317/4305 L3: Parsing #11 Parsing #1 Leonidas Fegaras.
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.
CMSC 330: Organization of Programming Languages Pushdown Automata Parsing.
WELCOME TO A JOURNEY TO CS419 Dr. Hussien Sharaf Dr. Mohammad Nassef Department of Computer Science, Faculty of Computers and Information, Cairo University.
Compiler Construction Parsing Part I
Parsing #1 Leonidas Fegaras.
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
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
Parsing — Part II (Top-down parsing, left-recursion removal)
Compiler Construction
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Presentation transcript:

Top-down Parsing lecture slides from C OMP 412 Rice University Houston, Texas, Fall 2001

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 the fringe of the parse tree matches the input string  At a node labeled A, select a production with A on its lhs and, for each symbol on its rhs, construct the appropriate child  When a terminal symbol is added to the fringe and it doesn’t match the fringe, backtrack  Find 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 Version with precedence derived last lecture

COMP 412, FALL Let’s try x – 2 * y : Example Goal Expr Term + Expr Term Fact.

COMP 412, FALL Let’s try x – 2 * y : This worked well, except that “–” doesn’t match “+” The parser must backtrack to here Example Goal Expr Term + Expr Term Fact.

COMP 412, FALL Example Continuing with x – 2 * y : Goal Expr Term – Expr Term Fact.

COMP 412, FALL Example Continuing with x – 2 * y : Goal Expr Term – Expr Term Fact. We can advance past “–” to look at “2” This time, “–” and “–” matched  Now, we need to expand Term - the last NT on the fringe

COMP 412, FALL Example Trying to match the “2” in x – 2 * y : Goal Expr Term – Expr Term Fact. Fact.

COMP 412, FALL Example Trying to match the “2” in x – 2 * y : 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 Goal Expr Term - Expr Term Fact. Fact.

COMP 412, FALL Example Trying again with “2” in x – 2 * y : This time, we matched & consumed all the input  Success! Goal Expr Term – Expr Term Fact. Fact. Term Fact. *

COMP 412, FALL Other choices for expansion are possible This doesn’t terminate (obviously) 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 consuming 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 expression grammar is left recursive This can lead to non-termination in a top-down parser For a top-down parser, any recursion must be right recursion We would like to convert the left recursion to right recursion Non-termination is a bad property in any part of 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 as Fee   Fie Fie   Fie |  where Fie is a new non-terminal This accepts the same language, but uses only right recursion

COMP 412, FALL Eliminating Left Recursion The expression grammar contains two cases of left recursion Applying the transformation yields These fragments use only right recursion They retains the original left associativity

COMP 412, FALL Eliminating Left Recursion Substituting back into the grammar yields This grammar is correct, if somewhat non-intuitive. It is left associative, as was the original A top-down parser will terminate using it. A top-down parser may need to backtrack with it.

COMP 412, FALL Top-down recursive descent parsing lecture slides from C OMP 412 Rice University Houston, Texas, Fall 2001

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

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 ! (Pursuing this idea leads to LL(1) parser generators...)

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 F IRST (  1 )  F IRST (  2 )  F IRST (  3 ) =  /* find an A */ if (current_word  F IRST (  1 )) find a  1 and return true else if (current_word  F IRST (  2 )) find a  2 and return true else if (current_word  F IRST (  3 )) find a  3 and return true else report an error and return false Of course, there is more detail to “find a  i ” ( § in EAC ) 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 Left Factoring What if my grammar does not have the LL(1) property?  Sometimes, we can transform the grammar The Algorithm  A  NT, find the longest prefix  that occurs in two or more right-hand sides of A if  ≠  then replace all of the A productions, A   1 |  2 | … |  n | , with A   Z |  Z   1 |  2 | … |  n where Z is a new element of NT Repeat until no common prefixes remain

COMP 412, FALL Left Factoring (An example) Consider the following fragment of the expression grammar After left factoring, it becomes This form has the same syntax, with the LL(1) property F IRST (rhs 1 ) = { Identifier } F IRST (rhs 2 ) = { Identifier } F IRS T(rhs 3 ) = { Identifier } F IRST (rhs 1 ) = { Identifier } F IRS T(rhs 2 ) = { [ } F IRST (rhs 3 ) = { ( } F IRST (rhs 4 ) = F OLLOW (Factor)  It has the LL(1) property

COMP 412, FALL A graphical explanation for the same idea becomes … Left Factoring A   1 |  2 |  3 A   Z Z   1 |  2 |  n A  1  3  2 ZZ 11 33 22 A

COMP 412, FALL Question By eliminating left recursion and left factoring, can we transform an arbitrary CFG to a form where it meets the LL(1) condition? (and can be parsed predictively with a single token lookahead?) Answer Given a CFG that doesn’t meet the LL(1) condition, it is undecidable whether or not an equivalent LL(1) grammar exists. Example {a n 0 b n | n  1}  {a n 1 b 2n | n  1} has no LL(1) grammar Left Factoring (Generality)

COMP 412, FALL Language that Cannot Be LL(1) Example {a n 0 b n | n  1}  {a n 1 b 2n | n  1} has no LL(1) grammar G  aAb | aBbb A  aAb | 0 B  aBbb | 1 Problem: need an unbounded number of a characters before you can determine whether you are in the A group or the B group.

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 The term descent refers to the direction in which the parse tree is traversed (or built).

COMP 412, FALL Recursive Descent Parsing (Procedural) A couple of routines from the expression parser Goal( ) token  next_token( ); if (Expr( ) = true) then next compilation step; else return false; Expr( ) result  true; if (Term( ) = false) then result  false; else if (EPrime( ) = false) then result  true; // term found return result; Factor( ) result  true; if (token = Number) then token  next_token( ); else if (token = identifier) then token  next_token( ); else report syntax error; result  false; return result; EPrime, Term, & TPrime follow along the same basic lines (Figure 3.4, EAC)

COMP 412, FALL x-2*y Goal Expr Term Eprime Tprime Fact. Eprime Term  – Tprime Fact.  Eprime Term Tprime Fact.  * 

COMP 412, FALL Recursive Descent Parsing To build a parse tree: Augment parsing routines to build nodes Pass nodes between routines using a stack Node for each symbol on rhs Action is to pop rhs nodes, make them children of lhs node, and push this subtree To build an abstract syntax tree Build fewer nodes Put them together in a different order Expr( ) result  true; if (Term( ) = false) then result  false; else if (EPrime( ) = false) then result  true; else build an Expr node pop EPrime node pop Term node make EPrime & Term children of Expr push Expr node return result; This is a preview of Chapter 4