Notatypewriter's Blog

Umm… what?

An algorithm for doing closure in LR(1)

leave a comment »

At least, it’s one that is simple enough for me to remember. The ones typically presented in lectures and books were confusing to me.

Mine seems to work on examples from lecture, in books, and on Wikipedia.

Define closure( item=[A→β•Bδ,a] ), where:

  • A is a non-terminal
  • β is a sentence of terminals and non-terminals
  • • is the position in the string being parsed
  • B is a non-terminal
  • δ is a sentence of terminals and non-terminals
  • , is the lookahead position
  • a is the lookahead terminal

If the item does not match this pattern, then closure returns empty.

Else, for each production B→γ and each terminal b in FIRST(δ), do closure( [B→•γ, b] ).

From Wikipedia:

FIRST(A) is the set of terminals which can appear as the first element of any chain of rules matching non-terminal A.

Example 1

Running through an example grammar…

  1. S→E
  2. E→T
  3. E→(E)
  4. T→n
  5. T→+T
  6. T→T+n

closure( [S→•E,$] ) –> (E, FIRST($)={$})

Productions for E are E→T | (E), so:

[E→•T,$] –> (T, FIRST($)={$})
[E→•(E),$] –> no match

Productions for T are T→n | +T | T+n, so:

[T→•n,$] –> no match
[T→•+T,$] –> no match
[T→•T+n,$] –> (T, FIRST(+n$)={+})

Productions for T are T→n | +T | T+n, so:

[T→•n,+] –> no match
[T→•+T,+] –> no match
[T→•T+n,+] –> (T, FIRST(+n$)={+}) –> previously done

FINISH

Example 2

Unfortunately, this example doesn’t show the case where FIRST is applied to a non-terminal and produces multiple terminals. In this grammar:

  1. S→E
  2. E→E+T
  3. E→T
  4. T→TF
  5. T→F
  6. F→F*
  7. F→a
  8. F→b

when trying to determine closure( [T→•TF,$] ), you have to get FIRST(F), which is {a,b}.

Productions for T are T→TF | F, so

[T→•TF,a]
[T→•TF,b]
[T→•F,a]
[T→•F,b]

Written by notatypewriter

2012 September 22 at 3:37 pm

Posted in Nerding out

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: