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

Size: px
Start display at page:

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

Transcription

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 : Principles, Techniques and Tools Aho + Ullman, Theory of Parsing and Compiling, vol II. 1 TD Parsing Elimination of left recursion. E " E # \$ becomes E " \$ A A " # A % Example: S " E S " E E " E + T E " T A E " T A " + T A % T " id T " id Can also left factor the grammar removing shared prefixes of right-hand-sides. 2

2 Parse Tree E + T T S E + T i d i d T id S E A + T A id Parse tree converted from left recursive to right recursive. id + T A id % 3 TD Parsing Problem: predicting which nonterminal to expand next, from a leading string of symbols Idea: generate parse tree top down so its frontier is always a sentential form Use First and Follow sets to understand the shape of sentential forms possibly generated by the grammar 4

3 TD Stack Parser, EG Stack Input Production S " E \$S id+id+id\$ \$E id+id+id\$ S " E \$A T id+id+id\$ E " T A \$A +id+id\$ T " id \$A T id+id\$ A " + T A \$A +id\$ T " id \$A T id\$ A " + T A \$A \$ T " id \$ \$ A " % E " T A A " + T A % T " id See algm in ASU Fig 4.14, p How to mechanize? Define # to be string of nonterminals and terminals First(#) is the set of terminals that begin strings derivable from #. If # * %, then % is in First(#). Follow(A) is the set of terminals that can appear directly to the right of A in a sentential form S * # A a \$ means a is in Follow(A). If A can be rightmost symbol in a sentential form, that is, X * # & ' where ' * %, then Follow(A)( Follow(X). 6

4 Example First(S) = First(E) = First(T) = {id} First(A) = { +, % } Follow(S) = Follow(E) = Follow(A) = {\$} Follow(T) = {+, \$} S " E E " T A A " + T A % T " id 7 LL(k) Grammars Can choose next production to expand by during TD phase, by looking k symbols ahead into input Use First sets to choose production Use Follow sets to handle % cases 8

5 Example: LL(1) Nonterms\Inputs: id + \$ S S " E E E " T A T T " id A A " + T A A " % Ambiguous or left recursive grammars result in multiply defined entries in table First(S) = First(E) = First(T) = {id} First(A) = { +, % } Follow(S) = Follow(E) = Follow(A) = {\$} Follow(T) = {+, \$} S " E E " T A A " + T A % T " id 9 A View During TD Parsing S derives # ), a string of terminals; X is nonterminal at top of stack, X derives ); Initially X==S, # == %, ) is input S X partially constructed parse tree # ) 10

6 A View During BU Parsing * S rm # A w " # \$ w, rm so \$ is the handle. S # partially constructed parse tree A \$ w, a string of terminals 11 Intuitive Comparison S w x z LR(k) can recognize A " # knowing w, x, and First k (z). LL(k) can recognize A " # knowing only w and First k (x). Therefore, the set of languages recognizable by LR(k) contain those recognizable by LL(k). A # 12

7 BU Parsing (Shift-Reduce) Handle - part of sentential form last added in a rightmost derivation. BU parsing as handle hunting (1) S " * (2) * " * + + (3) * " T (4) T " id Rightmost derivation of a+b+c, handles in red S " E " * + + " * + id " * id " * + id + id " T + id + id " id + id + id 13 Shift-Reduce Parser, Example Actions: shift, reduce, accept, error Stack Input Action \$ id1 + id2 + id3 \$ shift \$ id1 + id2 + id3 \$ reduce (4) \$ T + id2 + id3 \$ reduce (3) \$ E + id2 + id3 \$ shift \$ E + id2 + id3 \$ shift \$ E + id2 + id3 \$ reduce(4) \$ E + T + id3 \$ reduce (2) \$ E + id3 \$ shift \$ E + id3 \$ shift \$ E + id3 \$ reduce (4) \$ E + T \$ reduce(2) \$ E \$ reduce (1) \$ S \$ accept (1) S " * (2) * " * + + (3) * " T (4) T " id 14

8 Problems Shift-reduce conflicts S " if E then S if E then S else S other On stack: if E then S Input: else Should shift trying for 2nd alternative or reduce by first rule? Reduce-reduce conflicts if A " # and B " # both in grammar When # on stack, how know which production to choose? 15 Predictive Parsing Top Down: LL(k), Bottom Up: LR(k) Avoids backtracking while parsing by using lookahead into input NO cases where more than 1 action possible 16

