Docsity

LR(1) Parsing: Shift-Reduce Parsers and Parsing Tables - Prof. Marvin V. Zelkowitz, Study notes of Computer Science

Toggle sidebar
bg1
1
CMSC430 Spring 2007 1
LR(1)
Parsers
•LR(1) parsers are table-driven, shift-reduce parsers
that use a limited right context (1 token) for handle recognition
•LR(1) parsers recognize languages that have an LR(1) grammar
Informal definition:
A grammar is LR(1) if, given a rightmost derivation
S
⇒γ
0
⇒γ
1
⇒γ
2
⇒…⇒γ
n–1
⇒γ
n
⇒
sentence
We can
1.
isolate the handle of each right-sentential form
γ
i
,
and
2.
determine the production by which to reduce,
by scanning γ
i
from left-to-right, going at most 1 symbol beyond
the right end of the handle of γ
i
CMSC430 Spring 2007 2
Shift Reduce Parsing
•a right-sentential form is any string that may occur in a legal
rightmost derivation
•a viable prefix of a right-sentential form is any prefix that does not
continue past the right end of its rightmost handle
Shift-reduce parsers
•operator precedence - define precedence between operands to
guide reductions
•LR(1) --- construct DFA for recognizing viable prefix, storing
lookahead information in DFA
•SLR(1) --- LR(0) + FOLLOW
>construct DFA for recognizing viable prefix, use
FOLLOW
to
guide reductions
•LALR(1) --- construct DFA for recognizing viable prefix,
propagating lookahead information in DFA
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download LR(1) Parsing: Shift-Reduce Parsers and Parsing Tables - Prof. Marvin V. Zelkowitz and more Study notes Computer Science in PDF only on Docsity!

CMSC430 Spring 2007 (^1)

LR(1) Parsers

  • LR(1) parsers are table-driven, shift-reduce parsers

that use a limited right context (1 token) for handle recognition

  • LR(1) parsers recognize languages that have an LR(1 ) grammar

Informal definition:

A grammar is LR(1) if, given a rightmost derivation

S ⇒ γ 0 ⇒ γ 1 ⇒ γ 2 ⇒ … ⇒ γ n–1 ⇒ γ n ⇒ sentence

We can

1.isolate the handle of each right-sentential form γ i, and 2.determine the production by which to reduce,

by scanning γ i from left-to-right, going at most 1 symbol beyond

the right end of the handle of γ i

CMSC430 Spring 2007 (^2)

Shift Reduce Parsing

  • a right-sentential form is any string that may occur in a legal

rightmost derivation

  • a viable prefix of a right-sentential form is any prefix that does not

continue past the right end of its rightmost handle

Shift-reduce parsers

  • operator precedence - define precedence between operands to

guide reductions

  • LR(1) --- construct DFA for recognizing viable prefix, storing

lookahead information in DFA

  • SLR(1) --- LR(0) + FOLLOW

construct DFA for recognizing viable prefix, useFOLLOW to

guide reductions

  • LALR(1) --- construct DFA for recognizing viable prefix,

propagating lookahead information in DFA

CMSC430 Spring 2007 (^3)

LR(1) Parsers

A table-driven LR(1) parser looks like

Tablescan be built by hand

It is a perfect task to automate

Scanner Table-driven Parser

A CTION &

GOTO

Tables

Parser Generator

source code

grammar

IR

CMSC430 Spring 2007 (^4)

LR(1) Skeleton Parser

