Parsing III (Eliminating left recursion, recursive descent parsing)

Slides:



Advertisements
Similar presentations
Parsing V: Bottom-up Parsing
Advertisements

Parsing 4 Dr William Harrison Fall 2008
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.
LESSON 18.
Top-Down Parsing.
1 CMPSC 160 Translation of Programming Languages Fall 2002 slides derived from Tevfik Bultan, Keith Cooper, and Linda Torczon Lecture-Module #7 Parsing.
By Neng-Fa Zhou Syntax Analysis lexical analyzer syntax analyzer semantic analyzer source program tokens parse tree parser tree.
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.
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.
1 Chapter 4: Top-Down Parsing. 2 Objectives of Top-Down Parsing an attempt to find a leftmost derivation for an input string. an attempt to construct.
Professor Yihjia Tsai Tamkang University
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
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.
1 Chapter 5 LL (1) Grammars and Parsers. 2 Naming of parsing techniques The way to parse token sequence L: Leftmost R: Righmost Top-down  LL Bottom-up.
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) )
Profs. Necula CS 164 Lecture Top-Down Parsing ICOM 4036 Lecture 5.
1 Syntax In Text: Chapter 3. 2 Chapter 3: Syntax and Semantics Outline Syntax: Recognizer vs. generator BNF EBNF.
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.
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.
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.
Syntax Analyzer (Parser)
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 Topic #4: Syntactic Analysis (Parsing) CSC 338 – Compiler Design and implementation Dr. Mohamed Ben Othman ( )
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) )
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) )
COP 4620 / 5625 Programming Language Translation / Compiler Writing Fall 2003 Lecture 5, 09/25/2003 Prof. Roy Levow.
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.
CS 540 George Mason University
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)
Recursive descent parsing
Compiler Construction
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Recursive descent parsing
Presentation transcript:

Parsing III (Eliminating left recursion, recursive descent parsing)

from Cooper & Torczon2 Roadmap (Where are we?) We set out to study parsing Specifying syntax  Context-free grammars   Ambiguity  Top-down parsers  Algorithm & its problem with left recursion   Left-recursion removal today Predictive top-down parsing  The LL(1) condition today  Simple recursive descent parsers today

from Cooper & Torczon3 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

from Cooper & Torczon4 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

from Cooper & Torczon5 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

from Cooper & Torczon6 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.

from Cooper & Torczon7 Eliminating Left Recursion The transformation eliminates immediate left recursion What about more general, indirect left recursion ? The general algorithm: arrange the NT s into some order A 1, A 2, …, A n for i  1 to n 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

from Cooper & Torczon8 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

from Cooper & Torczon9 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 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

from Cooper & Torczon10 Predictive Parsing Basic idea Given A    , the parser should be able to choose between  &  F IRST sets For some rhs   G, define FI RST (  ) as the set of tokens that appear as the first symbol in some string 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...)

from Cooper & Torczon11 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.

from Cooper & Torczon12 Recursive Descent Parsing Recall the expression grammar, after transformation This produces a parser with six mutually recursive routines: Goal Expr Expr_Prime Term Term_Prime Factor Each recognizes one NT The term descent refers to the direction in which the parse tree is traversed (or built).

from Cooper & Torczon13 Recursive Descent Parsing 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  false; 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)

from Cooper & Torczon14 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  false; 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

from Cooper & Torczon15 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

from Cooper & Torczon16 Left Factoring (An example) Consider the following fragment of grammar for array and function references 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

from Cooper & Torczon17 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

from Cooper & Torczon18 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)