9 LR(k) Left to right scan parsing does a rightmost derivation in reverse, using k symbols of lookahead into input Three flavors Simple LR, SLR(1) Cheap Doesn t always work LR Most powerful Most expensive 17 LR(k) LALR Intermediate in cost and power All SLR(1) languages are also LR(1), but parsers generated by corresponding grammars for the same language will differ in size. LR(k) catches syntax errors as early as possible in a left-to-right scan of the input Covers most programming languages 18

10 LR Parsing DFA is embedded in parser which is a PDA (top stack, input_symbol) accesses a particular entry in the parser table Shift to state s Reduce by A " \$ Accept Error Goto: (state, top stack ) " state 19 LR Parser symbol state input state\input Action/ goto table stack 20

11 LR Parsing Viable prefix - set of prefixes of right sentential forms which can appear on a stack of a shift/reduce parser Prefix of right sentential form that doesn t contain symbols beyond the handle Goto function is transition function of DFA that recognizes viable prefixes of the grammar Idea: continue to stack inputs until have handle on top of stack and then reduce 21 Building an SLR Parser Need states, goto s, Follow sets Item - rule with embedded dot S ". * Closure of item I I, {B ".), if A " #. B \$ in I} States built from items and their closures 22

12 Example - States S " E I 0 : S ". E E " E + T E ". E + T E " + E ". + + " id + ". id Closure of S ". E I 1 : S " *. - 2 : E " +. * " *. + T I 3 : + " id. I 4 : * " * +. T T ". id I 5 : * " * + T. 23 Example - Goto s + Follow sets goto (0, E) = 1 goto (0, id) = 3 goto (0, T) = 2 goto (1, +) = 4 goto (4, T) = 5 goto (4, id) = 3 goto ({set of items}, X) = closure {[A " # X. \$] [A " #. X \$] in {set of items}} where X is a terminal or nonterminal Follow(S) = {\$} Follow(E) = Follow(T) = { +, \$} 24

13 Example - Parser Table si, shift to state I; r(j) reduce by rule j States\ inputs: id + \$ E T 0 s s4 accept 2 r(3) r(3) 3 r(4) r(4) 4 s3 5 5 r(2) r(2) goto s 25 Example Stack input action 0 id1 + id2 \$ s3 0 id1 3 + id2 \$ r(4), goto on T 0 T 2 + id2 \$ r(3), goto on E 0 E 1 + id2 \$ s4 0 E id2 \$ s3 0 E id2 3 \$ r(4), goto on T 0 E T 5 \$ r(2), goto on E 0 E 1 \$ accept 26

14 SLR(1) Parser Rules If A " #. a \$ is in state I j and goto(i j, a) is I r then (I j,, a) transitions by shift r (sr) If A " #. is in state I j, set action [j,a] to reduce A " # for all a in Follow(A) Note: A!= S If S " *. in I j, action (j,\$) is accept Any table entry not defined is error. 27 Problems Shift-reduce conflicts happen when Ab can occur in some sentential form and b. Follow(A). S " L = R I 0 : S ". L = R S " R S ". R L " * R R ". L L " id L ". * R R " L L ".!d I 1 : S " L. = R (1) R " L. (2) In I 1 shift when see = in input(item 1); reduce on = because = in Follow(R) (item 2). Note: S " L = R " * R = R, but this is not a rightmost derivation! 28

15 Problems, cont. Can see that rightmost derivation is: S " L = R " L = L "L = id " * R = id " *L = id " * id = id Therefore, should reduce *R to L when see =, not shift in order to get *R onto the stack. Problem is that we can t distinguish those Follow elements corresponding to a rightmost derivation in a specific context. 29 Nomenclature in ASU An item [ A " \$. ) ] is valid for viable prefix # \$ if S * # A w # \$ ) w. rm Means can continue towards accumulating an handle on the stack by shifting Previously, shift would have changed viable prefix *R to nonviable prefix *R= If I is set of items valid for viable prefix \$ then goto(i, X) is set of items valid for viable prefix \$X where X is terminal or nonterminal rm 30

16 LR Parsing LR items include a lookahead symbol, (into the input) which helps in conflict resolution Need new closure rule: For [ A " #. B ), a ] item add [B ". ', b] for every b in First() a). 31 Example I 0 : S ". E, \$ - initial item E ". * + +, \$ - closure initial item E ". T, \$ E ". E + T, + - closure 1st red item E ". +, + + ".id, \$ - closure 2nd red item T ".id, + - closure 2nd blue item Will write these in more compact form by combining lookaheads. For [ A " #. B ), a ] item add [B ". ', b] for every b in First() a). 32

17 Example, LR(1) Parser I 0 :S ".E, \$ I 1 : [goto (I 0, E)] E ".E + T, \$/+ S " E., \$ E ". T, \$/+ S " E. + T, \$/+ T ".id, +/\$ I 2 :[goto (I 0, T)] I 4 :[goto(i 1, +)] E " T., \$/+ E " * +. +, \$/+ I 3 : [goto (I 0, id)] T ". id, \$/+ T " id., \$/+ I 5 : [goto (I 4, T)] E " * + +., \$/+ 33 LR(1) Parser Reduce based on lookaheads in item which are a subset of Follow set Rules similar to SLR Shift in I k, [A " #. a \$, b], goto (I k, a) = I j Reduce [A " #., b] reduce # to A on b Accept [S " E., \$], accept on \$ 34

18 LALR Parsing Idea: merge all states with common first components in their LR(1) items Implementation problem: need to reduce number of states to get smaller parser table Reduced size parser will perform Same as LR on correct inputs (will be parsed by LALR) On incorrect inputs, LR may find error faster; LALR will never do an incorrect shift but may do some wrong reductions 35 LALR Parsing Conceptually, build LALR(1) parser from LR(1) parser Merge all states with same first components Union all goto s of these merged states (goto s are independent of second components) Correctness of conceptual derivation Can never produce a shift-reduce conflict or else [A " #., a] and [B "\$. a ), b] existed in some LR(1) state 36

19 LALR, cont. But can create reduce-reduce conflicts State 1 State 2 [A " c., d] [A " c., e] [B " c., e] [B " c., d] After merge: [A " c., d/e] [B " c., e/d] 37 Handles (Informal) Show the handle always remains on the top of the stack in shift-reduce parsing Assume ) B w is a right sentential form with ) B on the stack. 1. Assume handle includes B. * handle S # 1 A # 2 # 1 \$ 1 / \$ 2 # 2 rm rm ) w where \$ 1 or \$ 2 can be %. 38

