The role of the parser

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

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

3. Parsing. Oscar Nierstrasz

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

Chapter 4: LR Parsing

Compiler Construction 2016/2017 Syntax Analysis

Part 5 Program Analysis Principles and Techniques

CS 406/534 Compiler Construction Parsing Part I

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

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

Context-free grammars

Parsing. Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice.

Compiler Construction: Parsing

Parsing II Top-down parsing. Comp 412

Syntactic Analysis. Top-Down Parsing

CA Compiler Construction

Introduction to Parsing. Comp 412

Types of parsing. CMSC 430 Lecture 4, Page 1

CS415 Compilers. Syntax Analysis. These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University

Syntax Analysis, III Comp 412

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

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

CSCI312 Principles of Programming Languages

Parsing Part II. (Ambiguity, Top-down parsing, Left-recursion Removal)

Parsing Wrapup. Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing. This lecture LR(1) parsing

Syntax Analysis, III Comp 412

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

Wednesday, September 9, 15. Parsers

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

Academic Formalities. CS Modern Compilers: Theory and Practise. Images of the day. What, When and Why of Compilers

Parsing III. (Top-down parsing: recursive descent & LL(1) )

Monday, September 13, Parsers

Introduction to Parsing

Wednesday, August 31, Parsers

UNIT-III BOTTOM-UP PARSING

