Parsing Part II (Top-down parsing, left-recursion removal)

Similar documents
Syntactic Analysis. Top-Down Parsing

CS 406/534 Compiler Construction Parsing Part I

Syntax Analysis, III Comp 412

Parsing III. (Top-down parsing: recursive descent & LL(1) )

Syntax Analysis, III Comp 412

CSCI312 Principles of Programming Languages

Parsing. Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice.

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones

Types of parsing. CMSC 430 Lecture 4, Page 1

Computer Science 160 Translation of Programming Languages

Parsing II Top-down parsing. Comp 412

Parsing Part II. (Ambiguity, Top-down parsing, Left-recursion Removal)

Introduction to Parsing. Comp 412

Compilers. Yannis Smaragdakis, U. Athens (original slides by Sam

Syntactic Analysis. Top-Down Parsing. Parsing Techniques. Top-Down Parsing. Remember the Expression Grammar? Example. Example

CS1622. Today. A Recursive Descent Parser. Preliminaries. Lecture 9 Parsing (4)

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing

CA Compiler Construction

3. Parsing. Oscar Nierstrasz

Prelude COMP 181 Tufts University Computer Science Last time Grammar issues Key structure meaning Tufts University Computer Science

CS415 Compilers. Syntax Analysis. These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University

COMP 181. Prelude. Next step. Parsing. Study of parsing. Specifying syntax with a grammar

Parsing II Top-down parsing. Comp 412

Top-Down Parsing and Intro to Bottom-Up Parsing. Lecture 7

Syntax Analysis, V Bottom-up Parsing & The Magic of Handles Comp 412

Top down vs. bottom up parsing

Syntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38

Top-Down Parsing and Intro to Bottom-Up Parsing. Lecture 7

CS 314 Principles of Programming Languages

CS 406/534 Compiler Construction Parsing Part II LL(1) and LR(1) Parsing

CS502: Compilers & Programming Systems

Monday, September 13, Parsers

CS2210: Compiler Construction Syntax Analysis Syntax Analysis

Chapter 3. Parsing #1

CMSC 330: Organization of Programming Languages

Context-free grammars

Chapter 4: LR Parsing

8 Parsing. Parsing. Top Down Parsing Methods. Parsing complexity. Top down vs. bottom up parsing. Top down vs. bottom up parsing

Topdown parsing with backtracking

Abstract Syntax Trees & Top-Down Parsing


Parser Generation. Bottom-Up Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottom-up --- from leaves to the root

Parsing #1. Leonidas Fegaras. CSE 5317/4305 L3: Parsing #1 1

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing

Administrativia. WA1 due on Thu PA2 in a week. Building a Parser III. Slides on the web site. CS164 3:30-5:00 TT 10 Evans.

Compiler Construction: Parsing

Compilerconstructie. najaar Rudy van Vliet kamer 140 Snellius, tel rvvliet(at)liacs(dot)nl. college 3, vrijdag 22 september 2017

Ambiguity, Precedence, Associativity & Top-Down Parsing. Lecture 9-10

Compilers. Predictive Parsing. Alex Aiken

Compiler Construction 2016/2017 Syntax Analysis

Concepts Introduced in Chapter 4

The Parsing Problem (cont d) Recursive-Descent Parsing. Recursive-Descent Parsing (cont d) ICOM 4036 Programming Languages. The Complexity of Parsing

Building a Parser III. CS164 3:30-5:00 TT 10 Evans. Prof. Bodik CS 164 Lecture 6 1

4. Lexical and Syntax Analysis

CS Parsing 1

Sometimes an ambiguous grammar can be rewritten to eliminate the ambiguity.

Wednesday, August 31, Parsers

Chapter 4. Lexical and Syntax Analysis

4. Lexical and Syntax Analysis

Lexical Analysis - An Introduction. Lecture 4 Spring 2005 Department of Computer Science University of Alabama Joel Jones

Introduction to Parsing

Wednesday, September 9, 15. Parsers

Parsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs:

EECS 6083 Intro to Parsing Context Free Grammars

1 Introduction. 2 Recursive descent parsing. Predicative parsing. Computer Language Implementation Lecture Note 3 February 4, 2004

4 (c) parsing. Parsing. Top down vs. bo5om up parsing

Syntax Analysis, VII One more LR(1) example, plus some more stuff. Comp 412 COMP 412 FALL Chapter 3 in EaC2e. target code.

Bottom-up parsing. Bottom-Up Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form

Parsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468

CSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis

Bottom-up Parser. Jungsik Choi

CS 230 Programming Languages

Table-driven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and non-terminals.

Syntax Analysis: Context-free Grammars, Pushdown Automata and Parsing Part - 4. Y.N. Srikant

Table-Driven Parsing

Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich Ben-Gurion University of the Negev

Compiler Design 1. Top-Down Parsing. Goutam Biswas. Lect 5

Compila(on (Semester A, 2013/14)

CSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall

Table-Driven Top-Down Parsers

MIT Top-Down Parsing. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology

Ambiguity. Grammar E E + E E * E ( E ) int. The string int * int + int has two parse trees. * int

A programming language requires two major definitions A simple one pass compiler

CS 321 Programming Languages and Compilers. VI. Parsing

Chapter 2 Syntax Analysis

Compilers: CS31003 Computer Sc & Engg: IIT Kharagpur 1. Top-Down Parsing. Lect 5. Goutam Biswas

Building a Parser Part III

CSE 3302 Programming Languages Lecture 2: Syntax

Fall Compiler Principles Lecture 3: Parsing part 2. Roman Manevich Ben-Gurion University

Syntax Analysis. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

CMSC 330: Organization of Programming Languages

Lexical and Syntax Analysis. Top-Down Parsing

Bottom-Up Parsing. Parser Generation. LR Parsing. Constructing LR Parser

Note that for recursive descent to work, if A ::= B1 B2 is a grammar rule we need First k (B1) disjoint from First k (B2).

CS415 Compilers. Lexical Analysis

Syntax Analysis. The Big Picture. The Big Picture. COMP 524: Programming Languages Srinivas Krishnan January 25, 2011

PART 3 - SYNTAX ANALYSIS. F. Wotawa TU Graz) Compiler Construction Summer term / 309

3. Syntax Analysis. Andrea Polini. Formal Languages and Compilers Master in Computer Science University of Camerino

CS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F).

Transcription:

Parsing Part II (Top-down parsing, left-recursion removal) Copyright 2003, Keith D. Cooper, Ken Kennedy & 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.

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 (predictive parsing) Some grammars are backtrack-free 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

Top-down Parsing 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 1 At a node labeled A, select a production with A on its lhs and, for each symbol on its rhs, construct the appropriate child 2 When a terminal symbol is added to the fringe and it doesn t match the input, backtrack 3 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

Remember the expression grammar? Version with precedence derived last lecture And the input x 2 * y

Example Let s try x 2 * y : Goal Expr Expr + Term Term Fact. <id,x> Leftmost derivation, choose productions in an order that exposes problems

Example Let s try x 2 * y : Goal Expr Expr + Term Fact. <id,x> This worked well, except that doesn t match + The parser must backtrack to here Term

Example Continuing with x 2 * y : Goal Expr Expr Term Fact. <id,x> Term

Example Continuing with x 2 * y : Goal Expr Expr Term Term Fact. <id,x> This time, and matched We can advance past to look at 2 Now, we need to expand Term - the last NT on the fringe

Example Trying to match the 2 in x 2 * y : Goal Expr Expr Term Term Fact. Fact. <num,2> <id,x>

Example Trying to match the 2 in x 2 * y : Goal Expr Expr - Term Term Fact. Fact. <num,2> Where are we? <id,x> 2 matches 2 We have more input, but no NTs left to expand The expansion terminated too soon Need to backtrack

Example Trying again with 2 in x 2 * y : Goal Expr Expr Term Term Term * Fact. Fact. <id,x> <num,2> This time, we matched & consumed all the input Success! Fact. <id,y>

Another possible parse Other choices for expansion are possible Rule Sentential Form Input Goal x 2 * y 1 Expr x 2 * y 2 Expr + Term x 2 * y 2 Expr + Term +Term x 2 * y 2 Expr + Term + Term +Term x 2 * y 2 Expr +Term + Term + +Term x 2 * y consuming no input! 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

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

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

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

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 A top-down parser will terminate using it. A top-down parser may need to backtrack with it.

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, A2,, An Must start with 1 to ensure that A1 for i 1 to n A1 β is transformed for s 1 to i 1 replace each production Ai Asγ with Ai δ1γ δ2γ δkγ, where As δ1 δ2 δk are all the current productions for As eliminate any immediate left recursion on A i using the direct transformation This assumes that the initial grammar has no cycles (Ai + Ai ), and no epsilon productions

Lookahead in predictive parsing The Lookahead token (next token in the input) is used to determine which rule should be used next Consider the following example: 7+3-2 term num term' term term' + num term - num term' ε num 0 1 9 num term

Lookahead in predictive parsing The Lookahead token (next token in the input) is used to determine which rule should be used next Consider the following example: 7+3-2 term num term' term term' + num term - num term' ε num 0 1 9 num 7 term + num term

Lookahead in predictive parsing The Lookahead token (next token in the input) is used to determine which rule should be used next Consider the following example: 7+3-2 term num term' term term' + num term - num term' ε num 7 term + num num 0 1 2 3 9 3 term

Lookahead in predictive parsing The Lookahead token (next token in the input) is used to determine which rule should be used next Consider the following example: 7+3-2 term num term' term term' + num term - num term' ε num 7 term + num term num 0 1 9 3 - num term

Lookahead in predictive parsing The Lookahead token (next token in the input) is used to determine which rule should be used next Consider the following example: 7+3-2 term num term' term term' + num term - num term' ε num 7 term + num term num 0 1 2 9 3 - num 2 term

Lookahead in predictive parsing The Lookahead token (next token in the input) is used to determine which rule should be used next Consider the following example: 7+3-2_ term num term' term term' + num term - num term' ε num 7 term + num term num 0 1 2 9 3 - num term 2 ε

Predictive Parsing Basic idea Given A α β, the parser should be able to choose between α & β FIRST sets For some rhs α G, define FIRST(α) as the set of tokens that appear as the first symbol in some string that derives from α That is, x FIRST(α) iff α * x γ, for some γ The LL(1) Property If A α and A β both appear in the grammar, we would like FIRST(α) FIRST(β) = 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

Predictive Parsing What about ε-productions? They complicate the definition of LL(1) If A α and A β and ε FIRST(α), then we need to ensure that FIRST(β) is disjoint from FOLLOW(α), too Define FIRST+(α) as FIRST(α) FOLLOW(α), if ε FIRST(α) FIRST(α), otherwise Then, a grammar is LL(1) iff A α and A β implies FIRST+(α) FIRST+(β) = FOLLOW(α) is the set of all words in the grammar that can legally appear immediately after an α

Determining First Sets If α is a terminal symbol, α T FIRST(α) = {α} If A is a non-terminal symbol, A NT For each production A β, where β is β1 β2 βk FIRST(A) = FIRST(A) = FIRST(A) (FIRST{β1} - ε) i=1 While ε FIRST(βi) and i k-1 FIRST(A) = FIRST(A) (FIRST{βi+1} - ε) If i == k and ε FIRST(βk) FIRST (A) = FIRST(A) ε

First Sets (Example) S AC C c ε A B Q abcd BQ ε bb d q What is FIRST(C)? FIRST(C)= FIRST(c) FIRST(ε ) = {c, ε } What is FIRST(B)? FIRST(B) = FIRST(b) FIRST(d) = {b, d} What is FIRST(A)? FIRST(A) = FIRST(aBCd) FIRST(BQ) FIRST(ε ) FIRST(A) = {a, b, d, ε } What is FIRST(Q)? FIRST(Q) = {q} What is FIRST(S)? FIRST(S) = FIRST(AC) FIRST(S) =FIRST(A)- ε FIRST(C) FIRST(S) = {a, b, c, d, ε }

Determining Follow Sets For each A NT FOLLOW(A) = FOLLOW(S) = {$} $ is eof Start Symbol While (Follow sets are still changing) For each production A αbβ, ε FIRST(β) FOLLOW(B) = FOLLOW(B) (FIRST(β) For each production A αbβ, ε FIRST(β) FOLLOW(B) = FOLLOW(B) (FIRST (β)- ε) Follow(A)

Follow Sets (Example) S AC C c ε A B Q abcd BQ ε bb d q What is FOLLOW(S)? FOLLOW(S) = {$} What is FOLLOW(C)? FOLLOW(C) = {d} FOLLOW(S) = {d, $} What is FOLLOW(B)? FOLLOW(B) = FIRST(Cd) FIRST(Q) FOLLOW(B) FOLLOW(B) = {c, d, q} What is FOLLOW(A)? FOLLOW(A) = FIRST(C) FOLLOW(S) = {c, $} What is FOLLOW(Q)? FOLLOW(Q) = FOLLOW(A) = {c, $}

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 Grammars with the LL(1) Consider A β1 β2 β3, with property are called predictive FIRST+(β1) FIRST+ (β2) FIRST+ (β3) = /* find an A */ if (current_word FIRST(β1)) find a β1 and return true else if (current_word FIRST(β2)) find a β2 and return true else if (current_word FIRST(β3)) find a β3 and return true else report an error and return false 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. Of course, there is more detail to find a βi ( 3.3.4 in EAC)

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.

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( ); looking for EOF, found token Factor( ) if (token = Number) then token next_token( ); return true; else if (token = Identifier) then token next_token( ); return true; else report syntax error; return false; looking for Number or Identifier, found token instead

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

Left Factoring A graphical explanation for the same idea αβ1 A αβ1 αβ2 αβ3 A becomes A αz Z β1 β2 βn αβ2 αβ3 β1 A αz β2 β3

Left Factoring (An example) Consider the following fragment of the expression grammar FIRST(rhs1) = { Identifier } FIRST(rhs2) = { Identifier } FIRST(rhs3) = { Identifier } After left factoring, it becomes FIRST(rhs1) = { Identifier } FIRST(rhs2) = { [ } FIRST(rhs3) = { ( } FIRST(rhs4) = FOLLOW(Factor) It has the LL(1) property This form has the same syntax, with the LL(1) property

Left Factoring Graphically Identifier Factor No basis for choice Identifier [ ExprList ] Identifier ( ExprList ) [ ExprList ] ( ExprList ) becomes Factor ε Identifier Word determines correct choice

Left Factoring (Generality) 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 {an 0 bn n 1} {an 1 b2n n 1} has no LL(1) grammar

Language that Cannot Be LL(1) Example {an 0 bn n 1} {an 1 b2n n 1} has no LL(1) grammar G aa b abbb A a Ab 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.

Recursive Descent (Summary) 1. Build FIRST (and FOLLOW) sets 2. Massage grammar to have LL(1) condition Remove left recursion b. Left factor it Define a procedure for each non-terminal a. Implement a case for each right-hand side b. Call procedures as needed for non-terminals Add extra code, as needed a. Perform context-sensitive checking b. Build an IR to record the code a. 3. 4. Can we automate this process?