20 Handles (Informal) 2. Assume handle included in w. S * # 1 / # 2 A # 3 # 1 B # 2 \$ # 3 3. Assume handle included in ). * rm S # 1 & # 2 # 1 \$ B w rm rm But if \$ is handle, then A isn t rightmost nonterminal, B is. This is a contradiction! rm handle ) ) handle w 39 Handles, More Formally A " \$ 1. \$ 2 valid for viable prefix # \$ * 1 means 0 S # A w # \$ 1 \$ 2 w rm If \$ 2 = % then should reduce by A " \$ 1 If \$ 2!= % then should shift Note can have two valid items indicating different actions for same viable prefix A " \$ 1. \$ 2 and A " \$ 1. Lookahead chooses which action is taken rm 40

21 Handles, More Formally Previous argument shows if A " \$. is valid item for viable prefix # \$ then # A is viable prefix (i.e., we needn t rescan the parse after a reduction) 41 Ambiguous Grammars Used to build compact parse trees Get rid of useless nonterminal to nonterminal productions (e.g., S-->E-->T) Conflicts resolvable through desired properties of operators (e.g., precedence) Generate smaller parsers Example of expression grammar 42

22 Example S " E I 0 : S ". * - 1 : goto (I 0,E) E " * + * * ". * + * S " E. E " id E ". id E " E. + E I 2 : goto (- 1,+) I 3 : goto (- 2,E) I 4 :goto(- 0,id) E " E +. E E " E + E. E " id. E ". * + * * " E. + E E ". id (reduce on + in Follow(E) shift on +) Choose reduce action making + left associative; can resolve operator precedences the same way (e.g., + versus *) 43 Grammar Classification CFL {0 n 1 n n >= 1} union {0 n 1 2n n >= 1} LR(k) ~ LR(1) SLR(k) LL(k) LALR(k) S " L = R R L " *R a R " L 44

### 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/

### 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

### 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

### 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

### 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

### 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

### 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

### Bottom up parsing. The sentential forms happen to be a right most derivation in the reverse order. S a A B e a A d e. a A d e a A B e S.