Compilers. Yannis Smaragdakis, U. Athens (original slides by Sam

LR Parsing Techniques


Bottom-Up Parsing. Lecture 11-12

Syntactic Analysis. Top-Down Parsing. Parsing Techniques. Top-Down Parsing. Remember the Expression Grammar? Example. Example

4. Lexical and Syntax Analysis

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

Syntax Analysis Part I

CS 314 Principles of Programming Languages

Formal Languages and Compilers Lecture VII Part 3: Syntactic A

Syntax Analysis. Amitabha Sanyal. ( as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

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

4. Lexical and Syntax Analysis

Bottom-up Parser. Jungsik Choi

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

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

Lecture 8: Deterministic Bottom-Up Parsing

Lecture 7: Deterministic Bottom-Up Parsing

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

Syntax Analysis, V Bottom-up Parsing & The Magic of Handles Comp 412

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

CMSC 330: Organization of Programming Languages

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

Downloaded from Page 1. LR Parsing

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

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

Formal Languages and Compilers Lecture VII Part 4: Syntactic A

LR Parsers. Aditi Raste, CCOEW

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

Concepts Introduced in Chapter 4

Parsing Part II (Top-down parsing, left-recursion removal)

EECS 6083 Intro to Parsing Context Free Grammars

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.

Syntax Analysis, VI Examples from LR Parsing. Comp 412

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

Computer Science 160 Translation of Programming Languages

Bottom-Up Parsing. Lecture 11-12

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

Chapter 3. Parsing #1

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

Lexical and Syntax Analysis. Bottom-Up Parsing

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

CS 4120 Introduction to Compilers

Syntax Analysis, VII One more LR(1) example, plus some more stuff. Comp 412 COMP 412 FALL Chapter 3 in EaC2e. target code.

Optimizing Finite Automata

LR Parsing LALR Parser Generators

Principles of Programming Languages

VIVA QUESTIONS WITH ANSWERS

CMSC 330: Organization of Programming Languages

Parsing. source code. while (k<=n) {sum = sum+k; k=k+1;}

Bottom-Up Parsing II. Lecture 8

Syntax Analysis. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

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

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

CMSC 330: Organization of Programming Languages

Syntax. Syntax. We will study three levels of syntax Lexical Defines the rules for tokens: literals, identifiers, etc.

Lecture Bottom-Up Parsing

SLR parsers. LR(0) items

LR Parsing - The Items

In One Slide. Outline. LR Parsing. Table Construction

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

Alternatives for semantic processing

How do LL(1) Parsers Build Syntax Trees?

LR Parsing LALR Parser Generators

Transcription:

The role of the parser source code tokens scanner parser IR errors Parser performs context-free syntax analysis guides context-sensitive analysis constructs an intermediate representation produces meaningful error messages attempts error correction For the next few weeks, we will look at parser construction Copyright c 2001 by Antony L. Hosking. Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and full citation on the first page. To copy otherwise, to republish, to post on servers, or to redistribute to lists, requires prior specific permission and/or fee. Request permission to publish from hosking@cs.purdue.edu. 1

Syntax analysis Context-free syntax is specified with a context-free grammar. Formally, a CFG G is a 4-tuple V n V t P Sµ, where: V n, the nonterminals, is a set of syntactic variables that denote sets of (sub)strings occurring in the language. These are used to impose a structure on the grammar. V t is the set of terminal symbols in the grammar. For our purposes, V t is the set of tokens returned by the scanner. P is a finite set of productions specifying how terminals and non-terminals can be combined to form strings in the language. Each production must have a single non-terminal on its left hand side. S is a distinguished nonterminal S ¾ V n µ denoting the entire set of strings in L Gµ. This is sometimes called a goal symbol. The set V V t V n is called the vocabulary of G 2

α β γ ¾ V Notation and terminology a b c ¾ V t A B C ¾ V n U V W ¾ V u v w ¾ V t If A γ then αaβ µ αγβ is a single-step derivation using A γ Similarly, µ and µ denote derivations of 0 and 1 steps If S µ β then β is said to be a sentential form of G ¾ w V t S µ w, w ¾ L Gµ is called a sentence of G L Gµ L Gµ Note, ¾ β V S µ β V t 3

Syntax analysis Grammars are often written in Backus-Naur form (BNF). Example: goal :: expr 1 expr :: expr op expr 2 ÒÙÑ 3 4 op :: 5 6 7 8 This describes simple expressions over numbers and identifiers. In a BNF for a grammar, we represent 1. non-terminals with angle brackets or capital letters 2. terminals with ØÝÔ ÛÖ Ø Ö font or underline 3. productions as in the example 4

Scanning vs. parsing Where do we draw the line? term :: Þ Þ Þ Þ 0 9 µ 0 expr term term op Regular expressions are used to classify: identifiers, numbers, keywords REs are more concise and simpler for tokens than a grammar more efficient scanners can be built from REs (DFAs) than grammars Context-free grammars are used to count: brackets: µ, Ò... Ò,... Ø Ò... Ð imparting structure: expressions Syntactic analysis is complicated enough: grammar for C has around 200 productions. Factoring out lexical analysis as a separate phase makes compiler more manageable. 5

Derivations We can view the productions of a CFG as rewriting rules. Using our example CFG: µ expr goal expr op expr µ expr op expr op expr µ id,ü op expr op expr µ id,ü expr op expr µ id,ü num,¾ op expr µ id,ü num,¾ expr µ id,ü num,¾ id,ý µ We have derived the sentence Ü ¾ Ý. We denote this goal µ ÒÙÑ. Such a sequence of rewrites is a derivation or a parse. The process of discovering a derivation is called parsing. 6

Derivations At each step, we chose a non-terminal to replace. This choice can lead to different derivations. Two are of particular interest: leftmost derivation the leftmost non-terminal is replaced at each step rightmost derivation the rightmost non-terminal is replaced at each step The previous example was a leftmost derivation. 7

Rightmost derivation For the string Ü ¾ Ý: µ expr goal expr op expr µ expr op id,ý µ expr id,ý µ expr op expr id,ý µ expr op num,¾ id,ý µ expr num,¾ id,ý µ id,ü num,¾ id,ý µ Again, goal µ ÒÙÑ. 8

Precedence goal expr expr op expr expr op expr * <id,y> <id,x> + <num,2> Treewalk evaluation computes (Ü ¾) Ý the wrong answer! Should be Ü (¾ Ý) 9

Precedence These two derivations point out a problem with the grammar. It has no notion of precedence, or implied order of evaluation. To add precedence takes additional machinery: goal :: expr 1 expr :: expr term 2 expr term 3 term 4 term :: term factor 5 term factor 6 factor 7 factor :: ÒÙÑ 8 9 This grammar enforces a precedence on the derivation: terms must be derived from expressions forces the correct tree 10

Precedence Now, for the string Ü ¾ Ý: µ expr goal expr term µ expr term factor µ expr term id,ý µ expr factor id,ý µ expr num,¾ id,ý µ term num,¾ id,ý µ factor num,¾ id,ý µ µ id,ü num,¾ id,ý Again, goal µ ÒÙÑ, but this time, we build the desired tree. 11

Precedence goal expr expr + term term term * factor factor factor <id,y> <id,x> <num,2> Treewalk evaluation computes Ü (¾ Ý) 12

Ambiguity If a grammar has more than one derivation for a single sentential form, then it is ambiguous Example: ::= expr Ø Ò stmt stmt expr Ø Ò stmt Ð stmt ÓØ Ö ØÑØ Consider deriving the sentential form: E 1 E Ø Ò 2 S Ø Ò 1 S Ð 2 It has two derivations. This ambiguity is purely grammatical. It is a context-free ambiguity. 13

Ambiguity May be able to eliminate ambiguities by rearranging the grammar: ::= matched stmt unmatched ::= expr Ø Ò matched Ð matched matched ÓØ Ö ØÑØ ::= expr Ø Ò stmt unmatched expr Ø Ò matched Ð unmatched This generates the same language as the ambiguous grammar, but applies the common sense rule: match each Ð with the closest unmatched Ø Ò This is most likely the language designer s intent. 14

Ambiguity Ambiguity is often due to confusion in the context-free specification. Context-sensitive confusions can arise from overloading. Example: ½ µ In many Algol-like languages, could be a function or subscripted variable. Disambiguating this statement requires context: need values of declarations not context-free really an issue of type Rather than complicate parsing, we will handle this separately. 15

Parsing: the big picture tokens grammar parser generator parser code IR Our goal is a flexible parser generator system 16

Top-down versus bottom-up Top-down parsers start at the root of derivation tree and fill in picks a production and tries to match the input may require backtracking some grammars are backtrack-free (predictive) Bottom-up parsers start at the leaves and fill in start in a state valid for legal first tokens as input is consumed, change state to encode possibilities (recognize valid prefixes) use a stack to store both state and sentential forms 17

Top-down parsing A top-down parser starts with the root of the parse tree, labelled with the start or goal symbol of the grammar. To build a parse, it repeats the following steps until the fringe of the parse tree matches the input string 1. At a node labelled A, select a production A α and construct the appropriate child for each symbol of α 2. When a terminal is added to the fringe that doesn t match the input string, backtrack 3. Find the next node to be expanded (must have a label in V n ) The key is selecting the right production in step 1 µ should be guided by input string 18

Simple expression grammar Recall our grammar for simple expressions: goal :: expr 1 expr :: expr term 2 expr term 3 term 4 term :: term factor 5 term factor 6 factor 7 factor :: ÒÙÑ 8 9 Consider the input string Ü ¾ Ý 19

Example Prod n Sentential form Input goal Ü ¾ Ý 1 expr Ü ¾ Ý 2 expr term Ü ¾ Ý 4 term term Ü ¾ Ý 7 factor term Ü ¾ Ý 9 term Ü ¾ Ý term Ü ¾ Ý expr Ü ¾ Ý 3 expr term Ü ¾ Ý 4 term term Ü ¾ Ý 7 factor term Ü ¾ Ý 9 term Ü ¾ Ý term Ü ¾ Ý term Ü ¾ Ý 7 factor Ü ¾ Ý 8 ÒÙÑ Ü ¾ Ý ÒÙÑ Ü ¾ Ý term Ü ¾ Ý 5 term factor Ü ¾ Ý 7 factor factor Ü ¾ Ý 8 ÒÙÑ factor Ü ¾ Ý ÒÙÑ factor Ü ¾ Ý ÒÙÑ factor Ü ¾ Ý 9 ÒÙÑ Ü ¾ Ý ÒÙÑ Ü ¾ Ý 20

Example Another possible parse for Ü ¾ Ý Prod n Sentential form Input goal Ü ¾ Ý 1 expr Ü ¾ Ý 2 expr term Ü ¾ Ý 2 expr term term Ü ¾ Ý 2 expr term Ü ¾ Ý 2 expr term Ü ¾ Ý 2 Ü ¾ Ý If the parser makes the wrong choices, expansion doesn t terminate. This isn t a good property for a parser to have. (Parsers should terminate!) 21

δ q 0 x xµ q 0 εµ Top-down parsing with pushdown automaton A top-down parser for grammar G V n V t P Sµ is a pushdown automaton A Q V t V k δ q 0 k 0 µ that accepts input with empty pushdown where Q q 0 is the set of states V k V n V t is the alphabet of pushdown symbols δ : Q V t ε V k Q V k q 0 is the initial state k 0 S is the initial pushdown symbol where δ q 0 ε Aµ q 0 αµ for each production A α ¾ P 22

Pushdown automaton example goal expr term expr term term factor term term term term term factor factor factor factor ÒÙÑ factor factor Pushdown (rev) Input Prod n x-2*y 1 x-2*y 3 x-2*y 4 x-2*y 7 x-2*y 9 x-2*y shift -2*y shift 2*y 5 2*y 7 2*y 8 2*y shift *y shift y 9 y shift accepted 23

Left-recursion Top-down parsers cannot handle left-recursion in a grammar Formally, a grammar is left-recursive if A ¾ V n such that A µ Aα for some string α Our simple expression grammar is left-recursive 24

Eliminating left-recursion To remove left-recursion, we can transform the grammar Consider the grammar fragment: :: foo α foo β where α and β do not start foo with We can rewrite this as: where bar is a new non-terminal :: β bar foo :: α bar bar ε This fragment contains no left-recursion 25

Example Our expression grammar contains two cases of left-recursion :: expr term expr expr term term :: term factor term term factor Applying the transformation gives factor :: ¼ expr :: ¼ term expr term expr ε term expr factor term factor term ε factor term With this grammar, a top-down parser will terminate backtrack on some inputs 26

Example This cleaner grammar defines the same language It is right-recursive free of ε-productions goal :: expr 1 expr :: term expr 2 term expr 3 term 4 term :: factor term 5 factor term 6 factor 7 factor :: ÒÙÑ 8 9 Unfortunately, it generates different associativity Same syntax, different meaning 27

Example Our long-suffering expression grammar: goal expr :: expr :: :: ¼ ¼ ¼ :: ¼ term :: ¼ ¼ ¼ ÒÙÑ factor :: 1 2 term expr 3 term expr 4 term expr 5 ε 6 factor term 7 factor term 8 factor term 9 ε 10 11 Recall, we factored out left-recursion 28

How much lookahead is needed? We saw that top-down parsers may need to backtrack when they select the wrong production Do we need arbitrary lookahead to parse CFGs? in general, yes use the Earley or Cocke-Younger, Kasami algorithms Fortunately large subclasses of CFGs can be parsed with limited lookahead most programming language constructs can be expressed in a grammar that falls in these subclasses Among the interesting subclasses are: LL 1µ: left to right scan, left-most derivation, 1-token lookahead; and LR 1µ: left to right scan, right-most derivation, 1-token lookahead 29

Predictive parsing Basic idea: For any two productions A α β, we would like a distinct way of choosing the correct production to expand. For α V and k ¾ N, define FIRSTk αµ as the set of terminal strings of ¾ length less than or equal to k that appear first in a string derived from α. That is, µ if α ¾ w V t, then k w ¾ FIRSTk αµ.. Key property: Whenever two productions A α and A β both appear in the grammar, we would like k αµ FIRST k βµ FIRST φ for some k. If k 1, then the parser could make a correct choice with a lookahead of only one symbol! The example grammar has this property! 30

Left factoring What if a grammar does not have this property? Sometimes, we can transform a grammar to have this property. For each non-terminal A find the longest prefix α common to two or more of its alternatives. if α ε then replace all of the A productions A αβ 1 αβ 2 αβ n with A αa A ¼ β 1 β 2 β n where A ¼ is a new non-terminal. ¼ Repeat until no two alternatives for a single non-terminal have a common prefix. 31

Example Consider a right-recursive version of the expression grammar: goal :: expr 1 expr :: term expr 2 term expr 3 term 4 term :: factor term 5 factor term 6 factor 7 factor :: ÒÙÑ 8 9 To choose between productions 2, 3, & 4, the parser must see past the ÒÙÑ or and look at the,,, or. FIRST1 3µ FIRST1 4µ /0 FIRST1 2µ This grammar fails the test. Note: This grammar is right-associative. 32

Example There are two nonterminals that must be left-factored: :: term expr expr term expr term :: factor term term factor term Applying the transformation gives us: factor :: term expr ¼ expr :: expr ¼ expr ε :: factor term ¼ term :: term ¼ term ε 33

Example Substituting back into the grammar yields goal :: expr 1 expr :: 2 term expr 3 ¼ :: expr 4 ¼ expr 5 ε term :: 6 factor term 7 ¼ :: term 8 ¼ term 9 ε factor :: ÒÙÑ 10 11 Now, selection requires only a single token lookahead. Note: This grammar is still right-associative. 34

Example Sentential form Input goal Ü ¾ Ý 1 expr Ü ¾ Ý 2 term expr ¼ Ü ¾ Ý 6 factor term ¼ expr ¼ Ü ¾ Ý 11 term ¼ expr ¼ Ü ¾ Ý term ¼ expr ¼ Ü ¹ ¾ Ý 9 ε expr ¼ Ü ¹ ¾ 4 expr Ü ¹ ¾ Ý expr Ü ¾ Ý 2 term expr ¼ Ü ¾ Ý 6 factor term ¼ expr ¼ Ü ¾ Ý 10 ÒÙÑ term ¼ expr ¼ Ü ¾ Ý ÒÙÑ term ¼ expr ¼ Ü ¾ Ý 7 ÒÙÑ term expr ¼ Ü ¾ Ý ÒÙÑ term expr ¼ Ü ¾ Ý 6 ÒÙÑ factor term ¼ expr ¼ Ü ¾ Ý 11 ÒÙÑ term ¼ expr ¼ Ü ¾ Ý ÒÙÑ term ¼ expr ¼ Ü ¾ Ý 9 ÒÙÑ expr ¼ Ü ¾ Ý 5 ÒÙÑ Ü ¾ Ý The next symbol determined each choice correctly. 35

Back to left-recursion elimination Given a left-factored CFG, to eliminate left-recursion: if A Aα then replace all of the A productions A Aα β γ with A NA N ¼ β γ A αa ¼ ε where N and A ¼ are new productions. ¼ Repeat until there are no left-recursive productions. 36

Generality Question: Answer: By left factoring and eliminating left-recursion, can we transform an arbitrary context-free grammar to a form where it can be predictively parsed with a single token lookahead? Given a context-free grammar that doesn t meet our conditions, it is undecidable whether an equivalent grammar exists that does meet our conditions. Many context-free languages do not have such a grammar: a n 0b n n 1 a n 1b 2n n 1 Must look past an arbitrary number of a s to discover the 0 or the 1 and so determine the derivation. 37

Recursive descent parsing General idea: Turn the grammar into a set of mutually recursive functions! Each non-terminal maps to a function The body of the function for A ¾ V n is determined by the productions A α 1 α k on function entry, use lookahead to determine the correct RHS α α j, say in the body, generate code for each symbol of α in sequence for a terminal symbol, the code consumes a matching input token for a non-terminal symbol, the code invokes the non-terminal s function 38

Recursive descent parsing In that manner, we can produce a simple recursive descent parser from the (right-associative) grammar. Ó Ð ØÓ Ò Ò ÜØ ØÓ Ò µ ÜÔÖ µ ÊÊÇÊ ØÓ Ò Ç µ Ø Ò Ö ØÙÖÒ ÊÊÇÊ ÜÔÖ Ø ÖÑ µ ÊÊÇʵ Ø Ò Ö ØÙÖÒ ÊÊÇÊ Ð Ö ØÙÖÒ ÜÔÖ ÔÖ Ñ µ ÜÔÖ ÔÖ Ñ ØÓ Ò ÈÄÍ˵ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÜÔÖ µ Ð ØÓ Ò ÅÁÆÍ˵ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÜÔÖ µ Ð Ö ØÙÖÒ Çà 39

Recursive descent parsing Ø ÖÑ ØÓÖ µ ÊÊÇʵ Ø Ò Ö ØÙÖÒ ÊÊÇÊ Ð Ö ØÙÖÒ Ø ÖÑ ÔÖ Ñ µ Ø ÖÑ ÔÖ Ñ ØÓ Ò ÅÍÄ̵ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ Ø ÖÑ µ Ð ØÓ Ò Áε Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ Ø ÖÑ µ Ð Ö ØÙÖÒ Çà ØÓÖ ØÓ Ò ÆÍŵ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ Çà РØÓ Ò Á µ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÇÃ Ð Ö ØÙÖÒ ÊÊÇÊ 40

Building the tree One of the key jobs of the parser is to build an intermediate representation of the source code. To build an abstract syntax tree, we have each function return the AST for the word parsed by it. The function for a production gobbles up the ASTs for the non-terminal s on the RHS and applies the appropriate AST constructor. Alternatively, the functions use an auxiliary stack for AST fragments. 41

Non-recursive predictive parsing Observation: Our recursive descent parser encodes state information in its run-time stack, or call stack. Using recursive procedure calls to implement a stack abstraction may not be particularly efficient. This suggests other implementation methods: explicit stack, hand-coded parser stack-based, table-driven parser 42

Non-recursive predictive parsing Now, a predictive parser looks like: stack source code scanner tokens table-driven parser IR parsing tables Rather than writing code, we build tables. Building tables can be automated! 43

Table-driven parsers A parser generator system often looks like: stack source code scanner tokens table-driven parser IR grammar parser generator parsing tables This is true for both top-down (LL) and bottom-up (LR) parsers 44

Non-recursive predictive parsing Input: a string w and a parsing table M for G ØÓ ¼ ËØ ØÓ Ç ËØ ØÓ Start Symbol ØÓ Ò Ò ÜØ ØÓ Ò µ Ö Ô Ø ËØ ØÓ Ø ÖÑ Ò Ð ÓÖ Ç Ø Ò ØÓ Ò Ø Ò ÔÓÔ ØÓ Ò Ò ÜØ ØÓ Ò µ Ð ÖÖÓÖ µ л X is a non-terminal» M ØÓ Ò X Y 1 Y 2 Y k Ø Ò ÔÓÔ ÔÙ Y k Y k 1 Y 1 Ð ÖÖÓÖ µ ÙÒØ Ð Ç 45

Non-recursive predictive parsing What we need now is a parsing table M. Our expression grammar: goal :: expr 1 expr :: 2 term expr 3 ¼ :: expr 4 ¼ expr 5 ε term :: 6 factor term 7 ¼ :: term 8 ¼ term 9 ε factor :: ÒÙÑ 10 11 Its parse table: ÒÙÑ $ goal expr term factor 1 1 2 2 3 4 5 6 6 9 9 7 8 9 11 10 we use $ to represent Ç 46

Computing FIRST FIRST 1 For a string of grammar symbols α, define FIRST αµ as: the set of terminal symbols that begin strings derived from α: ¾ a V t α µ aβ If α µ ε then ε ¾ FIRST αµ FIRST αµ contains the set of tokens valid in the initial position in α To compute FIRST αµ it is sufficient to know FIRST Xµ, for all X ¾ V: where FIRST Y 1 Y 2 Y k µ FIRST Y 1 µ FIRST Y 2 µ FIRST Y k µ Clearly, FIRST aµ a for a ¾ V t. M ε ¾ M M N M N ¾ ε ε µ Ò M 47

Computing FIRST Initialize FIRST Aµ /0, for all A ¾ V n Repeat the following steps for all productions until no further additions can be made: 1. If A ε then: FIRST Aµ ε FIRST Aµ 2. If A Y 1 Y 2 Y k : FIRST Aµ FIRST Aµ FIRST Y 1 µ FIRST Y 2 µ FIRST Y k µµ 48

FOLLOW For a non-terminal A, define FOLLOW Aµ as the set of terminals that can appear immediately to the right of A in some sentential form That is, FOLLOW Aµ a S$ µ αaaβ Thus, a non-terminal s FOLLOW set specifies the tokens that can legally appear after it, with $ acting as end of input marker. A terminal symbol has no FOLLOW set. To build FOLLOW Aµ: 1. Initialize FOLLOW Aµ /0, for A ¾ V n, A S, and FOLLOW Sµ $ 2. Repeat the following steps for all productions A αbβ until no further additions can be made: (a) FOLLOW Bµ FOLLOW Bµ FIRST βµ ε µ (b) If ε ¾ FIRST βµ, then FOLLOW Bµ FOLLOW Bµ FOLLOW Aµ 49

LL(1) grammars Previous definition A grammar G has a deterministic unambiguous predictive parser if for all non-terminals A, each distinct pair of productions A β and A γ satisfy the condition FIRST βµ Ì FIRST γµ φ. What if A µ ε? Revised definition A grammar G is LL(1) iff. for each set of productions A α 1 α 2 α n : 1. FIRST α 1 µ FIRST α 2 µ FIRST α n µ are all pairwise disjoint 2. If α i µ ε then FIRST α j µ Ì FOLLOW Aµ φ 1 j n i j. If G is ε-free, condition 1 is sufficient. 50

LL(1) grammars Provable facts about LL(1) grammars: 1. No left-recursive grammar is LL(1) 2. No ambiguous grammar is LL(1) 3. Some languages have no LL(1) grammar 4. An ε free grammar where each alternative expansion for A begins with a distinct terminal is a simple LL(1) grammar. Example S as ¼ S ¼ as ¼ ε accepts the same language and is LL(1) S as a is not LL(1) because FIRST asµ FIRST aµ a 51

LL(1) parse table construction Input: Grammar G Output: Parsing table M Method: 1. productions A α: (a) ¾ a FIRST αµ, add A α M A a to (b) If ¾ ε FIRST αµ: i. ¾ b FOLLOW Aµ, add A α M A b to ii. If ¾ FOLLOW Aµ $ then add A α M A $ to 2. Set each undefined entry of M to ÖÖÓÖ If M A a with multiple entries then grammar is not LL(1). Note: recall a b ¾ V t, so a b ε 52

Example Our long-suffering expression grammar: S E E T E E ¼ E E ε ¼ T FT T ¼ T T ε F ¼ ÒÙÑ FIRST FOLLOW ÒÙÑ $ S ÒÙÑ $ E E ¼ $ ε ÒÙÑ $ T T ¼ $ ε ÒÙÑ $ F ÒÙÑ ÒÙÑ $ S S E S E E E T E E T E E T T FT T FT T F F F 53

Ø ÖÑ Ò Ð ÓÖ Ç Ø Ò ØÓ Ò Ø Ò ÖÖÓÖ µ Ð Ç ÙÒØ Ð Building the tree Again, we insert code at the right points: ¼ ØÓ Ç ËØ ØÓ root node ËØ ØÓ Start Symbol ËØ ØÓ Ò ÜØ ØÓ Ò µ ØÓ Ò Ö Ô Ø ËØ ØÓ ÔÓÔ Ò ÜØ ØÓ Ò µ ØÓ Ò pop and fill in node ÖÖÓÖ µ л X is a non-terminal» Ð M X,token X Y 1 Y 2 Y k Ø Ò ÔÓÔ pop node for X build node for each child and make it a child of node for X n ÔÙ k Y k n k 1 Y k 1 n 1 Y 1 54

A grammar that is not LL(1) :: expr Ø Ò stmt stmt expr Ø Ò stmt Ð stmt Left-factored: :: expr Ø Ò stmt stmt ¼ :: Ð stmt stmt ε Now, FIRST stmt ¼ µ ε Ð Also, FOLLOW stmt ¼ µ Ð $ But, FIRST stmt ¼ µ Ì FOLLOW stmt ¼ µ Ð φ On seeing Ð, conflict between choosing stmt ¼ :: Ð stmt and stmt ¼ :: ε µ grammar is not LL(1)! The fix: Put priority on stmt ¼ :: Ð stmt to associate Ð with closest previous Ø Ò. 55

Error recovery Key notion: For each non-terminal, construct a set of terminals on which the parser can synchronize When an error occurs looking for A, scan until an element of is found SYNCH Aµ Building SYNCH: 1. a ¾ FOLLOW Aµ µ a ¾ SYNCH Aµ 2. place keywords that start statements in SYNCH Aµ 3. add symbols in FIRST Aµ to SYNCH Aµ If we can t match a terminal on top of stack: 1. pop the terminal 2. print a message saying the terminal was inserted 3. continue the parse (i.e., SYNCH aµ V t a ) 56

If ¾ α V t, then α is a sentence in L Gµ Some definitions Recall For a grammar G, with start symbol S, any string α such that S µ α is a sentential form A left-sentential form is a sentential form that occurs in the leftmost derivation of some sentence. A right-sentential form is a sentential form that occurs in the rightmost derivation of some sentence. 57

Bottom-up parsing Goal: Given an input string w and a grammar G, construct a parse tree by starting at the leaves and working to the root. The parser repeatedly matches a right-sentential form from the language against the tree s upper frontier. At each match, it applies a reduction to build on the frontier: each reduction matches an upper frontier of the partially built tree to the RHS of some production each reduction adds a node on top of the frontier The final result is a rightmost derivation, in reverse. 58

Example Consider the grammar and the input string 1 S AB 2 A A 3 4 B Prod n. Sentential Form 3 2 A 4 A 1 aabe S Scan the input and find valid sentential forms! 59

Handles What are we trying to find? A substring α of the tree s upper frontier that matches some production A α where reducing α to A is one step in the reverse of a rightmost derivation We call such a string a handle. Formally: In a right-sentential form αβw, the string β is a handle for production A β i.e., if S µ rm αaw µ rm αβw then β is a handle for A β in αβw All right-sentential forms have a suffix containing only terminal symbols. 60

Handles S α A β The handle A β in the parse tree for αβw w 61

Handles Theorem: If G is unambiguous then every right-sentential form has a unique handle. Proof: (by definition) 1. G is unambiguous µ rightmost derivation is unique 2. µ a unique production A β applied to take γ i 1 to γ i 3. µ a unique position k at which A β is applied 4. µ a unique handle A β 62

Example The left-recursive expression grammar goal :: expr 1 expr :: expr term 2 expr term 3 term 4 term :: term factor 5 term factor 6 factor 7 factor :: ÒÙÑ 8 9 (original form) Prod n. Sentential Form goal 1 expr 3 expr term 5 expr term factor 9 expr term 7 expr factor 8 expr ÒÙÑ 4 term ÒÙÑ 7 factor ÒÙÑ 9 ÒÙÑ 63

Handle-pruning The process to construct a bottom-up parse is called handle-pruning. To construct a rightmost derivation S γ 0 µ γ 1 µ γ 2 µ µ γ n 1 µ γ n w we set i to n and apply the following simple algorithm ÓÖ n ÓÛÒØÓ ½ 1. Ò Ø Ò Ð A i β i Ò γ i 2. Ö ÔÐ β i Û Ø A i ØÓ Ò Ö Ø γ i 1 This takes 2n steps, where n is the length of the derivation 64

Stack implementation One scheme to implement a handle-pruning, bottom-up parser is called a shift-reduce parser. Shift-reduce parsers use a stack and an input buffer 1. initialize stack with $ 2. Repeat until the top of the stack is the goal symbol and the input token is $ a) find the handle if we don t have a handle on top of the stack, shift an input symbol onto the stack b) prune the handle if we have a handle for A β on the stack, reduce: i) pop β symbols off the stack ii) push A onto the stack 65

