# Bottom-up Parser. Jungsik Choi

Size: px
Start display at page:

Download "Bottom-up Parser. Jungsik Choi"

Transcription

1 Formal Languages and Compiler (CSE322) Bottom-up Parser Jungsik Choi * Some slides taken from SKKU SWE3010 (Prof. Hwansoo Han) and TAMU CSCE (Prof. Lawrence Rauchwerger)

2 Bottom-up Parsing Bottom-up parsing and reverse rightmost derivation A derivation consists of a series of rewrite steps A bottom-up parser builds a derivation by working from the input sentence back toward the start symbol S S Þ γ # Þ γ \$ Þ γ & Þ Þ γ '(\$ Þ γ ' Þ sentence bottom-up In terms of the parse tree, this is working from leaves to root Nodes with no parent in a partial tree form its upper fringe Since each replacement of β with A shrinks the upper fringe, we call it a reduction 2

3 Bottom-Up Parser Example The expression grammar Goal Expr Term Expr Expr + Term Expr Term Term Term * Factor Term / Factor Factor Factor number id (Expr) Handles for rightmost derivation of x 2 * y Prod n Sentential From Handle Goal Expr Expr Term Expr Term * Factor Expr Term * <id,y> Expr Factor * <id,y> Expr - <num,2> * <id,y> Term - <num,2> * <id,y> Factor - <num,2> * <id,y> <id,x> - <num,2> * <id,y> - 1,1 3,3 5,5 9,5 7,3 8,3 4,1 7,1 9,1 Reverse rightmost derivation (RRD) Handles are specified in blue 3

4 Finding Reductions - Handles Parser must find a substring β of the tree s frontier Matches some production A β that occurs as one step in the rightmost derivation Informally, we call this substring β a handle Formally, A handle of a right-sentential form γ is a pair <A β, k> A β P k is the position in γ of β s rightmost symbol If <A β, k> is a handle, then replace β at k with A Handle pruning The process of discovering a handle & reducing it to the appropriate lhs (nonterminal) is called handle pruning Because γ is a right-sentential form, the substring to the right of a handle contains only terminal symbols 4

5 Shift-Reduce Parser One of Bottom-up Parsers push INVALID token next_token( ) repeat until (top of stack = Goal and token = EOF) if the top of the stack can reduce using a handle <A b.k> then // reduce b to A pop b (=k) symbols off the stack push A onto the stack else if (token!= EOF) then // push token token next_token( ) else // need to, but out of input report an error How do errors show up? - failure to find a handle - hitting EOF & needing to (Final else clause) Either generates an error 5

6 Back to x 2 * y \$ \$ id Stack Input Handle Action id num * id \$ num * id \$ none 6

7 Back to x 2 * y \$ \$ id \$ Factor \$ Term \$ Expr Stack Input Handle Action id num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ none 9, 1 7, 1 4, 1 red. 9 red. 7 red. 4 7

8 Back to x 2 * y \$ \$ id \$ Factor \$ Term \$ Expr \$ Expr \$ Expr num Stack Input Handle Action id num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ * id \$ none 9, 1 7, 1 4, 1 none none red. 9 red. 7 red. 4 8

9 Back to x 2 * y \$ \$ id \$ Factor \$ Term \$ Expr \$ Expr \$ Expr num \$ Expr Factor \$ Expr Term Stack Input Handle Action id num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ * id \$ * id \$ * id \$ none 9, 1 7, 1 4, 1 none none 8, 3 7, 3 red. 9 red. 7 red. 4 red. 8 red. 7 9

10 Back to x 2 * y \$ \$ id \$ Factor \$ Term \$ Expr \$ Expr \$ Expr num \$ Expr Factor \$ Expr Term \$ Expr Term * \$ Expr Term * id Stack Input Handle Action id num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ * id \$ * id \$ * id \$ id \$ \$ none 9, 1 7, 1 4, 1 none none 8, 3 7, 3 none none red. 9 red. 7 red. 4 red. 8 red. 7 10

11 Back to x 2 * y Stack Input Handle Action \$ \$ id \$ Factor \$ Term \$ Expr \$ Expr \$ Expr num \$ Expr Factor \$ Expr Term \$ Expr Term * \$ Expr Term * id \$ Expr Term * Factor \$ Expr Term \$ Expr \$ Goal id num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ num * id \$ * id \$ * id \$ * id \$ id \$ \$ \$ \$ \$ \$ none 9, 1 7, 1 4, 1 none none 8, 3 7, 3 none none 9, 5 5, 5 3, 3 1, 1 none red. 9 red. 7 red. 4 red. 8 red. 7 red. 9 red. 5 red. 3 red. 1 accept 5 s + 9 reduces + 1 accept 11