Bottom up parsing Construct a parse tree for an input string beginning at leaves and going towards root OR Reduce a string w of input to start symbol of grammar Consider a grammar S aabe A Abc b B d And

### 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

### 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

### 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

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:

### 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

### Lecture Bottom-Up Parsing

Lecture 14+15 Bottom-Up Parsing CS 241: Foundations of Sequential Programs Winter 2018 Troy Vasiga et al University of Waterloo 1 Example CFG 1. S S 2. S AyB 3. A ab 4. A cd 5. B z 6. B wz 2 Stacks in

### 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

### 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

### 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

### UNIT-III BOTTOM-UP PARSING

UNIT-III BOTTOM-UP PARSING Constructing a parse tree for an input string beginning at the leaves and going towards the root is called bottom-up parsing. A general type of bottom-up parser is a shift-reduce

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

Formal Languages and Compilers Lecture VII Part 4: 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/

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

8 Parsing Parsing A grammar describes syntactically legal strings in a language A recogniser simply accepts or rejects strings A generator produces strings A parser constructs a parse tree for a string

### 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

### LALR Parsing. What Yacc and most compilers employ.

LALR Parsing Canonical sets of LR(1) items Number of states much larger than in the SLR construction LR(1) = Order of thousands for a standard prog. Lang. SLR(1) = order of hundreds for a standard prog.

### 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

### 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

### 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

### 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

### 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

### 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

### CS308 Compiler Principles Syntax Analyzer Li Jiang

CS308 Syntax Analyzer Li Jiang Department of Computer Science and Engineering Shanghai Jiao Tong University Syntax Analyzer Syntax Analyzer creates the syntactic structure of the given source program.

### LR Parsers. Aditi Raste, CCOEW

LR Parsers Aditi Raste, CCOEW 1 LR Parsers Most powerful shift-reduce parsers and yet efficient. LR(k) parsing L : left to right scanning of input R : constructing rightmost derivation in reverse k : number

### 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

### 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

WWW.STUDENTSFOCUS.COM UNIT -3 SYNTAX ANALYSIS 3.1 ROLE OF THE PARSER Parser obtains a string of tokens from the lexical analyzer and verifies that it can be generated by the language for the source program.

### 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

### 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

### 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

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

Top-Down Parsing and Intro to Bottom-Up Parsing Lecture 7 1 Predictive Parsers Like recursive-descent but parser can predict which production to use Predictive parsers are never wrong Always able to guess

### 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)

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

Top-Down Parsing and Intro to Bottom-Up Parsing Lecture 7 1 Predictive Parsers Like recursive-descent but parser can predict which production to use Predictive parsers are never wrong Always able to guess

### Principle of Compilers Lecture IV Part 4: Syntactic Analysis. Alessandro Artale

Free University of Bolzano Principles of Compilers Lecture IV Part 4, 2003/2004 AArtale (1) Principle of Compilers Lecture IV Part 4: Syntactic Analysis Alessandro Artale Faculty of Computer Science Free

### Example CFG. Lectures 16 & 17 Bottom-Up Parsing. LL(1) Predictor Table Review. Stacks in LR Parsing 1. Sʹ " S. 2. S " AyB. 3. A " ab. 4.

Example CFG Lectures 16 & 17 Bottom-Up Parsing CS 241: Foundations of Sequential Programs Fall 2016 1. Sʹ " S 2. S " AyB 3. A " ab 4. A " cd Matt Crane University of Waterloo 5. B " z 6. B " wz 2 LL(1)

### 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,

### 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

### 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

### 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

### 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.

### SLR parsers. LR(0) items

SLR parsers LR(0) items As we have seen, in order to make shift-reduce parsing practical, we need a reasonable way to identify viable prefixes (and so, possible handles). Up to now, it has not been clear

### Bottom-Up Parsing II. Lecture 8

Bottom-Up Parsing II Lecture 8 1 Review: Shift-Reduce Parsing Bottom-up parsing uses two actions: Shift ABC xyz ABCx yz Reduce Cbxy ijk CbA ijk 2 Recall: he Stack Left string can be implemented by a stack

### 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

### 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

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

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 ----

### Syn S t yn a t x a Ana x lysi y s si 1

Syntax Analysis 1 Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token, tokenval Get next token Parser and rest of front-end Intermediate representation Lexical error Syntax

