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 group tokens 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 group tokens according to certain rules. This is called syntax checking. • May actually create the hierarchical structure that arises out of such grouping. This information is required by subsequent phases.

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 4/124 Syntax Analysis – Example

fundef

fname params compound-stmt

identifier ( ) { vdecl slist }

main type varlist ; . . . main () { int varlist , var int i,sum; sum = 0; var identifier for (i=1; i<=10; i++); sum = sum + i; identifier sum printf("%d\n",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 specification of what is a well-formed program. 1. the specification be precise. 2. the specification be complete. Must cover all the syntactic details of the language 3. 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 .

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 ) were written manually. • A better understanding of algorithms has resulted in tools that can automatically generate parsers. • Examples of parser generating tools: I /Bison: Bottom-up (LALR) parser generator I 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

get next Source Lexical token Parser Rest of the Program analyser compiler token

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 token comma • followed by token semicolon

Question: Can the list of identifier tokens be empty?

declaration → type idlist ; idlist → id | idlist , id type → 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 S T )

declaration → type idlist ; start symbol idlist → id | idlist , id terminals type → integer | real non-terminals production

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 a non-terminal by the corresponding right hand side of a production is called a derivation. • The set of all possible terminal strings that can be derived from the start 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 form non-terminal → sequence of terminals and non-terminals 2. Rules are used to replace an occurrence of the lhs non-terminal by its rhs. The replacement is made regardless of the context (symbols surrounding 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 names such as declaration , list and 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 called sentences of G. ∗ ∗ • A string α, α ∈ (N S T ) , such that S =⇒ α, is called a sentential form 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 sentential form. I choice of the nonterminal to be replaced I choice of a rule corresponding to the nonterminal. • Instead of choosing the nonterminal to be replaced, in an arbitrary fashion, it is possible to make an uniform choice at each step. I replace the leftmost nonterminal in a sentential form I replace the rightmost nonterminal in a sentential form The corresponding derivations are known as leftmost and rightmost derivations respectively. • Given a sentence w of a grammar G, there are several distinct derivations 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 node from left to right are labeled with X1, X2, . . . , Xn then there must be a 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 | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T

E + T

E + T F

T F id

F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T

E + T F

T F id

F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T

E + T F

T F id

F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T ⇒ F + T + T E + T F

T F id

F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T ⇒ F + T + T E + T F ⇒ id + T + T

T F id

F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T ⇒ F + T + T E + T F ⇒ id + T + T T F id ⇒ id + F + T

F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T ⇒ F + T + T E + T F ⇒ id + T + T T F id ⇒ id + F + T ⇒ id + id + T F id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

The parse tree: Leftmost derivation: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T ⇒ F + T + T E + T F ⇒ id + T + T T F id ⇒ id + F + T ⇒ id + id + T F id ⇒ id + id + F

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

Leftmost derivation: The parse tree: E E ⇒ E + T ⇒ E + T + T E + T ⇒ T + T + T ⇒ F + T + T E + T F ⇒ id + T + T ⇒ id + F + T T F id ⇒ id + id + T ⇒ id + id + F F id ⇒ id + id + id

id

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 30/124 Illustration E → E + T | T T → T ∗ F | F F → (E) | id

Leftmost derivation: The parse tree: Rightmost derivation: E ⇒ E + T E E ⇒ E + T ⇒ E + T + T ⇒ E + F ⇒ T + T + T E + T ⇒ E + id ⇒ F + T + T ⇒ E + T + id E + T F ⇒ id + T + T ⇒ E + F + id ⇒ id + F + T ⇒ E + id + id T F id ⇒ id + id + T ⇒ T + id + id ⇒ id + id + F F id ⇒ F + id + id ⇒ id + id + 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 two concepts • Parse tree filters out the choice of replacements made in the sentential 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 two concepts • Parse tree filters out the choice of replacements made in the sentential forms. • Given a left (right) derivation for a sentence, one can construct a unique 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 two concepts • Parse tree filters out the choice of replacements made in the sentential forms. • Given a left (right) derivation for a sentence, one can construct a unique parse tree for the sentence. • For every parse tree for a sentence there is a unique leftmost and a unique 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 two concepts • Parse tree filters out the choice of replacements made in the sentential forms. • Given a left (right) derivation for a sentence, one can construct a unique parse tree for the sentence. • For every parse tree for a sentence there is a unique leftmost and a unique rightmost derivation. • Can a sentence have more than one distinct parse trees, and therefore 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 S S → if C then S S → ass

First parse tree: S First rightmost derivation: if C then S S → if C then S else S

if C then S else S

ass 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 S S → if C then S S → ass

First parse tree: S First rightmost derivation: → if then else if C then S else S S C S S S → if C then S else ass

if C then assS

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 S S → if C then S S → ass

First parse tree: S First rightmost derivation: → if then else if C then S else S S C S S S → if C then S else ass S → if C then if C then S else ass if C then S assS

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 S S → if C then S S → ass

First parse tree: S First rightmost derivation: → if then else if C then S else S S C S S S → if C then S else ass S → if C then if C then S else ass if C then S assS S → if C then if C then ass else ass

ass

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars

The second parse tree: The second rightmost derivation: S S → if C then S else S if C then S

if C then S else S

ass ass

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars

The second parse tree: The second rightmost derivation: S S → if C then S else S S → if C then S else if C then S else S if C then S

if C then S else S

S

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars

The second parse tree: The second rightmost derivation: S S → if C then S else S S → if C then S else if C then S else S if C then S S → if C then S else if C then S else ass

if C then S else S

ass

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars

The second rightmost derivation: The second parse tree: S 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 if C then S S → if C then S else if C then ass else ass

if C then S else S

ass 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 free grammar is indeed ambiguous ? • A parse tree would be used subsequently for semantic analysis; more than one parse tree would imply several interpretations and there is no 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 same nonterminal as that in the lhs list → list , id | id

Right recursive rule: the last symbol in the rhs of the rule is the same nonterminal as that in the lhs list → id , list | id

Languages denote by list in both case are the same. Important consequences 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 an input w, • either verifies that w is a sentence of G and, additionally, may also give the parse tree for w. • or gives an error message stating that w is not a sentence. May provide 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 | real list → 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 are var 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 the reverse 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 which matches the rhs of a rule 2. when this substring is replaced by the lhs of the matching rule, it must produce the previous rm-sentential form. Such a substring is called a handle .

Bottom up parsing is essentially the process of detecting handles and reducing them. Different bottom-up parsers use different methods for handle 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 resulting string 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 rightmost sentential 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 parsing outlined. 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 be adequate) 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 , one symbol at a time. This move is called a shift action. Reduce: Checking whether a handle occurs in the stack; if a handle is detected then a reduction by an appropriate rule is performed ( popping off the rhs of a rule from the stack and pushing its lhs), this move is called a reduce action. Accept: If the stack contains the start symbol only and input buffer is empty, then it announces a successful parse. This move is known as accept action. Error: A situation when the parser can neither shift nor reduce nor 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 | T T → T ∗ F | T /F | F F → P ∗ ∗ F | P P → −P | B B → (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 , say jth 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 more symbols 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 following conflicting situations. • Shift-reduce conflict A handle β occurs at tos; the nexttoken a is such that βaγ happens to be another handle. The parser has two options 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 move over 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

non- nexttoken input terminals terminals states $ Action goto S0 shift to state state S 1 reduce S2 stack LR Parser error

S0 tos Sn $ output parsing table Initial Configuration Working of a LR Parser

tos nexttoken Action parser action

Sj a s i push a ; push S i ; continue α α a rj rj : A ; = r ; S pop 2 r symbols ; tos= k ; goto[ S k , a ] =S l ; push A ; push Sl ; continue S j $ acc successful parse ; halt

Sj a error error handling

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 a state. • a parsing table which comprises two parts, usually named as Action and Goto. The entries in the Action part are:

• si which means shift to state i th • rj which stands for reduce by the j 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 a token (nexttoken). • For any configuration, as indicated by (tos , nexttoken), it consults the 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 is encountered.

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 | T T T * F | F F (E) | id

Action Goto state id + * ( ) $ E T F

0 s5 s4 1 2 3

1 s6 acc

2 r2 s7 r2 r2 3 r4 r4 r4 r4 4 s5 s4 8 2 3 5 r6 r6 r6 r6

6 s5 s4 9 3

7 s5 s4 10 8 s6 s11

9 r1 s7 r1 r1 10 r3 r3 r3 r3 r5 11 r5 r5 r5 Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 72/124 Working of a SLR(1) Parser

Parsing the Input * a = * * b using LR Parsing Table of Fig 3.17

Stack Input Action table Goto table

$ 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 = * * b $ [ 8 , = ] = r 5 [ 4 , R] = 7

$ 0 *4 R 7 = * * b $ [ 7 , = ] = r 3 [ 0, L ] = 2 ___ $ 0 L 2 = * * b $ [ 2 , = ] = s 6 ___ $ 0 L 2 = 6 * * b $ [ 6 , * ] = s12 ___ $ 0 L 2 = 6 * 12 * b $ [ 12 , * ] = s12 ___ $ 0L2=6*12*12 b $ [12 , id ] = s11 $ 0L2=6*12*12id 11 $ [ 11 , $ ] = r 4 [12, L] = 10 $ 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 [ 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, ( stack contents , unexpended part of input).

• Initial configuration is (s0, a1a2 . . . an$), where s0 is a designated start state and the second component is the entire sentence to be parsed.

• Let an intermediate configuration be given by (s0X1s1 . . . Xi si , aj aj+1 . . . an$) , then resulting configuration i) after a shift action is given by (s0X1s1 . . . Xi si aj sk , aj+1 . . . an$) provided Action[si , aj ] = sk ; both stack and nexttoken change after a shift. ii) after a reduce action is given by (s0X1s1 . . . Xi−r As, aj . . . an$) where Action[si , aj ] = rl ; rule pl : A → β, β has r grammar symbols 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 rule of G with the symbol • ( read as dot or bullet) inserted at some position in the rhs of the rule. • Example of LR(0) items : For the rule given below