Example: back to Ü ¾ Ý goal :: expr 1 expr :: expr term 2 expr term 3 term 4 term :: term factor 5 term factor 6 factor 7 factor :: ÒÙÑ 8 9 ÒÙÑ ÒÙÑ $ $ factor ÒÙÑ ÒÙÑ $ term $ expr ÒÙÑ $ expr ÒÙÑ ÒÙÑ $ expr $ expr factor term $ expr $ expr term term $ expr $ expr factor term $ expr term $ expr Stack Input Action $ shift reduce 9 reduce 7 reduce 4 shift shift reduce 8 reduce 7 shift shift reduce 9 reduce 5 reduce 3 reduce 1 accept $ goal 1. Shift until top of stack is the right end of a handle 2. Find the left end of the handle and reduce 5 shifts + 9 reduces + 1 accept 66

Shift-reduce parsing Shift-reduce parsers are simple to understand A shift-reduce parser has just four canonical actions: 1. shift next input symbol is shifted onto the top of the stack 2. reduce right end of handle is on top of stack; locate left end of handle within the stack; pop handle off stack and push appropriate non-terminal LHS 3. accept terminate parsing and signal success 4. error call an error recovery routine But how do we know that there is a complete handle on the stack? which handle to use? 67

LR parsing: key insight Recognize handles with a DFA [Knuth1965] DFA transitions shift states instead of symbols accepting states trigger reductions 68