12 Example Stack Input Action G \$ \$ id \$ Factor \$ Term \$ Expr \$ Expr \$ Expr num \$ Expr Factor \$ Expr Term \$ Expr Term * \$ Expr Term * id \$ Expr Term * Factor \$ Expr Term \$ Expr \$ Goal id num * id num * id num * id num * id num * id num * id * id * id * id id red. 9 red. 7 red. 4 red. 8 red. 7 red. 9 red. 5 red. 3 red. 1 accept E T F x E - T F 2 T * F y bottom-up building 12

13 Shift-Reduce Parsing Shift reduce parsers are easily built and easily understood A -reduce parser has just four actions Shift : next word is ed onto the stack Reduce : right end of handle is at top of stack Locate left end of handle within the stack Pop handle off stack & push appropriate lhs Accept : stop parsing & report success Error : call an error reporting/recovery routine Handle finding is key - handle is on stack - finite set of handles à use a DFA! Critical Question: How can we know when we have found a handle without generating lots of different derivations? Answer: we use look ahead in the grammar along with tables produced as the result of analyzing the grammar. LR(1) parsers build a DFA that runs over the stack & finds them 13

14 Another Bottom-Up Parser LR(1) Parsers LR(1) parsers are table-driven, -reduce parsers that use a limited right context (1 token) for handle recognition LR(1) parsers recognize languages that have an LR(1) grammar Informal definition: A grammar is LR(1) if, given a rightmost derivation S Þ γ # Þ γ \$ Þ γ & Þ Þ γ '(\$ Þ γ ' Þ sentence We can 1. isolate the handle of each right-sentential form γ *, and 2. determine the production with which to reduce, by scanning γ * from leftto-right, going at most 1 symbol beyond the right end of the handle of γ * 14

15 LR(1) Parsers A table-driven LR(1) parser looks like source code Scanner Table-driven Parser IR grammar Parser Generator ACTION & GOTO Tables Tables can be built by hand However, this is a perfect task to automate 15