decls → decls decl the possible LR(0) items are : I1 : decls → •decls decl I2 : decls → decls • decl I3 : 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 incomplete items. • An LR(0) item is called a kernel item, if the dot is not at the left end. However the item S 0 → •S is an exception and is defined to be a 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 closure and goto.

closure: Let U be the collection of all LR(0) items of a cfg G. Then closure : U → 2U . 1. closure(I ) = {I }, for I ∈ U 2. If A → α • Bβ ∈ closure(I ), then the item B → •η is added to closure(I ). 3. Apply step (ii) above repeatedly till no more new items can be added 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 by appropriate generalizations

• closure(S) = SI∈S{closure(I )}

• goto(S, X ) = SI∈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 0, C); begin 0 i := 0; I0 := { closure( S → •S )}; C := Ii ; repeat for each set of items Ii in C and each grammar symbol X , such that goto(Ii ,X ) is not empty and ∈/ C, do i := i + 1 ; Ii := goto(Ii ,X ); C := C S Ii until no more sets of items can be added to C end

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 86/124 Illustration of the Algorithm

For the grammar: E → E + T | T T → T ∗ F | F F → (E) | id

0 I0 is closure(E → •E). 0 • 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 and T → •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

E’ E F ( E ) T T * F . . I . E . E + T E . E + T 7 F . (E) F id E . T E . T . I I T T * F 0 T . T * F 4 . T . F T . F F (E) F (E) . . F ( E ) F id I . F . id . 8 E E . + T