ÓÖ Ú Ö Ö Ô Ø ØÓÔ Ó Ø β Ø Ø ÔÓÔ ¼ ØÓÔ Ó Ø Ø ÓÒ ØÓ Ò ÔØ Ø Ò Ð Ö ØÙÖÒ LR parsing The skeleton parser: s ÔÙ 0 Ò ÜØ ØÓ Ò µ ØÓ Ò Ø ÓÒ ØÓ Ò Ø s i Ø Ò s ÔÙ i ØÓ Ò Ò ÜØ ØÓ Ò µ Ø ÓÒ ØÓ Ò Ö Ù A β Ð Ø Ò ÔÙ ÓØÓ ¼ A Ð ÖÖÓÖ µ This takes k shifts, l reduces, and 1 accept, where k is the length of the input string and l is the length of the reverse rightmost derivation 69

Example tables state ACTION GOTO $ 0 s4 1 2 3 1 acc 2 s5 r3 3 r5 s6 r5 4 r6 r6 r6 5 s4 7 2 3 6 s4 8 3 7 r2 8 r4 r4 The Grammar goal :: expr 1 expr :: term expr 2 term 3 term :: factor term 4 factor 5 factor :: 6 Note: This is a simple little right-recursive grammar; not the same as in previous lectures. 70

