# LR Parsing. Table Construction

Size: px
Start display at page:

Transcription

1 #1 LR Parsing Table Construction

2 #2 Outline Review of bottom-up parsing Computing the parsing DFA Closures, LR(1) Items, States Transitions Using parser generators Handling Conflicts

3 #3 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 possible parser context. After we extend LR(1) items by closing them they become LR(1) DFA states. Grammars can have shift/reduce or reduce/reduce conflicts. You can fix most conflicts with precedence and associativity declarations. LALR(1) tables are formed from LR(1) tables by merging states with similar cores.

4 #4 Bottom-up Parsing (Review) A bottom-up parser rewrites the input string to the start symbol The state of the parser is described as α I γ α is a stack of terminals and non-terminals γ is the string of terminals not yet examined Initially: I x 1 x 2... x n

5 #5 Shift and Reduce Actions (Review) Recall the CFG: E! int E + (E) A bottom-up parser uses two kinds of actions: Shift pushes a terminal from input on the stack E + (I int ) E + (int I ) Reduce pops 0 or more symbols off of the stack (production RHS) and pushes a non-terminal on the stack (production LHS) E + (E + ( E ) I ) E +(E I )

6 #6 Key Issue: When to Shift or Reduce? Idea: use a finite automaton (DFA) to decide when to shift or reduce The input is the stack The language consists of terminals and non-terminals We run the DFA on the stack and we examine the resulting state X and the token tok after I If X has a transition labeled tok then shift If X is labeled with A! β on tok then reduce

7 LR(1) Parsing. An Example accept on \$ E E! E + (E) on \$, + int ( ) + 10 E 6 E ( ) 5 11 E! int on \$, + int 9 E! int on ), + int E! E + (E) on ), + I int + (int) + (int)\$ shift int I + (int) + (int)\$ E! int E I + (int) + (int)\$ shift(x3) E + (int I ) + (int)\$ E! int E + (E I ) + (int)\$ shift E + (E) I + (int)\$ E! E+(E) E I + (int)\$ shift (x3) E + (int I )\$ E! int E + (E I )\$ shift E + (E) I \$ E! E+(E) E I \$ accept #7

8 End of review #8

9 #9 Key Issue: How is the DFA Constructed? The stack describes the context of the parse What non-terminal we are looking for What production rhs we are looking for What we have seen so far from the rhs

10 LR(1) Table Construction Three hours later, you can finally parse E! E + E int #10

11 #11 Parsing Contexts Consider the state: E int + ( int ) + ( int ) The stack is E + ( I int ) + ( int ) Context: Red dot = We are looking for an E! E + ( ² E ) where we are. Have have seen E + ( from the right-hand side We are also looking for E! ² int or E! ² E + ( E ) Have seen nothing from the right-hand side One DFA state describes several contexts

12 #12 LR(1) Items An LR(1) item is a pair: X! α²β, a X! αβ is a production a is a terminal (the lookahead terminal) LR(1) means 1 lookahead terminal [X! α²β, a] describes a context of the parser We are trying to find an X followed by an a, and We have α already on top of the stack Thus we need to see next a prefix derived from βa

13 #13 Note The symbol I was used before to separate the stack from the rest of input α I γ, where α is the stack and γ is the remaining string of terminals In LR(1) items ² is used to mark a prefix of a production rhs: X! α²β, a Here β might contain non-terminals as well In both case the stack is on the left

14 #14 Convention We add to our grammar a fresh new start symbol S and a production S! E Where E is the old start symbol No need to do this if E had only one production The initial parsing context contains: S! ² E, \$ Trying to find an S as a string derived from E\$ The stack is empty

15 #15 LR(1) Items (Cont.) In context containing E! E + ² ( E ), + If ( follows then we can perform a shift to context containing E! E + (² E ), + In context containing E! E + ( E ) ², + We can perform a reduction with E! E + ( E ) But only if a + follows

16 LR(1) Items (Cont.) Consider a context with the item E! E + (² E ), + We expect next a string derived from E ) + There are two productions for E E! int and E! E + ( E) We describe this by extending the context with two more items: E! ² int, ) E! ² E + ( E ), ) #16

