Docsity

Understanding LR Parsers: Handles, Lookahead, and LR(1) Parsing Algorithm, Slides of Compiler Construction

Partial preview of the text

Download Understanding LR Parsers: Handles, Lookahead, and LR(1) Parsing Algorithm and more Slides Compiler Construction in PDF only on Docsity!

Compiler

Construction

Lecture 23

2

Handles

 The number of potential handles for the grammar is simply the sum of the lengths of the right- hand side of all the productions

 The number of complete handles is simply the number of productions

4

Handles

 These two facts lead to the critical insight behind LR parsers: A given grammar generates a finite set of handles (and potential handles) that the parser must recognize

5

Handles

 These two facts lead to the critical insight behind LR parsers: A given grammar generates a finite set of handles (and potential handles) that the parser must recognize

7

Lookahead

 However, it is not a simple matter of putting the placeholder in right-hand side to generate handles

 The parser needs to recognize the correct handle by different right contexts

8

word Stack Handle Action 9 × Expr – Term ► - none - shift 10 id Expr – Term × ► - none - shift 11 $ Expr – Term × id► 〈Factor → id, 5 〉 reduce 12 $ Expr–Term × Factor► 〈Term→Term×Factor, 5 〉 reduce 13 $ Expr – Term ► 〈Expr → Expr – Term, 3 〉 reduce 14 $ Expr ► 〈Goal → Expr, 1 〉 reduce 15 $ Goal - none - accept

Consider the parser’s action at step 9.The frontier is Expr – Term, suggesting a handle 〈Expr → Expr – Term •〉

However, the parser decides to extend the frontier by shifting × on to the stack rather than reducing frontier to Expr

10

Lookahead

 Clearly, this the correct move for the parser

 No potential handle contains Expr followed by ×

11

Lookahead

 At step 9, the set of potential handles is

〈Expr → Expr – Term•〉

〈Term →Term• × Factor〉

〈Term →Term• / Factor 〉

13

Lookahead

 The parser needs a basis for deciding between first (reduce) and second (shift) choices:

〈Expr → Expr – Term•〉

〈Term →Term• × Factor〉

14

Lookahead

 This requires more context

than the parser has in the frontier (stack)

16

LR(1) Parsers

 The LR(1) parsers can

recognize precisely those languages in which one- symbol lookahead suffices to determine whether to shift or reduce.

17

LR(1) Parsers

 The LR(1) construction algorithm builds a handle- recognizing DFA

 The parsing algorithm uses this DFA to recognize handles and potential handles on the parse stack

19

0

10

1

2 3 4

7

(^6 )

11

(^8 )

Reduce:E → int on ),+

int

E

E

  • ( E )

int

(^ int

)

Reduce: E → int on $,+

accept on $

Reduce:E → E+(E) on ),+

Reduce:E → E+(E) on ),+

20

Parsing DFA

►int + (int) + (int) $ shift 1 int ► + (int) + (int) $ reduce E → int E ► + (int) + (int) $ shift 3 times E + (int ►) + (int) $ reduce E → int E + (E ►) + (int) $ shift E + (E) ► + (int) $ red E → E+(E)