16 LR(1) Skeleton Parser The skeleton parser push tokens & NTs along with DFA states uses ACTION & GOTO tables (DFA) does words s dose derivation reductions does 1 accept detects errors by failure of 3 other cases stack.push(invalid); stack.push(s 0 ); not_found = true; token = scanner.next_token(); do while (not_found) { s = stack.top(); if ( ACTION[s,token] == s next ) then { stack.push(token); stack.push(s next ); token scanner.next_token(); } else if ( ACTION[s,token] == reduce A b ) then { stack.popnum(2* b ); // pop 2* b symbols s = stack.top(); stack.push(a); stack.push(goto[s,a]); } else if ( ACTION[s,token] == accept & token == EOF ) then { not_found = false; } else report a syntax error and recover; } report success; 16

17 LR(1) Parsers How does this LR(1) stuff work? Unambiguous grammar à unique rightmost derivation Keep upper fringe on a stack All active handles include top of stack (TOS) Shift inputs until TOS is right end of a handle Language of handles is regular (finite) Build a handle-recognizing DFA ACTION & GOTO tables encode the DFA The Big Picture Model the state of the parser Use two functions goto(s, X) and closure(s) goto() is analogous to move() in subset construction (NFAà DFA) closure() adds information to form a state Build up the states and transition functions of the DFA Use this information to fill in the ACTION and GOTO tables 17

18 LR(0) example Z E E E + T T T i (E) 18

19 LR(1) Parsing - Example LIST LIST, ELEMENT ELEMENT ELEMENT a ACTION GOTO State a, \$ LIST ELEMENT 0 s s4 acc 2 r2 r2 3 r3 r3 4 s3 5 5 r1 r1 LR(1) Parsing a,a Stack Input Action 0 a,a\$ s3 0 a 3,a\$ r3 GOTO2 0 ELEMENT 2,a\$ r2 GOTO1 0 LIST 1,a\$ s4 0 LIST 1, 4 a\$ s3 0 LIST 1, 4 a 3 \$ r3 GOTO5 0 LIST 1, 4 ELEMENT 5 \$ r1 GOTO1 0 LIST 1 \$ accept 19

20 LR(k) Items A state of parser == a set of LR(k) items An LR(k) item is a pair [P, δ], where P is a production A β with a - at some position in the rhs δ is a lookahead string of length k (words/tokens or EOF) 20

21 LR(k) Items LR(1) items The - in an item indicates the position of the top of the stack [A - βγ, a] means that the input seen so far is consistent with the use of A βγ immediately after the symbol on top of the stack (possibility) [A β - γ, a] means that the input seen so far is consistent with the use of A βγ at this point, and that the parser has already recognized β (partially complete) [A βγ -, a] means that the parser has seen βγ, and that a lookahead symbol of a is consistent with reducing to A (complete) 21

22 Computing goto() goto(s, x) computes the state that the parser would reach if it recognized an x while in state s goto({ [A β -Xδ, a] }, X ) produces [A βx- δ, a] Should also includes closure( [A βx- δ, a] ) The algorithm goto(s, X) moved for each item [A β -Xδ, a] s moved moved [A βx- δ, a] return closure(moved) 22

23 Computing closure() closure(s) add all the items implied by items already in s Any item [A β -Bδ, a] implies [B - τ, x] for each production with B on the lhs, and each x FIRST(δa) Since βbδ is valid, any way to derive βbδ is valid, too The algorithm closure(s) while(s is still changing) for each item [A β -Cδ, a] s for each production C τ P for each b FISRT(δa) // δ might be ε s s [C - τ,b] 23

24 LR(1) Table Construction High-level overview 1. Build the canonical collection of sets of LR(1) Items a. Begin in an appropriate state, CC # [S -S, EOF], along with any equivalent items Derive equivalent items as closure(cc # ) b. Repeatedly compute, for each CC 9, and each X, goto(cc 9, X) If the set is not already in the collection, and it Record all the transitions created by goto() This eventually reaches a fixed point 2. Fill in the table from the collection of sets of LR(1) items 24

25 Canonical Collection Building CC: all possible states Start from CC # = closure( [S -S, EOF] ) Repeatedly construct new states, until all are found The algorithm CC # closure( [S S, EOF] ) CC { CC # } k 1 while ( CC is still changing ) for each CC : CC and for each x (T NT) CC 9 goto(cc :, x) record CC : CC 9 on x if CC 9 CC then CC CC CC 9 // new state in DFA k k

26 Example-1 (grammar & sets) Simplified, right recursive expression grammar Goal Expr Expr Term Expr Term Term Factor * Term Factor Factor ident Symbol Goal Expr Term Factor - * ident FIRST {ident} {ident} {ident} {ident} {-} {*} {ident} 26

27 Example-1 (building the collection 1) Initialization step CC # closure( { [Goal -Expr, EOF] } ) { [Goal -Expr, EOF], [Expr -Term - Expr, EOF], [Expr -Term, EOF], [Term -Factor * Term, EOF], [Term -Factor * Term, -], [Term -Factor, EOF], [Term -Factor, -], [Factor -ident, EOF], [Factor -ident, -], [Factor -ident, *] } Add CC # to a set of states, CC { CC # } 27

28 Example-1 (building the collection 2) Iteration 1 cc1 goto(cc0, Expr) cc2 goto(cc0, Term) cc3 goto(cc0, Factor) cc4 goto(cc0, ident ) Iteration 2 cc5 goto(cc2, ) cc6 goto(cc3, * ) Iteration 3 cc7 goto(cc5, Expr ) cc8 goto(cc6, Term ) # Term, Factor, ident existing states # Factor, ident existing states 28

29 Example-1 (summary 1) cc0 : { [Goal Expr, EOF], [Expr Term Expr, EOF], [Expr Term, EOF], [Term Factor * Term, EOF], [Term Factor * Term, ], [Term Factor, EOF], [Term Factor, ], [Factor ident, EOF], [Factor ident, ], [Factor ident, *] } cc1 : { [Goal Expr, EOF] } cc2 : { [Expr Term Expr, EOF], [Expr Term, EOF] } cc3 : { [Term Factor * Term, EOF],[Term Factor * Term, ], [Term Factor, EOF], [Term Factor, ] } cc4 : { [Factor ident, EOF],[Factor ident, ], [Factor ident, *] } cc5 : { [Expr Term Expr, EOF], [Expr Term Expr, EOF], [Expr Term, EOF], [Term Factor * Term, EOF], [Term Factor * Term, ], [Term Factor, EOF], [Term Factor, ], [Factor ident, EOF ], [Factor ident, ], [Factor ident, *] } 29

30 Example-1 (summary 2) cc6 : { [Term Factor * Term, EOF], [Term Factor * Term, ], [Term Factor * Term, EOF], [Term Factor * Term, ], [Term Factor, EOF], [Term Factor, ], [Factor ident, EOF], [Factor ident, ], [Factor ident, *] } cc7 : { [Expr Term Expr, EOF] } cc8 : { [Term Factor * Term, EOF], [Term Factor * Term, ] } 1 E T 0 F id 2 3 T F - F * E id id T

31 Example-1 (summary 3) The goto() relationship (from the construction) State Expr Term Factor - * ident

32 The algorithm Filling in the ACTION and GOTO Tables for each set CC < CC for each item i CC < if i is [A β -aγ,b] and goto(cc <,a)= CC 9, a T then ACTION[x,a] k else if i is [S S -,EOF] then ACTION[x, EOF] accept else if i is[a β -, a] then ACTION[x, a] reduce A β for each nt NT if goto(cc <, nt) = CC 9 then GOTO[x, nt] k 32

33 Example-1 (filling in the tables) The algorithm produces the following table State GOTO ACTION Expr Term Factor - * ident EOF s4 1 accept 2 s5 r3 3 r5 s6 r5 4 r6 r6 r s s4 7 r2 8 r4 r4 33

34 Example-2 (grammar & sets) Simplified, right recursive expression grammar S E E T + E T T id Symbol S E T FIRST {id} {id} {id} 34

35 Example-2 (building the collection ) S E E T + E T T id 35

36 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] S E E T + E T T id 36

37 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] S E E T + E T T id E S 1 [ S E, \$ ] 37