17 The Closure Operation The operation of extending the context with items is called the closure operation Closure(Items) = repeat for each [X! α²yβ, a] in Items for each production Y! γ for each b 2 First(βa) add [Y! ²γ, b] to Items until Items is unchanged #17

18 #18 Constructing the Parsing DFA (1) Construct the start context: Closure({S! ²E, \$}) = S! ²E, \$ E! ²E+(E), \$ E! ²int, \$ E! ²E+(E), + E! ²int, + We abbreviate as: S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+

19 #19

20 #20 Constructing the Parsing DFA (2) An LR(1) DFA state is a closed set of LR(1) items This means that we performed Closure The start state contains [S! ²E, \$] A state that contains [X! α², b] is labeled with reduce with X! α on b And now the transitions

21 The DFA Transitions A state State that contains [X! α²yβ, b] has a transition labeled y to a state that contains the items Transition(State, y) y can be a terminal or a non-terminal Transition(State, y) = Items Ã ; for each [X! α²yβ, b] 2 State add [X! αy²β, b] to Items return Closure(Items) #21

22 #22 LR(1) DFA Construction Example S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ 0

23 #23 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ E 0 1 int

24 #24 LR(1) DFA Construction Example S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ 0 int 1 E! int², \$/+ 2 E

25 #25 LR(1) DFA Construction Example S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ 0 int 1 E! int², \$/+ E! int on \$, + 2 E

26 #26 LR(1) DFA Construction Example S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ 0 int 1 E! int², \$/+ E! int on \$, + 2 E S! E², \$ E! E²+(E), \$/+

27 #27 LR(1) DFA Construction Example S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ 0 int 1 E! int², \$/+ E! int on \$, + 2 accept on \$ E + S! E², \$ E! E²+(E), \$/+

28 #28 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 int E + S! E², \$ E! E²+(E), \$/+ 1 E! int², \$/+ E! E+² (E), \$/+ E! int on \$, + 3

29 #29 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 E + S! E², \$ E! E²+(E), \$/+ int 1 E! int², \$/+ E! E+² (E), \$/+ ( E! int on \$, + 3

30 #30 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 E + S! E², \$ E! E²+(E), \$/+ int 1 E! int², \$/+ E! E+² (E), \$/+ ( E! E+(²E), \$/+ E! ²E+(E), )/+ E! ²int, )/+ E! int on \$, + 4 3

31 #31 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 E + S! E², \$ E! E²+(E), \$/+ E int 1 E! int², \$/+ E! E+² (E), \$/+ E! E+(²E), \$/+ E! ²E+(E), )/+ E! ²int, )/+ ( int E! int on \$, + 4 3

32 #32 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 E + S! E², \$ E! E²+(E), \$/+ E int 1 E! int², \$/+ E! E+² (E), \$/+ E! E+(²E), \$/+ E! ²E+(E), )/+ E! ²int, )/+ ( int E! int on \$, E! int², )/+

33 #33 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 E + S! E², \$ E! E²+(E), \$/+ E int 1 E! int², \$/+ E! E+² (E), \$/+ E! E+(²E), \$/+ E! ²E+(E), )/+ E! ²int, )/+ ( E! int on \$, int 5 E! int², )/+ E! int on ), +

34 #34 LR(1) DFA Construction Example 2 S! ²E, \$ E! ²E+(E), \$/+ E! ²int, \$/+ accept on \$ 0 E + S! E², \$ E! E²+(E), \$/+ E int 1 E! int², \$/+ E! E+² (E), \$/+ E! E+(²E), \$/+ E! ²E+(E), )/+ E! ²int, )/+ ( E! int on \$, E! E+(E²), \$/+ E! E²+(E), )/+ and so on int 5 E! int², )/+ E! int on ), +

35 Q: Movie Music (420 / 842) In a 1995 Disney movie that has been uncharitably referred to as "Hokey-Hontas", the Stephen Schwartz lyrics "what I love most about rivers is: / you can't step in the same river twice" refer to the ideas of which Greek philosopher?

