BottomUp Parsing. Parser Generation. LR Parsing. Constructing LR Parser


 Jayson Whitehead
 3 years ago
 Views:
Transcription
1 Parser Generation Main Problem: given a grammar G, how to build a topdown parser or a bottomup parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence  if done sucessfully, it recognize the sentence all parsers read their input lefttoright, but construct parse tree differently. bottomup parsers  construct the tree from leaves to root BottomUp Parsing Construct parse tree bottomup  from leaves to the root Bottomup parsing always constructs rightmost derivation Important parsing algorithms: shiftreduce, LR parsing LR parser components: input, stack (strings of grammar symbols and states), driver routine, parsing tables. input: a 1 a 2 a 3 a 4... a n $ shiftreduce, LR, LR, LLR, operator precedence topdown parsers  construct the tree from root to leaves recursive descent, predictive parsing, LL(1) stack s m X m.. s 1 X 1 s 0 LR Parsing parsing output Copyright Zhong hao, Yale University Parser Generation: Page 1 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 2 of 27 LR Parsing sequence of new state symbols s 0, s 1, s 2,..., s m each state sumarize the information contained in the stack below it. Parsing configurations: (stack, remaining input) written as (s 0 X 1 s 1 X 2 s 2...X m s m, a i a i+1 a i+2...a n $) next move is determined by s m and a i Parsing tables: CTION[s,a] and GOTO[s,X] Table CTION[s,a]  s : state, a : terminal its entries (1) shift s k (2) reduce > (3) accept (4) error Table G GOTO[s,X]  s : state, X : nonterminal its entries are states Constructing LR Parser How to construct the parsing table CTION and GOTO? basic idea: first construct DF to recognize handles, then use DF to construct the parsing tables! different parsing table yield different LR parsers LR(1), LR(1), or LLR(1) augmented grammar for contextfree grammar G = G(T,N,P,) is defined as G = G (T, N { }, P { > }, ) adding nonterminal and the production >, and is the new start symbol. When > is reduced, parser accepts. LR(0) item for productions of a contextfree grammar G is a production with dot at some position in the r.h.s. For > XYZ, its items are >.XYZ > X.YZ > XY.Z > XYZ. For >, its items are just >. Copyright Zhong hao, Yale University Parser Generation: Page 3 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 4 of 27
2 LR(0) items and LR(0) DF Informally, item > X.YZ means a string derivable from X has been seen, and one from YZ is expected. LR(0) items are used as state names for LR(0) DF or LR(0) NF that recognizes viable prefixes. Viable prefixes of a CFG are prefixes of rightsentential forms with no symbols to right of the handle; we can always add terminals on right to form a rightsentential form. Two way to construct the LR(0) DF: 1. first construct LR(0) NF and then convert it to a DF! 2. construct the LR(0) DF directly! From LR(0) DF to the Parsing Table transition table for the DF is the GOTO table; the states of DF are states of the parser. Example: LR(0) Items CFG Grammar: E > E + T T T > T * F F ugmented Grammar: LR(0) terms: E > E E > E + T T T > T * F F E >. E T >. T * F F > ( E. ) E > E. T > T. * F F > ( E ). E >. E + T T > T *. F F >. id E > E. + T T > T * F. F > id. E > E +. T T >. F E > E + T. T > F. E >. T F >. ( E ) E > T. F > (. E ) Copyright Zhong hao, Yale University Parser Generation: Page 5 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 6 of 27 From LR(0) NF to LR(0) DF Construct LR(0) NF with all LR(0) items of G as states, connect states by moving the dot; final states are those with dots at the end. 1. for each item >.X >.X > X. 2. for each pair >.B, B >. (expect to see a string derivable from ) >.B B >. Convert NF to DF using subset construction algorithm. The states of the resulting LR(0) DF  C = {I 1,I 2,..., I n } are called canonical LR(0) collection for grammar G Disadvantage: the NF is often huge, and converting from NF to DF is tedious and timeconsuming. X Building LR(0) DF Directly Instead of building DF from NF, we can build the LR(0) DF directly. Given a set of LR(0) items I, CLOURE(I) is defined as for each item >.B in I and each production B > add B >. to I, if it s not in I until I does not change GOTO(I,X) is defined as CLOURE(all items > X. for each >.X in I) Canonical LR(0) collection is computed by the following procedure: I 0 = CLOURE({ >.}) and C = {I 0 } for each I C and grammar symbol X T = GOTO(I,X); if T and T C then C = C { T }; until C does not change Resulting LR(0) DF: C is the set of states; GOTO is the transition table Copyright Zhong hao, Yale University Parser Generation: Page 7 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 8 of 27
3 Constructing LR(1) Parsing Table From the LR(0) DF, we can construct the parsing table LR(1) parsing table. The parser based on LR(1) parsing table is called LR(1) parser. The LR(1) grammars are those whose LR(1) parsing table does not contain any conflicts. lgorithm  use C = {I 0,...,I n }, GOTO, FOLLOW: 1. If > a.a is in I i and GOTO(I i,a) = I j where a is a terminal, set CTION[i,a] to shift j. 2. If >. is in I i, set CTION[i,a] to reduce > for all terminal a in FOLLOW(). 3. If >. is in I i, set CTION[ i,$] to accept 4. If GOTO(I i,) = I j, set GOTO[i,] = j 5. set all other entries to error 6. set initial state to be I i with >. Limitation of LR(1) Parser Unfortunately, many unambiguous grammars are not LR(1) gammars > L = R R L > *R id R > L Canonical LR(0) collection  L means lvalue R means rvalue * means contents of I0 : >. I3: > R. I6: > L=.R >.L=R R >.L >.R I4: L > *.R L >.*R L >.*R R >.L L >.id L >.id L >.*R R >.L L >.id I7: L > *R. I1 : >. I5: L > id. I8: R > L. I2 : > L.=R I9: > L=R. R > L. FOLLOW(R) = {=,...} state 2 has a shift/reduce conflict on = : shift 6 or reduce R > L Copyright Zhong hao, Yale University Parser Generation: Page 9 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 10 of 27 LR(1) Parsing Conflict arises because LR(0) states do not encode enough left context  in the previous example, reduction R > L is wrong upon input = because R =... never appears in rightsentential form. olution: split LR(0) states by adding terminals to states, for example, [  >., a] results in reduction only if next symbol is a. n LR(1) term is in the form of [ >., a ] where > is a production and a is a terminal or $ To build LR(1) parsing table  we first build LR(1) DF  then construct the parsing table using the same LR(1) algorithm except 2. only if [ >., a] is in I i, then set CTION[i,a] to reduce > To way to build LR(1) DF  from NF > DF or build DF directly Building LR(1) DF Construct LR(1) NF with all LR(1) items of G as states, connect states by moving the dot; then convert the NF to DF. 1. for each item [ >.X,a] Construct the LR(1) DF directly (see the Dragon book) Given a set of LR(1) items I, >.X a 2. for each pair [ >.B, a] B >. and b in FIRT( a ). >.B a CLOURE(I) is now defined as for each item [ >.B, a] in I and each production B > and each terminal b in FIRT( a) add [B >. a] to I, if it s not in I until I does not change X > X. a B >. b Copyright Zhong hao, Yale University Parser Generation: Page 11 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 12 of 27
4 Constructing LR(1) Parser Canonical LR(1) collection is computed by the following procedure: I 0 = CLOURE([ >., $]) and C = {I 0 } for each I C and grammar symbol X T = GOTO(I,X); if T and T C then C = C { T }; until C does not change Resulting LR(1) DF: C is the set of states; GOTO is the transition table From the LR(1) DF, we can construct the parsing table LR(1) parsing table. The parser based on LR(1) parsing table is called LR(1) parser. The LR(1) grammars are those whose LR(1) parsing table does not contain any conflicts (no duplicate entries). Example: > > C C C > c C d LLR(1) Parsing Bad News: LR(1) parsing tables are too big; for PCL, LR tables has about 100 states, LR table has about 1000 states. LLR (LookheadLR) parsing tables have same number of states as LR, but use lookahead for reductions. The LLR(1) DF can be constructed from the LR(1) DF. LLR(1) states can be constructed from LR(1) states by merging states with same core, or same LR(0) items, and union their lookahead sets. Merging I8: C > cc., c/d I9: C > cc., $ into a new state I89: C > cc., c/d/$ Merging I3: C > c.c, c/d I6: C > c.c, $ C >.cc, c/d C >.cc, $ C >.d, c/d C >.d, $ into a new state I36: C > c.c, c/d/$ C >.cc, c/d/$ C >.d, c/d/$i Copyright Zhong hao, Yale University Parser Generation: Page 13 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 14 of 27 LLR(1) Parsing (cont d) From the LLR(1) DF, we can construct the parsing table LLR(1) parsing table. The parser based on LLR(1) parsing table is called LLR(1) parser. The LLR(1) grammars are those whose LLR(1) parsing table does not contain any conflicts (no duplicate entries). LLR(1) DF and LLR(1) parsing table can be constructed without creating LR(1) DF  see Dragon book for detailed algorithm. LLR parser makes same number of moves as LR parser on correct input. On incorrect input, LLR parser may make erroneous reductions, but will signal error before shifting input, i.e., merging states makes reduce determination less accurate, but has no effect on shift actions. ummary: LR Parser Relation of three LR parsers: LR(1) > LLR(1) > LR(1) Most programming language constructs are LLR(1). The LR(1) is unnecessary in practice, but the LR(1) is not enough. YCC is an LLR(1) Parser Generator. When parsing ambiguious grammars using LR parsers, the parsing table will contain multiple entries. We can specify the precedence and associativity for terminals and productions to resolve the conflicts. YCC uses this trick. Other Issues in parser implementation: 1. compact representation of parsing table 2. error recovery and diagnosis. Copyright Zhong hao, Yale University Parser Generation: Page 15 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 16 of 27
5 TopDown Parsing tarting from the start symbol and guessing which production to use next step. It often uses next input token to guide guessing. example: > c d > ab a TopDown Parsing (cont d) Typical implementation is to write a recursive procedure for each nonterminal (according to the r.h.s. of each grammar rule) advance sets c to next input token Grammar: err reports error message input symbols: cad we are looking ahead only one at a time! c c matches d c a try to decide which rule of to use here? b d decide to use 1st alternative of c backtrack! a d guessed wrong, backtrack and try another one! E > T E E > + T E T > F T T > * F T F > id ( E ) fun e() = (t(); eprime()) and eprime() = if (c = + ) then (advance(); t(); eprime()) and t() = (f(); tprime()) and tprime() = if (c = * ) then (advance(); f(); tprime()) and f() = (if (c = id) then advance() else if (c = ( ) then (advance(); e(); if (c= ) ) then advance() else err()) else err() Copyright Zhong hao, Yale University Parser Generation: Page 17 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 18 of 27 Recursive Descent Parsing The previously referred topdown parsing method is often called recursive descent parsing! Main challenges: 1. backtracking is messy, difficult and inefficient (solution: use input lookahead to help make the right choice) 2. more alternatives  even if we use one lookahead input char, there are still > 1 rules to choose  > ab a (solution: rewrite the grammar by leftfactoring) 3. leftrecursion might cause infinite loop what is the procedure for E > E + E? (solution: rewrite the grammar by eliminating leftrecursions) 4. error handling  errors detected far away from actual source. lgorithm: Recursive Descent Parsing lgorithm (using 1symbol lookahead in the input) 1. Given a set of grammar rules for a nonterminal > n we choose proper alternative by looking at first symbol it derives  next input symbol decides which i we use 2. for >, it is taken when none of the others are selected lgorithm: constructing a recursive descent parser for grammar G 1. transform grammer G to G by removing leftrecursions and do the leftfactoring. 2. write a (recursive) procedure for each nonterminal in G the Copyright Zhong hao, Yale University Parser Generation: Page 19 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 20 of 27
6 Left Recursion Elimination Elimination of Left Recursion (useful for topdown parsing only) replace productions of the form with Important: read ppel pp for details > > > (yields different parse trees but same language) example: E > E + T T T > T * F F become E > T E E > + T E T > F T T > * F T Left Factoring ome grammars are unsuitable for recursive descent, even if there is no left recursion danglingelse stmt > if expr then stmt if expr then stmt else stmt... input symbol if does not uniquely determine alternative. Left Factoring  factor out the common prefixes (see HU pp 178) change the production > x y x z to > x > y z thus stmt > if expr then stmt > else stmt Copyright Zhong hao, Yale University Parser Generation: Page 21 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 22 of 27 Predictive Parsing Predictive parsing is just tabledriven recursive descent; it contains: parsing stack  contains terminals and nonterminals parsing table : a 2dimensional table M[X,a] where X is nonterminal, a is terminal, and table entries are grammar productions or error indicators. algorithm $ is endoffile, is start symbol push($); push(); while top <> $ do ( a < the input char if top is a terminal or $ then (if top == a then pop(); advance() else err()) else if M[top,a] is X>Y 1 Y 2...Y k then (pop(); push(y k );...; push(y 1 )) else err() ) input: X... Y Z $ stack a 1 a 2 a 3 a 4... a n $ Predictive Parser Parsing Table M output Constructing Predictive Parser The key is to build the parse table M[,a] for each production > do for each a FIRT( ) do add > to M[,a] if FIRT( ) then for each b FOLLOW() do add > to M[,b] rest of M is error FIRT( ) is a set of terminals (plus ) that begin strings derived from, where is any string of nonterminals and terminals. FOLLOW() is a set of terminals that can follow in a sentential form, where is any nonterminal Copyright Zhong hao, Yale University Parser Generation: Page 23 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 24 of 27
7 First & Follow To compute FIRT(X) for any grammar symbol X : FIRT(X) = {X}, if X is a terminal; FIRT(X) = FIRT(X) {a}, if X > a ; FIRT(X) = FIRT(X) { }, if X > ; and FIRT(X) = FIRT(X) FIRT(Y 1 Y 2...Y k ), if X > Y 1 Y 2...Y k. until nothing new is added to any FIRT FIRT(Y 1 Y 2...Y k ) = FIRT(Y 1 ){ } FIRT(Y 2 ){ } if FIRT(Y 1 ) FIRT(Y 3 ){ } if FIRT(Y 1 Y 2 )... FIRT(Y k ){ } if FIRT(Y 1...Y k1 ) { } if all FIRT(Y i ) (i=1,...,k) contain First & Follow (cont d) To compute FOLLOW(X) for any nonterminal X : FOLLOW() = FOLLOW() {$}, if is start symbol; FOLLOW(B) = FOLLOW(B) (FIRT( )  { }), if > B and FOLLOW(B) = FOLLOW(B) FOLLOW() if > B or > B and FIRT( ) Example: reason FOLLOW(E) = {$}, E is start symbol = {$ )}, F > ( E ) FOLLOW(E )= FOLLOW(E) E > T E = {$ )}, (Read ppel pp for detailed examples) Copyright Zhong hao, Yale University Parser Generation: Page 25 of 27 Copyright Zhong hao, Yale University Parser Generation: Page 26 of 27 ummary: LL(1) Grammars grammar is LL(1) if parsing table M[,a] has no duplicate entries, which is equivalent to specifying that for each production 1. ll FIRT( i ) are disjoint. > n 2. t most one i can derive ; in that case, FOLLOW() must be disjoint from FIRT( 1 ) FIRT( 2 ) FIRT( n ) Leftrecursion and ambiguity grammar lead to multiple entries in the parsing table. (try the danglingelse example) The main difficulty in using (topdown) predicative parsing is in rewriting a grammar into an LL(1) grammar. There is no general rule on how to resolve multiple entries in the parsing table. Copyright Zhong hao, Yale University Parser Generation: Page 27 of 27
Parser Generation. BottomUp Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottomup  from leaves to the root
Parser Generation Main Problem: given a grammar G, how to build a topdown parser or a bottomup parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence 
More informationLR Parsing Techniques
LR Parsing Techniques BottomUp Parsing  LR: a special form of BU Parser LR Parsing as Handle Pruning ShiftReduce Parser (LR Implementation) LR(k) Parsing Model  k lookaheads to determine next action
More informationBottomup parsing. BottomUp Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form
Bottomup parsing Bottomup 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 informationContextfree grammars
Contextfree grammars Section 4.2 Formal way of specifying rules about the structure/syntax of a program terminals  tokens nonterminals  represent higherlevel structures of a program start symbol,
More informationCompiler Construction: Parsing
Compiler Construction: Parsing Mandar Mitra Indian Statistical Institute M. Mitra (ISI) Parsing 1 / 33 Contextfree grammars. Reference: Section 4.2 Formal way of specifying rules about the structure/syntax
More informationSection 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 informationLR Parsing Techniques
LR Parsing Techniques Introduction BottomUp Parsing LR Parsing as Handle Pruning ShiftReduce Parser LR(k) Parsing Model Parsing Table Construction: SLR, LR, LALR 1 BottomUP Parsing A bottomup parser
More informationSYNTAX 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 informationPrinciples 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 informationLet 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 informationParsing. 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 informationA leftsentential form is a sentential form that occurs in the leftmost derivation of some sentence.
Bottomup 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 leftsentential form is a sentential form that occurs
More informationFormal Languages and Compilers Lecture VII Part 4: Syntactic A
Formal Languages and Compilers Lecture VII Part 4: Syntactic Analysis Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationParsing Wrapup. Roadmap (Where are we?) Last lecture Shiftreduce parser LR(1) parsing. This lecture LR(1) parsing
Parsing Wrapup Roadmap (Where are we?) Last lecture Shiftreduce parser LR(1) parsing LR(1) items Computing closure Computing goto LR(1) canonical collection This lecture LR(1) parsing Building ACTION
More informationParsing #1. Leonidas Fegaras. CSE 5317/4305 L3: Parsing #1 1
Parsing #1 Leonidas Fegaras CSE 5317/4305 L3: Parsing #1 1 Parser source file get next character scanner get token parser AST token A parser recognizes sequences of tokens according to some grammar and
More informationMODULE 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 informationCSE 401 Compilers. LR Parsing Hal Perkins Autumn /10/ Hal Perkins & UW CSE D1
CSE 401 Compilers LR Parsing Hal Perkins Autumn 2011 10/10/2011 200211 Hal Perkins & UW CSE D1 Agenda LR Parsing Tabledriven Parsers Parser States ShiftReduce and ReduceReduce conflicts 10/10/2011
More informationCSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D1
CSE P 501 Compilers LR Parsing Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 D1 Agenda LR Parsing Tabledriven Parsers Parser States ShiftReduce and ReduceReduce conflicts UW CSE P 501 Spring 2018
More information3. 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 informationPrinciple 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
More informationS 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 informationFormal Languages and Compilers Lecture VII Part 3: Syntactic A
Formal Languages and Compilers Lecture VII Part 3: Syntactic Analysis Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationChapter 3. Parsing #1
Chapter 3 Parsing #1 Parser source file get next character scanner get token parser AST token A parser recognizes sequences of tokens according to some grammar and generates Abstract Syntax Trees (ASTs)
More informationPART 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 informationLALR 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.
More informationCSCI312 Principles of Programming Languages
Copyright 2006 The McGrawHill 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 McGrawHill
More informationWWW.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.
More informationParsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones
Parsing III (Topdown parsing: recursive descent & LL(1) ) (Bottomup parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,
More informationTabledriven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and nonterminals.
Bottomup Parsing: Tabledriven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and nonterminals. Basic operation is to shift terminals from the input to the
More informationLR 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 informationMonday, 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 nonterminals S is the start symbol P is the set of productions
More informationCSC 4181 Compiler Construction. Parsing. Outline. Introduction
CC 4181 Compiler Construction Parsing 1 Outline Topdown v.s. Bottomup Topdown parsing Recursivedescent parsing LL1) parsing LL1) parsing algorithm First and follow sets Constructing LL1) parsing table
More informationshiftreduce parsing
Parsing #2 Bottomup 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 bottomup
More informationMIT 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 informationBottom 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
More informationParsing III. (Topdown parsing: recursive descent & LL(1) )
Parsing III (Topdown parsing: recursive descent & LL(1) ) Roadmap (Where are we?) Previously We set out to study parsing Specifying syntax Contextfree grammars Ambiguity Topdown parsers Algorithm &
More informationNote 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
More informationSyntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38
Syntax Analysis Martin Sulzmann Martin Sulzmann Syntax Analysis 1 / 38 Syntax Analysis Objective Recognize individual tokens as sentences of a language (beyond regular languages). Example 1 (OK) Program
More informationSyntactic Analysis. TopDown Parsing
Syntactic Analysis TopDown 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 informationLR Parsers. Aditi Raste, CCOEW
LR Parsers Aditi Raste, CCOEW 1 LR Parsers Most powerful shiftreduce parsers and yet efficient. LR(k) parsing L : left to right scanning of input R : constructing rightmost derivation in reverse k : number
More informationTypes of parsing. CMSC 430 Lecture 4, Page 1
Types of parsing Topdown 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 backtrackfree (predictive)
More informationParsing. Roadmap. > Contextfree grammars > Derivations and precedence > Topdown parsing > Leftrecursion > Lookahead > Tabledriven parsing
Roadmap > Contextfree grammars > Derivations and precedence > Topdown parsing > Leftrecursion > Lookahead > Tabledriven parsing The role of the parser > performs contextfree syntax analysis > guides
More informationBottomUp Parsing. Lecture 1112
BottomUp Parsing Lecture 1112 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 BottomUp Parsing Bottomup parsing is more general than topdown parsing And just as efficient
More informationCompiler Construction 2016/2017 Syntax Analysis
Compiler Construction 2016/2017 Syntax Analysis Peter Thiemann November 2, 2016 Outline 1 Syntax Analysis Recursive topdown parsing Nonrecursive topdown parsing Bottomup parsing Syntax Analysis tokens
More informationChapter 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 informationCA Compiler Construction
CA4003  Compiler Construction David Sinclair A topdown 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 informationUNITIII BOTTOMUP PARSING
UNITIII BOTTOMUP PARSING Constructing a parse tree for an input string beginning at the leaves and going towards the root is called bottomup parsing. A general type of bottomup parser is a shiftreduce
More informationCompiler Design 1. BottomUP Parsing. Goutam Biswas. Lect 6
Compiler Design 1 BottomUP 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 informationUNIT 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 informationSyntax 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 informationEDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:
EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 20170911 This lecture Regular expressions Contextfree grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)
More informationCS1622. 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
More informationWednesday, 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 informationParsers. 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 informationConcepts Introduced in Chapter 4
Concepts Introduced in Chapter 4 Grammars ContextFree Grammars Derivations and Parse Trees Ambiguity, Precedence, and Associativity Top Down Parsing Recursive Descent, LL Bottom Up Parsing SLR, LR, LALR
More informationTopDown Parsing and Intro to BottomUp Parsing. Lecture 7
TopDown Parsing and Intro to BottomUp Parsing Lecture 7 1 Predictive Parsers Like recursivedescent but parser can predict which production to use Predictive parsers are never wrong Always able to guess
More informationWednesday, 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 informationCompilers. Bottomup Parsing. (original slides by Sam
Compilers Bottomup Parsing Yannis Smaragdakis U Athens Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) BottomUp Parsing More general than topdown parsing And just as efficient Builds
More informationCS308 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.
More informationParsers. 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 informationChapter 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 BottomUp parsing 2 Language Implementation Compilation There are three possible approaches
More informationChapter 4. Lexical and Syntax Analysis
Chapter 4 Lexical and Syntax Analysis Chapter 4 Topics Introduction Lexical Analysis The Parsing Problem RecursiveDescent Parsing BottomUp Parsing Copyright 2012 AddisonWesley. All rights reserved.
More informationIn One Slide. Outline. LR Parsing. Table Construction
LR Parsing Table Construction #1 In One Slide An LR(1) parsing table can be constructed automatically from a CFG. An LR(1) item is a pair made up of a production and a lookahead token; it represents a
More informationSyntax 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 informationIntroduction 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 informationParsing. 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 informationConflicts 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
More informationLR Parsing LALR Parser Generators
LR Parsing LALR Parser Generators Outline Review of bottomup parsing Computing the parsing DFA Using parser generators 2 Bottomup Parsing (Review) A bottomup parser rewrites the input string to the
More informationCompilers. 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 informationParsing II Topdown parsing. Comp 412
COMP 412 FALL 2018 Parsing II Topdown 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 informationLecture 7: Deterministic BottomUp Parsing
Lecture 7: Deterministic BottomUp 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 informationTopDown Parsing and Intro to BottomUp Parsing. Lecture 7
TopDown Parsing and Intro to BottomUp Parsing Lecture 7 1 Predictive Parsers Like recursivedescent but parser can predict which production to use Predictive parsers are never wrong Always able to guess
More informationSimple LR (SLR) LR(0) Drawbacks LR(1) SLR Parse. LR(1) Start State and Reduce. LR(1) Items 10/3/2012
LR(0) Drawbacks Consider the unambiguous augmented grammar: 0.) S E $ 1.) E T + E 2.) E T 3.) T x If we build the LR(0) DFA table, we find that there is a shiftreduce conflict. This arises because the
More informationReview: ShiftReduce Parsing. Bottomup parsing uses two actions: BottomUp Parsing II. Shift ABC xyz ABCx yz. Lecture 8. Reduce Cbxy ijk CbA ijk
Review: ShiftReduce Parsing Bottomup parsing uses two actions: BottomUp 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
More informationSyntax Analysis: Contextfree Grammars, Pushdown Automata and Parsing Part  4. Y.N. Srikant
Syntax Analysis: Contextfree 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 information4. 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 informationBottomUp Parsing II. Lecture 8
BottomUp Parsing II Lecture 8 1 Review: ShiftReduce Parsing Bottomup 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
More information3. 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 informationLecture 8: Deterministic BottomUp Parsing
Lecture 8: Deterministic BottomUp 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 informationSyntax 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 information4. 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 informationBottomUp Parsing II (Different types of ShiftReduce Conflicts) Lecture 10. Prof. Aiken (Modified by Professor Vijay Ganesh.
BottomUp Parsing II Different types of ShiftReduce Conflicts) Lecture 10 Ganesh. Lecture 10) 1 Review: BottomUp Parsing Bottomup parsing is more general than topdown parsing And just as efficient Doesn
More informationBottomUp Parsing LR Parsing
BottomUp 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
More informationLexical and Syntax Analysis (2)
Lexical and Syntax Analysis (2) In Text: Chapter 4 N. Meng, F. Poursardar Motivating Example Consider the grammar S > cad A > ab a Input string: w = cad How to build a parse tree topdown? 2 RecursiveDescent
More informationLR Parsing LALR Parser Generators
Outline LR Parsing LALR Parser Generators Review of bottomup parsing Computing the parsing DFA Using parser generators 2 Bottomup Parsing (Review) A bottomup parser rewrites the input string to the
More informationBottom Up Parsing. Shift and Reduce. Sentential Form. Handle. Parse Tree. Bottom Up Parsing 9/26/2012. Also known as ShiftReduce parsing
Also known as ShiftReduce 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 informationCS 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 informationSyn 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 frontend Intermediate representation Lexical error Syntax
More informationBottomUp Parsing. Lecture 1112
BottomUp Parsing Lecture 1112 (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 informationCompilerconstructie. najaar Rudy van Vliet kamer 140 Snellius, tel rvvliet(at)liacs(dot)nl. college 3, vrijdag 22 september 2017
Compilerconstructie najaar 2017 http://www.liacs.leidenuniv.nl/~vlietrvan1/coco/ Rudy van Vliet kamer 140 Snellius, tel. 071527 2876 rvvliet(at)liacs(dot)nl college 3, vrijdag 22 september 2017 + werkcollege
More informationCSE 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 informationParsing Part II (Topdown parsing, leftrecursion removal)
Parsing Part II (Topdown parsing, leftrecursion removal) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit
More informationParsing Techniques. CS152. Chris Pollett. Sep. 24, 2008.
Parsing Techniques. CS152. Chris Pollett. Sep. 24, 2008. Outline. Topdown versus Bottomup Parsing. Recursive Descent Parsing. Left Recursion Removal. Left Factoring. Predictive Parsing. Introduction.
More informationLL(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
More information8 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
More informationSyntaxDirected Translation
SyntaxDirected Translation ALSU Textbook Chapter 5.1 5.4, 4.8, 4.9 Tsansheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 What is syntaxdirected translation? Definition: The compilation
More informationThe Parsing Problem (cont d) RecursiveDescent Parsing. RecursiveDescent Parsing (cont d) ICOM 4036 Programming Languages. The Complexity of Parsing
ICOM 4036 Programming Languages Lexical and Syntax Analysis Lexical Analysis The Parsing Problem RecursiveDescent Parsing BottomUp Parsing This lecture covers review questions 1427 This lecture covers
More informationSyntax Analysis. Tokens > Parse Tree. Main Problems. Grammars. Convert the list of tokens into a parse tree ( hierarchical analysis)
Syntax Analysis Convert the list of tokens into a parse tree ( hierarchical analysis) source program lexical analyzer token get next token parser parse tree The syntactic structure is specified using contextfree
More informationSyntax Analysis Part I
Syntax Analysis Part I Chapter 4: ContextFree Grammars Slides adapted from : Robert van Engelen, Florida State University Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token,
More informationCSE431 Translation of Computer Languages
CSE431 Translation of Computer Languages Top Down Parsers Doug Shook Top Down Parsers Two forms: Recursive Descent Table Also known as LL(k) parsers: Read tokens from Left to right Produces a Leftmost
More information