38 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] T S 2 [ E T + E, \$ ] [ E T, \$ ] S E E T + E T T id E S 1 [ S E, \$ ] 38

39 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] T id S 2 [ E T + E, \$ ] [ E T, \$ ] S E E T + E T T id E S 3 [ T id, + ] [ T id, \$ ] S 1 [ S E, \$ ] 39

40 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] T id S 2 [ E T + E, \$ ] [ E T, \$ ] + S E E T + E T T id E S 1 [ S E, \$ ] S 3 [ T id, + ] [ T id, \$ ] S 4 [ E T + E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] 40

41 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] T id S 2 [ E T + E, \$ ] [ E T, \$ ] + S E E T + E T T id E S 1 [ S E, \$ ] S 3 [ T id, + ] [ T id, \$ ] S 5 [ E T + E, \$ ] E S 4 [ E T + E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] 41

42 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] T id S 2 [ E T + E, \$ ] [ E T, \$ ] T + S E E T + E T T id E S 1 [ S E, \$ ] S 3 [ T id, + ] [ T id, \$ ] S 5 [ E T + E, \$ ] E S 4 [ E T + E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] 42

43 Example-2 (building the collection ) S 0 [ S E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] T id S 2 [ E T + E, \$ ] [ E T, \$ ] T + S E E T + E T T id E S 1 [ S E, \$ ] S 3 [ T id, + ] [ T id, \$ ] S 5 [ E T + E, \$ ] id E S 4 [ E T + E, \$ ] [ E T + E, \$ ] [ E T, \$ ] [ T id, + ] [ T id, \$ ] 43

44 Example-2 (filling in the tables) The algorithm produces the following table 44

45 Left Recursion vs. Right Recursion Right recursion Required for termination in top-down parsers Uses (on average) more stack space Produces right-associative operators Left recursion Works fine in bottom-up parsers Limits required stack space Produces left-associative operators Rule of thumb Left recursion for bottom-up parsers Right recursion for top-down parsers 45

### Introduction to Parsing. Comp 412

COMP 412 FALL 2010 Introduction to Parsing 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

More information

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

