What is CLR (1) Parser?



CLR defines canonical lookahead. CLR parsing use the canonical collection of LR (1) items to construct the CLR (1) parsing table. CLR (1) parsing table makes the more number of states as compare to the SLR (1) parsing. In the CLR (1), it can locate the reduce node only in the lookahead symbols.

Working of CLR Parser


Construction of LR (1) collection of items for Grammar

It requires three things

  • Augmented Grammar
  • Closure Function
  • goto Function

Augmented Grammar  It is a new Grammar G′ which contains a new production

S′ → S with all other productions of given grammar G.

Closure

procedure closure (I)

begin
Repeat
for each item A → α ∙ B β, a in I,
   each production B → γ and
      each terminal b ∈ FIRST (β a)
If B → ∙ γ is not in I
Add B → ∙ γ, b to I
Until no more elements can be joined to I;
end

𝐠𝐨𝐭𝐨(𝐈, 𝐗): If there is a production 𝐀 → 𝛂 ∙ 𝐗 𝛃, 𝐚 𝐢𝐧 𝐈 then 𝐠𝐨𝐭𝐨(𝐈, 𝐗) is the closure of the set of items of 𝐀 → 𝛂 𝐗 ∙ 𝛃, 𝐚.

Algorithm for Construction of LR (1) Set of Items

begin
C = {closure(S′→∙S,$)}
Repeat
for each set of items 𝐈 in C and each grammar symbol X (terminal or non-terminal)
   Add 𝐠𝐨𝐭𝐨(𝐈, 𝐗) 𝐭𝐨 𝐂
Until no more sets of elements can be added to C.
end.

Construction of Canonical LR Parsing Table Algorithm

Input − An Augmented Grammar G.′

Output − CLR Parsing Table

Method

  • Initially construct set of items C = {I0, I1, I2 … … In} where C is a collection of LR (1) items for G.

  • Parsing actions are based on each item or state I1.

Various Actions are −

  • If A → α ∙ a β is in Ii and goto (Ii, a) = Ij then create an entry in Action table Action [i, a] = shift j".
  • If A → α ∙, a is in Ii then set in Action table Action [i, a] to reduce A→α. " Here, A should not be S′.
  • If S′ → S ∙ is in Ii then Action [i, $] = accept".
  • The goto part of the SLR table can be filled as −
  • If goto (Ii, A) = Ij then goto [i, A] = j


  • All entries not defined by rules 2 and 3 are considered to be "error. "

Advertisements