Top-Down Parsing CS 671 January 29, 2008. CS 671 – Spring 2008 1 Where Are We? Source code: if (b==0) a = “Hi”; Token Stream: if (b == 0) a = “Hi”; Abstract.

Slides:



Advertisements
Similar presentations
Parsing V: Bottom-up Parsing
Advertisements

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.
Mooly Sagiv and Roman Manevich School of Computer Science
By Neng-Fa Zhou Syntax Analysis lexical analyzer syntax analyzer semantic analyzer source program tokens parse tree parser tree.
CS Summer 2005 Top-down and Bottom-up Parsing - a whirlwind tour June 20, 2005 Slide acknowledgment: Radu Rugina, CS 412.
Parsing III (Eliminating left recursion, 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.
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.
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.
1 Bottom-up parsing Goal of parser : build a derivation –top-down parser : build a derivation by working from the start symbol towards the input. builds.
MIT Top-Down Parsing Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology.
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.
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.
Top-Down Parsing - recursive descent - predictive parsing
4 4 (c) parsing. Parsing A grammar describes the strings of tokens that are syntactically legal in a PL A recogniser simply accepts or rejects strings.
4 4 (c) parsing. Parsing A grammar describes syntactically legal strings in a language A recogniser simply accepts or rejects strings A generator produces.
10/13/2015IT 3271 Tow kinds of predictive parsers: Bottom-Up: The syntax tree is built up from the leaves Example: LR(1) parser Top-Down The syntax tree.
Parsing III (Top-down parsing: recursive descent & LL(1) )
Parsing Jaruloj Chongstitvatana Department of Mathematics and Computer Science Chulalongkorn University.
-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.
1 Compiler Construction Syntax Analysis Top-down parsing.
Review 1.Lexical Analysis 2.Syntax Analysis 3.Semantic Analysis 4.Code Generation 5.Code Optimization.
Syntax and Semantics Structure of programming languages.
4 4 (c) parsing. Parsing A grammar describes syntactically legal strings in a language A recogniser simply accepts or rejects strings A generator produces.
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.
Parsing Top-Down.
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.
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.
Top-Down Parsing.
CSE 5317/4305 L3: Parsing #11 Parsing #1 Leonidas Fegaras.
CS 330 Programming Languages 09 / 25 / 2007 Instructor: Michael Eckmann.
1 CMPSC 160 Translation of Programming Languages Fall 2002 slides derived from Tevfik Bultan, Keith Cooper, and Linda Torczon Lecture-Module #6 Parsing.
UMBC  CSEE   1 Chapter 4 Chapter 4 (b) parsing.
Parsing III (Top-down parsing: recursive descent & LL(1) )
Bottom Up Parsing CS 671 January 31, CS 671 – Spring Where Are We? Finished Top-Down Parsing Starting Bottom-Up Parsing Lexical Analysis.
COMP 3438 – Part II-Lecture 6 Syntax Analysis III Dr. Zili Shao Department of Computing The Hong Kong Polytechnic Univ.
Compilers: Bottom-up/6 1 Compiler Structures Objective – –describe bottom-up (LR) parsing using shift- reduce and parse tables – –explain how LR.
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.
CMSC 330: Organization of Programming Languages Pushdown Automata Parsing.
Syntax and Semantics Structure of programming languages.
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
Parsing — Part II (Top-down parsing, left-recursion removal)
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Presentation transcript:

Top-Down Parsing CS 671 January 29, 2008

CS 671 – Spring Where Are We? Source code: if (b==0) a = “Hi”; Token Stream: if (b == 0) a = “Hi”; Abstract Syntax Tree (AST) Lexical Analysis Syntactic Analysis Semantic Analysis if == b 0 = a “Hi” ; Do tokens conform to the language syntax?

CS 671 – Spring Last Time Parse trees vs. ASTs Derivations –Leftmost vs. Rightmost Grammar ambiguity

CS 671 – Spring Parsing What is parsing? Discovering the derivation of a string: If one exists Harder than generating strings Two major approaches Top-down parsing Bottom-up parsing Won’t work on all context-free grammars Properties of grammar determine parse-ability We may be able to transform a grammar

CS 671 – Spring Two Approaches 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 Bottom-up parsers LR(1), operator precedence Start at the leaves and grow toward root As input is consumed, encode possible parse trees in an internal state Bottom-up parsers handle a large class of grammars

CS 671 – Spring Grammars and Parsers LL(1) parsers Left-to-right input Leftmost derivation 1 symbol of look-ahead LR(1) parsers Left-to-right input Rightmost derivation 1 symbol of look-ahead Also: LL(k), LR(k), SLR, LALR, … Grammars that this can handle are called LL(1) grammars Grammars that this can handle are called LR(1) grammars

CS 671 – Spring Top-Down Parsing Start with the root of the parse tree Root of the tree: node labeled with the start symbol Algorithm: Repeat until the fringe of the parse tree matches input string At a node A, select a production for A Add a child node for each symbol on rhs If a terminal symbol is added that doesn’t match, backtrack Find the next node to be expanded (a non-terminal) Done when: Leaves of parse tree match input string (success) All productions exhausted in backtracking (failure)

CS 671 – Spring Example Expression grammar (with precedence) Input string x – 2 * y #Production rule expr → expr + term | expr - term | term term → term * factor | term / factor | factor factor → number | identifier

CS 671 – Spring Example Problem: Can’t match next terminal We guessed wrong at step 2 RuleSentential formInput string - expr x + term fact term 2 expr + term  x - 2 * y 3 term + term  x – 2 * y 6 factor + term  x – 2 * y 8 + term x  – 2 * y - + term x  – 2 * y  x - 2 * y Current position in the input stream

CS 671 – Spring Backtracking Rollback productions Choose a different production for expr Continue RuleSentential formInput string - expr 2 expr + term  x - 2 * y 3 term + term  x – 2 * y 6 factor + term  x – 2 * y 8 + term x  – 2 * y ? + term x  – 2 * y  x - 2 * y Undo all these productions

CS 671 – Spring Retrying Problem: More input to read Another cause of backtracking RuleSentential formInput string - expr x - term fact term 2 expr - term  x - 2 * y 3 term - term  x – 2 * y 6 factor - term  x – 2 * y 8 - term x  – 2 * y - - term x –  2 * y  x - 2 * y 3 - factor x –  2 * y 7 - x – 2  * y fact 2

CS 671 – Spring Successful Parse All terminals match – we’re finished RuleSentential formInput string - expr x - term fact term 2 expr - term  x - 2 * y 3 term - term  x – 2 * y 6 factor - term  x – 2 * y 8 - term x  – 2 * y - - term x –  2 * y  x - 2 * y 4 - term * fact x –  2 * y 6 - fact * fact x –  2 * y * fact x – 2  * y fact - - * fact x – 2 *  y 8 - * x – 2 * y  term * fact y

CS 671 – Spring Other Possible Parses Problem: termination Wrong choice leads to infinite expansion (More importantly: without consuming any input!) May not be as obvious as this Our grammar is left recursive RuleSentential formInput string - expr 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 + term  x – 2 * y  x - 2 * y

CS 671 – Spring Left Recursion Formally, A grammar is left recursive if  a non-terminal A such that A → * A  (for some set of symbols ) Bad news: Top-down parsers cannot handle left recursion Good news: We can systematically eliminate left recursion What does →* mean? A → B x B → A y

CS 671 – Spring Removing Left Recursion Two cases of left recursion: Transform as follows: #Production rule expr → expr + term | expr - term | term #Production rule term → term * factor | term / factor | factor #Production rule expr → term expr2 expr2 → + term expr2 | - term expr2 |  #Production rule term → factor term2 term2 → * factor term2 | / factor term2 | 

CS 671 – Spring Right-Recursive Grammar We can choose the right production by looking at the next input symbol This is called lookahead BUT, this can be tricky… #Production rule expr → term expr2 expr2 → + term expr2 | - term expr2 |  term → factor term2 term2 → * factor term2 | / factor term2 |  factor → number | identifier Two productions with no choice at all All other productions are uniquely identified by a terminal symbol at the start of RHS

CS 671 – Spring Top-Down Parsing Goal: Given productions A →  | , the parser should be able to choose between  and  How can the next input token help us decide? Solution: FIRST sets Informally: FIRST() is the set of tokens that could appear as the first symbol in a string derived from  Def: x in FIRST() iff  → * x 

CS 671 – Spring The LL(1) Property Given A →  and A → , we would like: FIRST()  FIRST() =  Parser can make right choice by looking at one lookahead token..almost..

CS 671 – Spring Example: Calculating FIRST Sets #Production rule goal → expr expr → term expr2 expr2 → + term expr2 | - term expr2 |  term → factor term2 term2 → * factor term2 | / factor term2 |  factor → number | identifier FIRST(3) = { + } FIRST(4) = { - } FIRST(5) = {  } FIRST(7) = { * } FIRST(8) = { / } FIRST(9) = {  } FIRST(1) = ? FIRST(1) = FIRST(2) = FIRST(6) = FIRST(10)  FIRST(11) = { number, identifier }

CS 671 – Spring Top-Down Parsing What about  productions? Complicates the definition of LL(1) Consider A →  and A →  and  may be empty In this case there is no symbol to identify  Solution Build a FOLLOW set for each production with  #Production rule A → x B | y C |  Example: What is FIRST(3)? = {  } What lookahead symbol tells us we are matching production 3?

CS 671 – Spring FIRST and FOLLOW Sets FIRST() For some  (T  NT)*, 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  FOLLOW(A) For some A  NT, define FOLLOW(A) as the set of symbols that can occur immediately after A in a valid sentence. FOLLOW(G) = {EOF}, where G is the start symbol

CS 671 – Spring Example: Calculating Follow Sets (1) #Production rule goal → expr expr → term expr2 expr2 → + term expr2 | - term expr2 |  term → factor term2 term2 → * factor term2 | / factor term2 |  factor → number | identifier F OLLOW (goal) = { EOF } F OLLOW (expr) = F OLLOW (goal) = { EOF } F OLLOW (expr2) = F OLLOW (expr) = { EOF } F OLLOW (term) = ? F OLLOW (term) += F IRST (expr2) += { +, -,  } += { +, -, F OLLOW (expr)} += { +, -, EOF }

CS 671 – Spring Example: Calculating Follow Sets (2) #Production rule goal → expr expr → term expr2 expr2 → + term expr2 | - term expr2 |  term → factor term2 term2 → * factor term2 | / factor term2 |  factor → number | identifier FOLLOW(term2) += FOLLOW(term) FOLLOW(factor) = ? FOLLOW(factor) += FIRST(term2) += { *, /,  } += { *, /, FOLLOW(term)} += { *, /, +, -, EOF }

CS 671 – Spring Updated LL(1) Property Including  productions FOLLOW(A) = the set of terminal symbols that can immediately follow A Def: FIRST+(A → ) as –FIRST() U FOLLOW(A), if   FIRST() –FIRST(), otherwise Def: a grammar is LL(1) iff A →  and A →  and FIRST+(A → )  FIRST+(A → ) = 

CS 671 – Spring Predictive Parsing Given an LL(1) Grammar The parser can “predict” the correct expansion Using lookahead and FIRST and FOLLOW sets Two kinds of predictive parsers Recursive descent Often hand-written Table-driven Generate tables from First and Follow sets

CS 671 – Spring Recursive Descent This produces a parser with six mutually recursive routines: Goal Expr Expr2 Term Term2 Factor Each recognizes one NT or T The term descent refers to the direction in which the parse tree is built. #Production rule goal → expr expr → term expr2 expr2 → + term expr2 | - term expr2 |  term → factor term2 term2 → * factor term2 | / factor term2 |  factor → number | identifier | ( expr )

CS 671 – Spring Example Code Goal symbol: Top-level expression main() /* Match goal  expr */ tok = nextToken(); if ( expr() && tok == EOF) then proceed to next step; else return false; expr() /* Match expr  term expr2 */ if ( term() && expr2() ); return true; else return false;

CS 671 – Spring Example Code Match expr2 expr2() /* Match expr2  + term expr2 */ /* Match expr2  - term expr2 */ if (tok == ‘+’ or tok == ‘-’) tok = nextToken(); if ( term() ) then return expr2() ; else return false; /* Match expr2 --> empty */ return true; Check F IRST and F OLLOW sets to distinguish

CS 671 – Spring Example Code factor() /* Match factor --> ( expr ) */ if (tok == ‘(‘) tok = nextToken(); if ( expr() && tok == ‘)’) return true; else syntax error: expecting ) return false /* Match factor --> num */ if (tok is a num) return true /* Match factor --> id */ if (tok is an id) return true;