stack.push(INVALID); stack.push( s 0 ); not_found = true; token = scanner.next_token(); do while (not_found) { s = stack.top();

if ( ACTION[s,token] == “reduce A →β” ) then { stack.popnum(2|β|); // pop 2|β| symbols s = stack.top(); stack.push( A ); stack.push(GOTO[s, A ]); } else if ( ACTION[s,token] == “ shift s (^) i ” ) then { stack.push(token); stack.push( s (^) i ); token ← scanner.next_token(); } else if ( ACTION[s,token] == “ accept ” & token == EOF ) then not_found = false;

else report a syntax error and recover; } report success;

The skeleton parser

  • uses A CTION & GOTO tables
  • does |words| shifts
  • does |derivation| reductions
  • does 1 accept
  • detects errors by failure of 3 other cases

CMSC430 Spring 2007 (^7)

Example Parse 2

Stack Input Action

$ s 0 baa baa EOF shift 2

$ s 0 baa s 2 baa EOF reduce 3

$ s 0 SN s 1 baa EOF shift 3 $ s 0 SN s 1 baa s 3 EOF reduce 2 $ s 0 SN s 1 EOF accept

The string “baa baa ”

ACTION

State EOF baa 0 — shift 2 1 accept shift 3 2 reduce 3 reduce 3 3 reduce 2 reduce 2

GOTO

State SheepNoise 0 1 1 0 2 0 3 0

1 Goal →^ Sheep Noise 2 Sheep Noise →^ Sheep Noise baa 3 | baa

CMSC430 Spring 2007 (^8)

LR(0) items

  • An LR(0) item is a string α, where α is a production fromG with a
    • at some position in the rhs

> The • indicates how much of an item we have seen at a given

state in the parse.

  • [A ::= • X Y Z] indicates that the parser is looking for a string that can be derived fromX Y Z
  • [A ::= X Y • Z] indicates that the parser has seen a string derived fromX Y and is looking for one derivable fromZ

LR(0) Items ( no lookahead)

  • The production A ::= X Y Z generates 4LR(0) items.

> [A ::= • X Y Z]

> [A ::= X • Y Z]

> [A ::= X Y • Z]

> [A ::= X Y Z •]

CMSC430 Spring 2007 (^9)

LR(0) machine

Definitions

  • closure of[A ::= α • B β] contains itself and any items of form[B ::= • ω], repeat for new items.
  • goto(X) of[A ::= α • X β] contains the closure of[A ::= α X • β]

LR(0) DFA construction

1. begin with closure of start symbol[S ::= • α ]

2. for each state, calculategoto(X) for all grammar symbolsX,

generating states

3. repeat step 2 for all newly generated states

Properties

  • states in the DFA are sets of LR(0) items
  • states represent viable prefixes of productions
  • to recognize viable prefixes of language, save state of current

production on stack when reducing new nonterminal

CMSC430 Spring 2007 (^10)

LR(0) items

  • The Grammar

P1 E ::= T + E P2 | T P3 T ::= id

  • The Augmented Grammar

P0 S' ::= E P1 E ::= T + E P2 | T P3 T ::= id

S [ S' ::=• E ] goto(S1) [ E ::=• T + E ] goto(S2) [ E ::=• T ] goto(S2) [ T ::=• id ] goto(S3) S [ S' ::= E• ] Reduce (and accept) S [ E ::= T• + E ] goto(S4) [ E ::= T• ] Reduce S [ T ::= id• ] Reduce S [ E ::= T +• E ] goto(S5) [ E ::=• T + E ] goto(S2) [ E ::=• T ] goto(S2) [ T ::=• id] goto(S3) S [ E ::= T + E• ] Reduce

Oops - Shift-reduce Conflict. What do you do here?

CMSC430 Spring 2007 (^13)

Redo Expression grammar – Grammar now SLR(1)

  • The Grammar

P1 E ::= T + E P2 | T P3 T ::= id

  • The Augmented Grammar

P0 S' ::= E P1 E ::= T + E P2 | T P3 T ::= id

S [ S' ::=• E ] goto(S1) [ E ::=• T + E ] goto(S2) [ E ::=• T ] goto(S2) [ T ::=• id ] goto(S3) S [ S' ::= E• ] Reduce (and accept) S [ E ::= T• + E ] First(+)= +, goto(S4) [ E ::= T• ] Follow(E) =eof, Reduce S [ T ::= id• ] Reduce S [ E ::= T +• E ] goto(S5) [ E ::=• T + E ] goto(S2) [ E ::=• T ] goto(S2) [ T ::=• id] goto(S3) S [ E ::= T + E• ] Reduce

CMSC430 Spring 2007 (^14)

Computing F IRST Sets

Define F IRST as

  • If α ⇒* aβ, a ∈ T, β ∈ (T ∪ NT)*, then a ∈ FIRST(α)
  • If α ⇒* ε, then ε ∈ FIRST(α)

Note: if α =Xβ, FIRST(α) = FIRST(X)

To compute FIRST

  • Use a fixed-point method
  • F IRST(A) ∈ 2 (T^ ∪^ ε)
  • Loop is monotonic

⇒ Algorithm halts

ForSheepNoise:

F IRST(Goal) = { baa } F IRST(SN) = { baa } F IRST(baa) = { baa }

for each x ∈ T, F IRST (x) ← { x } for each A ∈ NT, F IRST (A) ← Ø while (F IRST sets are still changing) for each p ∈ P, of the form A → β , if β is ε then F IRST (A) ← F IRST (A) ∪ { ε } else if β is B 1 B 2 …B (^) k then begin F IRST (A) ← F IRST (A) ∪ ( F IRST (B 1 ) – { ε } ) for i ← 1 to k–1 by 1 while ε ∈ F IRST (B (^) i ) F IRST (A) ← F IRST (A) ∪ ( F IRST (B (^) i +1) – { ε } ) if i = k–1 and ε ∈ FIRST(B (^) k ) then F IRST (A) ← F IRST (A) ∪ { ε } end

CMSC430 Spring 2007 (^15)

LR(1) items

We can get more powerful parsers by keeping track of lookahead

information in the states of theLR parser.

  • AnLR(k) item is a pair [α,β] where

α is a production fromG with a• at some position in therhs β is a lookahead string containingk symbols (terminals oreof)

LR(1) items

  • example: [A ::= X• Y Z, a]
  • several LR(1) items may have the samecore {i.e., LR(0) item lists}

[A ::= X• Y Z, a] [A ::= X• Y Z, b]

  • we represent this as [A ::= X• Y Z, ab]

CMSC430 Spring 2007 (^16)

LR(1) Lookahead

What's the point of all these lookahead symbols?

  • carry them along to allow us to choose correct reduction when

there is any choice

  • lookaheads are bookkeeping, unless item has• at right end.

in [A ::= X• Y Z, a], a has no direct use in [A ::= X Y Z•, a], a is useful

  • allows use of (non-invertible) grammars where productions have the samerhs

The point

  • For [A ::= α •, a] and [B ::= α •, b],
  • we can decide between reducing toA and toB by looking at

limited right context!

CMSC430 Spring 2007 (^19)

LALR(1) parsers

Problem

  • LR(1) parsers are powerful, but have many more states than

LR(0) (approximately x 10 for Pascal)

  • larger state tables longer to construct, run

LALR(1) parsers

  • define thecore of a set of LR(1) items to be the set of LR(0) items

derived by ignoring the lookahead symbols.

> example of two sets of LR(1) items with same core:

[A ::= α • β, a], [A ::= α • β,b], and [A ::= α • β, c], [A ::= α • β, d]

  • if two sets of LR(1) items, I1 and I2 have the same core, we can

merge the states that represent them in the ACTION and GOTO

tables

  • almost as powerful as LR}(1), same size as LR(0)