Example using the tables Stack Input Action $ 0 $ s4 $ 0 4 $ r6 $ 0 3 $ s6 $ 0 3 6 $ s4 $ 0 3 6 4 $ r6 $ 0 3 6 3 $ r5 $ 0 3 6 8 $ r4 $ 0 2 $ s5 $ 0 2 5 $ s4 $ 0 2 5 4 $ r6 $ 0 2 5 3 $ r5 $ 0 2 5 2 $ r3 $ 0 2 5 7 $ r2 $ 0 1 $ acc 71

grammars LR kµ Informally, we say that a grammar G LR kµ is if, given a rightmost derivation S γ 0 µ γ 1 µ γ 2 µ µ γ n w we can, for each right-sentential form in the derivation, 1. isolate the handle of each right-sentential form, and 2. determine the production by which to reduce by scanning γ i from left to right, going at most k symbols beyond the right end of the handle of γ i. 72

LR kµ grammars Formally, a grammar G is LR kµ iff.: 1. S µ rm αaw µ rm αβw, and 2. S µ rm γbx µ rm αβy, and 3. FIRST k wµ FIRST k yµ impliers αay γbx i.e., Assume sentential forms αβw and αβy, with common prefix αβ and common k-symbol lookahead k yµ FIRST FIRSTk wµ, such that αβw reduces to αaw and αβy reduces to γbx. But, the common prefix means αβy also reduces to αay, for the same result. Thus αay γbx. 73