36 Q: Games (522 / 842) In this 1982 arcade game features lance-wielding knights mounted on giant flying birds and dueling over a pit of lava. Destroying an enemy knight required ramming it such that your lance was higher than the enemy's.

37 #37 LR Parsing Tables. Notes Parsing tables (= the DFA) can be constructed automatically for a CFG The tables which cannot be constructed are constructed automatically in response to a CFG input. You asked for a miracle, Theo. I give you the L-R-1. Hans Gruber, Die Hard But we still need to understand the construction to work with parser generators e.g., they report errors in terms of sets of items What kind of errors can we expect?

38 #38

39 #39 Shift/Reduce Conflicts If a DFA state contains both [X! α²aβ, b] and [Y! γ², a] Then on input a we could either Shift into state [X! αa²β, b], or Reduce with Y! γ This is called a shift-reduce conflict

40 #40 Shift/Reduce Conflicts Typically due to ambiguities in the grammar Classic example: the dangling else S! if E then S if E then S else S OTHER Will have DFA state containing [S! if E then S², else] [S! if E then S² else S, x] If else follows then we can shift or reduce Default (bison, CUP, etc.) is to shift Default behavior is as needed in this case

41 #41 More Shift/Reduce Conflicts Consider the ambiguous grammar E! E + E E * E int We will have the states containing [E! E * ² E, +] [E! E * E², +] [E! ² E + E, +] E [E! E ² + E, +] Again we have a shift/reduce on input + We need to reduce (* binds more tightly than +) Solution: declare the precedence of * and +

42 #42 More Shift/Reduce Conflicts In bison declare precedence and associativity: %left + %left * // high precedence Precedence of a rule = that of its last terminal See bison manual for ways to override this default Resolve shift/reduce conflict with a shift if: no precedence declared for either rule or terminal input terminal has higher precedence than the rule the precedences are the same and right associative

43 #43 Using Precedence to Solve S/R Conflicts Back to our example: [E! E * ² E, +] [E! E * E², +] [E! ² E + E, +] E [E! E ² + E, +] Will choose reduce on input + because precedence of rule E! E * E is higher than of terminal +

44 #44 Using Precedence to Solve S/R Conflicts Same grammar as before E! E + E E * E int We will also have the states [E! E + ² E, +] [E! E + E², +] [E! ² E + E, +] E [E! E ² + E, +] Now we also have a shift/reduce on input + We choose reduce because E! E + E and + have the same precedence and + is left-associative

45 #45 Using Precedence to Solve S/R Conflicts Back to our dangling else example [S! if E then S², else] [S! if E then S² else S, x] Can eliminate conflict by declaring else with higher precedence than then Or just rely on the default shift action But this starts to look like hacking the parser Avoid overuse of precedence declarations or you ll end with unexpected parse trees The kiss of death

46 #46 Reduce/Reduce Conflicts If a DFA state contains both [X! α², a] and [Y! β², a] Then on input a we don t know which production to reduce This is called a reduce/reduce conflict

47 #47 Reduce/Reduce Conflicts Usually due to gross ambiguity in the grammar Example: a sequence of identifiers S! ε id id S There are two parse trees for the string id S! id S! id S! id How does this confuse the parser?

48 #48 More on Reduce/Reduce Conflicts Consider the states [S! id ², \$] [S! ² S, \$] [S! id ² S, \$] [S! ², \$] id [S! ², \$] [S! ² id, \$] [S! ² id, \$] [S! ² id S, \$] [S! ² id S, \$] Reduce/reduce conflict on input \$ S! S! id S! S! id S! id Better rewrite the grammar: S! ε id S

49 Can s someone learn this for me? #49

50 #50 Using Parser Generators Parser generators construct the parsing DFA given a CFG Use precedence declarations and default conventions to resolve conflicts The parser algorithm is the same for all grammars (and is provided as a library function) But most parser generators do not construct the DFA as described before Why might that be?