CMSC430 Spring 2007 (^20)

LR(1) Parsers – Formal definitions – Repeat of previous slides

How does this LR(1) stuff work?

  • Unambiguous grammar ⇒ unique rightmost derivation
  • Keep upper fringe on a stack

> All active handles include top of stack (TOS)

> Shift inputs until TOS is right end of a handle

  • Language of handles is regular (finite)

> Build a handle-recognizing DFA

> A CTION & G OTO tables encode the DFA

  • To match subterm, invoke subterm DFA

& leave old DFA ’s state on stack

  • Final state in DFA ⇒ areduce action

> New state is GOTO[state at TOS (after pop),lhs]

ForSN, this takes the DFA to s 1

S 0

S 3

S 2

S 1

baa

baa

SN

Control DFA for SN

Reduce action

Reduce action

CMSC430 Spring 2007 (^21)

Building LR(1) Parsers

How do we generate the A CTION and G OTO tables?

  • Use the grammar to build a model of the DFA
  • Use the model to build ACTION & G OTO tables
  • If construction succeeds, the grammar is LR(1)

The Big Picture

  • Model the state of the parser
  • Use two functionsgoto( s, X ) andclosure( s )

goto() is analogous tomove() in the subset construction closure() adds information to round out a state

  • Build up the states and transition functions of the DFA
  • Use this information to fill in the A CTION and G OTO tables