E’ E I I . 5 F id I E E + T . 1 E E . + T . 9 T T. * F

E T I 2 . I T T. * F 10 T T * F . E E + . T I T . T * F 6 T . F F (E) I . I 3 T F. F . id 11 F (E) . Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 90/124 LR Automaton For Expression Grammar I T 0 E F ( id T I I F I I 2 4 3 5 I1 ( id F + E id ( I I 8 + 6 * T ) I9 I 11 * (

I I 7 I I 1 2 0 I F E' E . E T . 3 I10 E' .E E E .+ T T T.* F T F.

I I I 4 I5 6 7 F ( .E ) F id . E E +.T T T * .F I8 I9 F (E. ) E E + T . I10 I11 E E . + T T T . *F T T*F . F (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 augmented grammar G 0. 2. Use the algorithm for constructing FOLLOW sets to compute FOLLOW(A), ∀ A ∈ N0. 3. Call procedure items(G 0, C) to get the desired canonical collection C = {I0, I1, . . . , In}. 4. Choose as many state symbols as the cardinality of C. We use numbers 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 all a ∈ FOLLOW (A). 0 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 as error.

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

State Item with GOTO Complete Action i t in I item . i ( Ii, t ) Table I 0 F . id 5 shift 5 I F . (E) 4 shift 4 none

1 E . + T shift 6 E I6 E’ E . acc on $

Item with GOTO goto State A in I i . i (I i, A ) Table 1 0 A = E I1 A = T I2 2 3 A = F I3

1 none

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 is called a SLR(1) grammar and a parser which uses such a table is known as 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 also 2. an incomplete item of the form B → β• a γ • A reduce-reduce conflict is noticed when a state has two or more complete items of the form A → α• and B → β•, and FOLLOW(A) T 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 in the action table ?

To answer these questions, we need to see the canonical collection of LR(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 ) is added labeled with X .

• The graph is a deterministic finite automaton if the node labeled I0 is 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 right sentential forms that do not contain any symbols to the right of a handle. 1. By adding terminal symbols to viable prefixes, rightmost sentential forms can be constructed. 2. Viable prefixes are precisely the set of symbols that can ever appear on the stack of a shift-reduce parser 3. A viable prefix either contains a handle or contains parts of one or more handles. 4. Given a viable prefix, if one could identify the set of potential handles associated with it then a recognizer for viable prefixes would also recognize handles. The significance of LR(0) item can now be understood. A complete item corresponds to a handle while an incomplete item indicates the part of a handle 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 → δ, then B → •δ is also a valid item for this viable prefix. 2. There could be several distinct items which are valid for the same viable 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 item sense, it indicates a move from •S to S•. This is the reason for augmenting 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, these concepts 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 determined 0 below. 1. E =⇒rm E =⇒ T =⇒ F =⇒ (E) =⇒ (E + T ) shows that E → E + •T is a valid item 2. E 0 =⇒ E =⇒ T =⇒ F =⇒ (E) =⇒ (E + T ) =⇒ (E + T ∗ F ) shows that T → •T ∗ F is also a valid item. 3. 0 ∗ E =⇒rm(E + T ) =⇒ (E + F ) shows that T → •F is another such 0 ∗ item. 4. E =⇒rm(E + T ) =⇒ (E + F ) =⇒ (E + (E)) shows that 0 ∗ 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 other valid 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 viable prefixes for which it is valid. 0 1. E =⇒rm E =⇒ T =⇒ T ∗ F shows that this item is valid for the viable prefix T . 2. E 0 =⇒ E =⇒ T =⇒ F =⇒ (E) =⇒ (T ) =⇒ (T ∗ F ) shows that it is also valid for ( T . 3. E 0 =⇒ E =⇒ T =⇒ T ∗F =⇒ T ∗(E) =⇒ T ∗(T ) =⇒ T ∗(T ∗F ) shows that it is valid also for T * ( T . 4. E 0 =⇒ 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 the viable prefix γ. • The theorem stated without proof above is a key result in LR Parsing. It provides the basis for the correctness of the construction process we learnt earlier. • An LR parser does not scan the entire stack to determine when and which handle appears on top of stack ( compare with shift-reduce parser ). • The state symbol on top of stack provides all the information that is present 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 be applied is not obvious. • In SLR(1) parser the FOLLOW information is used to guide reductions.

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|R L → ∗R|id R → 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

I o I 4 S * I 1 S' .S S .L = R | . R L * . R S' S . L . * R | . id R . L R . L L . * R * L L id id . I 2 R I 3 L id S L . = R S R . R R L . I 7 = L * R . I 6 *

S L = . R R . L L id . id L . * R R L . L id I 5 . L I 8 R

FOLLOW S L = R . S' { $ } I 9 S { $ } L { = $ } R { = $ }

Amitabha Sanyal IIT Bombay College of Engineering, Pune Syntax Analysis: 118/124 SLR Parsing Table

Grammar : S' S S L = R | R L * R | id R L Action Goto state id * = $ S L R

0 s5 s4 - - 1 2 3

1 - - - acc - - - s6 - 2 - - r5 - - r5 3 - - - r2 - - - 4 s5 s4 - - - 8 7 5 - - r4 r4 - - -

6 s5 s4 - - - 8 9 7 - - r3 r3 - - - 8 - - r5 r5 - - - 9 - - - r1 - - -

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 state 2. There is another item, S → L• = R in the same state • Note that state 2 recognizes the viable prefix L and the shift entry is justifiable. • 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 prefix R = . . . and hence a right sentential form of the form R = z. It can be shown that such is not possible. The problem seems to be with our 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 of FOLLOW constrains the parser. Given an item and a state the need is to identify the terminal symbols that 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 a LR(1) item. The second component is known as lookahead symbol. The value 1 indicates that the length of lookahead is 1. • The lookahead symbol is used in a reduce operation only. For an item of the form, A → α • β, a if β is not , the lookahead has no effect. But for an item, A → α•, a the reduction is applied only if the nexttoken is a.

Amitabha Sanyal IIT Bombay