### LR(0) Parsing Summary. LR(0) Parsing Table. LR(0) Limitations. A Non-LR(0) Grammar. LR(0) Parsing Table CS412/CS413

LR(0) Parsing ummary C412/C41 Introduction to Compilers Tim Teitelbaum Lecture 10: LR Parsing February 12, 2007 LR(0) item = a production with a dot in RH LR(0) state = set of LR(0) items valid for viable

### 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 ----

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

CS 2210 Sample Midterm 1. Determine if each of the following claims is true (T) or false (F). F A language consists of a set of strings, its grammar structure, and a set of operations. (Note: a language

### COMPILER (CSE 4120) (Lecture 6: Parsing 4 Bottom-up Parsing )

COMPILR (CS 4120) (Lecture 6: Parsing 4 Bottom-up Parsing ) Sungwon Jung Mobile Computing & Data ngineering Lab Dept. of Computer Science and ngineering Sogang University Seoul, Korea Tel: +82-2-705-8930

### 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,

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

Building a Parser III CS164 3:30-5:00 TT 10 Evans 1 Overview Finish recursive descent parser when it breaks down and how to fix it eliminating left recursion reordering productions Predictive parsers (aka

### 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

### LL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012

Predictive Parsers LL(k) Parsing Can we avoid backtracking? es, if for a given input symbol and given nonterminal, we can choose the alternative appropriately. his is possible if the first terminal of

### 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:

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

CS1622 Lecture 9 Parsing (4) CS 1622 Lecture 9 1 Today Example of a recursive descent parser Predictive & LL(1) parsers Building parse tables CS 1622 Lecture 9 2 A Recursive Descent Parser. Preliminaries

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

### 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

### Compilers. Predictive Parsing. Alex Aiken

Compilers Like recursive-descent but parser can predict which production to use By looking at the next fewtokens No backtracking Predictive parsers accept LL(k) grammars L means left-to-right scan of input

### Bottom-Up Parsing II (Different types of Shift-Reduce Conflicts) Lecture 10. Prof. Aiken (Modified by Professor Vijay Ganesh.

Bottom-Up Parsing II Different types of Shift-Reduce Conflicts) Lecture 10 Ganesh. Lecture 10) 1 Review: Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient Doesn

### Bottom-Up Parsing LR Parsing

Bottom-Up Parsing LR Parsing Maryam Siahbani 2/19/2016 1 What we need for LR parsing LR0) states: Describe all possible states in which parser can be Parsing table ransition between LR0) states Actions

### SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram

CS6660 COMPILER DESIGN Question Bank UNIT I-INTRODUCTION TO COMPILERS 1. Define compiler. 2. Differentiate compiler and interpreter. 3. What is a language processing system? 4. List four software tools

### 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

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

Ambiguity, Precedence, Associativity & Top-Down Parsing Lecture 9-10 (From slides by G. Necula & R. Bodik) 9/18/06 Prof. Hilfinger CS164 Lecture 9 1 Administrivia Please let me know if there are continued

### 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

### Concepts Introduced in Chapter 4

Concepts Introduced in Chapter 4 Grammars Context-Free Grammars Derivations and Parse Trees Ambiguity, Precedence, and Associativity Top Down Parsing Recursive Descent, LL Bottom Up Parsing SLR, LR, LALR

### 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

### LR Parsing LALR Parser Generators

LR Parsing LALR Parser Generators Outline Review of bottom-up parsing Computing the parsing DFA Using parser generators 2 Bottom-up Parsing (Review) A bottom-up parser rewrites the input string to the

### 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

### 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/

### Conflicts in LR Parsing and More LR Parsing Types

Conflicts in LR Parsing and More LR Parsing Types Lecture 10 Dr. Sean Peisert ECS 142 Spring 2009 1 Status Project 2 Due Friday, Apr. 24, 11:55pm The usual lecture time is being replaced by a discussion

### LR Parsing - The Items

LR Parsing - The Items Lecture 10 Sections 4.5, 4.7 Robb T. Koether Hampden-Sydney College Fri, Feb 13, 2015 Robb T. Koether (Hampden-Sydney College) LR Parsing - The Items Fri, Feb 13, 2015 1 / 31 1 LR

### Table-Driven Parsing

Table-Driven Parsing It is possible to build a non-recursive predictive parser by maintaining a stack explicitly, rather than implicitly via recursive calls [1] The non-recursive parser looks up the production

