Fall Compiler Principles Lecture 3: Parsing part 2. Roman Manevich BenGurion University


 Dorcas Horton
 3 years ago
 Views:
Transcription
1 Fall Compiler Principles Lecture 3: Parsing part 2 Roman Manevich BenGurion University
2 Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning Lowering Local Optimizations Register Allocation Topdown Parsing (LL) Dataflow Analysis Instruction Selection Bottomup Parsing (LR) Loop Optimizations Attribute Grammars midterm exam 2
3 Previously Role of syntax analysis Contextfree grammars refresher Topdown (predictive) parsing Recursive descent 3
4 Functions for nonterminals E LIT (E OP E) not E LIT true false OP and or xor E() { } if (current {TRUE, FALSE}) else if (current == LPAREN) else if (current == NOT) else LIT(); match(lparent); E(); OP(); E(); match(rparen); match(not); E(); error; LIT() { } if (current == TRUE) else if (current == FALSE) else match(true); match(false); error; OP() { } if (current == AND) else if (current == OR) else if (current == XOR) else match(and); match(or); match(xor); error; 4
5 Technical challenges with recursive descent 5
6 Recursive descent: problem 1 term ID indexed_elem indexed_elem ID [ expr ] With lookahead 1, the function for indexed_elem will never be tried What happens for input of the form ID[expr] 6
7 Recursive descent: problem 2 S A a b A a int S() { return A() && match(token( a )) && match(token( b )); } int A() { return match(token( a )) 1; } What happens for input ab? What happens if you flip order of alternatives and try aab? 7
8 Recursive descent: problem 3 p. 127 E E  term term int E() { } return E() && match(token(  )) && term(); What happens when we execute this procedure? Recursive descent parsers cannot handle leftrecursive grammars 8
9 Agenda Predicting productions via FIRST/FOLLOW/NULLABLE sets Handling conflicts LL(k) via pushdown automata 9
10 How do we predict? E LIT (E OP E) not E LIT true false OP and or xor How can we decide which production of E to take? 10
11 FIRST sets For a nonterminal A, FIRST(A) is the set of terminals that can start in a sentence derived from A Formally: FIRST(A) = {t A * t ω} For a sentential form α, FIRST(α) is the set of terminals that can start in a sentence derived from α Formally: FIRST(α) = {t α * t ω} 11
12 FIRST sets example E LIT (E OP E) not E LIT true false OP and or xor FIRST(E) =? FIRST(LIT) =? FIRST(OP) =? 12
13 FIRST sets example E LIT (E OP E) not E LIT true false OP and or xor FIRST(E) = FIRST(LIT) FIRST(( E OP E )) FIRST(not E) FIRST(LIT) = { true, false } FIRST(OP) = {and, or, xor} A set of recursive equations How do we solve them? 13
14 Computing FIRST sets Assume no null productions (A ) 1. Initially, for all nonterminals A, set FIRST(A) = { t A t ω for some ω } 2. Repeat the following until no changes occur: for each nonterminal A for each production A α 1 α k FIRST(A) = FIRST(α 1 ) FIRST(α k ) This is known as a fixedpoint algorithm We will see such iterative methods later in the course and learn to reason about them 14
15 Exercise: compute FIRST STMT if EXPR then STMT while EXPR do STMT EXPR ; EXPR TERM > id zero? TERM not EXPR ++ id  id TERM id constant STMT EXPR TERM 15
16 1. Initialization STMT if EXPR then STMT while EXPR do STMT EXPR ; EXPR TERM > id zero? TERM not EXPR ++ id  id TERM id constant STMT if while EXPR zero? Not TERM id constant 16
17 2. Iterate 1 STMT if EXPR then STMT while EXPR do STMT EXPR ; EXPR TERM > id zero? TERM not EXPR ++ id  id TERM id constant STMT if while zero? Not EXPR zero? Not TERM id constant 17
18 2. Iterate 2 STMT if EXPR then STMT while EXPR do STMT EXPR ; EXPR TERM > id zero? TERM not EXPR ++ id  id TERM id constant STMT if while zero? Not EXPR zero? Not id constant TERM id constant 18
19 2. Iterate 3 fixedpoint STMT if EXPR then STMT while EXPR do STMT EXPR ; EXPR TERM > id zero? TERM not EXPR ++ id  id TERM id constant STMT if while zero? Not EXPR zero? Not id constant TERM id constant id constant 19
20 Reasoning about the algorithm Assume no null productions (A ) 1. Initially, for all nonterminals A, set FIRST(A) = { t A t ω for some ω } 2. Repeat the following until no changes occur: for each nonterminal A for each production A α 1 α k FIRST(A) = FIRST(α 1 ) FIRST(α k ) Is the algorithm correct? Does it terminate? (complexity) 20
21 Reasoning about the algorithm Termination: Correctness: 21
22 LL(1) Parsing of grammars without epsilon productions 22
23 Using FIRST sets Assume G has no epsilon productions and for every nonterminal X and every pair of productions X and X we have that FIRST( ) FIRST( ) = {} No intersection between FIRST sets => can always pick a single rule 23
24 Using FIRST sets In our Boolean expressions example FIRST( LIT ) = { true, false } FIRST( ( E OP E ) ) = { ( } FIRST( not E ) = { not } If the FIRST sets intersect, may need longer lookahead LL(k) = class of grammars in which production rule can be determined using a lookahead of k tokens LL(1) is an important and useful class What if there are epsilon productions? 24
25 Extending LL(1) Parsing for epsilon productions 25
26 FIRST, FOLLOW, NULLABLE sets For each nonterminal X FIRST(X) = set of terminals that can start in a sentence derived from X FIRST(X) = {t X * t ω} NULLABLE(X) if X * FOLLOW(X) = set of terminals that can follow X in some derivation FOLLOW(X) = {t S * X t } 26
27 Computing the NULLABLE set Lemma: NULLABLE( 1 k ) = NULLABLE( 1 ) NULLABLE( k ) 1. Initially NULLABLE(X) = false 2. For each nonterminal X if exists a production X then NULLABLE(X) = true 3. Repeat for each production Y 1 k if NULLABLE( 1 k ) then NULLABLE(Y) = true until NULLABLE stabilizes 27
28 Exercise: compute NULLABLE S A a b A a B A B C C b NULLABLE(S) = NULLABLE(A) NULLABLE(a) NULLABLE(b) NULLABLE(A) = NULLABLE(a) NULLABLE( ) NULLABLE(B) = NULLABLE(A) NULLABLE(B) NULLABLE(C) NULLABLE(C) = NULLABLE(b) NULLABLE( ) 28
29 FIRST with epsilon productions How do we compute FIRST( 1 k ) when epsilon productions are allowed? FIRST( 1 k ) =? 29
30 FIRST with epsilon productions How do we compute FIRST( 1 k ) when epsilon productions are allowed? FIRST( 1 k ) = if not NULLABLE( 1 ) then FIRST( 1 ) else FIRST( 1 ) FIRST ( 2 k ) 30
31 Exercise: compute FIRST S A c b A a NULLABLE(S) = NULLABLE(A) NULLABLE(c) NULLABLE(b) NULLABLE(A) = NULLABLE(a) NULLABLE( ) FIRST(S) = FIRST(A) FIRST(cb) FIRST(A) = FIRST(a) FIRST ( ) FIRST(S) = FIRST(A) {c} FIRST(A) = FIRST(a) 31
32 FOLLOW sets if X α Y then FOLLOW(Y)? if NULLABLE( ) or = then FOLLOW(Y)? p
33 FOLLOW sets if X α Y then FOLLOW(Y) FIRST( ) if NULLABLE( ) or = then FOLLOW(Y)? p
34 FOLLOW sets if X α Y then FOLLOW(Y) FIRST( ) if NULLABLE( ) or = then FOLLOW(Y) FOLLOW(X) p
35 FOLLOW sets p. 189 if X α Y then FOLLOW(Y) FIRST( ) if NULLABLE( ) or = then FOLLOW(Y) FOLLOW(X) Allows predicting epsilon productions: X when the lookahead token is in FOLLOW(X) S A c b A a What should we predict for input cb? What should we predict for input acb? 35
36 LL(k) grammars 36
37 Conflicts FIRSTFIRST conflict X α and X and If FIRST(α) FIRST(β) {} FIRSTFOLLOW conflict NULLABLE(X) If FIRST(X) FOLLOW(X) {} 37
38 LL(1) grammars A grammar is in the class LL(1) when it can be derived via: Topdown derivation Scanning the input from left to right (L) Producing the leftmost derivation (L) With lookahead of one token For every two productions A α and A β we have FIRST(α) FIRST(β) = {} and if NULLABLE(A) then FIRST(A) FOLLOW(A) = {} A language is said to be LL(1) when it has an LL(1) grammar 38
39 LL(k) grammars Generalizes LL(1) for k lookahead tokens Need to generalize FIRST and FOLLOW for k lookahead tokens 39
40 Agenda Predicting productions via FIRST/FOLLOW/NULLABLE sets Handling conflicts LL(k) via pushdown automata 40
41 Handling conflicts 41
42 Back to problem 1 term ID indexed_elem indexed_elem ID [ expr ] FIRST(term) = { ID } FIRST(indexed_elem) = { ID } FIRSTFIRST conflict 42
43 Solution: left factoring Rewrite the grammar to be in LL(1) term ID indexed_elem indexed_elem ID [ expr ] New grammar is more complex has epsilon production term ID after_id After_ID [ expr ] Intuition: just like factoring in algebra: x*y + x*z into x*(y+z) 43
44 Exercise: apply left factoring S if E then S else S if E then S T 44
45 Exercise: apply left factoring S if E then S else S if E then S T S if E then S S T S else S 45
46 Back to problem 2 S A a b A a FIRST(S) = { a } FOLLOW(S) = { } FIRST(A) = { a } FOLLOW(A) = { a } FIRSTFOLLOW conflict 46
47 Solution: substitution S A a b A a Substitute A in S S a a b a b 47
48 Solution: substitution S A a b A a Substitute A in S S a a b a b Left factoring S a after_a after_a a b b 48
49 Back to problem 3 E E  term term Left recursion cannot be handled with a bounded lookahead What can we do? 49
50 Left recursion removal p. 130 N Nα β N βn N αn G 1 G 2 L(G 1 ) = β, βα, βαα, βααα, L(G 2 ) = same For our 3 rd example: Can be done algorithmically. Problem 1: grammar becomes mangled beyond recognition Problem 2: grammar may not be LL(1) E E  term term E term TE term TE  term TE 50
51 Recap Given a grammar Compute for each nonterminal NULLABLE FIRST using NULLABLE FOLLOW using FIRST and NULLABLE Compute FIRST for each sentential form appearing on righthand side of a production Check for conflicts If exist: attempt to remove conflicts by rewriting grammar 51
52 Agenda Predicting productions via FIRST/FOLLOW/NULLABLE sets Handling conflicts LL(k) via pushdown automata 52
53 LL(1) parsing: the automata approach By MG (talk contribs) (Own work) [GFDL ( or CCBYSA3.0 ( via Wikimedia Commons 53
54 Marking endoffile Sometimes it will be useful to transform a grammar G with start nonterminal S into a grammar G with a new start nonterminal S and a new production rule S S $ where $ is not part of the set of tokens To parse an input α with G we change it into α $ Simplifies topdown parsing with null productions and LR parsing 54
55 Another convention We will assume that all productions have been consecutively numbered (1) S E $ (2) E T (3) E E + T (4) T id (5) T ( E ) 55
56 LL(1) Parsers Recursive Descent Manual construction (parsing combinators make this easier, but ) Uses recursion Wanted A parser that can be generated automatically Does not use recursion 56
57 LL(1) parsing via pushdown automata Pushdown automaton uses Input stream Prediction stack Parsing table Nonterminal token production rule Entry indexed by nonterminal N and token t contains the alternative of N that must be predicated when current input starts with t Essentially, classic conversion from CFG to PDA The only difference is that we replace nondeterministic choice with the parsing table 57
58 Model of nonrecursive predictive parser a + b $ Stack X Y Predictive Parsing program Output Z $ Parsing Table 58
59 LL(1) parsing algorithm Set stack=s$ While true Prediction When top of stack is nonterminal N pop N, lookup table[n,t] If table[n,t] is not empty, push table[n,t] on prediction stack Otherwise: return syntax error Match When top of prediction stack is a terminal t, must be equal to next input token t. If (t = t ), pop t and consume t. If (t t ): return syntax error End When prediction stack is empty If input is empty at that point: return success Otherwise: return syntax error 59
60 Nonterminals Example transition table (1) E LIT (2) E ( E OP E ) (3) E not E (4) LIT true (5) LIT false (6) OP and (7) OP or (8) OP xor ( FIRST(E) Input tokens Which rule should be used ( ) not true false and or xor $ E LIT 4 5 OP
61 Running parser example aacbb$ A aab c Input suffix Stack content Move aacbb$ A$ predict(a,a) = A aab aacbb$ aab$ match(a,a) acbb$ Ab$ predict(a,a) = A aab acbb$ aabb$ match(a,a) cbb$ Abb$ predict(a,c) = A c cbb$ cbb$ match(c,c) bb$ bb$ match(b,b) b$ b$ match(b,b) $ $ match($,$) success a b c A A aab A c 61
62 Illegal input example abcbb$ A aab c Input suffix Stack content Move abcbb$ A$ predict(a,a) = A aab abcbb$ aab$ match(a,a) bcbb$ Ab$ predict(a,b) = ERROR a b c A A aab A c 62
63 Creating the prediction table Let G be an LL(1) grammar Compute FIRST/NULLABLE/FOLLOW Check for conflicts For nonterminal N and token t predict: 63
64 Topdown parsing summary Recursive descent LL(k) grammars LL(k) parsing with pushdown automata Cannot deal with left recursion Leftrecursion removal might result with complicated grammar 64
65 Next lecture: Bottomup parsing
Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich BenGurion University of the Negev
Fall 20172018 Compiler Principles Lecture 2: LL parsing Roman Manevich BenGurion University of the Negev 1 Books Compilers Principles, Techniques, and Tools Alfred V. Aho, Ravi Sethi, Jeffrey D. Ullman
More informationFall Compiler Principles Lecture 2: LL parsing. Roman Manevich BenGurion University of the Negev
Fall 20162017 Compiler Principles Lecture 2: LL parsing Roman Manevich BenGurion University of the Negev 1 Books Compilers Principles, Techniques, and Tools Alfred V. Aho, Ravi Sethi, Jeffrey D. Ullman
More informationCompilation Lecture 3: Syntax Analysis: TopDown parsing. Noam Rinetzky
Compilation 03683133 Lecture 3: Syntax Analysis: TopDown parsing Noam Rinetzky 1 Recursive descent parsing Define a function for every nonterminal Every function work as follows Find applicable production
More informationCompila(on (Semester A, 2013/14)
Compila(on 03683133 (Semester A, 2013/14) Lecture 4: Syntax Analysis (Top Down Parsing) Modern Compiler Design: Chapter 2.2 Noam Rinetzky Slides credit: Roman Manevich, Mooly Sagiv, Jeff Ullman, Eran
More information1 Introduction. 2 Recursive descent parsing. Predicative parsing. Computer Language Implementation Lecture Note 3 February 4, 2004
CMSC 51086 Winter 2004 Computer Language Implementation Lecture Note 3 February 4, 2004 Predicative parsing 1 Introduction This note continues the discussion of parsing based on context free languages.
More informationCS1622. Today. A Recursive Descent Parser. Preliminaries. Lecture 9 Parsing (4)
CS1622 Lecture 9 Parsing (4) CS 1622 Lecture 9 1 Today Example of a recursive descent parser Predictive & LL(1) parsers Building parse tables CS 1622 Lecture 9 2 A Recursive Descent Parser. Preliminaries
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 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 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 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 informationCS502: Compilers & Programming Systems
CS502: Compilers & Programming Systems Topdown Parsing Zhiyuan Li Department of Computer Science Purdue University, USA There exist two wellknown schemes to construct deterministic topdown parsers:
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 informationLL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012
Predictive Parsers LL(k) Parsing Can we avoid backtracking? es, if for a given input symbol and given nonterminal, we can choose the alternative appropriately. his is possible if the first terminal of
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 informationTableDriven Parsing
TableDriven Parsing It is possible to build a nonrecursive predictive parser by maintaining a stack explicitly, rather than implicitly via recursive calls [1] The nonrecursive parser looks up the production
More informationParsing. 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 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 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 informationCompilers. Predictive Parsing. Alex Aiken
Compilers Like recursivedescent but parser can predict which production to use By looking at the next fewtokens No backtracking Predictive parsers accept LL(k) grammars L means lefttoright scan of input
More informationBuilding a Parser III. CS164 3:305:00 TT 10 Evans. Prof. Bodik CS 164 Lecture 6 1
Building a Parser III CS164 3:305:00 TT 10 Evans 1 Overview Finish recursive descent parser when it breaks down and how to fix it eliminating left recursion reordering productions Predictive parsers (aka
More informationLL parsing Nullable, FIRST, and FOLLOW
EDAN65: Compilers LL parsing Nullable, FIRST, and FOLLOW Görel Hedin Revised: 201409 22 Regular expressions Context free grammar ATribute grammar Lexical analyzer (scanner) SyntacKc analyzer (parser)
More informationCompiler construction in4303 lecture 3
Compiler construction in4303 lecture 3 Topdown parsing Chapter 2.22.2.4 Overview syntax analysis: tokens AST program text lexical analysis language grammar parser generator tokens syntax analysis AST
More informationCompiler construction lecture 3
Compiler construction in4303 lecture 3 Topdown parsing Chapter 2.22.2.4 Overview syntax analysis: tokens AST language grammar parser generator program text lexical analysis tokens syntax analysis AST
More informationPart 3. Syntax analysis. Syntax analysis 96
Part 3 Syntax analysis Syntax analysis 96 Outline 1. Introduction 2. Contextfree grammar 3. Topdown parsing 4. Bottomup parsing 5. Conclusion and some practical considerations Syntax analysis 97 Structure
More informationTop down vs. bottom up parsing
Parsing A grammar describes the strings that are syntactically legal A recogniser simply accepts or rejects strings A generator produces sentences in the language described by the grammar A parser constructs
More informationAdministrativia. WA1 due on Thu PA2 in a week. Building a Parser III. Slides on the web site. CS164 3:305:00 TT 10 Evans.
Administrativia Building a Parser III CS164 3:305:00 10 vans WA1 due on hu PA2 in a week Slides on the web site I do my best to have slides ready and posted by the end of the preceding logical day yesterday,
More informationAbstract Syntax Trees & TopDown Parsing
Review of Parsing Abstract Syntax Trees & TopDown Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree
More informationAbstract Syntax Trees & TopDown Parsing
Abstract Syntax Trees & TopDown Parsing Review of Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree
More informationAbstract Syntax Trees & TopDown Parsing
Review of Parsing Abstract Syntax Trees & TopDown Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree
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 informationCS2210: Compiler Construction Syntax Analysis Syntax Analysis
Comparison with Lexical Analysis The second phase of compilation Phase Input Output Lexer string of characters string of tokens Parser string of tokens Parse tree/ast What Parse Tree? CS2210: Compiler
More informationLexical and Syntax Analysis. TopDown Parsing
Lexical and Syntax Analysis TopDown Parsing Easy for humans to write and understand String of characters Lexemes identified String of tokens Easy for programs to transform Data structure Syntax A syntax
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 informationAmbiguity, Precedence, Associativity & TopDown Parsing. Lecture 910
Ambiguity, Precedence, Associativity & TopDown Parsing Lecture 910 (From slides by G. Necula & R. Bodik) 9/18/06 Prof. Hilfinger CS164 Lecture 9 1 Administrivia Please let me know if there are continued
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 informationNote that for recursive descent to work, if A ::= B1 B2 is a grammar rule we need First k (B1) disjoint from First k (B2).
LL(k) Grammars We need a bunch of terminology. For any terminal string a we write First k (a) is the prefix of a of length k (or all of a if its length is less than k) For any string g of terminal and
More informationLexical and Syntax Analysis
Lexical and Syntax Analysis (of Programming Languages) TopDown Parsing Lexical and Syntax Analysis (of Programming Languages) TopDown Parsing Easy for humans to write and understand String of characters
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 informationLL(1) predictive parsing
LL(1) predictive parsing Informatics 2A: Lecture 11 Mary Cryan School of Informatics University of Edinburgh mcryan@staffmail.ed.ac.uk 10 October 2018 1 / 15 Recap of Lecture 10 A pushdown automaton (PDA)
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 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 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 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 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 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 informationPrelude COMP 181 Tufts University Computer Science Last time Grammar issues Key structure meaning Tufts University Computer Science
Prelude COMP Lecture Topdown Parsing September, 00 What is the Tufts mascot? Jumbo the elephant Why? P. T. Barnum was an original trustee of Tufts : donated $0,000 for a natural museum on campus Barnum
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 information8 Parsing. Parsing. Top Down Parsing Methods. Parsing complexity. Top down vs. bottom up parsing. Top down vs. bottom up parsing
8 Parsing Parsing A grammar describes syntactically legal strings in a language A recogniser simply accepts or rejects strings A generator produces strings A parser constructs a parse tree for a string
More informationCompiler Design 1. TopDown Parsing. Goutam Biswas. Lect 5
Compiler Design 1 TopDown Parsing Compiler Design 2 Nonterminal as a Function In a topdown parser a nonterminal may be viewed as a generator of a substring of the input. We may view a nonterminal
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 informationParser. Larissa von Witte. 11. Januar Institut für Softwaretechnik und Programmiersprachen. L. v. Witte 11. Januar /23
Parser Larissa von Witte Institut für oftwaretechnik und Programmiersprachen 11. Januar 2016 L. v. Witte 11. Januar 2016 1/23 Contents Introduction Taxonomy Recursive Descent Parser hift Reduce Parser
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 informationMore BottomUp Parsing
More BottomUp Parsing Lecture 7 Dr. Sean Peisert ECS 142 Spring 2009 1 Status Project 1 Back By Wednesday (ish) savior lexer in ~cs142/s09/bin Project 2 Due Friday, Apr. 24, 11:55pm My office hours 3pm
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 informationAmbiguity. Grammar E E + E E * E ( E ) int. The string int * int + int has two parse trees. * int
Administrivia Ambiguity, Precedence, Associativity & opdown Parsing eam assignments this evening for all those not listed as having one. HW#3 is now available, due next uesday morning (Monday is a holiday).
More informationCompilers: CS31003 Computer Sc & Engg: IIT Kharagpur 1. TopDown Parsing. Lect 5. Goutam Biswas
Compilers: CS31003 Computer Sc & Engg: IIT Kharagpur 1 TopDown Parsing Compilers: CS31003 Computer Sc & Engg: IIT Kharagpur 2 Nonterminal as a Function In a topdown parser a nonterminal may be viewed
More informationParsing. Lecture 11: Parsing. Recursive Descent Parser. Arithmetic grammar.  drops irrelevant details from parse tree
Parsing Lecture 11: Parsing CSC 131 Fall, 2014 Kim Bruce Build parse tree from an expression Interested in abstract syntax tree  drops irrelevant details from parse tree Arithmetic grammar ::=
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 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 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 informationTopdown parsing with backtracking
Top down parsing Types of parsers: Top down: repeatedly rewrite the start symbol; find a leftmost derivation of the input string; easy to implement; not all contextfree grammars are suitable. Bottom
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. (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 informationDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
KATHMANDU UNIVERSITY SCHOOL OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REPORT ON NONRECURSIVE PREDICTIVE PARSER Fourth Year First Semester Compiler Design Project Final Report submitted
More informationEDA180: Compiler Construc6on. Top down parsing. Görel Hedin Revised: a
EDA180: Compiler Construc6on Top down parsing Görel Hedin Revised: 201301 30a Compiler phases and program representa6ons source code Lexical analysis (scanning) Intermediate code genera6on tokens intermediate
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 informationReview of CFGs and Parsing II Bottomup Parsers. Lecture 5. Review slides 1
Review of CFGs and Parsing II Bottomup Parsers Lecture 5 1 Outline Parser Overview opdown Parsers (Covered largely through labs) Bottomup Parsers 2 he Functionality of the Parser Input: sequence of
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Parsing CMSC 330  Spring 2017 1 Recall: Front End Scanner and Parser Front End Token Source Scanner Parser Stream AST Scanner / lexer / tokenizer converts
More informationFall Compiler Principles Contextfree Grammars Refresher. Roman Manevich BenGurion University of the Negev
Fall 20162017 Compiler Principles Contextfree Grammars Refresher Roman Manevich BenGurion University of the Negev 1 xample grammar S S ; S S id := S print (L) id num + L L L, shorthand for Statement
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 informationExtra Credit Question
TopDown Parsing #1 Extra Credit Question Given this grammar G: E E+T E T T T * int T int T (E) Is the string int * (int + int) in L(G)? Give a derivation or prove that it is not. #2 Revenge of Theory
More informationCMSC 330, Fall 2009, Practice Problem 3 Solutions
CMC 330, Fall 2009, Practice Problem 3 olutions 1. Context Free Grammars a. List the 4 components of a context free grammar. Terminals, nonterminals, productions, start symbol b. Describe the relationship
More informationDefining syntax using CFGs
Defining syntax using CFGs Roadmap Last time Defined contextfree grammar This time CFGs for specifying a language s syntax Language membership List grammars Resolving ambiguity CFG Review G = (N,Σ,P,S)
More informationIntroduction to parsers
Syntax Analysis Introduction to parsers Contextfree grammars Pushdown automata Topdown parsing LL grammars and parsers Bottomup parsing LR grammars and parsers Bison/Yacc  parser generators Error
More informationFall Compiler Principles Lecture 4: Parsing part 3. Roman Manevich BenGurion University of the Negev
Fall 20162017 Compiler Principles Lecture 4: Parsing part 3 Roman Manevich BenGurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning
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 informationSometimes an ambiguous grammar can be rewritten to eliminate the ambiguity.
Eliminating Ambiguity Sometimes an ambiguous grammar can be rewritten to eliminate the ambiguity. Example: consider the following grammar stat if expr then stat if expr then stat else stat other One can
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 informationSyntax Analyzer  Parser
Syntax Analyzer  Parser ASU Textbook Chapter 4.24.9 (w/o error handling) Tsansheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 A program represented by a sequence of tokens
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 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 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 informationCSE 401 Midterm Exam Sample Solution 2/11/15
Question 1. (10 points) Regular expression warmup. For regular expression questions, you must restrict yourself to the basic regular expression operations covered in class and on homework assignments:
More informationFall Compiler Principles Lecture 5: Parsing part 4. Roman Manevich BenGurion University
Fall 20142015 Compiler Principles Lecture 5: Parsing part 4 Roman Manevich BenGurion University Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning Lowering
More informationCSE443 Compilers. Dr. Carl Alphonce 343 Davis Hall
CSE443 Compilers Dr. Carl Alphonce alphonce@buffalo.edu 343 Davis Hall Phases of a compiler Syntactic structure Figure 1.6, page 5 of text Recap Lexical analysis: LEX/FLEX (regex > lexer) Syntactic analysis:
More informationCS 321 Programming Languages and Compilers. VI. Parsing
CS 321 Programming Languages and Compilers VI. Parsing Parsing Calculate grammatical structure of program, like diagramming sentences, where: Tokens = words Programs = sentences For further information,
More information4 (c) parsing. Parsing. Top down vs. bo5om up parsing
4 (c) parsing Parsing A grammar describes syntac2cally legal strings in a language A recogniser simply accepts or rejects strings A generator produces strings A parser constructs a parse tree for a string
More informationTopic 3: Syntax Analysis I
Topic 3: Syntax Analysis I Compiler Design Prof. Hanjun Kim CoreLab (Compiler Research Lab) POSTECH 1 BackEnd FrontEnd The Front End Source Program Lexical Analysis Syntax Analysis Semantic Analysis
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 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 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 informationCOP 3402 Systems Software Syntax Analysis (Parser)
COP 3402 Systems Software Syntax Analysis (Parser) Syntax Analysis 1 Outline 1. Definition of Parsing 2. Context Free Grammars 3. Ambiguous/Unambiguous Grammars Syntax Analysis 2 Lexical and Syntax Analysis
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 informationSyntax Analysis/Parsing. Contextfree grammars (CFG s) Contextfree grammars vs. Regular Expressions. BNF description of PL/0 syntax
Susan Eggers 1 CSE 401 Syntax Analysis/Parsing Contextfree grammars (CFG s) Purpose: determine if tokens have the right form for the language (right syntactic structure) stream of tokens abstract syntax
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 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 III : Parsing. From Regular to ContextFree Grammars. Deriving a Parser from a ContextFree Grammar. Scanners and Parsers.
Part III : Parsing From Regular to ContextFree Grammars Deriving a Parser from a ContextFree Grammar Scanners and Parsers A Parser for EBNF LeftParsable Grammars Martin Odersky, LAMP/DI 1 From Regular
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 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 information