CS 671 – Spring Top-Down Parsing So far: Gives us a yes or no answer We want to build the parse tree How? Add actions to matching routines Create a node for each production How do we assemble the tree?

CS 671 – Spring Notice: Recursive calls match the shape of the tree Idea: use a stack Each routine: –Pops off the children it needs –Creates its own node –Pushes that node back on the stack Building a Parse Tree main expr term factor expr2 term

CS 671 – Spring Building a Parse Tree With stack operations expr() /* Match expr  term expr2 */ if ( term() && expr2() ) expr2_node = pop() ; term_node = pop() ; expr_node = new exprNode (term_node, expr2_node) push (expr_node); return true; else return false;

CS 671 – Spring Recursive Descent Parsing Massage grammar to have LL(1) condition Remove left recursion Left factor, where possible Build FIRST (and FOLLOW) sets Define a procedure for each non-terminal Implement a case for each right-hand side Call procedures as needed for non-terminals Add extra code, as needed Can we automate this process?

CS 671 – Spring Table-driven approach Encode mapping in a table Row for each non-terminal Column for each terminal symbol Table[NT, symbol] = rule# if symbol  FIRST+(NT  rhs(#)) +,-*, /id, num expr2term expr2error term2errorfactor term2error factorerror (do nothing)

CS 671 – Spring Code Note: Missing else conditions for errors push the start symbol, G, onto Stack top  top of Stack loop forever if top = EOF and token = EOF then break & report success if top is a terminal then if top matches token then pop Stack// recognized top token  next_token() else // top is a non-terminal if TABLE[top,token] is A  B 1 B 2 …B k then pop Stack // get rid of A push Bk, Bk-1, …, B1 // in that order top  top of Stack

CS 671 – Spring Next Time … Bottom-up Parsers More powerful Widely used – yacc, bison, JavaCUP Overview of YACC Removing shift/reduce reduce/reduce conflicts Just in case you haven’t started your homework!