Syntax Analysis
Amitabha Sanyal
(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 Analysis – Recap
A syntax analyzer or parser
• Ensures that the input program is well-formed by attemting to grouptokens according to certain rules. This is called syntax checking.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 2/124
Syntax Analysis – Recap
A syntax analyzer or parser
• Ensures that the input program is well-formed by attemting to grouptokens according to certain rules. This is called syntax checking.
• May actually create the hierarchical structure that arises out of suchgrouping. This information is required by subsequent phases.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 4/124
Syntax Analysis – Example
main ()
{
int i,sum;
sum = 0;
for (i=1; i<=10; i++);
sum = sum + i;
printf("%d\n",sum);
}
fundef
fname params compound-stmt
identifier
main
( ) { vdecl slist }
varlist ;type
int varlist , var
var identifier
identifier sum
i
. . .
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 6/124
Syntax Analysis – Recap
• To check whether a program is well-formed requires a specificationof what is a well-formed program.
1. the specification be precise.2. the specification be complete. Must cover all the syntactic details of
the language3. the specification must be convenient to use by both language
designer and the implementer
A context free grammar meets these requirements.
• How is the hierarchical structure of the program represented?
1. Using a data structure called a parse tree.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 8/124
Syntax Analysis
How are parsers constructed ?
• Till early seventies, parsers (in fact all of the compiler) were writtenmanually.
• A better understanding of parsing algorithms has resulted in toolsthat can automatically generate parsers.
• Examples of parser generating tools:I Yacc/Bison: Bottom-up (LALR) parser generatorI Antlr: Top-down (LL) scanner cum parser generator.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 10/124
Syntax Analysis
Interface of a parser with the rest of the compiler
Source Program
token
get nexttokenLexical
analyser Parser Rest of thecompiler
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 12/124
Specification of Syntax by Context Free Grammars
Informal description of variable declarations in C:
• starts with integer or real as the first token.
• followed by one or more identifier tokens, separated by tokencomma
• followed by token semicolon
Question: Can the list of identifier tokens be empty?
declaration → type idlist ;idlist → id | idlist , idtype → integer | real
Illustrates the usefulness of a formal specification.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 14/124
Context Free Grammar
A CFG G is formally defined to have four components (N,T ,S ,P):
1. T is a finite set of terminals.
2. N is a finite set of nonterminals.
3. S is a special nonterminal ( from N ) called the start symbol.
4. P is a finite set of production rules of the form such as A→ α,where A is from N and α from (N
⋃T )∗
declaration → type idlist ;idlist → id | idlist , idtype → integer | real
non-terminals
terminals
production
start symbol
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 16/124
Derivation
Example : G = ({list}, {id, ,}, list, {list → list, id, list → id})
A derivation is traced out as follows
list ⇒ list, id⇒ list, id, id⇒ id, id, id
• The transformation of a string of grammar symbols by replacing anon-terminal by the corresponding right hand side of a production iscalled a derivation.
• The set of all possible terminal strings that can be derived from thestart symbol of a CFG is the language generated by the CFG.
This grammar generates a list of one or more ids separated by commas.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 18/124
Why the Term Context Free ?
Why the term context free ?
1. The only kind of productions permitted are of the formnon-terminal → sequence of terminals and non-terminals
2. Rules are used to replace an occurrence of the lhs non-terminal byits rhs. The replacement is made regardless of the context (symbolssurrounding the non-terminal).
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 20/124
Notational Conventions
Symbol type Convention
single terminal letters a, b, c, operators
delimiters, keywords
single nonterminal letters A, B , C and namessuch as declaration , listand S is the start symbol
single grammar symbol X , Y , Z(symbol from {N ∪ T} )
string of terminals letters x , y , z
string of grammar symbols α, β, γ
null string ε
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 22/124
Formal Definitions
Let
• A → γ be a production rule
• α A β be a string of grammar symbols
• I Replacing the nonterminal A in α A β yields α γ β.I Formally, this is stated as α A β derives α γ β in one step.I Symbolically α A β ⇒ α γ β.
• α1∗⇒ α2 means α1 derives α2 in zero or more steps. Clearly α
∗⇒ α
is always true for any α.
• α1+⇒ α2 means α1 derives α2 in one or more steps.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 24/124
FOrmal Definitions
• The language L(G ) generated by a context free grammar G is
defined as {w | S+
=⇒ w ,w ∈ T ∗}. Strings in L(G ) are calledsentences of G .
• A string α, α ∈ (N⋃
T )∗, such that S∗
=⇒ α, is called a sententialform of G.
• Two grammars are equivalent,if they generate the same language.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 26/124
Basic Concepts in Parsing
• For constructing a derivation, there are choices at each sententialform.
I choice of the nonterminal to be replacedI choice of a rule corresponding to the nonterminal.
• Instead of choosing the nonterminal to be replaced, in an arbitraryfashion, it is possible to make an uniform choice at each step.
I replace the leftmost nonterminal in a sentential formI replace the rightmost nonterminal in a sentential form
The corresponding derivations are known as leftmost and rightmostderivations respectively.
• Given a sentence w of a grammar G, there are several distinctderivations for w.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 28/124
Parse Trees
A parse tree is a pictorial form of depicting a derivation.
1. root of the tree is labeled with S
2. each leaf node is labeled by a token or by ε
3. an internal node of the tree is labeled by a nonterminal
4. if an internal node has A as its label and the children of this nodefrom left to right are labeled with X1,X2, . . . ,Xn then there must bea production
A → X1X2 . . . Xn
where Xi is a grammar symbol.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
E T
id
F
FT
idF
id
+
Leftmost derivation:
E ⇒ E + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
T
F
id
F
id
E
E
+ T
T+E
id
F
Leftmost derivation:
E ⇒ E + T⇒ E + T + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
FT+E
T
id
F
F
id
id
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
T+E
T
F
id
F
id
id
F
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
+E
T
F
id
F
id
id
FT
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T⇒ id + T + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
T+E
T
F
id
id
id
F
F
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T⇒ id + T + T⇒ id + F + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
T+E
T
F
id
F id
F
id
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T⇒ id + T + T⇒ id + F + T⇒ id + id + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
T+E
T
F
id
F id
id
F
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T⇒ id + T + T⇒ id + F + T⇒ id + id + T⇒ id + id + F
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
T+E
T
F
id
F
id
F
id
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T⇒ id + T + T⇒ id + F + T⇒ id + id + T⇒ id + id + F⇒ id + id + id
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 30/124
Illustration
E → E + T | TT → T ∗ F | FF → (E ) | id
The parse tree:
E
E
+ T
T+E
T
F
id
F
id
F
id
Leftmost derivation:
E ⇒ E + T⇒ E + T + T⇒ T + T + T⇒ F + T + T⇒ id + T + T⇒ id + F + T⇒ id + id + T⇒ id + id + F⇒ id + id + id
Rightmost derivation:
E ⇒ E + T⇒ E + F⇒ E + id⇒ E + T + id⇒ E + F + id⇒ E + id + id⇒ T + id + id⇒ F + id + id⇒ id + id + id
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 32/124
Derivations and Parse Trees
The following summarize some interesting relations between the twoconcepts
• Parse tree filters out the choice of replacements made in thesentential forms.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 32/124
Derivations and Parse Trees
The following summarize some interesting relations between the twoconcepts
• Parse tree filters out the choice of replacements made in thesentential forms.
• Given a left (right) derivation for a sentence, one can construct aunique parse tree for the sentence.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 32/124
Derivations and Parse Trees
The following summarize some interesting relations between the twoconcepts
• Parse tree filters out the choice of replacements made in thesentential forms.
• Given a left (right) derivation for a sentence, one can construct aunique parse tree for the sentence.
• For every parse tree for a sentence there is a unique leftmost and aunique rightmost derivation.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 32/124
Derivations and Parse Trees
The following summarize some interesting relations between the twoconcepts
• Parse tree filters out the choice of replacements made in thesentential forms.
• Given a left (right) derivation for a sentence, one can construct aunique parse tree for the sentence.
• For every parse tree for a sentence there is a unique leftmost and aunique rightmost derivation.
• Can a sentence have more than one distinct parse trees, andtherefore more than one left (right) derivations?
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 34/124
Ambiguous Grammars
Produces more than one parse trees for some sentence of the grammar.
Example:S → if C then S else SS → if C then SS → ass
First parse tree:
S
if C then S
ass
Sthen Cif else
ass
S
First rightmost derivation:
S → if C then S else S
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 34/124
Ambiguous Grammars
Produces more than one parse trees for some sentence of the grammar.
Example:S → if C then S else SS → if C then SS → ass
First parse tree:
Sthen Cif else
S
S
if then SC ass
ass
First rightmost derivation:
S → if C then S else S
S → if C then S else ass
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 34/124
Ambiguous Grammars
Produces more than one parse trees for some sentence of the grammar.
Example:S → if C then S else SS → if C then SS → ass
First parse tree:
Sthen Cif else
S
S
Sif C then assS S
ass
First rightmost derivation:
S → if C then S else S
S → if C then S else ass
S → if C then if C then S else ass
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 34/124
Ambiguous Grammars
Produces more than one parse trees for some sentence of the grammar.
Example:S → if C then S else SS → if C then SS → ass
First parse tree:
Sthen Cif else
S
S
Sif C then assS
ass
First rightmost derivation:
S → if C then S else S
S → if C then S else ass
S → if C then if C then S else ass
S → if C then if C then ass else ass
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 36/124
Ambiguous Grammars
The second parse tree:S
if C then S
ass
Sthen Cif else
ass
S
The second rightmost derivation:
S → if C then S else S
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 36/124
Ambiguous Grammars
The second parse tree:S
if C then
S Sthen Cif else
S
S
The second rightmost derivation:
S → if C then S else S
S → if C then S else if C then S else S
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 36/124
Ambiguous Grammars
The second parse tree:S
if C then
S Sthen Cif else
S
ass
The second rightmost derivation:
S → if C then S else S
S → if C then S else if C then S else S
S → if C then S else if C then S else ass
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 36/124
Ambiguous Grammars
The second parse tree:S
if C then
S Sthen Cif else
S
assass
The second rightmost derivation:
S → if C then S else S
S → if C then S else if C then S else S
S → if C then S else if C then S else ass
S → if C then S else if C then ass else ass
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 38/124
Ambiguous Grammars
Ambiguous grammars are usually not suitable for parsing:
• It cannot be decided by an algorithm that a given context freegrammar is indeed ambiguous ?
• A parse tree would be used subsequently for semantic analysis; morethan one parse tree would imply several interpretations and there isno obvious way of preferring one over another.
• What can be done with such grammars in the context of parsing?
1. Rewrite the grammar such that it becomes unambiguous.2. Use the grammar but supply disambiguating rules (as in YACC).
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 40/124
Left Recursive and Right Recursive Grammar Rules
Left recursive rule: the first symbol in the rhs of the rule is the samenonterminal as that in the lhslist → list , id | id
Right recursive rule: the last symbol in the rhs of the rule is the samenonterminal as that in the lhslist → id , list | id
Languages denote by list in both case are the same. Importantconsequences on parsers generated.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 42/124
Introduction to Parsing
A parser for a context free grammar G is a program P that given aninput w ,
• either verifies that w is a sentence of G and, additionally, may alsogive the parse tree for w .
• or gives an error message stating that w is not a sentence. Mayprovide some information to locate the error.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 44/124
Parsing Strategies
Two ways of creating a parse tree:
• Top-down parsers – Created from the root down to leaves.
• Bottom-up parsers – Created from leaves upwards to the root.
Both the parsing strategies can also be rephrased in terms of derivations.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 46/124
Example of Bottom Up Parsing
Grammar:
D → var list : type ;type → integer | reallist → list,id | id
The input string is var id,id : integer;
• The parse tree construction from the leaves is shown in next page.
• The sentential forms that were produced during the parse arevar id , id : integer ;
⇒ var list , id : integer ;
⇒ var list : integer ;⇒ var list : type ;⇒ D
• The sentential forms happen to be a right most derivation in thereverse order.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 48/124
Principles of Bottom Up Parsing
The basic steps of a bottom-up parser are
1. to identify a substring within a rightmost sentential form whichmatches the rhs of a rule
2. when this substring is replaced by the lhs of the matching rule, itmust produce the previous rm-sentential form.
Such a substring is called a handle .
Bottom up parsing is essentially the process of detecting handles andreducing them. Different bottom-up parsers use different methods forhandle detection.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 50/124
Example of Handles
Handles are underlined
var id , id : integer ;
⇒ var list , id : integer ;
⇒ var list : integer ;
⇒ var list : type ;
⇒ D
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 52/124
Principles of Bottom Up Parsing
A handle of a right sentential form γ, is
• a production rule A → β, and
• a position in γ
such that when β is replaced by A in γ at the given position, the resultingstring is the previous right sentential form in a rightmost derivation of γ.
Formally, if
S∗
=⇒rm α A w∗
=⇒rm αβ w
then rule A → β in the position following α in γ is a handle of γ ( = αβw).
Only terminal symbols can appear to the right of a handle in a rightmostsentential form.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 54/124
Shift-Reduce Parsers
A parsing method that directly uses the principle of bottom up parsingoutlined. A shift-reduce parser requires the following data structures.
1. a buffer for holding the input string to be parsed.
2. a data structure for detecting handles (a stack happens to beadequate)
3. a data structure for storing and accessing the lhs and rhs of rules.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 56/124
Shift-Reduce Parsers
Actions of the shift-reduce parser are:
Shift: Moving symbols from the input buffer onto the stack , onesymbol at a time. This move is called a shift action.
Reduce: Checking whether a handle occurs in the stack; if a handleis detected then a reduction by an appropriate rule isperformed ( popping off the rhs of a rule from the stackand pushing its lhs), this move is called a reduce action.
Accept: If the stack contains the start symbol only and input bufferis empty, then it announces a successful parse. This moveis known as accept action.
Error: A situation when the parser can neither shift nor reducenor accept, it declares an error, error action and halts.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 58/124
Example of Shift-Reduce Parsing
Consider the grammar:
E → E + T | E − T | TT → T ∗ F | T/F | FF → P ∗ ∗ F | PP → −P | BB → (E ) | id
stack input parser move$ -id ** id / id $ shift -$- id ** id / id $ shift id$-id ** id / id $ reduce by B → id
$-B ** id / id $ reduce by P → B$-P ** id / id $ reduce by P → −P$P ** id / id $ shift **. . . . . . . . .
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 60/124
Handle Detection in Shift-Reduce Parsing
Result: Handle in a shift-reduce parser is never buried inside the stack.Proof Outline :Consider the stack contents at some intermediate stage of parsing , sayj th sentential form, and assume the handle is on (tos) as shown below.
stack input
α B x y z
There are two possible forms for obtaining the (j − 1)th sentential form.
(j − 1)th sentential j th sentential rule used
a) αBxAz αBxyz A →y
b) δAyz αBxyz A → βBx
• In (i) after shifting y , the handle would be found on tos as claimed.
• In (ii), α = δβ and even in this situation, shifting of zero or moresymbols would allow this handle to occur on tos and get detected.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 62/124
Limitations of Shift-Reduce Parser
For some grammars, the shift-reduce parser may get into the followingconflicting situations.
• Shift-reduce conflict A handle β occurs at tos; the nexttoken a issuch that βaγ happens to be another handle. The parser has twooptions
I reduce the handle using A → βI ignore the handle β; shift a and continue parsing and eventually
reduce using B → βaγ.
• Reduce-reduce conflict the stack contents are αβγ and both βγ andγ are handles with A → βγ and B → γ as the corresponding rules.Then the parser has two reduce possibilities.
To handle such conflicts, the nexttoken could be used to prefer one moveover the other.
• choose shift (or reduce) in a shift-reduce conflict
• prefer one reduce (over others) in a reduce-reduce conflict.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 64/124
LR Parser Model
Working of a LR Parser
tos nexttoken parser action
s i
rj
acc
error handling
Sj a
Action
ia S
a A α rpoprj α: ; = ;
r2 symbols ; tos= Sk ;goto[ kS , a ] = S l ;
pushpush ; ;
lSpush
pushA
;;
continue
continue
Sj
a error
successful parse ; halt$
$nexttoken input
output
LR Parser
Initial Configuration
$S0 tos
stack
S0
parsing table
Action goto
shift to state
reduce
error
state
terminalsnon-
1
2
n
terminals
SS
S
states
Sj
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 66/124
LR Parsers
Consist of
• a stack which contains strings of the form s0X1s1X2 . . . Xmsm,where Xi is a grammar symbol and si is a special symbol called astate.
• a parsing table which comprises two parts, usually named as Actionand Goto.
The entries in the Action part are:
• si which means shift to state i
• rj which stands for reduce by the j th rule,
• accept
• error
The Goto part contains blank entries or state symbols.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 68/124
Configuration of a SLR Parser
The SLR parser has a driver routine which
• initializes the stack with the start state and calls scanner to get atoken (nexttoken).
• For any configuration, as indicated by (tos , nexttoken), it consultsthe parsing table and performs the action specified there.
• The goto part of the table is used only after a reduction.
• The parsing continues till either an error or accept entry isencountered.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 70/124
SLR(1) Parser
LR Parsing Table for an expression grammar
Grammar : E E + T | TT T * F | FF (E) | id
state id + * ( ) $ E T F
r2
r4
0
1
2
3
4
5
6
7
8
9
10
11
acc
r1
r3
r5
r6
s11
s4s5
s6
s7
1 2 3
r2r2
r4r4r4
s5 s4
r6 r6r6
s5 s4 39
s5 s4 10
s6
r1 r1s7
r3 r3 r3
r5 r5 r5
8 2 3
Action Goto
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 72/124
Working of a SLR(1) Parser
$ 0 * a = * * b $ [ 0 , *] = s4 ___
$ 0 * 4 a = * * b $ [ 4 , id ] = s5
$ 0 *4 id 5 = * * b $ [ 5 , = ] = r 4 [ 4 , L ] = 8
$ 0 *4 L 8 [ 8 , = ] = r 5
$ 0 *4 R 7 = * * b $ [ 7 , = ] = r 3
$ 0 L 2 = * * b $ [ 2 , = ] = s 6
$ 0 L 2 = 6 [ 6 , * ] = s12
$ 0 L 2 = 6 * 12 [ 12 , * ] = s12
$ 0L2=6*12*12 [12 , id ] = s11
$ 0L2=6*12*12id 11 $ [ 11 , $ ] = r 4
$ 0L2=6*12*12L10 $ [ 10 , $ ] = r 5 [12 , R ] = 13
$ 0L2=6*12*12R13 $ [ 13 , $ ] = r 3 [12 , L ] = 10
$ 0 L 2 = 6 *12 L 10 $ [ 10 , $ ] = r 5 [ 12 , R ] =13
$ 0L 2 = 6 *12 R 13 $ [ 13, $ ] = r 3
Stack Input Action table Goto table
= * * b $
* * b $
* b $
b $
Parsing the Input * a = * * b using LR Parsing Table of Fig 3.17
___
[ 4 , R] = 7
[ 0, L ] = 2
___
___
___
___
[12, L] = 10
[ 6, L ] = 10
$ 0 L 2 = 6 L 10 $ [ 10, $ ] = r5 [ 6, R ] = 9
$ 0 L 2 = 6 R 9 $ [ 9, $ ] = r1 [ 0, S ] = 1
$ 0 S 1 $ [ 1, $ ] = acc ___
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 74/124
Configuration of a LR Parser
• A configuration of a LR parser is defined by a tuple, ( stackcontents , unexpended part of input).
• Initial configuration is (s0, a1a2 . . . an$), where s0 is a designatedstart state and the second component is the entire sentence to beparsed.
• Let an intermediate configuration be given by (s0X1s1 . . . Xisi ,ajaj+1 . . . an$) , then resulting configurationi) after a shift action is given by (s0X1s1 . . . Xisiajsk , aj+1 . . . an$)provided Action[si , aj ] = sk ; both stack and nexttoken change aftera shift.ii) after a reduce action is given by (s0X1s1 . . . Xi−rAs, aj . . . an$)where Action[si , aj ] = rl ; rule pl : A → β, β has r grammarsymbols and goto(si−r ,A) = s . Only the stack changes here.
$
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 76/124
LR(0) Items
• LR(0) item : An LR(0) item for a grammar G is a production ruleof G with the symbol • ( read as dot or bullet) inserted at someposition in the rhs of the rule.
• Example of LR(0) items : For the rule given below
decls → decls declthe possible LR(0) items are :
I1 : decls → •decls declI2 : decls → decls • declI3 : decls → decls decl•
The rule decls → ε has only one LR(0) item,I4 : decls → •
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 78/124
LR(0) Items
• An LR(0) item is complete if the • is the last symbol in the rhs.Example : I3 and I4 are complete items and I1 and I2 are incompleteitems.
• An LR(0) item is called a kernel item, if the dot is not at the leftend. However the item S ′ → •S is an exception and is defined to bea kernel item.Example : I1, I2, I3 are all kernel items and I4 is a non-kernel item.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 80/124
Canonical Collection of LR(0) Items
The construction of the SLR parsing table requires two functions closureand goto.
closure: Let U be the collection of all LR(0) items of a cfg G . Thenclosure : U → 2U .
1. closure(I ) = {I}, for I ∈ U
2. If A → α • Bβ ∈ closure(I ), then the item B → •η is added toclosure(I ).
3. Apply step (ii) above repeatedly till no more new items can beadded to closure(I ).
Example: Consider the grammar A → A a | b
closure(A → •A a) = {A → •A a, A → •b}
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 82/124
Canonical Collection of LR(0) Items
goto: goto : U × X → 2U , where X is a grammar symbol.
goto(A → α • Xβ,X ) = closure(A → αX • β).
Example: goto(A → •Aa,A) = closure(A → A • a) = {A → A • a}closure and goto can be extended to a set S of LR(0) items byappropriate generalizations
• closure(S) =⋃
I∈S{closure(I )}
• goto(S ,X ) =⋃
I∈S{goto(I ,X )}
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 84/124
Algorithm for Constructing Canonical Collection of LR(0)Items
.
procedure items(G ′, C);begin
i := 0; I0 := { closure( S ′ → •S )}; C := Ii ;repeat
for each set of items Ii in C and each grammarsymbol X , such that goto(Ii ,X ) is not emptyand /∈ C, doi := i + 1 ; Ii := goto(Ii ,X ); C := C
⋃Ii
until no more sets of items can be added to Cend
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 86/124
Illustration of the Algorithm
For the grammar:
E → E + T | TT → T ∗ F | FF → (E ) | id
I0 is closure(E ′ → •E ).
• The items E ′ → •E , E → •E + T and E → •T are added to I0.
• The last one in turn causes the addition of T → •T ∗ F andT → •F .
• The item T → •F leads to the addition of F → •(E ) and F → •id.
• No more items can be added and the collection I0 is complete
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 88/124
Canonical Collection of LR(0) items
T * F .TF (E) .F id.
+ T.E E .T T * F
T F.F (E) .F id.
F ( . E )
.T T * F .E T.E E + T
F id.F (E) .T F.
.E’ E
.T T * F .E T.E E + T
F id.F (E) .T F.0
I 4I
7I
T F.3I
6I
.E T .T * F T 2I
.E E + T.E’ E
1I F id.5
I
F (E) .I 11
.T T * F 10I
.E E + T .T * F T 9
I
F ( .E ) .E E + T8I
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 90/124
LR Automaton For Expression Grammar
I10
I1I5I3
I2
I8 I6
I9I11
ETF
id (
)
+
*
F
T F
(
id E
T
id F
(
(
*
+
I 0
7I
I4
I8F (E ).
.E E + T
I1
E’ E
E E + T
.
.
I 7T T * F.
I 6E E + T.F id.
I5
I10.T T*F
I 3T F.
I4
F ( E ).
.E E + TT T *F
I9 .F (E)
I11.
I2
E TT T * F
.
.I 0
E’ E.
Only the kernel items of each state is shown in the above
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 92/124
Construction of SLR(1) Parsing Table
The procedure is described below:
1. From the input grammar G , construct an equivalent augmentedgrammar G ′.
2. Use the algorithm for constructing FOLLOW sets to computeFOLLOW(A), ∀ A ∈ N ′.
3. Call procedure items(G ′,C ) to get the desired canonical collectionC = {I0, I1, . . . , In}.
4. Choose as many state symbols as the cardinality of C . We usenumbers 0 through n to represent states.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 94/124
Construction of SLR(1) Parsing Table
For each Ii , 0 ≤ i ≤ n do steps given below.
1. if A → α• a β ∈ Ii and goto(Ii ,a) = Ij , then action[i , a] = shift j .
2. If A → α• ∈ Ii , then action[i , a] = reduce A → α for alla ∈ FOLLOW (A).
3. If Ii contains the item S ′ → S• , then action[i , $] = accept
4. All remaining entries of state i in the action table are marked aserror .
5. For nonterminals A , such that goto(Ii ,A) = Ij create goto[i ,A] = j .The remaining entries in the goto table are marked as error .
The initial state of the parser is the state corresponding to the set I0.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 96/124
Illustration of Algorithm
.E’ E
4I5
I
State.
Item with t
GOTO in , t )i iI iI(
0
6
Complete item
none
Action Table
shift 5shift 4
1 I shift 6acc on $
GOTO , A )iI(
Item with in iI
A = EA = TA = F
I123
II
goto Table
123
none
Statei
0
1
. A
F id.F (E) .
.E E + T
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 98/124
SLR(1) Grammar and Parser
stack input
$ • ((id + id))$
$( • (id + id))$
$(( • id + id))$
$((id • + id))$
$((F • + id))$
$((T • + id))$
$((E • + id))$
$((E + • id))$
$((E + id • ))$
$((E + F • ))$
$((E + T • ))$
$((E • ))$
$((E) • )$
$(F • )$
$(T • )$
$(E • )$
$(E) • $
$F • $
$T • $
$E • $
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 100/124
SLR(1) Grammar and Parser
A grammar for which there is a conflict free SLR(1) parsing table iscalled a SLR(1) grammar and a parser which uses such a table is knownas SLR(1) parser.
How do conflicts manifest in a SLR(1) parser ?
• A shift- reduce conflict is detected when a state has
1. a complete item of the form A → α• with a ∈ FOLLOW(A), and also2. an incomplete item of the form B → β• a γ
• A reduce-reduce conflict is noticed when a state has two or morecomplete items of the form A → α• and B → β•, and FOLLOW(A)⋂
FOLLOW(B) 6= Φ.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 102/124
Conceptual Issues
1. What information do the states contain?
2. Where exactly is handle detection taking place in the parser?
3. Why is FOLLOW information used to create the reduce entries inthe action table ?
To answer these questions, we need to see the canonical collection ofLR(0) items as a graph.
• A node labeled Ii is constructed for each member of C.
• For every nonempty goto(Ii , X ) = Ij , a directed edge (Ii , Ij) isadded labeled with X .
• The graph is a deterministic finite automaton if the node labeled I0is treated as the start state and all other nodes are made final states.
What does the automaton recognize?
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 104/124
Viable Prefix and Valid Items
A viable prefix of a grammar is defined to be the prefixes of rightsentential forms that do not contain any symbols to the right of a handle.
1. By adding terminal symbols to viable prefixes, rightmost sententialforms can be constructed.
2. Viable prefixes are precisely the set of symbols that can ever appearon the stack of a shift-reduce parser
3. A viable prefix either contains a handle or contains parts of one ormore handles.
4. Given a viable prefix, if one could identify the set of potentialhandles associated with it then a recognizer for viable prefixes wouldalso recognize handles.
The significance of LR(0) item can now be understood. A complete itemcorresponds to a handle while an incomplete item indicates the part of ahandle seen so far.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 106/124
Viable Prefix and Valid Items
A LR(0) item A → β1 • β2 is defined to be valid for a viable prefix, αβ1,
provided S∗
=⇒rm αA w =⇒rm αβ1β2 w
1. It is interesting to note that in above, if β2 = Bγ and B → δ, thenB → •δ is also a valid item for this viable prefix.
2. There could be several distinct items which are valid for the sameviable prefix γ.
3. A particular item may be valid for many distinct viable prefixes.
4. The parser would halt when the viable prefix S is seen, in the itemsense, it indicates a move from •S to S•. This is the reason foraugmenting the input grammar.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 108/124
Viable Prefixes and Valid Items
• Example : For the LR-automaton given in Figure 3.21, theseconcepts and their relationships are explained in the following.
• Consider the path { I0, I4, I8, I6 } which has the label (E+along it.The items that are valid for the viable prefix, (E+are determinedbelow. 1. E ′ =⇒rm E =⇒ T =⇒ F =⇒ (E ) =⇒ (E + T ) showsthat E → E + •T is a valid item 2.E ′ =⇒ E =⇒ T =⇒ F =⇒ (E ) =⇒ (E + T ) =⇒ (E + T ∗ F )shows that T → •T ∗ F is also a valid item. 3.E ′ ∗
=⇒rm(E + T ) =⇒ (E + F ) shows that T → •F is another such
item. 4. E ′ ∗=⇒rm(E + T ) =⇒ (E + F ) =⇒ (E + (E )) shows that
F → •(E ) is a valid item. 5. E ′ ∗=⇒rm(E + F ) =⇒ (E+id ) shows
that F → • id is a valid item. It should be noted that are no othervalid items for this viable prefix.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 110/124
Viable Prefixes and Valid Items
Given a LR(0) item, say T → T • ∗F , there may be several viableprefixes for which it is valid.
1. E ′ =⇒rm E =⇒ T =⇒ T ∗ F shows that this item is valid for theviable prefix T .
2. E ′ =⇒ E =⇒ T =⇒ F =⇒ (E ) =⇒ (T ) =⇒ (T ∗ F ) shows that itis also valid for ( T .
3. E ′ =⇒ E =⇒ T =⇒ T ∗F =⇒ T ∗ (E ) =⇒ T ∗ (T ) =⇒ T ∗ (T ∗F )shows that it is valid also for T * ( T .
4. E ′ =⇒ E =⇒ E + T =⇒ E + T ∗ F shows validity for E + T .
There may be several other viable prefixes for which this item is valid.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 112/124
Theory of LR Parsing
THEOREM : Starting from I0, if traversing the LR(0) automaton γresults in state j , then set items in Ij are the only valid items for theviable prefix γ.
• The theorem stated without proof above is a key result in LRParsing. It provides the basis for the correctness of the constructionprocess we learnt earlier.
• An LR parser does not scan the entire stack to determine when andwhich handle appears on top of stack ( compare with shift-reduceparser ).
• The state symbol on top of stack provides all the information that ispresent in the stack.
• In a state which contains a complete item a reduction is called for.However, the lookahead symbols for which the reduction should beapplied is not obvious.
• In SLR(1) parser the FOLLOW information is used to guidereductions.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 114/124
Limitations of SLR(1) PARSER
Using FOLLOW information for is imprecise
S → L = R |RL → ∗R |idR → L
The SLR automaton and the parsing table for this grammar are shown.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 116/124
SLR Automaton for a Grammar
S’ S .
.RS
.idL
LS R .=
* R .L
L R .
S’ S.S L = R | . . R
L R . * R | ..L id
LS R .=L R .* R .L .L id
L R .* R .L
* .L R
.L id
LS = R .L R .
I o
I 1
I 2 I 3
I 4
I 5
I 6
I 7
I 8
I 9
S
LR id
*
=
*
L
Rid
R
L
id
*
FOLLOW
S’ { $ }S { $ }L { = $ }R { = $ }
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 118/124
SLR Parsing Table
Grammar : S’ SS L = R | RL * R | id
state id * = $ S L R
r4
0
1
2
3
4
5
6
7
8
9
acc
r1
r3
s4s5 1 2 3
s5 s4
s5 s4 98
r3
r5 r5
8 7
Action Goto
LR
s6 r5r5
r2
- -
- - -
- -
- - -
- - -
- - -
- - -
- -- - -r4
-
-
-
- -
-
-
- - - - -
- - - -
- - - - - -
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 120/124
SLR Parsing Table
• Observe that {=} ∈ FOLLOW(R), and R → L• is an item in state2. There is another item, S → L• = R in the same state
• Note that state 2 recognizes the viable prefix L and the shift entry isjustifiable.
• How about the reduce entry ? After seeing L, if we reduce it to R ,with the expectation of = to follow, there must exist a viable prefixR = . . . and hence a right sentential form of the form R = z. It canbe shown that such is not possible. The problem seems to be withour FOLLOW information.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 122/124
Limitations of SLR(1) Parser
What is wrong with FOLLOW ?
• This information is not correct for state 2.
• The sentential forms that permit = to follow R are of the form∗L . . . and taken care of in the state 8 of the parser.
• The context in state 2 is different ( viable prefix is L ), and use ofFOLLOW constrains the parser.
Given an item and a state the need is to identify the terminal symbolsthat can actually follow the lhs nonterminal.
Amitabha Sanyal IIT Bombay
College of Engineering, Pune Syntax Analysis: 124/124
Limitations of SLR(1) Parser
An item of the form, A → α • β, a where the first component is a LR(0)item and the second component is a set of terminal symbols is called aLR(1) item. The second component is known as lookahead symbol. Thevalue 1 indicates that the length of lookahead is 1.
• The lookahead symbol is used in a reduce operation only. For anitem of the form, A → α • β, a if β is not ε, the lookahead has noeffect. But for an item, A → α•, a the reduction is applied only ifthe nexttoken is a.
Amitabha Sanyal IIT Bombay