51 #51 Using Parser Generators Parser generators construct the parsing DFA given a CFG Use precedence declarations and default conventions to resolve conflicts The parser algorithm is the same for all grammars (and is provided as a library function) But most parser generators do not construct the DFA as described before Because the LR(1) parsing DFA has 1000s of states even for a simple language

52 #52 LR(1) Parsing Tables are Big But many states are similar, e.g. 1 E! int on \$, + E! int², \$/+ E! int², )/+ and 5 E! int on ), + Idea: merge the DFA states whose items differ only in the lookahead tokens We say that such states have the same core We obtain 1 E! int², \$/+) E! int on \$, +, )

53 #53 The Core of a Set of LR Items Definition: The core of a set of LR items is the set of first components Without the lookahead terminals Example: the core of { [X! α²β, b], [Y! γ²δ, d]} is {X! α²β, Y! γ²δ}

54 #54 LALR States Consider for example the LR(1) states {[X! α², a], [Y! β², c]} {[X! α², b], [Y! β², d]} They have the same core and can be merged And the merged state contains: {[X! α², a/b], [Y! β², c/d]} These are called LALR(1) states Stands for LookAhead LR Typically 10x fewer LALR(1) states than LR(1)

55 #55 LALR(1) DFA Repeat until all states have distinct core Choose two distinct states with same core Merge the states by creating a new one with the union of all the items Point edges from predecessors to new state New state points to all the previous successors A B C A C BE D E F D F

56 Example LALR(1) to LR(1) E E! E + (E) on \$, + int ( accept on \$ ) E E ) ( 5 11 E! int on \$, + int 9 E! int on ), + int E! E + (E) on ), + E accept on \$ E! E + (E) on \$, +, ) int 0 1,5 int ( 2 + 3,8 4,9 7,11 ) + 6,10 E E! int on \$, +, ) #56

57 #57 The LALR Parser Can Have Conflicts Consider for example the LR(1) states {[X! α², a], [Y! β², b]} {[X! α², b], [Y! β², a]} And the merged LALR(1) state {[X! α², a/b], [Y! β², a/b]} Has a new reduce-reduce conflict In practice such cases are rare

58 #58 LALR vs. LR Parsing LALR languages are not natural They are an efficiency hack on LR languages Any reasonable programming language has a LALR(1) grammar LALR(1) has become a standard for programming languages and for parser generators

59 #59 A Hierarchy of Grammar Classes From Andrew Appel, Modern Compiler Implementation in Java

60 #60 Notes on Parsing Parsing A solid foundation: context-free grammars A simple parser: LL(1) A more powerful parser: LR(1) An efficiency hack: LALR(1) LALR(1) parser generators Now we move on to semantic analysis

61 Take a bow, you survived! #61

62 #62 Supplement to LR Parsing Strange Reduce/Reduce Conflicts Due to LALR Conversion (from the bison manual)

63 #63 Strange Reduce/Reduce Conflicts Consider the grammar S! P R, P! T NL : T N! id NL! N N, NL R! T N : T T! id P - parameters specification R - result specification N - a parameter or result name T - a type name NL - a list of names

64 #64 Strange Reduce/Reduce Conflicts In P an id is a N when followed by, or : T when followed by id In R an id is a N when followed by : T when followed by, This is an LR(1) grammar. But it is not LALR(1). Why? For obscure reasons

65 #65 A Few LR(1) States P ² T id P ² NL : T id NL ² N : NL ² N, NL : 1 id T id ² id N id ² : N id ², 3 LALR reduce/reduce conflict on, N ² id : N ² id, T ² id id LALR merge T id ² id/, N id ² :/, R ² T, R ² N : T, 2 id T id ², N id ² : 4 T ² id, N ² id :

66 #66 What Happened? Two distinct states were confused because they have the same core Fix: add dummy productions to distinguish the two confused states E.g., add R! id bogus bogus is a terminal not used by the lexer This production will never be used during parsing But it distinguishes R from P

67 #67 A Few LR(1) States After Fix P ² T id P ² NL : T id NL ² N : NL ² N, NL : N ² id : N ² id, T ² id id 1 id T id ² id 3 N id ² : N id ², Different cores no LALR merging R. T, R. N : T, R. id bogus, T. id, N. id : 2 id T id ², N id ² : R id ² bogus, 4

68 #68 Homework Today: WA2 Was Due Thursday: Chapter Optional Wikipedia Article Tuesday February 26: WA3 due Wednesday February 27: PA3 due Parsing! Thursday Feb 28 Midterm 1 in Class

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

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

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

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

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

### 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 Bottom-Up Parsing

More Bottom-Up Parsing Lecture 7 Dr. Sean Peisert ECS 142 Spring 2009 1 Status Project 1 Back By Wednesday (ish) savior lexer in ~cs142/s09/bin Project 2 Due Friday, Apr. 24, 11:55pm My office hours 3pm

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

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

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

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

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

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

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

### LALR stands for look ahead left right. It is a technique for deciding when reductions have to be made in shift/reduce parsing. Often, it can make the

LALR parsing 1 LALR stands for look ahead left right. It is a technique for deciding when reductions have to be made in shift/reduce parsing. Often, it can make the decisions without using a look ahead.

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

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

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

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

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

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

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

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

### Simple 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 shift-reduce conflict. This arises because the

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### Lecture Notes on Bottom-Up LR Parsing

Lecture Notes on Bottom-Up LR Parsing 15-411: Compiler Design Frank Pfenning Lecture 9 September 23, 2009 1 Introduction In this lecture we discuss a second parsing algorithm that traverses the input string

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

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

### CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution

CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution Exam Facts Format Wednesday, July 20 th from 11:00 a.m. 1:00 p.m. in Gates B01 The exam is designed to take roughly 90

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

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

### Lecture Notes on Bottom-Up LR Parsing

Lecture Notes on Bottom-Up LR Parsing 15-411: Compiler Design Frank Pfenning Lecture 9 1 Introduction In this lecture we discuss a second parsing algorithm that traverses the input string from left to

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

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

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

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

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

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

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

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

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

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

### Configuration Sets for CSX- Lite. Parser Action Table

