Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

Similar documents
Bottom-up parsing. Bottom-Up Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form

Formal Languages and Compilers Lecture VII Part 3: Syntactic A

Bottom up parsing. The sentential forms happen to be a right most derivation in the reverse order. S a A B e a A d e. a A d e a A B e S.

LR Parsing Techniques

3. Syntax Analysis. Andrea Polini. Formal Languages and Compilers Master in Computer Science University of Camerino

PART 3 - SYNTAX ANALYSIS. F. Wotawa TU Graz) Compiler Construction Summer term / 309

Context-free grammars

Section A. A grammar that produces more than one parse tree for some sentences is said to be ambiguous.

Compiler Design 1. Bottom-UP Parsing. Goutam Biswas. Lect 6

Compiler Construction: Parsing

UNIT-III BOTTOM-UP PARSING

A left-sentential form is a sentential form that occurs in the leftmost derivation of some sentence.

Compiler Construction 2016/2017 Syntax Analysis

S Y N T A X A N A L Y S I S LR

LR Parsing. Leftmost and Rightmost Derivations. Compiler Design CSE 504. Derivations for id + id: T id = id+id. 1 Shift-Reduce Parsing.

Principles of Programming Languages

MODULE 14 SLR PARSER LR(0) ITEMS

MIT Parse Table Construction. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology


LR Parsers. Aditi Raste, CCOEW

4. Lexical and Syntax Analysis

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

4. Lexical and Syntax Analysis

LR Parsing, Part 2. Constructing Parse Tables. An NFA Recognizing Viable Prefixes. Computing the Closure. GOTO Function and DFA States

Lexical and Syntax Analysis. Bottom-Up Parsing

Formal Languages and Compilers Lecture VII Part 4: Syntactic A


Syntax Analysis: Context-free Grammars, Pushdown Automata and Parsing Part - 4. Y.N. Srikant

UNIT III & IV. Bottom up parsing

Concepts Introduced in Chapter 4

Lecture Bottom-Up Parsing

CS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F).

Chapter 4. Lexical and Syntax Analysis

Bottom Up Parsing. Shift and Reduce. Sentential Form. Handle. Parse Tree. Bottom Up Parsing 9/26/2012. Also known as Shift-Reduce parsing

CSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis

Bottom-Up Parsing. Lecture 11-12

Syntax Analysis Part I

Monday, September 13, Parsers

Bottom-Up Parsing. Lecture 11-12

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing

Wednesday, September 9, 15. Parsers

Parsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs:

LALR Parsing. What Yacc and most compilers employ.

Parsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468

Wednesday, August 31, Parsers

EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:

VIVA QUESTIONS WITH ANSWERS

Let us construct the LR(1) items for the grammar given below to construct the LALR parsing table.

Parsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1)