Terminal or non-terminal

CMSC430 Spring 2007 (^22)

LR(k) items

An LR(k) item is a pair [P, δ], where

P is a productionA→β with a • at some position in therhs

δ is a lookahead string of length ≤ k (words or EOF)

The • in an item indicates the position of the top of the stack

[A→•βγ,a] means that the input seen so far is consistent with the use ofA →βγ immediately after the symbol on top of the stack

[A →β•γ,a] means that the input sees so far is consistent with the use ofA →βγ at this point in the parse,and that the parser has

already recognized β.

[A →βγ•,a] means that the parser has seen βγ,and that a lookahead symbol of a is consistent with reducing toA.

The table construction algorithm uses items to represent

valid configurations of an LR(1) parser

CMSC430 Spring 2007 (^25)

Back to Finding Handles

Revisiting an issue from last class

Parser in a state where the stack (the fringe) was

Expr –Term

With lookahead of *

How did it choose to expandTerm rather than reduce toExpr?

  • Lookahead symbol is the key
  • With lookahead of + or –, parser should reduce toExpr
  • With lookahead of * or /, parser should shift
  • Parser uses lookahead to decide
  • All this context from the grammar is encoded in the handle

recognizing mechanism

CMSC430 Spring 2007 (^26)

Back to x – 2 * y

Stack Input Handle Action $ id – num * id none shift $ id – num * id 9,1 red. 9 $Factor – num * id 7,1 red. 7 $Term – num * id 4,1 red. 4 $Expr – num * id none shift $Expr – num * id none shift $Expr – num * id 8,3 red. 8 $Expr –Factor * id 7,3 red. 7 $Expr –Term * id none shift $Expr –Term * id none shift $Expr –Term * id 9,5 red. 9 $Expr –Term *Factor 5,5 red. 5 $Expr –Term 3,3 red. 3 $Expr 1,1 red. 1 $Goal none accept

  1. Shift until TOS is the right end of a handle
  2. Find the left end of the handle & reduce

Remember this slide?

shift here

reduce here

CMSC430 Spring 2007 (^27)

Computing Closures

Closure(s) adds all the items implied by items already ins

  • Any item [A→β•Bδ,a] implies [B→•τ,x] for each production

withB on thelhs, and eachx ∈ F IRST(δa)

  • Since β Bδ is valid, any way to derive β Bδ is valid, too

The algorithm

Closure( s ) while ( s is still changing ) ∀ items [ A → β • B δ ,a] ∈ s ∀ productions B →τ ∈ P ∀ b ∈ F IRST ( δ a) // δ might be ε if [ B → • τ ,b] ∉ s then add [ B → • τ ,b] to s

  • Classic fixed-point algorithm
  • Halts becauses ⊂ I TEMS
  • Worklist version is faster

Closure “fills out” a state

CMSC430 Spring 2007 (^28)

Example From SheepNoise

Initial step builds the item [Goal→•SheepNoise, EOF]

and takes itsclosure( )

Closure( [Goal→•SheepNoise, EOF])

So,S 0 is { [Goal→ • SheepNoise,EOF], [SheepNoise→ • SheepNoise baa,EOF] , [SheepNoise→• baa,EOF], [SheepNoise→ • SheepNoise baa,baa] , [SheepNoise→ • baa,baa] }

Item From [Goal→•SheepNoise, EOF] Original item [SheepNoise→•SheepNoise baa, EOF] 1, δa is EOF [SheepNoise→ • baa, EOF] 1,^ δa is^ EOF [SheepNoise→•SheepNoise baa,baa] 2, δa is baa EOF [SheepNoise→ • baa,baa] 2, δa is baa EOF

CMSC430 Spring 2007 (^31)

Example from SheepNoise

S 0 : { [Goal→ • SheepNoise, EOF], [SheepNoise→ • SheepNoise baa, EOF] , [SheepNoise→• baa, EOF], [SheepNoise→ • SheepNoise baa, baa] , [SheepNoise→ • baa, baa] }

