The role of the parser


 Hilary Preston
 3 years ago
 Views:
Transcription
1 The role of the parser source code tokens scanner parser IR errors Parser performs contextfree syntax analysis guides contextsensitive 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 1
2 Syntax analysis Contextfree syntax is specified with a contextfree grammar. Formally, a CFG G is a 4tuple 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 nonterminals can be combined to form strings in the language. Each production must have a single nonterminal 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
3 α β γ ¾ 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 singlestep 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
4 Syntax analysis Grammars are often written in BackusNaur form (BNF). Example: goal :: expr 1 expr :: expr op expr 2 ÒÙÑ 3 4 op :: This describes simple expressions over numbers and identifiers. In a BNF for a grammar, we represent 1. nonterminals with angle brackets or capital letters 2. terminals with ØÝÔ ÛÖ Ø Ö font or underline 3. productions as in the example 4
5 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 Contextfree 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
6 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
7 Derivations At each step, we chose a nonterminal to replace. This choice can lead to different derivations. Two are of particular interest: leftmost derivation the leftmost nonterminal is replaced at each step rightmost derivation the rightmost nonterminal is replaced at each step The previous example was a leftmost derivation. 7
8 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
9 Precedence goal expr expr op expr expr op expr * <id,y> <id,x> + <num,2> Treewalk evaluation computes (Ü ¾) Ý the wrong answer! Should be Ü (¾ Ý) 9
10 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
11 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
12 Precedence goal expr expr + term term term * factor factor factor <id,y> <id,x> <num,2> Treewalk evaluation computes Ü (¾ Ý) 12
13 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 contextfree ambiguity. 13
14 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
15 Ambiguity Ambiguity is often due to confusion in the contextfree specification. Contextsensitive confusions can arise from overloading. Example: ½ µ In many Algollike languages, could be a function or subscripted variable. Disambiguating this statement requires context: need values of declarations not contextfree really an issue of type Rather than complicate parsing, we will handle this separately. 15
16 Parsing: the big picture tokens grammar parser generator parser code IR Our goal is a flexible parser generator system 16
17 Topdown versus bottomup Topdown 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 backtrackfree (predictive) Bottomup 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
18 Topdown parsing A topdown 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
19 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
20 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
21 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
22 δ q 0 x xµ q 0 εµ Topdown parsing with pushdown automaton A topdown 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
23 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 x2*y 1 x2*y 3 x2*y 4 x2*y 7 x2*y 9 x2*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
24 Leftrecursion Topdown parsers cannot handle leftrecursion in a grammar Formally, a grammar is leftrecursive if A ¾ V n such that A µ Aα for some string α Our simple expression grammar is leftrecursive 24
25 Eliminating leftrecursion To remove leftrecursion, 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 nonterminal :: β bar foo :: α bar bar ε This fragment contains no leftrecursion 25
26 Example Our expression grammar contains two cases of leftrecursion :: 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 topdown parser will terminate backtrack on some inputs 26
27 Example This cleaner grammar defines the same language It is rightrecursive 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
28 Example Our longsuffering 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 ε Recall, we factored out leftrecursion 28
29 How much lookahead is needed? We saw that topdown 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 CockeYounger, 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, leftmost derivation, 1token lookahead; and LR 1µ: left to right scan, rightmost derivation, 1token lookahead 29
30 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
31 Left factoring What if a grammar does not have this property? Sometimes, we can transform a grammar to have this property. For each nonterminal 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 nonterminal. ¼ Repeat until no two alternatives for a single nonterminal have a common prefix. 31
32 Example Consider a rightrecursive 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 rightassociative. 32
33 Example There are two nonterminals that must be leftfactored: :: 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
34 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 :: ÒÙÑ Now, selection requires only a single token lookahead. Note: This grammar is still rightassociative. 34
35 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
36 Back to leftrecursion elimination Given a leftfactored CFG, to eliminate leftrecursion: 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 leftrecursive productions. 36
37 Generality Question: Answer: By left factoring and eliminating leftrecursion, can we transform an arbitrary contextfree grammar to a form where it can be predictively parsed with a single token lookahead? Given a contextfree grammar that doesn t meet our conditions, it is undecidable whether an equivalent grammar exists that does meet our conditions. Many contextfree 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
38 Recursive descent parsing General idea: Turn the grammar into a set of mutually recursive functions! Each nonterminal 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 nonterminal symbol, the code invokes the nonterminal s function 38
39 Recursive descent parsing In that manner, we can produce a simple recursive descent parser from the (rightassociative) grammar. Ó Ð ØÓ Ò Ò ÜØ ØÓ Ò µ ÜÔÖ µ ÊÊÇÊ ØÓ Ò Ç µ Ø Ò Ö ØÙÖÒ ÊÊÇÊ ÜÔÖ Ø ÖÑ µ ÊÊÇÊµ Ø Ò Ö ØÙÖÒ ÊÊÇÊ Ð Ö ØÙÖÒ ÜÔÖ ÔÖ Ñ µ ÜÔÖ ÔÖ Ñ ØÓ Ò ÈÄÍËµ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÜÔÖ µ Ð ØÓ Ò ÅÁÆÍËµ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÜÔÖ µ Ð Ö ØÙÖÒ ÇÃ 39
40 Recursive descent parsing Ø ÖÑ ØÓÖ µ ÊÊÇÊµ Ø Ò Ö ØÙÖÒ ÊÊÇÊ Ð Ö ØÙÖÒ Ø ÖÑ ÔÖ Ñ µ Ø ÖÑ ÔÖ Ñ ØÓ Ò ÅÍÄÌµ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ Ø ÖÑ µ Ð ØÓ Ò ÁÎµ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ Ø ÖÑ µ Ð Ö ØÙÖÒ ÇÃ ØÓÖ ØÓ Ò ÆÍÅµ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÇÃ Ð ØÓ Ò Á µ Ø Ò ØÓ Ò Ò ÜØ ØÓ Ò µ Ö ØÙÖÒ ÇÃ Ð Ö ØÙÖÒ ÊÊÇÊ 40
41 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 nonterminal s on the RHS and applies the appropriate AST constructor. Alternatively, the functions use an auxiliary stack for AST fragments. 41
42 Nonrecursive predictive parsing Observation: Our recursive descent parser encodes state information in its runtime 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, handcoded parser stackbased, tabledriven parser 42
43 Nonrecursive predictive parsing Now, a predictive parser looks like: stack source code scanner tokens tabledriven parser IR parsing tables Rather than writing code, we build tables. Building tables can be automated! 43
44 Tabledriven parsers A parser generator system often looks like: stack source code scanner tokens tabledriven parser IR grammar parser generator parsing tables This is true for both topdown (LL) and bottomup (LR) parsers 44
45 Nonrecursive predictive parsing Input: a string w and a parsing table M for G ØÓ ¼ ËØ ØÓ Ç ËØ ØÓ Start Symbol ØÓ Ò Ò ÜØ ØÓ Ò µ Ö Ô Ø ËØ ØÓ Ø ÖÑ Ò Ð ÓÖ Ç Ø Ò ØÓ Ò Ø Ò ÔÓÔ ØÓ Ò Ò ÜØ ØÓ Ò µ Ð ÖÖÓÖ µ Ð» X is a nonterminal» M ØÓ Ò X Y 1 Y 2 Y k Ø Ò ÔÓÔ ÔÙ Y k Y k 1 Y 1 Ð ÖÖÓÖ µ ÙÒØ Ð Ç 45
46 Nonrecursive 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 :: ÒÙÑ Its parse table: ÒÙÑ $ goal expr term factor we use $ to represent Ç 46
47 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
48 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
49 FOLLOW For a nonterminal 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 nonterminal 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
50 LL(1) grammars Previous definition A grammar G has a deterministic unambiguous predictive parser if for all nonterminals 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
51 LL(1) grammars Provable facts about LL(1) grammars: 1. No leftrecursive 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
52 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
53 Example Our longsuffering 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
54 Ø ÖÑ Ò Ð ÓÖ Ç Ø Ò ØÓ Ò Ø Ò ÖÖÓÖ µ Ð Ç ÙÒØ Ð Building the tree Again, we insert code at the right points: ¼ ØÓ Ç ËØ ØÓ root node ËØ ØÓ Start Symbol ËØ ØÓ Ò ÜØ ØÓ Ò µ ØÓ Ò Ö Ô Ø ËØ ØÓ ÔÓÔ Ò ÜØ ØÓ Ò µ ØÓ Ò pop and fill in node ÖÖÓÖ µ Ð» X is a nonterminal» Ð 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
55 A grammar that is not LL(1) :: expr Ø Ò stmt stmt expr Ø Ò stmt Ð stmt Leftfactored: :: 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
56 Error recovery Key notion: For each nonterminal, 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
57 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 leftsentential form is a sentential form that occurs in the leftmost derivation of some sentence. A rightsentential form is a sentential form that occurs in the rightmost derivation of some sentence. 57
58 Bottomup 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 rightsentential 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
59 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
60 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 rightsentential 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 rightsentential forms have a suffix containing only terminal symbols. 60
61 Handles S α A β The handle A β in the parse tree for αβw w 61
62 Handles Theorem: If G is unambiguous then every rightsentential 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
63 Example The leftrecursive 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
64 Handlepruning The process to construct a bottomup parse is called handlepruning. 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
65 Stack implementation One scheme to implement a handlepruning, bottomup parser is called a shiftreduce parser. Shiftreduce 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
66 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
67 Shiftreduce parsing Shiftreduce parsers are simple to understand A shiftreduce 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 nonterminal 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
68 LR parsing: key insight Recognize handles with a DFA [Knuth1965] DFA transitions shift states instead of symbols accepting states trigger reductions 68
69 ÓÖ Ú Ö Ö Ô Ø ØÓÔ Ó Ø β Ø Ø ÔÓÔ ¼ ØÓÔ Ó Ø Ø ÓÒ ØÓ Ò ÔØ Ø Ò Ð Ö ØÙÖÒ 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
70 Example tables state ACTION GOTO $ 0 s acc 2 s5 r3 3 r5 s6 r5 4 r6 r6 r6 5 s s 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 rightrecursive grammar; not the same as in previous lectures. 70
71 Example using the tables Stack Input Action $ 0 $ s4 $ 0 4 $ r6 $ 0 3 $ s6 $ $ s4 $ $ r6 $ $ r5 $ $ r4 $ 0 2 $ s5 $ $ s4 $ $ r6 $ $ r5 $ $ r3 $ $ r2 $ 0 1 $ acc 71
72 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 rightsentential form in the derivation, 1. isolate the handle of each rightsentential 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
73 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 ksymbol 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
74 Why study LR grammars? LR 1µ grammars are often used to construct parsers. We call these parsers LR 1µ parsers. virtually all contextfree programming language constructs can be expressed in LR 1µ an form LR grammars are the most general grammars parsable by a deterministic, bottomup parser efficient parsers can be implemented for LR 1µ grammars LR parsers detect an error as soon as possible in a lefttoright 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
75 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
76 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
77 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
78 The characteristic finite state machine (CFSM) The CFSM for a grammar is a DFA which recognizes viable prefixes of rightsentential 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
79 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
80 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
81 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
82 example LR 0µ 1 S E$ 2 E E T 3 T 4 T Eµ 5 The corresponding CFSM: T ( id id 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 $ T )
83 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
84 LR 0µ example 9 T ( T id id E id ( E $ T ) ( state ACTION GOTO ( ) $ S E T 0 s5 s 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 s s8 s3 8 r5 r5 r5 r5 r5 9 r3 r3 r3 r3 r3 84
85 Conflicts in the ACTION table If the LR 0µ parsing table contains any multiplydefined ACTION entries then G is not LR 0µ Two conflicts arise: shiftreduce: both shift and reduce possible in same item set reducereduce: more than one distinct reduce action possible in same item set Conflicts can be resolved through lookahead in ACTION. Consider: A ε aα µ shiftreduce conflict requires lookahead to avoid shiftreduce conflict after shifting (need to see to give precedence over ) 85
86 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
87 From previous example 1 S E$ 2 E E T 3 T 4 T 5 Eµ id id E $ T ( id T ( T E ) ( µ $ µ FOLLOW Eµ µ FOLLOW T state ACTION GOTO S E T 0 s5 s s3 acc 2 3 s5 s6 4 4 r2 r2 r2 5 r4 r4 r4 6 s5 s s8 s3 8 r5 r5 r5 9 r3 r3 r3 87
88 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
89 Example: But it is SLR 1µ state ACTION GOTO ( ) $ S E T F 0 s5 s s3 acc 2 3 s5 s r5 r5 r5 r5 5 r6 r6 r6 r6 6 s5 s 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
90 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
91 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
92 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
93 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
94 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
95 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
96 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
97 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 shiftreduce conflict: reduce on $, shift on 97
98 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
99 Another example Consider: 0 S ¼ S 1 S CC 2 C cc 3 d state ACTION GOTO c d $ S C 0 s3 s 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
100 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
101 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
102 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
103 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 s acc 2 s36 s s36 s 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
104 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
105 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
106 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
107 print an informative message to Ø ÖÖ Error recovery in shiftreduce 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
108 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 online CUP manual 108
109 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
110 Left versus right recursion Right Recursion: needed for termination in predictive parsers requires more stack space right associative operators Left Recursion: works fine in bottomup parsers limits required stack space left associative operators Rule of thumb: right recursion for topdown parsers left recursion for bottomup parsers 110
111 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
112 Complexity of parsing: grammar hierarchy type0: α >β ambiguous type1: contextsensitive ααβ >αδβ Linearbounded automaton: PSPACE complete type2: contextfree Α >α Earley s algorithm: O(n³) type3: 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
113 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 leftfactoring, this grammar is not LL 1µ. 113
Parsing. Roadmap. > Contextfree grammars > Derivations and precedence > Topdown parsing > Leftrecursion > Lookahead > Tabledriven parsing
Roadmap > Contextfree grammars > Derivations and precedence > Topdown parsing > Leftrecursion > Lookahead > Tabledriven parsing The role of the parser > performs contextfree syntax analysis > guides
More informationA leftsentential form is a sentential form that occurs in the leftmost derivation of some sentence.
Bottomup parsing Recall For a grammar G, with start symbol S, any string α such that S α is a sentential form If α V t, then α is a sentence in L(G) A leftsentential form is a sentential form that occurs
More information3. Parsing. Oscar Nierstrasz
3. Parsing Oscar Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes. http://www.cs.ucla.edu/~palsberg/ http://www.cs.purdue.edu/homes/hosking/
More informationBottomup parsing. BottomUp Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form
Bottomup parsing Bottomup parsing Recall Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form If α V t,thenα is called a sentence in L(G) Otherwise it is just
More informationChapter 4: LR Parsing
Chapter 4: LR Parsing 110 Some definitions Recall For a grammar G, with start symbol S, any string α such that S called a sentential form α is If α Vt, then α is called a sentence in L G Otherwise it is
More informationCompiler Construction 2016/2017 Syntax Analysis
Compiler Construction 2016/2017 Syntax Analysis Peter Thiemann November 2, 2016 Outline 1 Syntax Analysis Recursive topdown parsing Nonrecursive topdown parsing Bottomup parsing Syntax Analysis tokens
More informationPart 5 Program Analysis Principles and Techniques
1 Part 5 Program Analysis Principles and Techniques Front end 2 source code scanner tokens parser il errors Responsibilities: Recognize legal programs Report errors Produce il Preliminary storage map Shape
More informationCS 406/534 Compiler Construction Parsing Part I
CS 406/534 Compiler Construction Parsing Part I Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof. Ken Kennedy and Dr.
More informationS Y N T A X A N A L Y S I S LR
LR parsing There are three commonly used algorithms to build tables for an LR parser: 1. SLR(1) = LR(0) plus use of FOLLOW set to select between actions smallest class of grammars smallest tables (number
More information3. Syntax Analysis. Andrea Polini. Formal Languages and Compilers Master in Computer Science University of Camerino
3. Syntax Analysis Andrea Polini Formal Languages and Compilers Master in Computer Science University of Camerino (Formal Languages and Compilers) 3. Syntax Analysis CS@UNICAM 1 / 54 Syntax Analysis: the
More informationContextfree grammars
Contextfree grammars Section 4.2 Formal way of specifying rules about the structure/syntax of a program terminals  tokens nonterminals  represent higherlevel structures of a program start symbol,
More informationParsing. Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice.
Parsing Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP 412 at Rice. Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students
More informationCompiler Construction: Parsing
Compiler Construction: Parsing Mandar Mitra Indian Statistical Institute M. Mitra (ISI) Parsing 1 / 33 Contextfree grammars. Reference: Section 4.2 Formal way of specifying rules about the structure/syntax
More informationParsing II Topdown parsing. Comp 412
COMP 412 FALL 2018 Parsing II Topdown parsing Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled
More informationSyntactic Analysis. TopDown Parsing
Syntactic Analysis TopDown Parsing Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in Compilers class at University of Southern California (USC) have explicit permission to make
More informationCA Compiler Construction
CA4003  Compiler Construction David Sinclair A topdown parser starts with the root of the parse tree, labelled with the goal symbol of the grammar, and repeats the following steps until the fringe of
More informationIntroduction to Parsing. Comp 412
COMP 412 FALL 2010 Introduction to Parsing Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit permission to make
More informationTypes of parsing. CMSC 430 Lecture 4, Page 1
Types of parsing Topdown 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 backtrackfree (predictive)
More informationCS415 Compilers. Syntax Analysis. These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University
CS415 Compilers Syntax Analysis These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Limits of Regular Languages Advantages of Regular Expressions
More informationSyntax Analysis, III Comp 412
COMP 412 FALL 2017 Syntax Analysis, III Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp
More informationSection A. A grammar that produces more than one parse tree for some sentences is said to be ambiguous.
Section A 1. What do you meant by parser and its types? A parser for grammar G is a program that takes as input a string w and produces as output either a parse tree for w, if w is a sentence of G, or
More informationPART 3  SYNTAX ANALYSIS. F. Wotawa TU Graz) Compiler Construction Summer term / 309
PART 3  SYNTAX ANALYSIS F. Wotawa (IST @ TU Graz) Compiler Construction Summer term 2016 64 / 309 Goals Definition of the syntax of a programming language using context free grammars Methods for parsing
More informationCSCI312 Principles of Programming Languages
Copyright 2006 The McGrawHill Companies, Inc. CSCI312 Principles of Programming Languages! LL Parsing!! Xu Liu Derived from Keith Cooper s COMP 412 at Rice University Recap Copyright 2006 The McGrawHill
More informationParsing Part II. (Ambiguity, Topdown parsing, Leftrecursion Removal)
Parsing Part II (Ambiguity, Topdown parsing, Leftrecursion Removal) Ambiguous Grammars Definitions If a grammar has more than one leftmost derivation for a single sentential form, the grammar is ambiguous
More informationParsing Wrapup. Roadmap (Where are we?) Last lecture Shiftreduce parser LR(1) parsing. This lecture LR(1) parsing
Parsing Wrapup Roadmap (Where are we?) Last lecture Shiftreduce parser LR(1) parsing LR(1) items Computing closure Computing goto LR(1) canonical collection This lecture LR(1) parsing Building ACTION
More informationSyntax Analysis, III Comp 412
Updated algorithm for removal of indirect left recursion to match EaC3e (3/2018) COMP 412 FALL 2018 Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, III Comp 412 source code
More informationParsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones
Parsing III (Topdown parsing: recursive descent & LL(1) ) (Bottomup parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,
More informationWednesday, September 9, 15. Parsers
Parsers What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda
More informationParsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs:
What is a parser Parsers A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda
More informationAcademic Formalities. CS Modern Compilers: Theory and Practise. Images of the day. What, When and Why of Compilers
Academic Formalities CS6013  Modern Compilers: Theory and Practise Introduction V. Krishna Nandivada IIT Madras Written assignment = 5 marks. Programming assignments = 40 marks. Midterm = 25 marks, Final
More informationParsing III. (Topdown parsing: recursive descent & LL(1) )
Parsing III (Topdown parsing: recursive descent & LL(1) ) Roadmap (Where are we?) Previously We set out to study parsing Specifying syntax Contextfree grammars Ambiguity Topdown parsers Algorithm &
More informationMonday, September 13, Parsers
Parsers Agenda Terminology LL(1) Parsers Overview of LR Parsing Terminology Grammar G = (Vt, Vn, S, P) Vt is the set of terminals Vn is the set of nonterminals S is the start symbol P is the set of productions
More informationIntroduction to Parsing
Introduction to Parsing The Front End Source code Scanner tokens Parser IR Errors Parser Checks the stream of words and their parts of speech (produced by the scanner) for grammatical correctness Determines
More informationWednesday, August 31, Parsers
Parsers How do we combine tokens? Combine tokens ( words in a language) to form programs ( sentences in a language) Not all combinations of tokens are correct programs (not all sentences are grammatically
More informationUNITIII BOTTOMUP PARSING
UNITIII BOTTOMUP PARSING Constructing a parse tree for an input string beginning at the leaves and going towards the root is called bottomup parsing. A general type of bottomup parser is a shiftreduce
More informationCompilers. Yannis Smaragdakis, U. Athens (original slides by Sam
Compilers Parsing Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Next step text chars Lexical analyzer tokens Parser IR Errors Parsing: Organize tokens into sentences Do tokens conform
More informationLR Parsing Techniques
LR Parsing Techniques Introduction BottomUp Parsing LR Parsing as Handle Pruning ShiftReduce Parser LR(k) Parsing Model Parsing Table Construction: SLR, LR, LALR 1 BottomUP Parsing A bottomup parser
More informationSYNTAX ANALYSIS 1. Define parser. Hierarchical analysis is one in which the tokens are grouped hierarchically into nested collections with collective meaning. Also termed as Parsing. 2. Mention the basic
More informationBottomUp Parsing. Lecture 1112
BottomUp Parsing Lecture 1112 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 BottomUp Parsing Bottomup parsing is more general than topdown parsing And just as efficient
More informationSyntactic Analysis. TopDown Parsing. Parsing Techniques. TopDown Parsing. Remember the Expression Grammar? Example. Example
Syntactic Analysis opdown Parsing Parsing echniques opdown Parsers (LL(1), recursive descent) Start at the root of the parse tree and grow toward leaves Pick a production & try to match the input Bad
More information4. Lexical and Syntax Analysis
4. Lexical and Syntax Analysis 4.1 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal
More informationParsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468
Parsers Xiaokang Qiu Purdue University ECE 468 August 31, 2018 What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure
More informationSyntax Analysis Part I
Syntax Analysis Part I Chapter 4: ContextFree Grammars Slides adapted from : Robert van Engelen, Florida State University Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token,
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 5: Syntax Analysis (Parsing) Zheng (Eddy) Zhang Rutgers University January 31, 2018 Class Information Homework 1 is being graded now. The sample solution
More informationFormal Languages and Compilers Lecture VII Part 3: Syntactic A
Formal Languages and Compilers Lecture VII Part 3: Syntactic Analysis Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationSyntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay
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
More informationCompilers. Bottomup Parsing. (original slides by Sam
Compilers Bottomup Parsing Yannis Smaragdakis U Athens Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) BottomUp Parsing More general than topdown parsing And just as efficient Builds
More information4. Lexical and Syntax Analysis
4. Lexical and Syntax Analysis 4.1 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal
More informationBottomup Parser. Jungsik Choi
Formal Languages and Compiler (CSE322) Bottomup Parser Jungsik Choi chjs@khu.ac.kr * Some slides taken from SKKU SWE3010 (Prof. Hwansoo Han) and TAMU CSCE434500 (Prof. Lawrence Rauchwerger) Bottomup
More informationMIT Parse Table Construction. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology
MIT 6.035 Parse Table Construction Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Parse Tables (Review) ACTION Goto State ( ) $ X s0 shift to s2 error error goto s1
More informationEDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:
EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 20170911 This lecture Regular expressions Contextfree grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)
More informationLecture 8: Deterministic BottomUp Parsing
Lecture 8: Deterministic BottomUp Parsing (From slides by G. Necula & R. Bodik) Last modified: Fri Feb 12 13:02:57 2010 CS164: Lecture #8 1 Avoiding nondeterministic choice: LR We ve been looking at general
More informationLecture 7: Deterministic BottomUp Parsing
Lecture 7: Deterministic BottomUp Parsing (From slides by G. Necula & R. Bodik) Last modified: Tue Sep 20 12:50:42 2011 CS164: Lecture #7 1 Avoiding nondeterministic choice: LR We ve been looking at general
More informationCompiler Design 1. BottomUP Parsing. Goutam Biswas. Lect 6
Compiler Design 1 BottomUP Parsing Compiler Design 2 The Process The parse tree is built starting from the leaf nodes labeled by the terminals (tokens). The parser tries to discover appropriate reductions,
More informationSyntax Analysis, V Bottomup Parsing & The Magic of Handles Comp 412
Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, V Bottomup Parsing & The Magic of Handles Comp 412 COMP 412 FALL 2018 source code IR Front End Optimizer Back End IR target
More informationCSE P 501 Compilers. LR Parsing Hal Perkins Spring UW CSE P 501 Spring 2018 D1
CSE P 501 Compilers LR Parsing Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 D1 Agenda LR Parsing Tabledriven Parsers Parser States ShiftReduce and ReduceReduce conflicts UW CSE P 501 Spring 2018
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Context Free Grammars and Parsing 1 Recall: Architecture of Compilers, Interpreters Source Parser Static Analyzer Intermediate Representation Front End Back
More informationParser Generation. BottomUp Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottomup  from leaves to the root
Parser Generation Main Problem: given a grammar G, how to build a topdown parser or a bottomup parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence 
More informationDownloaded from Page 1. LR Parsing
Downloaded from http://himadri.cmsdu.org Page 1 LR Parsing We first understand Context Free Grammars. Consider the input string: x+2*y When scanned by a scanner, it produces the following stream of tokens:
More informationCompilerconstructie. najaar Rudy van Vliet kamer 140 Snellius, tel rvvliet(at)liacs(dot)nl. college 3, vrijdag 22 september 2017
Compilerconstructie najaar 2017 http://www.liacs.leidenuniv.nl/~vlietrvan1/coco/ Rudy van Vliet kamer 140 Snellius, tel. 071527 2876 rvvliet(at)liacs(dot)nl college 3, vrijdag 22 september 2017 + werkcollege
More informationSyntax Analysis: Contextfree Grammars, Pushdown Automata and Parsing Part  4. Y.N. Srikant
Syntax Analysis: Contextfree Grammars, Pushdown Automata and Part  4 Department of Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler
More informationFormal Languages and Compilers Lecture VII Part 4: Syntactic A
Formal Languages and Compilers Lecture VII Part 4: Syntactic Analysis Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationLR Parsers. Aditi Raste, CCOEW
LR Parsers Aditi Raste, CCOEW 1 LR Parsers Most powerful shiftreduce parsers and yet efficient. LR(k) parsing L : left to right scanning of input R : constructing rightmost derivation in reverse k : number
More informationSyntax Analysis. Martin Sulzmann. Martin Sulzmann Syntax Analysis 1 / 38
Syntax Analysis Martin Sulzmann Martin Sulzmann Syntax Analysis 1 / 38 Syntax Analysis Objective Recognize individual tokens as sentences of a language (beyond regular languages). Example 1 (OK) Program
More informationConcepts Introduced in Chapter 4
Concepts Introduced in Chapter 4 Grammars ContextFree Grammars Derivations and Parse Trees Ambiguity, Precedence, and Associativity Top Down Parsing Recursive Descent, LL Bottom Up Parsing SLR, LR, LALR
More informationParsing Part II (Topdown parsing, leftrecursion removal)
Parsing Part II (Topdown parsing, leftrecursion removal) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit
More informationEECS 6083 Intro to Parsing Context Free Grammars
EECS 6083 Intro to Parsing Context Free Grammars Based on slides from text web site: Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. 1 Parsing sequence of tokens parser
More informationBottom 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.
Bottom up parsing Construct a parse tree for an input string beginning at leaves and going towards root OR Reduce a string w of input to start symbol of grammar Consider a grammar S aabe A Abc b B d And
More informationSyntax Analysis, VI Examples from LR Parsing. Comp 412
Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, VI Examples from LR Parsing Comp 412 COMP 412 FALL 2018 source code IR IR target Front End Optimizer Back End code Copyright
More informationLR Parsing, Part 2. Constructing Parse Tables. An NFA Recognizing Viable Prefixes. Computing the Closure. GOTO Function and DFA States
TDDD16 Compilers and Interpreters TDDB44 Compiler Construction LR Parsing, Part 2 Constructing Parse Tables Parse table construction Grammar conflict handling Categories of LR Grammars and Parsers An NFA
More informationComputer Science 160 Translation of Programming Languages
Computer Science 160 Translation of Programming Languages Instructor: Christopher Kruegel TopDown Parsing Parsing Techniques Topdown parsers (LL(1), recursive descent parsers) Start at the root of the
More informationBottomUp Parsing. Lecture 1112
BottomUp Parsing Lecture 1112 (From slides by G. Necula & R. Bodik) 2/20/08 Prof. Hilfinger CS164 Lecture 11 1 Administrivia Test I during class on 10 March. 2/20/08 Prof. Hilfinger CS164 Lecture 11
More informationCOP4020 Programming Languages. Syntax Prof. Robert van Engelen
COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview n Tokens and regular expressions n Syntax and contextfree grammars n Grammar derivations n More about parse trees n Topdown and
More informationChapter 3. Parsing #1
Chapter 3 Parsing #1 Parser source file get next character scanner get token parser AST token A parser recognizes sequences of tokens according to some grammar and generates Abstract Syntax Trees (ASTs)
More informationCS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F).
CS 2210 Sample Midterm 1. Determine if each of the following claims is true (T) or false (F). F A language consists of a set of strings, its grammar structure, and a set of operations. (Note: a language
More informationLexical and Syntax Analysis. BottomUp Parsing
Lexical and Syntax Analysis BottomUp Parsing Parsing There are two ways to construct derivation of a grammar. TopDown: begin with start symbol; repeatedly replace an instance of a production s LHS with
More informationChapter 4. Lexical and Syntax Analysis
Chapter 4 Lexical and Syntax Analysis Chapter 4 Topics Introduction Lexical Analysis The Parsing Problem RecursiveDescent Parsing BottomUp Parsing Copyright 2012 AddisonWesley. All rights reserved.
More informationBottom Up Parsing. Shift and Reduce. Sentential Form. Handle. Parse Tree. Bottom Up Parsing 9/26/2012. Also known as ShiftReduce parsing
Also known as ShiftReduce parsing More powerful than top down Don t need left factored grammars Can handle left recursion Attempt to construct parse tree from an input string eginning at leaves and working
More informationCS 4120 Introduction to Compilers
CS 4120 Introduction to Compilers Andrew Myers Cornell University Lecture 6: BottomUp Parsing 9/9/09 Bottomup parsing A more powerful parsing technology LR grammars  more expressive than LL can handle
More informationSyntax Analysis, VII One more LR(1) example, plus some more stuff. Comp 412 COMP 412 FALL Chapter 3 in EaC2e. target code.
COMP 412 FALL 2017 Syntax Analysis, VII One more LR(1) example, plus some more stuff Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon,
More informationOptimizing Finite Automata
Optimizing Finite Automata We can improve the DFA created by MakeDeterministic. Sometimes a DFA will have more states than necessary. For every DFA there is a unique smallest equivalent DFA (fewest states
More informationLR Parsing LALR Parser Generators
LR Parsing LALR Parser Generators Outline Review of bottomup parsing Computing the parsing DFA Using parser generators 2 Bottomup Parsing (Review) A bottomup parser rewrites the input string to the
More informationPrinciples of Programming Languages
Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 8! Bo;om Up Parsing Shi? Reduce LR(0) automata and
More informationVIVA QUESTIONS WITH ANSWERS
VIVA QUESTIONS WITH ANSWERS 1. What is a compiler? A compiler is a program that reads a program written in one language the source language and translates it into an equivalent program in another languagethe
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Context Free Grammars 1 Architecture of Compilers, Interpreters Source Analyzer Optimizer Code Generator Abstract Syntax Tree Front End Back End Compiler
More informationParsing. source code. while (k<=n) {sum = sum+k; k=k+1;}
Compiler Construction Grammars Parsing source code scanner tokens regular expressions lexical analysis Lennart Andersson parser context free grammar Revision 2012 01 23 2012 parse tree AST builder (implicit)
More informationBottomUp Parsing II. Lecture 8
BottomUp Parsing II Lecture 8 1 Review: ShiftReduce Parsing Bottomup parsing uses two actions: Shift ABC xyz ABCx yz Reduce Cbxy ijk CbA ijk 2 Recall: he Stack Left string can be implemented by a stack
More informationSyntax Analysis. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill
Syntax Analysis Björn B. Brandenburg The University of North Carolina at Chapel Hill Based on slides and notes by S. Olivier, A. Block, N. Fisher, F. HernandezCampos, and D. Stotts. The Big Picture Character
More informationParsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1)
TD parsing  LL(1) Parsing First and Follow sets Parse table construction BU Parsing Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1) Problems with SLR Aho, Sethi, Ullman, Compilers
More informationTopDown Parsing and Intro to BottomUp Parsing. Lecture 7
TopDown Parsing and Intro to BottomUp Parsing Lecture 7 1 Predictive Parsers Like recursivedescent but parser can predict which production to use Predictive parsers are never wrong Always able to guess
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Context Free Grammars 1 Architecture of Compilers, Interpreters Source Analyzer Optimizer Code Generator Abstract Syntax Tree Front End Back End Compiler
More informationSyntax. Syntax. We will study three levels of syntax Lexical Defines the rules for tokens: literals, identifiers, etc.
Syntax Syntax Syntax defines what is grammatically valid in a programming language Set of grammatical rules E.g. in English, a sentence cannot begin with a period Must be formal and exact or there will
More informationLecture BottomUp Parsing
Lecture 14+15 BottomUp Parsing CS 241: Foundations of Sequential Programs Winter 2018 Troy Vasiga et al University of Waterloo 1 Example CFG 1. S S 2. S AyB 3. A ab 4. A cd 5. B z 6. B wz 2 Stacks in
More informationSLR parsers. LR(0) items
SLR parsers LR(0) items As we have seen, in order to make shiftreduce parsing practical, we need a reasonable way to identify viable prefixes (and so, possible handles). Up to now, it has not been clear
More informationLR Parsing  The Items
LR Parsing  The Items Lecture 10 Sections 4.5, 4.7 Robb T. Koether HampdenSydney College Fri, Feb 13, 2015 Robb T. Koether (HampdenSydney College) LR Parsing  The Items Fri, Feb 13, 2015 1 / 31 1 LR
More informationIn One Slide. Outline. LR Parsing. Table Construction
LR Parsing Table Construction #1 In One Slide An LR(1) parsing table can be constructed automatically from a CFG. An LR(1) item is a pair made up of a production and a lookahead token; it represents a
More informationCSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis
Chapter 4 Lexical and Syntax Analysis Introduction  Language implementation systems must analyze source code, regardless of the specific implementation approach  Nearly all syntax analysis is based on
More informationAlternatives for semantic processing
Semantic Processing Copyright c 2000 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
More informationHow do LL(1) Parsers Build Syntax Trees?
How do LL(1) Parsers Build Syntax Trees? So far our LL(1) parser has acted like a recognizer. It verifies that input token are syntactically correct, but it produces no output. Building complete (concrete)
More informationLR Parsing LALR Parser Generators
Outline LR Parsing LALR Parser Generators Review of bottomup parsing Computing the parsing DFA Using parser generators 2 Bottomup Parsing (Review) A bottomup parser rewrites the input string to the
More information