Compilers. Bottom-up Parsing. (original slides by Sam

Chapter 4: LR Parsing

LR Parsing Techniques

Top down vs. bottom up parsing

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones

Lecture 8: Deterministic Bottom-Up Parsing

Compilerconstructie. najaar Rudy van Vliet kamer 140 Snellius, tel rvvliet(at)liacs(dot)nl. college 3, vrijdag 22 september 2017

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

Syntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38

Lecture 7: Deterministic Bottom-Up Parsing

CSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D-1

How do LL(1) Parsers Build Syntax Trees?

SLR parsers. LR(0) items

CSE302: Compiler Design

CS 314 Principles of Programming Languages

Syntax Analysis Check syntax and construct abstract syntax tree

Top-Down Parsing and Intro to Bottom-Up Parsing. Lecture 7

The analysis part breaks up the source program into constituent pieces and creates an intermediate representation of the source program.

LR Parsing - The Items

Chapter 4. Lexical and Syntax Analysis. Topics. Compilation. Language Implementation. Issues in Lexical and Syntax Analysis.

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

Bottom-up Parser. Jungsik Choi

Table-driven using an explicit stack (no recursion!). Stack can be viewed as containing both terminals and non-terminals.

3. Parsing. Oscar Nierstrasz

Syntactic Analysis. Top-Down Parsing

CS 4120 Introduction to Compilers

Syntax Analysis. Prof. James L. Frankel Harvard University. Version of 6:43 PM 6-Feb-2018 Copyright 2018, 2015 James L. Frankel. All rights reserved.

Parser Generation. Bottom-Up Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottom-up --- from leaves to the root

Bottom-Up Parsing II. Lecture 8

Syntax Analyzer --- Parser

Downloaded from Page 1. LR Parsing

Bottom-Up Parsing II (Different types of Shift-Reduce Conflicts) Lecture 10. Prof. Aiken (Modified by Professor Vijay Ganesh.

Bottom-Up Parsing LR Parsing

Introduction to Syntax Analysis

LR Parsing LALR Parser Generators

Top-Down Parsing and Intro to Bottom-Up Parsing. Lecture 7

Syntax. In Text: Chapter 3

8 Parsing. Parsing. Top Down Parsing Methods. Parsing complexity. Top down vs. bottom up parsing. Top down vs. bottom up parsing

Principle of Compilers Lecture IV Part 4: Syntactic Analysis. Alessandro Artale

Chapter 3. Describing Syntax and Semantics ISBN

Syn S t yn a t x a Ana x lysi y s si 1

Simple LR (SLR) LR(0) Drawbacks LR(1) SLR Parse. LR(1) Start State and Reduce. LR(1) Items 10/3/2012

Programming Language Syntax and Analysis

Review: Shift-Reduce Parsing. Bottom-up parsing uses two actions: Bottom-Up Parsing II. Shift ABC xyz ABCx yz. Lecture 8. Reduce Cbxy ijk CbA ijk

Introduction to Syntax Analysis. The Second Phase of Front-End

CSCI312 Principles of Programming Languages

Parsing - 1. What is parsing? Shift-reduce parsing. Operator precedence parsing. Shift-reduce conflict Reduce-reduce conflict

LL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012

CS308 Compiler Principles Syntax Analyzer Li Jiang

CS2210: Compiler Construction Syntax Analysis Syntax Analysis

Introduction to Parsing. Comp 412

Transcription:

Syntax Analysis (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.

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.

College of Engineering, Pune Syntax Analysis: 4/124 Syntax Analysis Example fundef fname params compound-stmt identifier ( ) { vdecl slist } main () { int i,sum; sum = 0; for (i=1; i<=10; i++); sum = sum + i; printf("%d\n",sum); } main type varlist ; int varlist, var var identifier identifier sum i...

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 parse tree.

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 written manually. A better understanding of parsing algorithms has resulted in tools that can automatically generate parsers. Examples of parser generating tools: Yacc/Bison: Bottom-up (LALR) parser generator Antlr: Top-down (LL) scanner cum parser generator.

College of Engineering, Pune Syntax Analysis: 10/124 Syntax Analysis Interface of a parser with the rest of the compiler Source Program Lexical analyser get next token token Parser Rest of the compiler

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.

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 ) start symbol non-terminals declaration type idlist ; idlist id idlist, id type integer real production terminals

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.

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).

College of Engineering, Pune Syntax Analysis: 20/124 Notational Conventions Symbol type single terminal single nonterminal single grammar symbol (symbol from {N T } ) string of terminals string of grammar symbols null string Convention letters a, b, c, operators delimiters, keywords letters A, B, C and names such as declaration, list and S is the start symbol X, Y, Z letters x, y, z α, β, γ ɛ

College of Engineering, Pune Syntax Analysis: 22/124 Formal Definitions Let A γ be a production rule α A β be a string of grammar symbols Replacing the nonterminal A in α A β yields α γ β. Formally, this is stated as α A β derives α γ β in one step. 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.

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 T ), such that S = α, is called a sentential form of G. Two grammars are equivalent,if they generate the same language.

College of Engineering, Pune Syntax Analysis: 26/124 Basic Concepts in Parsing For constructing a derivation, there are choices at each sentential form. choice of the nonterminal to be replaced 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. replace the leftmost nonterminal in a sentential form 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.

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 X 1, X 2,..., X n then there must be a production A X 1 X 2... X n where X i is a grammar symbol.

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E Leftmost derivation: E E + T E + T E + T F T F id F id id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T Leftmost derivation: E E + T E + T + T E + T F T F id F id id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T Leftmost derivation: E E + T E + T + T T + T + T E + T F T F id F id id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E + T F Leftmost derivation: E E + T E + T + T T + T + T F + T + T T F id F id id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E + T E E + T T F F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T F id id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T + T F F id Leftmost derivation: E E + T E + T + T T + T + T F + T + T id + T + T id + F + T F id id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T F + T 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

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T F + T 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

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E T F + T 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 id