### Review: Shift-Reduce Parsing. Bottom-up parsing uses two actions: Bottom-Up Parsing II. Shift ABC xyz ABCx yz. Lecture 8. Reduce Cbxy ijk CbA ijk

Review: Shift-Reduce Parsing Bottom-up parsing uses two actions: Bottom-Up Parsing II Lecture 8 Shift ABC xyz ABCx yz Reduce Cbxy ijk CbA ijk Prof. Aiken CS 13 Lecture 8 1 Prof. Aiken CS 13 Lecture 8 2

### 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

### LR Parsing LALR Parser Generators

Outline LR Parsing LALR Parser Generators Review of bottom-up parsing Computing the parsing DFA Using parser generators 2 Bottom-up Parsing (Review) A bottom-up parser rewrites the input string to the

### Acknowledgements. The slides for this lecture are a modified versions of the offering by Prof. Sanjeev K Aggarwal

Acknowledgements The slides for this lecture are a modified versions of the offering by Prof. Sanjeev K Aggarwal Syntax Analysis Check syntax and construct abstract syntax tree if == = ; b 0 a b Error

### ECE 468/573 Midterm 1 October 1, 2014

ECE 468/573 Midterm 1 October 1, 2014 Name: Purdue email: Please sign the following: I affirm that the answers given on this test are mine and mine alone. I did not receive help from any person or material

### 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

### Syntax Analyzer --- Parser

Syntax Analyzer --- Parser ASU Textbook Chapter 4.2--4.9 (w/o error handling) Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 A program represented by a sequence of tokens

### Automatic generation of LL(1) parsers

Automatic generation of LL(1) parsers Informatics 2A: Lecture 12 John Longley School of Informatics University of Edinburgh jrl@staffmail.ed.ac.uk 14 October, 2011 1 / 12 Generating parse tables We ve

### 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

### Syntax Analysis Part I

Syntax Analysis Part I Chapter 4: Context-Free Grammars Slides adapted from : Robert van Engelen, Florida State University Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token,

### Lecture 14: Parser Conflicts, Using Ambiguity, Error Recovery. Last modified: Mon Feb 23 10:05: CS164: Lecture #14 1

Lecture 14: Parser Conflicts, Using Ambiguity, Error Recovery Last modified: Mon Feb 23 10:05:56 2015 CS164: Lecture #14 1 Shift/Reduce Conflicts If a DFA state contains both [X: α aβ, b] and [Y: γ, a],

### CS606- compiler instruction Solved MCQS From Midterm Papers

CS606- compiler instruction Solved MCQS From Midterm Papers March 06,2014 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 Final Term MCQ s and Quizzes CS606- compiler instruction If X is a

VIVA QUESTIONS WITH ANSWERS 1. What is a compiler? A compiler is a program that reads a program written in one language the source language and translates it into an equivalent program in another language-the

### JavaCC Parser. The Compilation Task. Automated? JavaCC Parser

JavaCC Parser The Compilation Task Input character stream Lexer stream Parser Abstract Syntax Tree Analyser Annotated AST Code Generator Code CC&P 2003 1 CC&P 2003 2 Automated? JavaCC Parser The initial

### 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

### BSCS Fall Mid Term Examination December 2012

PUNJAB UNIVERSITY COLLEGE OF INFORMATION TECHNOLOGY University of the Punjab Sheet No.: Invigilator Sign: BSCS Fall 2009 Date: 14-12-2012 Mid Term Examination December 2012 Student ID: Section: Morning

### Review of CFGs and Parsing II Bottom-up Parsers. Lecture 5. Review slides 1

Review of CFGs and Parsing II Bottom-up Parsers Lecture 5 1 Outline Parser Overview op-down Parsers (Covered largely through labs) Bottom-up Parsers 2 he Functionality of the Parser Input: sequence of

### 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).

LL(k) Grammars We need a bunch of terminology. For any terminal string a we write First k (a) is the prefix of a of length k (or all of a if its length is less than k) For any string g of terminal and

### CSC 4181 Compiler Construction. Parsing. Outline. Introduction

CC 4181 Compiler Construction Parsing 1 Outline Top-down v.s. Bottom-up Top-down parsing Recursive-descent parsing LL1) parsing LL1) parsing algorithm First and follow sets Constructing LL1) parsing table