Parsing III (Top-down parsing: recursive descent & LL(1) ) (Bottom-up parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,

More information

### Syntax Analysis, VI Examples from LR Parsing. Comp 412

Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, VI Examples from LR Parsing Comp 412 COMP 412 FALL 2018 source code IR IR target Front End Optimizer Back End code Copyright

More information

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

CS 406/534 Compiler Construction Parsing Part II LL(1) and LR(1) Parsing Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof.

More information

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

Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, V Bottom-up Parsing & The Magic of Handles Comp 412 COMP 412 FALL 2018 source code IR Front End Optimizer Back End IR target

More information

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

Bottom-up parsing Bottom-up parsing Recall Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form If α V t,thenα is called a sentence in L(G) Otherwise it is just

More information

### CS415 Compilers. LR Parsing & Error Recovery

CS415 Compilers LR Parsing & Error Recovery These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Review: LR(k) items The LR(1) table construction

More information

### Chapter 4: LR Parsing

Chapter 4: LR Parsing 110 Some definitions Recall For a grammar G, with start symbol S, any string α such that S called a sentential form α is If α Vt, then α is called a sentence in L G Otherwise it is

More information

### Context-sensitive Analysis Part IV Ad-hoc syntax-directed translation, Symbol Tables, andtypes

Context-sensitive Analysis Part IV Ad-hoc syntax-directed translation, Symbol Tables, andtypes Quiz Name two differences between attribute grammars and ad-hoc syntax directed translation techniques? Example:

More information

### Chapter 4. Lexical and Syntax Analysis

Chapter 4 Lexical and Syntax Analysis Chapter 4 Topics Introduction Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing Copyright 2012 Addison-Wesley. All rights reserved.

More information

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

COMP 412 FALL 2017 Syntax Analysis, VII One more LR(1) example, plus some more stuff Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon,

More information

### A left-sentential form is a sentential form that occurs in the leftmost derivation of some sentence.

Bottom-up parsing Recall For a grammar G, with start symbol S, any string α such that S α is a sentential form If α V t, then α is a sentence in L(G) A left-sentential form is a sentential form that occurs

More information

### CMSC 430 Introduction to Compilers. Fall Lexing and Parsing

CMSC 430 Introduction to Compilers Fall 2014 Lexing and Parsing Overview Compilers are roughly divided into two parts Front-end deals with surface syntax of the language Back-end analysis and code generation

More information

### CSCI312 Principles of Programming Languages

Copyright 2006 The McGraw-Hill Companies, Inc. CSCI312 Principles of Programming Languages! LL Parsing!! Xu Liu Derived from Keith Cooper s COMP 412 at Rice University Recap Copyright 2006 The McGraw-Hill

More information

### Compiler Construction 2016/2017 Syntax Analysis

Compiler Construction 2016/2017 Syntax Analysis Peter Thiemann November 2, 2016 Outline 1 Syntax Analysis Recursive top-down parsing Nonrecursive top-down parsing Bottom-up parsing Syntax Analysis tokens

More information

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

Syntax Analysis: Context-free Grammars, Pushdown Automata and Part - 4 Department of Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler

More information

### CSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D-1

CSE P 501 Compilers LR Parsing Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 D-1 Agenda LR Parsing Table-driven Parsers Parser States Shift-Reduce and Reduce-Reduce conflicts UW CSE P 501 Spring 2018

More information

### 4. Lexical and Syntax Analysis

4. Lexical and Syntax Analysis 4.1 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal

More information

### S Y N T A X A N A L Y S I S LR

LR parsing There are three commonly used algorithms to build tables for an LR parser: 1. SLR(1) = LR(0) plus use of FOLLOW set to select between actions smallest class of grammars smallest tables (number

More information

### Compiler Design 1. Bottom-UP Parsing. Goutam Biswas. Lect 6

Compiler Design 1 Bottom-UP Parsing Compiler Design 2 The Process The parse tree is built starting from the leaf nodes labeled by the terminals (tokens). The parser tries to discover appropriate reductions,

More information

### 4. Lexical and Syntax Analysis

4. Lexical and Syntax Analysis 4.1 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal

More information

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

Parsing Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice. Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students

More information

### Parsing Wrapup. Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing. This lecture LR(1) parsing

Parsing Wrapup Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing LR(1) items Computing closure Computing goto LR(1) canonical collection This lecture LR(1) parsing Building ACTION

More information

### CS 4120 Introduction to Compilers

CS 4120 Introduction to Compilers Andrew Myers Cornell University Lecture 6: Bottom-Up Parsing 9/9/09 Bottom-up parsing A more powerful parsing technology LR grammars -- more expressive than LL can handle

More information

### Parsing II Top-down parsing. Comp 412

COMP 412 FALL 2018 Parsing II Top-down parsing Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled

More information

### Syntax Analysis, III Comp 412

COMP 412 FALL 2017 Syntax Analysis, III Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp

More information

### LR Parsing. Leftmost and Rightmost Derivations. Compiler Design CSE 504. Derivations for id + id: T id = id+id. 1 Shift-Reduce Parsing.

LR Parsing Compiler Design CSE 504 1 Shift-Reduce Parsing 2 LR Parsers 3 SLR and LR(1) Parsers Last modifled: Fri Mar 06 2015 at 13:50:06 EST Version: 1.7 16:58:46 2016/01/29 Compiled at 12:57 on 2016/02/26

More information

### Downloaded from Page 1. LR Parsing

Downloaded from http://himadri.cmsdu.org Page 1 LR Parsing We first understand Context Free Grammars. Consider the input string: x+2*y When scanned by a scanner, it produces the following stream of tokens:

More information

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

Compilers Parsing Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Next step text chars Lexical analyzer tokens Parser IR Errors Parsing: Organize tokens into sentences Do tokens conform

More information

### CS 406/534 Compiler Construction Parsing Part I

CS 406/534 Compiler Construction Parsing Part I Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof. Ken Kennedy and Dr.

More information

### Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

Syntax Analysis (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay September 2007 College of Engineering, Pune Syntax Analysis: 2/124 Syntax

More information

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

ICOM 4036 Programming Languages Lexical and Syntax Analysis Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing This lecture covers review questions 14-27 This lecture covers

More information

### Syntactic Analysis. Top-Down Parsing

Syntactic Analysis Top-Down Parsing Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in Compilers class at University of Southern California (USC) have explicit permission to make

More information

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

Chapter 4 Lexical and Syntax Analysis Introduction - Language implementation systems must analyze source code, regardless of the specific implementation approach - Nearly all syntax analysis is based on

More information

### CSE 401 Compilers. LR Parsing Hal Perkins Autumn /10/ Hal Perkins & UW CSE D-1

CSE 401 Compilers LR Parsing Hal Perkins Autumn 2011 10/10/2011 2002-11 Hal Perkins & UW CSE D-1 Agenda LR Parsing Table-driven Parsers Parser States Shift-Reduce and Reduce-Reduce conflicts 10/10/2011

More information

### LR Parsing Techniques

LR Parsing Techniques Introduction Bottom-Up Parsing LR Parsing as Handle Pruning Shift-Reduce Parser LR(k) Parsing Model Parsing Table Construction: SLR, LR, LALR 1 Bottom-UP Parsing A bottom-up parser

More information

### Bottom Up Parsing. Shift and Reduce. Sentential Form. Handle. Parse Tree. Bottom Up Parsing 9/26/2012. Also known as Shift-Reduce parsing

Also known as Shift-Reduce parsing More powerful than top down Don t need left factored grammars Can handle left recursion Attempt to construct parse tree from an input string eginning at leaves and working

More information

### 10/5/17. Lexical and Syntactic Analysis. Lexical and Syntax Analysis. Tokenizing Source. Scanner. Reasons to Separate Lexical and Syntax Analysis

Lexical and Syntactic Analysis Lexical and Syntax Analysis In Text: Chapter 4 Two steps to discover the syntactic structure of a program Lexical analysis (Scanner): to read the input characters and output

More information

### Computing Inside The Parser Syntax-Directed Translation. Comp 412 COMP 412 FALL Chapter 4 in EaC2e. source code. IR IR target.

COMP 412 FALL 2017 Computing Inside The Parser Syntax-Directed Translation Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights

More information

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

Roadmap > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing The role of the parser > performs context-free syntax analysis > guides

More information

### 10/4/18. Lexical and Syntactic Analysis. Lexical and Syntax Analysis. Tokenizing Source. Scanner. Reasons to Separate Lexical and Syntactic Analysis

Lexical and Syntactic Analysis Lexical and Syntax Analysis In Text: Chapter 4 Two steps to discover the syntactic structure of a program Lexical analysis (Scanner): to read the input characters and output

More information

### Formal Languages and Compilers Lecture VII Part 3: Syntactic A

Formal Languages and Compilers Lecture VII Part 3: Syntactic Analysis Free University of Bozen-Bolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/

More information

### Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient

More information

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

CS415 Compilers Syntax Analysis These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Limits of Regular Languages Advantages of Regular Expressions

More information

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

Parsing III (Top-down parsing: recursive descent & LL(1) ) Roadmap (Where are we?) Previously We set out to study parsing Specifying syntax Context-free grammars Ambiguity Top-down parsers Algorithm &

More information

### Principles of Programming Languages

Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 8! Bo;om- Up Parsing Shi?- Reduce LR(0) automata and

More information

### Syntax Analysis, III Comp 412

Updated algorithm for removal of indirect left recursion to match EaC3e (3/2018) COMP 412 FALL 2018 Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, III Comp 412 source code

More information

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 5: Syntax Analysis (Parsing) Zheng (Eddy) Zhang Rutgers University January 31, 2018 Class Information Homework 1 is being graded now. The sample solution

More information

### MIT Parse Table Construction. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology

MIT 6.035 Parse Table Construction Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Parse Tables (Review) ACTION Goto State ( ) \$ X s0 shift to s2 error error goto s1

More information

### Wednesday, August 31, Parsers

Parsers How do we combine tokens? Combine tokens ( words in a language) to form programs ( sentences in a language) Not all combinations of tokens are correct programs (not all sentences are grammatically

More information

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

3. Syntax Analysis Andrea Polini Formal Languages and Compilers Master in Computer Science University of Camerino (Formal Languages and Compilers) 3. Syntax Analysis CS@UNICAM 1 / 54 Syntax Analysis: the

More information

### Lexical and Syntax Analysis. Bottom-Up Parsing

Lexical and Syntax Analysis Bottom-Up Parsing Parsing There are two ways to construct derivation of a grammar. Top-Down: begin with start symbol; repeatedly replace an instance of a production s LHS with

More information

### Compilers. Bottom-up Parsing. (original slides by Sam

Compilers Bottom-up Parsing Yannis Smaragdakis U Athens Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Bottom-Up Parsing More general than top-down parsing And just as efficient Builds

More information

### EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:

EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 2017-09-11 This lecture Regular expressions Context-free grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)

More information

### Context-free grammars

Context-free grammars Section 4.2 Formal way of specifying rules about the structure/syntax of a program terminals - tokens non-terminals - represent higher-level structures of a program start symbol,

More information

### Lecture 8: Deterministic Bottom-Up Parsing

Lecture 8: Deterministic Bottom-Up Parsing (From slides by G. Necula & R. Bodik) Last modified: Fri Feb 12 13:02:57 2010 CS164: Lecture #8 1 Avoiding nondeterministic choice: LR We ve been looking at general

More information

### Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 2/20/08 Prof. Hilfinger CS164 Lecture 11 1 Administrivia Test I during class on 10 March. 2/20/08 Prof. Hilfinger CS164 Lecture 11

More information

### LR Parsing, Part 2. Constructing Parse Tables. An NFA Recognizing Viable Prefixes. Computing the Closure. GOTO Function and DFA States

TDDD16 Compilers and Interpreters TDDB44 Compiler Construction LR Parsing, Part 2 Constructing Parse Tables Parse table construction Grammar conflict handling Categories of LR Grammars and Parsers An NFA

More information

### Programming Language Syntax and Analysis

Programming Language Syntax and Analysis 2017 Kwangman Ko (http://compiler.sangji.ac.kr, kkman@sangji.ac.kr) Dept. of Computer Engineering, Sangji University Introduction Syntax the form or structure of

More information

### Compiler Construction: Parsing

Compiler Construction: Parsing Mandar Mitra Indian Statistical Institute M. Mitra (ISI) Parsing 1 / 33 Context-free grammars. Reference: Section 4.2 Formal way of specifying rules about the structure/syntax

More information

### Lecture 7: Deterministic Bottom-Up Parsing

Lecture 7: Deterministic Bottom-Up Parsing (From slides by G. Necula & R. Bodik) Last modified: Tue Sep 20 12:50:42 2011 CS164: Lecture #7 1 Avoiding nondeterministic choice: LR We ve been looking at general

More information

### Let us construct the LR(1) items for the grammar given below to construct the LALR parsing table.

MODULE 18 LALR parsing After understanding the most powerful CALR parser, in this module we will learn to construct the LALR parser. The CALR parser has a large set of items and hence the LALR parser is

More information

### Computer Science 160 Translation of Programming Languages

Computer Science 160 Translation of Programming Languages Instructor: Christopher Kruegel Top-Down Parsing Parsing Techniques Top-down parsers (LL(1), recursive descent parsers) Start at the root of the

More information

### 3. Parsing. Oscar Nierstrasz

3. Parsing Oscar Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes. http://www.cs.ucla.edu/~palsberg/ http://www.cs.purdue.edu/homes/hosking/

More information

### Parsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1)

TD parsing - LL(1) Parsing First and Follow sets Parse table construction BU Parsing Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1) Problems with SLR Aho, Sethi, Ullman, Compilers

More information

### Computing Inside The Parser Syntax-Directed Translation. Comp 412

COMP 412 FALL 2018 Computing Inside The Parser Syntax-Directed Translation Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights

More information

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

PART 3 - SYNTAX ANALYSIS F. Wotawa (IST @ TU Graz) Compiler Construction Summer term 2016 64 / 309 Goals Definition of the syntax of a programming language using context free grammars Methods for parsing

More information

### Monday, September 13, Parsers

Parsers Agenda Terminology LL(1) Parsers Overview of LR Parsing Terminology Grammar G = (Vt, Vn, S, P) Vt is the set of terminals Vn is the set of non-terminals S is the start symbol P is the set of productions

More information

### CA Compiler Construction

CA4003 - Compiler Construction David Sinclair A top-down parser starts with the root of the parse tree, labelled with the goal symbol of the grammar, and repeats the following steps until the fringe of

More information

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

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

More information

### Review main idea syntax-directed evaluation and translation. Recall syntax-directed interpretation in recursive descent parsers

Plan for Today Review main idea syntax-directed evaluation and translation Recall syntax-directed interpretation in recursive descent parsers Syntax-directed evaluation and translation in shift-reduce

More information

### Introduction to Parsing

Introduction to Parsing The Front End Source code Scanner tokens Parser IR Errors Parser Checks the stream of words and their parts of speech (produced by the scanner) for grammatical correctness Determines

More information

### Wednesday, September 9, 15. Parsers

Parsers What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information

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

What is a parser Parsers A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information

### Chapter 4. Lexical and Syntax Analysis. Topics. Compilation. Language Implementation. Issues in Lexical and Syntax Analysis.

Topics Chapter 4 Lexical and Syntax Analysis Introduction Lexical Analysis Syntax Analysis Recursive -Descent Parsing Bottom-Up parsing 2 Language Implementation Compilation There are three possible approaches

More information

### Building a Parser Part III

COMP 506 Rice University Spring 2018 Building a Parser Part III With Practical Application To Lab One source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda

More information

### Types of parsing. CMSC 430 Lecture 4, Page 1

Types of parsing Top-down parsers start at the root of derivation tree and fill in picks a production and tries to match the input may require backtracking some grammars are backtrack-free (predictive)

More information

### shift-reduce parsing

Parsing #2 Bottom-up Parsing Rightmost derivations; use of rules from right to left Uses a stack to push symbols the concatenation of the stack symbols with the rest of the input forms a valid bottom-up

More information

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

Parsers Xiaokang Qiu Purdue University ECE 468 August 31, 2018 What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure

More information

### Syntax Analysis Check syntax and construct abstract syntax tree

Syntax Analysis Check syntax and construct abstract syntax tree if == = ; b 0 a b Error reporting and recovery Model using context free grammars Recognize using Push down automata/table Driven Parsers

More information

### Outline CS412/413. Administrivia. Review. Grammars. Left vs. Right Recursion. More tips forll(1) grammars Bottom-up parsing LR(0) parser construction

C12/1 Introduction to Compilers and Translators pring 00 Outline More tips forll1) grammars Bottom-up parsing LR0) parser construction Lecture 5: Bottom-up parsing Lecture 5 C 12/1 pring '00 Andrew Myers

More information

### Top down vs. bottom up parsing

Parsing A grammar describes the strings that are syntactically legal A recogniser simply accepts or rejects strings A generator produces sentences in the language described by the grammar A parser constructs

More information

### CSE302: Compiler Design

CSE302: Compiler Design Instructor: Dr. Liang Cheng Department of Computer Science and Engineering P.C. Rossin College of Engineering & Applied Science Lehigh University March 20, 2007 Outline Recap LR(0)

More information

### How do LL(1) Parsers Build Syntax Trees?

How do LL(1) Parsers Build Syntax Trees? So far our LL(1) parser has acted like a recognizer. It verifies that input token are syntactically correct, but it produces no output. Building complete (concrete)

More information

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

Prelude COMP Lecture Topdown Parsing September, 00 What is the Tufts mascot? Jumbo the elephant Why? P. T. Barnum was an original trustee of Tufts : donated \$0,000 for a natural museum on campus Barnum

More information

### UNIT III & IV. Bottom up parsing

UNIT III & IV Bottom up parsing 5.0 Introduction Given a grammar and a sentence belonging to that grammar, if we have to show that the given sentence belongs to the given grammar, there are two methods.

More information

### Lexical and Syntax Analysis

Lexical and Syntax Analysis In Text: Chapter 4 N. Meng, F. Poursardar Lexical and Syntactic Analysis Two steps to discover the syntactic structure of a program Lexical analysis (Scanner): to read the input

More information

### Chapter 3. Describing Syntax and Semantics ISBN

Chapter 3 Describing Syntax and Semantics ISBN 0-321-49362-1 Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Copyright 2009 Addison-Wesley. All

More information

SYNTAX ANALYSIS 1. Define parser. Hierarchical analysis is one in which the tokens are grouped hierarchically into nested collections with collective meaning. Also termed as Parsing. 2. Mention the basic

More information

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

Parser Generation Main Problem: given a grammar G, how to build a top-down parser or a bottom-up parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence ----

More information

### MODULE 14 SLR PARSER LR(0) ITEMS

MODULE 14 SLR PARSER LR(0) ITEMS In this module we shall discuss one of the LR type parser namely SLR parser. The various steps involved in the SLR parser will be discussed with a focus on the construction

More information

### Front End. Hwansoo Han

Front nd Hwansoo Han Traditional Two-pass Compiler Source code Front nd IR Back nd Machine code rrors High level functions Recognize legal program, generate correct code (OS & linker can accept) Manage

More information

### COP4020 Programming Languages. Syntax Prof. Robert van Engelen

COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview n Tokens and regular expressions n Syntax and context-free grammars n Grammar derivations n More about parse trees n Top-down and

More information

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

COMP Lecture Parsing September, 00 Prelude What is the common name of the fruit Synsepalum dulcificum? Miracle fruit from West Africa What is special about miracle fruit? Contains a protein called miraculin

More information

### Section A. A grammar that produces more than one parse tree for some sentences is said to be ambiguous.

Section A 1. What do you meant by parser and its types? A parser for grammar G is a program that takes as input a string w and produces as output either a parse tree for w, if w is a sentence of G, or

More information

### Syntax-Directed Translation. Lecture 14

Syntax-Directed Translation Lecture 14 (adapted from slides by R. Bodik) 9/27/2006 Prof. Hilfinger, Lecture 14 1 Motivation: parser as a translator syntax-directed translation stream of tokens parser ASTs,

More information

### LR Parsing Techniques

LR Parsing Techniques Bottom-Up Parsing - LR: a special form of BU Parser LR Parsing as Handle Pruning Shift-Reduce Parser (LR Implementation) LR(k) Parsing Model - k lookaheads to determine next action

More information

### Lexical Analysis. Introduction

Lexical Analysis Introduction Copyright 2015, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University of Southern California have explicit permission to make copies

More information

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

Bottom-up Parsing: Table-driven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and non-terminals. Basic operation is to shift terminals from the input to the

More information

### CSE P 501 Compilers. Parsing & Context-Free Grammars Hal Perkins Winter /15/ Hal Perkins & UW CSE C-1

CSE P 501 Compilers Parsing & Context-Free Grammars Hal Perkins Winter 2008 1/15/2008 2002-08 Hal Perkins & UW CSE C-1 Agenda for Today Parsing overview Context free grammars Ambiguous grammars Reading:

More information