College of Engineering, Pune Syntax Analysis: 30/124 Illustration E E + T T T T F F F (E) id The parse tree: E E + T E + T F T F id F id 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

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.

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.

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.

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?

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 if C then S First rightmost derivation: S if C then S else S if C then S else S ass ass

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

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

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

College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S The second rightmost derivation: S if C then S else S if C then S else S ass ass

College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S The second rightmost derivation: S if C then S else S S if C then S else if C then S else S if C then S else S S

College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S 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 if C then S else S ass

College of Engineering, Pune Syntax Analysis: 36/124 Ambiguous Grammars The second parse tree: S if C then S 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 if C then S else S ass ass

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).

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.

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.

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.

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.

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.

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

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.

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.

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.

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 **.........

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 j th sentential form, and assume the handle is on (tos) as shown below. stack α B input 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.

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 reduce the handle using A β 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.

College of Engineering, Pune Syntax Analysis: 64/124 LR Parser Model nonnexttoken input terminals terminals $ states Action goto S0 shift to state S 1 state reduce S 2 stack LR Parser error S 0 $ tos S n output parsing Initial Configuration Working of a LR Parser table tos nexttoken Action parser action S j S j a s i push a ; push S i ; continue a rj rj : A α ; α = r ; pop 2 r symbols ; tos= S k ; goto[ S k, a ] = S l ; push A ; push S l ; continue $ acc successful parse ; halt S j a error error handling

College of Engineering, Pune Syntax Analysis: 66/124 LR Parsers Consist of a stack which contains strings of the form s 0 X 1 s 1 X 2... X m s m, where X i is a grammar symbol and s i 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: s i which means shift to state i r j which stands for reduce by the j th rule, accept error The Goto part contains blank entries or state symbols.

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.

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 1 2 3 4 5 6 7 8 9 10 11 s5 s5 s6 r2 r4 r6 r1 r3 r5 s7 r4 r6 s4 s4 r2 r4 r6 s11 acc r2 r4 r6 1 2 3 s5 s4 9 3 s5 s4 10 s6 s7 r1 r1 r3 r3 r3 r5 r5 r5 8 2 3

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

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 (s 0, a 1 a 2... a n $), where s 0 is a designated start state and the second component is the entire sentence to be parsed. Let an intermediate configuration be given by (s 0 X 1 s 1... X i s i, a j a j+1... a n $), then resulting configuration i) after a shift action is given by (s 0 X 1 s 1... X i s i a j s k, a j+1... a n $) provided Action[s i, a j ] = s k ; both stack and nexttoken change after a shift. ii) after a reduce action is given by (s 0 X 1 s 1... X i r As, a j... a n $) where Action[s i, a j ] = r l ; rule p l : A β, β has r grammar symbols and goto(s i r, A) = s. Only the stack changes here.

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 : I 1 : decls decls decl I 2 : decls decls decl I 3 : decls decls decl The rule decls ɛ has only one LR(0) item, I 4 : decls

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 : I 3 and I 4 are complete items and I 1 and I 2 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 S is an exception and is defined to be a kernel item. Example : I 1, I 2, I 3 are all kernel items and I 4 is a non-kernel item.

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 2 U. 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}

College of Engineering, Pune Syntax Analysis: 82/124 Canonical Collection of LR(0) Items goto: goto : U X 2 U, 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) = I S {closure(i )} goto(s, X ) = I S {goto(i, X )}

College of Engineering, Pune Syntax Analysis: 84/124 Algorithm for Constructing Canonical Collection of LR(0) Items. procedure items(g, C); begin i := 0; I 0 := { closure( S S )}; C := I i ; repeat for each set of items I i in C and each grammar symbol X, such that goto(i i,x ) is not empty and / C, do i := i + 1 ; I i := goto(i i,x ); C := C I i until no more sets of items can be added to C end

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 I 0 is closure(e E). The items E E, E E + T and E T are added to I 0. 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 I 0 is complete