Why study LR grammars? LR 1µ grammars are often used to construct parsers. We call these parsers LR 1µ parsers. virtually all context-free programming language constructs can be expressed in LR 1µ an form LR grammars are the most general grammars parsable by a deterministic, bottom-up parser efficient parsers can be implemented for LR 1µ grammars LR parsers detect an error as soon as possible in a left-to-right scan of the input LR grammars describe a proper superset of the languages recognized by predictive (i.e., LL) parsers LL kµ: recognize use of a production A β seeing first k symbols derived from β LR kµ: recognize the handle β after seeing everything derived from β plus k lookahead symbols 74

LR parsing Three common algorithms to build tables for an LR parser: 1. SLR 1µ smallest class of grammars smallest tables (number of states) simple, fast construction 2. LR 1µ full set of LR 1µ grammars largest tables (number of states) slow, large construction 3. LALR 1µ intermediate sized set of grammars same number of states as SLR 1µ canonical construction is slow and large better construction techniques exist An LR 1µ parser for either Algol or Pascal has several thousand states, while an SLR 1µ or LALR 1µ parser for the same language may have several hundred states. 75

items LR kµ The table construction algorithms use sets LR kµ of items or configurations to represent the possible states in a parse. An LR kµ item is a pair α β, where α is a production from G with a at some position in the RHS, marking how much of the RHS of a production has already been seen β is a lookahead string containing k symbols (terminals or µ Two cases of interest are k 0 and k 1: LR 0µ items play a key role in the SLR 1µ table construction algorithm. items play a key role in the LR 1µ and LALR 1µ table construction LR 1µ algorithms. 76

Example The indicates how much of an item we have seen at a given state in the parse: A XYZ indicates that the parser is looking for a string that can be derived from XYZ A XY Z indicates that the parser has seen a string derived from XY and is looking for one derivable from Z items: (no lookahead) LR 0µ A XY Z generates LR 0µ 4 items: 1. A XYZ 2. A X YZ 3. A XY Z 4. A XYZ 77

The characteristic finite state machine (CFSM) The CFSM for a grammar is a DFA which recognizes viable prefixes of right-sentential forms: A viable prefix is any prefix that does not extend beyond the handle. It accepts when a handle has been discovered and needs to be reduced. To construct the CFSM we need two functions: ÐÓ ÙÖ ¼ Iµ to build its states ÓØÓ¼ I Xµ to determine its transitions 78

closure0 Given an item A α Bβ, its closure contains the item and any other items that can generate legal substrings to follow α. Thus, if the parser has viable prefix α on its stack, the input should reduce to Bβ (or γ for some other item B γ in the closure). ÙÒØ ÓÒ ÐÓ ÙÖ ¼ Iµ Ö Ô Ø A α Bβ ¾ I B γ ØÓ I ÒÓ ÑÓÖ Ø Ñ Ò ØÓ I ÙÒØ Ð I Ö ØÙÖÒ 79

goto0 Let I be a set of LR 0µ items and X be a grammar symbol. Then, GOTO I Xµ is the closure of the set of all items A αx β such that A α Xβ ¾ I If I is the set of valid items for some viable prefix γ, then GOTO I Xµ is the set of valid items for the viable prefix γx. GOTO I Xµ represents state after recognizing X in state I. ÙÒØ ÓÒ ÓØÓ¼ I Xµ J Ø Ø Ó Ø Ñ A αx β Ð Ø Ø Ø A α Xβ ¾ I Ù Ö ØÙÖÒ ÐÓ ÙÖ ¼ Jµ 80

Building the LR 0µ item sets We start the construction with the item S ¼ S$, where S ¼ is the start symbol of the augmented grammar G ¼ S is the start symbol of G $ represents Ç To compute the collection of sets of LR 0µ items Ø Ñ G ¼ µ ÙÒØ ÓÒ s 0 ÐÓ ÙÖ ¼ S ¼ S$ µ S s 0 Ö Ô Ø ÓÖ Ø Ó Ø Ñ s ¾S ÓÖ Ö ÑÑ Ö ÝÑ ÓÐ X ÓØÓ¼ s Xµ φ Ò ÓØÓ¼ s Xµ ¾S ÓØÓ¼ s Xµ ØÓ S ÙÒØ Ð ÒÓ ÑÓÖ Ø Ñ Ø Ò ØÓ S Ö ØÙÖÒ S 81

example LR 0µ 1 S E$ 2 E E T 3 T 4 T Eµ 5 The corresponding CFSM: T ( id id 0 5 6 9 T ( I 0 : S E$ E E T E T T Eµ T I 1 : S E $ E E T I 2 : I 3 : E$ S E E T T Eµ T I 4 : I 5 : I 6 : I 7 : I 8 : I 9 : E T E T Eµ T E E T E T T Eµ T E µ T E E T Eµ T E T E id ( E 1 + + 3 7 $ T ) 2 4 8 82

Constructing the LR 0µ parsing table 1. construct the collection of sets of LR 0µ items for G ¼ 2. state i of the CFSM is constructed from I i (a) A α aβ ¾ I i and ÓØÓ¼ I i aµ I j µ ACTION i a shift j (b) A α ¾ I i A S ¼ µ ACTION i a reduce A α, a (c) S ¼ S$ ¾ I i µ ACTION i a accept, a 3. ÓØÓ¼ I i Aµ I j µ GOTO i A j 4. set undefined entries in ACTION and GOTO to error 5. initial state of parser s 0 is ÐÓ ÙÖ ¼ S ¼ S$ µ 83

LR 0µ example 9 T ( T id id 0 5 6 E id ( E + + 1 3 7 $ T ) 2 4 8 ( state ACTION GOTO ( ) $ S E T 0 s5 s6 1 9 1 s3 s2 2 acc acc acc acc acc 3 s5 s6 4 4 r2 r2 r2 r2 r2 5 r4 r4 r4 r4 r4 6 s5 s6 7 9 7 s8 s3 8 r5 r5 r5 r5 r5 9 r3 r3 r3 r3 r3 84

Conflicts in the ACTION table If the LR 0µ parsing table contains any multiply-defined ACTION entries then G is not LR 0µ Two conflicts arise: shift-reduce: both shift and reduce possible in same item set reduce-reduce: more than one distinct reduce action possible in same item set Conflicts can be resolved through lookahead in ACTION. Consider: A ε aα µ shift-reduce conflict requires lookahead to avoid shift-reduce conflict after shifting (need to see to give precedence over ) 85

SLR 1µ: simple lookahead LR Add lookaheads after building LR 0µ item sets Constructing the SLR 1µ parsing table: 1. construct the collection of sets of LR 0µ items for G ¼ 2. state i of the CFSM is constructed from I i (a) A α aβ ¾ I i and ÓØÓ¼ I i aµ I j µ ACTION i a shift j, a $ (b) A α ¾ I i A S ¼ ACTION i a reduce A α, a ¾ FOLLOW Aµ µ (c) S S $ ¾ I i ¼ ACTION i $ accept µ 3. ÓØÓ¼ I i Aµ I j µ GOTO i A j 4. set undefined entries in ACTION and GOTO to error 5. initial state of parser s 0 is ÐÓ ÙÖ ¼ S ¼ S$ µ 86

From previous example 1 S E$ 2 E E T 3 T 4 T 5 Eµ id id 0 5 6 1 2 E $ T ( id + + 3 4 T ( 9 7 8 T E ) ( µ $ µ FOLLOW Eµ µ FOLLOW T state ACTION GOTO S E T 0 s5 s6 1 9 1 s3 acc 2 3 s5 s6 4 4 r2 r2 r2 5 r4 r4 r4 6 s5 s6 7 9 7 s8 s3 8 r5 r5 r5 9 r3 r3 r3 87

Example: A grammar that is not LR 0µ 1 S E$ 2 E E T 3 T 4 T T F 5 F 6 F 7 Eµ E T F FOLLOW µ $ µ $ µ $ I 0 : S E$ E E T E T T T F T F F F Eµ I 1 : S E $ E E T I 2 : S E$ I 3 : E E T T T F T F F F Eµ I 4 : T F I 5 : F I 6 : F Eµ E E T E T T T F T F F F Eµ I 7 : E T T T F I 8 : T T F F F Eµ I 9 : T T F I 10 : F Eµ I 11 : E E T T T F I 12 : F E µ E E T 88

Example: But it is SLR 1µ state ACTION GOTO ( ) $ S E T F 0 s5 s6 1 7 4 1 s3 acc 2 3 s5 s6 11 4 4 r5 r5 r5 r5 5 r6 r6 r6 r6 6 s5 s6 12 7 4 7 r3 s8 r3 r3 8 s5 s6 9 9 r4 r4 r4 r4 10 r7 r7 r7 r7 11 r2 s8 r2 r2 12 s3 s10 89

Example: A grammar that is not SLR 1µ Consider: S L R R L R R L Its LR 0µ item sets: I 0 : S ¼ S$ S L R S R L R L R L I 1 : S ¼ S $ I 2 : S L R R L I 3 : S R I 4 : L Now consider I 2 : ¾ FOLLOW Rµ (S µ L R µ R R) I 5 : L R R L L R L I 6 : S L R R L L R L I 7 : L R I 8 : R L I 9 : S L R 90

Look something like A X Y Z a items LR 1µ Recall: LR kµ An item is a pair α β, where α is a production from G with a at some position in the RHS, marking how much of the RHS of a production has been seen β is a lookahead string containing k symbols (terminals or $) What about LR 1µ items? All the lookahead strings are constrained to have length 1 91

items LR 1µ What s the point of the lookahead symbols? carry along to choose correct reduction when there is a choice lookaheads are bookkeeping, unless item has at right end: in A X YZ a, a has no direct use in A XYZ a, a is useful allows use of grammars that are not uniquely invertible The point: For A α a and B α b, we can decide between reducing to A or B by looking at limited right context No two productions have the same RHS 92

closure1 Iµ Given an item A α Bβ a, its closure contains the item and any other items that can generate legal substrings to follow α. Thus, if the parser has viable prefix α on its stack, the input should reduce to Bβ (or γ for some other item B γ b in the closure). ÙÒØ ÓÒ ÐÓ ÙÖ ½ Iµ Ö Ô Ø A α Bβ a ¾ I B γ b ØÓ I Û Ö b ¾ Ö Ø βaµ ÒÓ ÑÓÖ Ø Ñ Ò ØÓ I ÙÒØ Ð Ö ØÙÖÒ I 93

goto1 Iµ Let I be a set LR 1µ of items and X be a grammar symbol. Then, GOTO I Xµ is the closure of the set of all items A αx β a such that A α Xβ a ¾ I If I is the set of valid items for some viable prefix γ, then GOTO I Xµ is the set of valid items for the viable prefix γx. goto I Xµ represents state after recognizing X in state I. ÙÒØ ÓÒ ÓØÓ½ I Xµ J Ø Ø Ó Ø Ñ A αx β a Ð Ø Ø Ø A α Xβ a ¾ I Ù Ö ØÙÖÒ ÐÓ ÙÖ ½ Jµ 94

Building the LR 1µ item sets for grammar G We start the construction with the item S ¼ S $, where S ¼ is the start symbol of the augmented grammar G ¼ S is the start symbol of G $ represents Ç To compute the collection of sets of LR 1µ items Ø Ñ G ¼ µ ÙÒØ ÓÒ s 0 ÐÓ ÙÖ ½ S ¼ S $ µ S s 0 Ö Ô Ø ÓÖ Ø Ó Ø Ñ s ¾S ÓÖ Ö ÑÑ Ö ÝÑ ÓÐ X ÓØÓ½ s Xµ φ Ò ÓØÓ½ s Xµ ¾S ÓØÓ½ s Xµ ØÓ S ÙÒØ Ð ÒÓ ÑÓÖ Ø Ñ Ø Ò ØÓ S Ö ØÙÖÒ S 95

Constructing the LR 1µ parsing table Build lookahead into the DFA to begin with 1. construct the collection of sets of LR 1µ items for G ¼ 2. state i of the LR 1µ machine is constructed from I i (a) A α aβ b ¾ I i and ÓØÓ½ I i aµ I j µ ACTION i a shift j (b) α a ¾ A I i A S ¼ ACTION i a reduce A α µ (c) S S $ ¾ I i ¼ ACTION i $ accept µ 3. ÓØÓ½ I i Aµ I j µ GOTO i A j 4. set undefined entries in ACTION and GOTO to error 5. initial state of parser s 0 is ÐÓ ÙÖ ½ S ¼ S $ µ 96

Back to previous example ( ¾ SLR 1µ) S L R R L R R L I 0 : S S $ S ¼ L R $ R S $ R L L L R $ R L $ L $ I 1 : S S $ I 2 : S ¼ L R $ L R $ I 3 : R S $ I 4 : R L $ L R $ R L $ L $ I 5 : L $ I 6 : S L R $ R L $ L R $ L $ I 7 : L R $ I 8 : R L $ I 9 : S L R $ I 10 : R L $ I 11 : L R $ R L $ L R $ L $ I 12 : L $ I 13 : L R $ I 2 no longer has shift-reduce conflict: reduce on $, shift on 97

Example: back to SLR 1µ expression grammar In general, LR 1µ has many more states than LR 0µ/SLR 1µ: item sets: LR 1µ I 0 : E S $ E T $ T E $ T F $ F T $ F $ Eµ F $ 1 S E 2 E E T 3 T I ¼ 0 :shifting F Eµ $ E E T µ E T µ T T F µ T F µ F µ F Eµ µ 4 T T F 5 F 6 F 7 Eµ I0 :shifting F ¼¼ Eµ µ E T µ T µ E T F µ F µ T µ F Eµ µ F 98

Another example Consider: 0 S ¼ S 1 S CC 2 C cc 3 d state ACTION GOTO c d $ S C 0 s3 s4 1 2 1 acc 2 s6 s7 5 3 s3 s4 8 4 r3 r3 5 r1 6 s6 s7 9 7 r3 8 r2 r2 9 r2 item sets: LR 1µ I 0 : S S $ S ¼ CC $ cc C cd d C cd I 1 : S S $ I 2 : S ¼ C C $ cc C $ d C $ I 3 : C C c cd C cc cd C d cd I 4 : d C cd I 5 : CC S $ I 6 : C C c $ cc C $ d C $ I 7 : d C $ I 8 : cc C cd I 9 : cc C $ 99

parsing LALR 1µ Define the core of a set LR 1µ of items to be the set LR 0µ of items derived by ignoring the lookahead symbols. Thus, the two sets A α β A α β, and A α β A α β have the same core. Key idea: If two sets of LR 1µ items, I i and I j, have the same core, we can merge the states that represent them in the ACTION and GOTO tables. 100

LALR 1µ table construction To construct LALR 1µ parsing tables, we can insert a single step into the LR 1µ algorithm (1.5) For each core present among the set of LR 1µ items, find all sets having that core and replace these sets by their union. The goto function must be updated to reflect the replacement sets. The resulting algorithm has large space requirements. 101

table construction LALR 1µ The revised (and renumbered) algorithm 1. construct the collection of sets of LR 1µ items for G ¼ 2. for each core present among the set of LR 1µ items, find all sets having that core and replace these sets by their union (update the ÓØÓ function incrementally) 3. state i of the LALR 1µ machine is constructed from I i. (a) A α aβ b ¾ I i and ÓØÓ½ I i aµ I j µ ACTION i a shift j (b) A α a ¾ I i A S ¼ µ ACTION i a reduce A α (c) S ¼ S $ ¾ I i µ ACTION i $ accept 4. ÓØÓ½ I i Aµ I j µ GOTO i A j 5. set undefined entries in ACTION and GOTO to error 6. initial state of parser s 0 is ÐÓ ÙÖ ½ S ¼ S $ µ 102

Example Reconsider: 0 S ¼ S 1 S CC 2 C cc 3 d Merged states: I 36 : C C c cd$ cc C cd$ d C cd$ I 47 : d C cd$ I 89 : cc C cd$ I 0 : S S $ S ¼ CC $ cc C cd d C cd I 1 : S S $ I 2 : S ¼ C C $ cc C $ d C $ I 3 : C C c cd cc C cd d C cd I 4 : d C cd I 5 : CC S $ state ACTION GOTO c d $ S C 0 s36 s47 1 2 1 acc 2 s36 s47 5 36 s36 s47 8 47 r3 r3 r3 5 r1 89 r2 r2 r2 I 6 : C c C $ C cc $ C d $ I 7 : C d $ I 8 : C cc cd I 9 : C cc $ 103

More efficient LALR 1µ construction Observe that we can: represent I i by its basis or kernel: items that are either S S $ ¼ or do not have at the left of the RHS compute shift, reduce and goto actions for state derived from I i directly from its kernel This leads to a method that avoids building the complete canonical collection of sets of LR 1µ items 104

The role of precedence Precedence and associativity can be used to resolve shift/reduce conflicts in ambiguous grammars. lookahead with higher precedence µ shift same precedence, left associative µ reduce Advantages: more concise, albeit ambiguous, grammars shallower parse trees µ fewer reductions Classic application: expression grammars 105

The role of precedence With precedence and associativity, we can use: E E E E E E E E E Eµ ¹E ÒÙÑ This eliminates useless reductions (single productions) 106

print an informative message to Ø ÖÖ Error recovery in shift-reduce parsers The problem encounter an invalid token bad pieces of tree hanging from stack incorrect entries in symbol table We want to parse the rest of the file Restarting the parser (line number) find a restartable state on the stack move to a consistent place in the input 107

Error recovery in yacc/bison/java CUP The error mechanism designated token ÖÖÓÖ valid in any production ÖÖÓÖ shows syncronization points When an error is discovered pops the stack until ÖÖÓÖ is legal skips input tokens until it successfully shifts 3 ÖÖÓÖ productions can have actions This mechanism is fairly general See ÜError Recovery of the on-line CUP manual 108

Example Using ÖÖÓÖ ØÑØ Ð Ø ØÑØ can be augmented with ÖÖÓÖ ØÑØ Ð Ø ØÑØ ØÑØ Ð Ø ØÑØ ÖÖÓÖ This should ØÑØ Ð Ø ØÑØ throw out the erroneous statement synchronize at or Ò invoke ÝÝ ÖÖÓÖ ÝÒØ Ü ÖÖÓÖ µ Other natural places for errors all the lists : Ð Ä Ø, Ä Ø missing parentheses or brackets extra operator or missing operator (ÝÝ Ö) 109

Left versus right recursion Right Recursion: needed for termination in predictive parsers requires more stack space right associative operators Left Recursion: works fine in bottom-up parsers limits required stack space left associative operators Rule of thumb: right recursion for top-down parsers left recursion for bottom-up parsers 110

Parsing review Recursive descent A hand coded recursive descent parser directly encodes a grammar (typically an LL 1µ grammar) into a series of mutually recursive procedures. It has most of the linguistic limitations of LL 1µ. LL kµ LL kµ An parser must be able to recognize the use of a production after seeing only the first k symbols of its right hand side. LR kµ LR kµ An parser must be able to recognize the occurrence of the right hand side of a production after having seen all that is derived from that right hand side with k symbols of lookahead. 111

Complexity of parsing: grammar hierarchy type-0: α >β ambiguous type-1: context-sensitive ααβ >αδβ Linear-bounded automaton: PSPACE complete type-2: context-free Α >α Earley s algorithm: O(n³) type-3: regular A->wX DFA: O(n) O(n²) LR(k) Knuth s algorithm: O(n) LR(1) LALR(1) SLR(1) LR(0) unambiguous LL(k) LL(1) LL(0) Note: this is a hierarchy of grammars not languages 112

Language vs. grammar For example, every regular language has a grammar that is LL 1µ, but not all regular grammars are LL 1µ. Consider: S ab S ac Without left-factoring, this grammar is not LL 1µ. 113