S 1 =Goto(S 0 , SheepNoise) =

{ [Goal→ SheepNoise • , EOF], [SheepNoise→ SheepNoise • baa, EOF] , [SheepNoise→ SheepNoise • baa, baa] }

S 2 =Goto(S 0 , baa) = { [SheepNoise→ baa•, EOF], [SheepNoise→ baa•, baa] }

S 3 =Goto(S 1 , baa) = { [SheepNoise→ SheepNoise baa•, EOF] ,

[SheepNoise→ SheepNoise baa•, baa] }

CMSC430 Spring 2007 (^32)

Building the Canonical Collection

Start froms 0 =closure( [S’→S,EOF])

Repeatedly construct new states, until all are found

The algorithm

s 0 ← closure( [ S’ → S ,EOF ] )

S ← { s 0 }

k ← 1

while ( S is still changing )

∀ sj ∈ S and ∀ x ∈ ( T ∪ NT )

sk ← goto(sj ,x)

record sj → sk on x

if sk ∉ S then

S ← S ∪ sk

k ← k + 1

  • Fixed-point computation
  • Loop adds toS
  • S ⊆ 2 ITEMS^ , soS is finite
  • Worklist version is faster

CMSC430 Spring 2007 (^33)

Example (grammar & sets)

Simplified, right recursive expression grammar

Goal → Expr Expr → Term – Expr Expr → Term Term → Factor * Term Term → Factor Factor → ident

Symbol FIRST Goal { ident } Expr { ident } Term { ident } Factor { ident }

  • { – }

ident { ident }

CMSC430 Spring 2007 (^34)

Example (building the collection)

Initialization Step

s 0 ← closure( { [ Goal → • Expr , EOF ] } )

{ [ Goal → • Expr , EOF], [ Expr → • Term – Expr , EOF], [ Expr → • Term , EOF],

[ Term → • Factor * Term , EOF], [ Term → • Factor * Term , –],

[ Term → • Factor , EOF], [ Term → • Factor , –],

[ Factor → • ident , EOF], [ Factor → • ident , –], [ Factor → • ident , *] }

S ← {s 0 }

CMSC430 Spring 2007 (^37)

Example (Summary)

S 6 : { [ Term → Factor * • Term , EOF ], [ Term → Factor * • Term , –],

[ Term → • Factor * Term , EOF ], [ Term → • Factor * Term , –],

[ Term → • Factor , EOF ], [ Term → • Factor , –],

[ Factor → • ident , EOF ], [ Factor → • ident , –], [ Factor → • ident , *] }

S 7 : { [ Expr → Term – Expr • , EOF ] }

S 8 : { [ Term → Factor * Term • , EOF ], [ Term → Factor * Term • , –] }

CMSC430 Spring 2007 (^38)

Example (Summary)

The Goto Relationship(from the construction)

State Expr Term Factor - * Ident 0 1 2 3 4 1 2 5 3 6 4 5 7 2 3 4 6 8 3 4 7 8

CMSC430 Spring 2007 (^39)

Filling in the ACTION and GOTO Tables

The algorithm

Many items generate no table entry

Closure( ) instantiates F IRST(X) directly for [A→β•Xδ,a ]

∀ set sx ∈ S ∀ item i ∈ sx if i is [A→β •aδ,b]and goto(sx ,a) = sk , a ∈ T then A CTION [x,a] ← “shift k” else if i is [S’→ S •, EOF] then A CTION [x ,a] ← “accept” else if i is [A→β •,a] then A CTION[x,a] ← “reduce A→β” ∀ n ∈ NT if goto(sx ,n) = sk then GOTO [x,n] ← k

x is the state number

CMSC430 Spring 2007 (^40)

Example (Filling in the tables)

The algorithm produces the following table

A CTION GOTO

Ident - * EOF Expr Term Factor

0 s 4 1 2 3

1 acc

2 s 5 r 3

3 r 5 s 6 r 5

4 r 6 r 6 r 6

5 s 4 7 2 3

6 s 4 8 3

7 r 2

8 r 4 r 4

END OF DUPLICATE DEFINITION OF LR(1)