College of Engineering, Pune Syntax Analysis: 88/124 Canonical Collection of LR(0) items I 0 E. E E E + T E T..... T T * F T F F (E) F id I 4 F (. E ) E E + T E T..... T T * F T F F (E) F id I 7 I 8. T T * F F. (E) F id. F ( E. ) E E + T. E E. I I F 1 E E. id. + T 5 I 9 E T E + T T.. * F I 2 I 3 E T. T T. T F. * F I 6 E T... E + T T * F T F F (E) F id I 10 I 11 T T * F F (E)..

College of Engineering, Pune Syntax Analysis: 90/124 LR Automaton For Expression Grammar * I 2 ( I T 0 E ( F id T I 4 F I I 3 5 ( id F E id ( I I 8 + 6 ) I 11 * + I 1 T I9 I 7 F I 10 I 0. E E I 1 E E. E E + T I 2 E T. T T * F. I 3 T F. I 4 F ( E ). I8 F (E ) E E + T.. I I 5 6 F id. E E +. T I9 E E + T T T *F.. T I 7 T T * F. I 10 T*F. F I 11 (E). Only the kernel items of each state is shown in the above

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. 2. Use the algorithm for constructing FOLLOW sets to compute FOLLOW(A), A N. 3. Call procedure items(g, C) to get the desired canonical collection C = {I 0, I 1,..., I n }. 4. Choose as many state symbols as the cardinality of C. We use numbers 0 through n to represent states.

College of Engineering, Pune Syntax Analysis: 94/124 Construction of SLR(1) Parsing Table For each I i, 0 i n do steps given below. 1. if A α a β I i and goto(i i,a) = I j, then action[i, a] = shift j. 2. If A α I i, then action[i, a] = reduce A α for all a FOLLOW (A). 3. If I i 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(i i, A) = I j 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 I 0.

College of Engineering, Pune Syntax Analysis: 96/124 Illustration of Algorithm State i 0 Item with GOTO. t in I i ( I i, t ) F. id F. (E) I I 5 4 Complete item none Action Table shift 5 shift 4 1 E E. + T I shift 6 6 E E. acc on $ State i Item with. A in I i GOTO (I i, A ) goto Table 0 A = E A = T A = F I 1 I2 I3 1 2 3 1 none

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 $

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) FOLLOW(B) Φ.

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 I i is constructed for each member of C. For every nonempty goto(i i, X ) = I j, a directed edge (I i, I j ) is added labeled with X. The graph is a deterministic finite automaton if the node labeled I 0 is treated as the start state and all other nodes are made final states. What does the automaton recognize?

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.

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.

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 { I 0, I 4, I 8, I 6 } which has the label (E+along it. The items that are valid for the viable prefix, (E+are determined below. 1. E = rm E = T = F = (E) = (E + T ) shows that 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 other valid items for this viable prefix.

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. 1. E = rm E = T = T F shows that this item is valid for the viable prefix T. 2. E = E = T = F = (E) = (T ) = (T F ) shows that it is 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.

College of Engineering, Pune Syntax Analysis: 112/124 Theory of LR Parsing THEOREM : Starting from I 0, if traversing the LR(0) automaton γ results in state j, then set items in I j 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.

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.

College of Engineering, Pune Syntax Analysis: 116/124 SLR Automaton for a Grammar I 1 S S.. S L = R R L L. * R L id. S L = R... R R.. * R id S S S. L = R L L L I 2 R I 3 S L = R S R R L. = R I 6 I 9 S * id L L I o. I 5 id. id * I 4 L * R. R L L. * R L id. id R I 7 L * R. FOLLOW S { $ } S { $ } L { = $ } R { = $ } R L. I 8 L *

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 1 2 3 4 5 6 7 8 9 s5 s4 1 2 3 - - - - - s5 s4 - - s6 r5 acc r5 r2 - - - - - - - r4 r4 - - - - - - - - - - - - 8 7 - - - s5 s4 8 9 - - r3 r3 - - - - - r5 r5 - - - - - - r1 - - - -

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.

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.

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.