Configuration Sets for CSX- Lite State s 6 s 7 Cofiguration Set Prog { Stmts } Eof Stmts Stmt Stmts State s s Cofiguration Set Prog { Stmts } Eof Prog { Stmts } Eof Stmts Stmt Stmts Stmts λ Stmt if ( Expr

### CS453 : JavaCUP and error recovery. CS453 Shift-reduce Parsing 1

CS453 : JavaCUP and error recovery CS453 Shift-reduce Parsing 1 Shift-reduce parsing in an LR parser LR(k) parser Left-to-right parse Right-most derivation K-token look ahead LR parsing algorithm using

### Introduction to Parsing. Lecture 5

Introduction to Parsing Lecture 5 1 Outline Regular languages revisited Parser overview Context-free grammars (CFG s) Derivations Ambiguity 2 Languages and Automata Formal languages are very important

### G53CMP: Lecture 4. Syntactic Analysis: Parser Generators. Henrik Nilsson. University of Nottingham, UK. G53CMP: Lecture 4 p.1/32

G53CMP: Lecture 4 Syntactic Analysis: Parser Generators Henrik Nilsson University of Nottingham, UK G53CMP: Lecture 4 p.1/32 This Lecture Parser generators ( compiler compilers ) The parser generator Happy

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

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

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

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

### Fall Compiler Principles Lecture 4: Parsing part 3. Roman Manevich Ben-Gurion University of the Negev

Fall 2016-2017 Compiler Principles Lecture 4: Parsing part 3 Roman Manevich Ben-Gurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning

### FROWN An LALR(k) Parser Generator

FROWN An LALR(k) Parser Generator RALF HINZE Institute of Information and Computing Sciences Utrecht University Email: ralf@cs.uu.nl Homepage: http://www.cs.uu.nl/~ralf/ September, 2001 (Pick the slides

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

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

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

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

### Compilers and computer architecture From strings to ASTs (2): context free grammars

1 / 1 Compilers and computer architecture From strings to ASTs (2): context free grammars Martin Berger October 2018 Recall the function of compilers 2 / 1 3 / 1 Recall we are discussing parsing Source

### Introduction to Parsing. Lecture 5

Introduction to Parsing Lecture 5 1 Outline Regular languages revisited Parser overview Context-free grammars (CFG s) Derivations Ambiguity 2 Languages and Automata Formal languages are very important

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

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

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

### MIT Specifying Languages with Regular Expressions and Context-Free Grammars

MIT 6.035 Specifying Languages with Regular essions and Context-Free Grammars Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Language Definition Problem How to precisely

### Compilation 2012 Context-Free Languages Parsers and Scanners. Jan Midtgaard Michael I. Schwartzbach Aarhus University

Compilation 2012 Parsers and Scanners Jan Midtgaard Michael I. Schwartzbach Aarhus University Context-Free Grammars Example: sentence subject verb object subject person person John Joe Zacharias verb asked

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

### Compiler Construction

Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ws-1819/cc/ Recap: LR(1) Parsing Outline of Lecture 11 Recap: LR(1)

### Lecture Notes on Shift-Reduce Parsing

Lecture Notes on Shift-Reduce Parsing 15-411: Compiler Design Frank Pfenning, Rob Simmons, André Platzer Lecture 8 September 24, 2015 1 Introduction In this lecture we discuss shift-reduce parsing, which

### Midterm I (Solutions) CS164, Spring 2002

Midterm I (Solutions) CS164, Spring 2002 February 28, 2002 Please read all instructions (including these) carefully. There are 9 pages in this exam and 5 questions, each with multiple parts. Some questions

### Compilation 2013 Parser Generators, Conflict Management, and ML-Yacc

Compilation 2013 Parser Generators, Conflict Management, and ML-Yacc Erik Ernst Aarhus University Parser generators, ML-Yacc LR parsers are tedious to write, but can be generated, e.g., by ML-Yacc Input:

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

### Midterm I - Solution CS164, Spring 2014

164sp14 Midterm 1 - Solution Midterm I - Solution CS164, Spring 2014 March 3, 2014 Please read all instructions (including these) carefully. This is a closed-book exam. You are allowed a one-page handwritten

### LR Parsing - Conflicts

LR Parsing - Conflicts Lecture 15 Sections 4.5, 4.6 Robb T. Koether Hampden-Sydney College Fri, Feb 20, 2015 Robb T. Koether (Hampden-Sydney College) LR Parsing - Conflicts Fri, Feb 20, 2015 1 / 15 1 Shift/Reduce

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

### Fall Compiler Principles Lecture 5: Parsing part 4. Roman Manevich Ben-Gurion University

Fall 2014-2015 Compiler Principles Lecture 5: Parsing part 4 Roman Manevich Ben-Gurion University Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning Lowering

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

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

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

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

### MIT Specifying Languages with Regular Expressions and Context-Free Grammars. Martin Rinard Massachusetts Institute of Technology

MIT 6.035 Specifying Languages with Regular essions and Context-Free Grammars Martin Rinard Massachusetts Institute of Technology Language Definition Problem How to precisely define language Layered structure

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

### COMP 181. Prelude. Prelude. Summary of parsing. A Hierarchy of Grammar Classes. More power? Syntax-directed translation. Analysis

Prelude COMP 8 October, 9 What is triskaidekaphobia? Fear of the number s? No aisle in airplanes, no th floor in buildings Fear of Friday the th? Paraskevidedekatriaphobia or friggatriskaidekaphobia Why

### Action Table for CSX-Lite. LALR Parser Driver. Example of LALR(1) Parsing. GoTo Table for CSX-Lite

LALR r Driver Action Table for CSX-Lite Given the GoTo and parser action tables, a Shift/Reduce (LALR) parser is fairly simple: { S 5 9 5 9 void LALRDriver(){ Push(S ); } R S R R R R5 if S S R S R5 while(true){