Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich BenGurion University of the Negev


 Garry Sherman
 2 years ago
 Views:
Transcription
1 Fall Compiler Principles Lecture 2: LL parsing Roman Manevich BenGurion University of the Negev 1
2 Books Compilers Principles, Techniques, and Tools Alfred V. Aho, Ravi Sethi, Jeffrey D. Ullman Modern Compiler Implementation in Java Andrew W. Appel Modern Compiler Design D. Grune, H. Bal, C. Jacobs, K. Langendoen Advanced Compiler Design and Implementation Steven Muchnik 2
3 Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning Operational Semantics Dataflow Analysis Register Allocation Topdown Parsing (LL) Lowering Loop Optimizations Instruction Selection Bottomup Parsing (LR) midterm exam 3
4 Contextfree grammars start nonterminal nonterminal S E $ E T E E + T T id T ( E ) terminal production / rule 4
5 Contextfree languages Sentential forms Derivations (leftmost, rightmost) Language = all derivable words Derivation tree (also called parse tree) Language = all yields of derivation trees Ambiguous grammars 5
6 Agenda Understand role of syntax analysis Parsing strategies LL parsing Building a predictor table via FIRST/FOLLOW/NULLABLE sets Handling conflicts 6
7 Role of syntax analysis Highlevel Language Lexical Analysis Syntax Analysis Parsing AST Symbol Table etc. Inter. Rep. (IR) Code Generation Executable Code (scheme) Recover structure from stream of tokens Parse tree / abstract syntax tree Error reporting (recovery) Other possible tasks Syntax directed translation (one pass compilers) Create symbol table Create prettyprinted version of the program, e.g., Auto Formatting function in IDE 7
8 From tokens to abstract syntax trees program text 59 + (1257 * xposition) Lexical Analyzer Regular expressions Finite automata Lexical error valid token stream num + ( num * id ) Grammar: E id E num E E + E E E * E E ( E ) syntax error + Parser valid Contextfree grammars Pushdown automata Abstract Syntax Tree num * num x 8
9 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 $ $ is not part of the set of tokens It is a special EndOfFile (EOF) token To parse α with G we change it into α $ Simplifies parsing grammars with null productions Also simplifies parsing LR grammars Blank space character 9
10 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 ) 10
11 Parsing strategies 11
12 Broad kinds of parsers Parsers for arbitrary grammars CockeYoungerKasami [ 65] method O(n 3 ) Earley s method (implemented by NLTK) O(n 3 ) but lower for restricted classes Not commonly used by compilers Parsers for restricted classes of grammars TopDown Predictive LL parsing Backtracking recursive descent / combinators BottomUp LR parsing 12
13 Topdown parsing Constructs parse tree in a topdown matter Find leftmost derivation Predictive: for every nonterminal and ktokens predict the next production LL(k) Challenge: beginning with the start symbol, try to guess the productions to apply to end up at the user's program By Fidelio (Own work) [GFDL ( or CCBYSA ( via Wikimedia Commons 13
14 Predictive parsing 14
15 Exercise: show leftmost derivation How did we decide which production of E to take? E not E not ( E OP E ) not ( not E OP E ) not ( not LIT OP E ) not ( not true OP E ) not ( not true or E ) not ( not true or LIT ) not ( not true or false ) (1) E LIT (2) (E OP E) (3) not E (4) LIT true (5) false (6) OP and (7) or (8) xor not E E ( E OP E ) not E or LIT LIT false true 15
16 Predictive parsing Given a grammar G attempt to derive a word ω Idea Scan input from left to right Apply production to leftmost nonterminal Pick production rule based on next (1) input token Problem: there is more than one production based for next token Solution: restrict grammars to LL(1) Parser correctly predicts which production to apply If grammar is not in LL(1) the parser construction algorithm will detect it 16
17 nonterminal LL(1) parsing via pushdown automata Input stream a + b $ Stack of symbols (current sentential form) X Y Z $ Parsing program token Derivation tree / error Prediction table production 17
18 LL(1) parsing algorithm Initialze stack to S $ while true Prediction When top of stack is nonterminal N 1. Pop N 2. lookup Table[N,t] 3. If table[n,t] is not empty, push Table[N,t] on stack else return syntax error Match When top of stack is terminal t If t=next input token, pop t and increment input index else return syntax error End When stack is empty If input is empty return success else return syntax error 18
19 Nonterminals Example prediction 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 Input tokens Table entries determine which production to take ( ) not true false and or xor $ E LIT 4 5 OP
20 Running parser example aacbb$ S asb c Input suffix Stack content Move aacbb$ S$ predict(s,a) = S asb aacbb$ asb$ match(a,a) acbb$ Sb$ predict(s,a) = S asb acbb$ asbb$ match(a,a) cbb$ Sbb$ predict(s,c) = S c cbb$ cbb$ match(c,c) bb$ bb$ match(b,b) b$ b$ match(b,b) $ $ match($,$) success a b c S S asb S c 20
21 Illegal input example abcbb$ S asb c Input suffix Stack content Move abcbb$ S$ predict(s,a) = S asb abcbb$ asb$ match(a,a) bcbb$ Sb$ predict(s,b) = ERROR a b c S S asb S c 21
22 Building the prediction table Let G be a grammar Compute FIRST/NULLABLE/FOLLOW Check for conflicts No conflicts => G is an LL(1) grammar Conflicts exit => G is not an LL(1) grammar Attempt to transform G into an equivalent LL(1) grammar G 22
23 First sets 23
24 FIRST sets Definition: 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 ω} Definition: For a sentential form α, FIRST(α) is the set of terminals that can start in a sentence derived from α Formally: FIRST(α) = {t α * t ω} 24
25 FIRST sets example E LIT (E OP E) not E LIT true false OP and or xor FIRST(E) =? FIRST(LIT) =? FIRST(OP) =? 25
26 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? 26
27 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 27
28 Exercise: compute FIRST FIRST(STMT) = FIRST(if EXPR then STMT) FIRST(while EXPR do STMT) FIRST(EXPR) FIRST(EXPR) = FIRST(TERM > id) FIRST(zero? TERM) FIRST(not EXPR) FIRST(++ id) FIRST( id) FIRST(TERM) = FIRST(id) FIRST(constant) 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 28
29 Exercise: compute FIRST FIRST(STMT) = {if, while} FIRST(EXPR) FIRST(EXPR) = {zero?, not, ++, } FIRST(TERM) FIRST(TERM) = {id, constant} 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 29
30 1. Initialization FIRST(STMT) = {if, while} FIRST(EXPR) FIRST(EXPR) = {zero?, not, ++, } FIRST(TERM) FIRST(TERM) = {id, constant} 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 30
31 2. Iterate 1 FIRST(STMT) = {if, while} FIRST(EXPR) FIRST(EXPR) = {zero?, not, ++, } FIRST(TERM) FIRST(TERM) = {id, constant} 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 31
32 2. Iterate 2 FIRST(STMT) = {if, while} FIRST(EXPR) FIRST(EXPR) = {zero?, not, ++, } FIRST(TERM) FIRST(TERM) = {id, constant} 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 32
33 2. Iterate 3 fixedpoint FIRST(STMT) = {if, while} FIRST(EXPR) FIRST(EXPR) = {zero?, not, ++, } FIRST(TERM) FIRST(TERM) = {id, constant} 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 33
34 Reasoning about the algorithm Assume no null productions (A ) 1. Initially, for all nonterminals A, set FIRST(A) = { t A t ω for some ω } 2. Iterate to fixpoint: for each nonterminal A for each production A α 1 α k FIRST(A) := FIRST(α 1 ) FIRST(α k ) Is the algorithm correct? Does it terminate? (complexity) 34
35 Reasoning about the algorithm Termination: Correctness: 35
36 LL(1) Parsing of grammars without epsilon productions 36
37 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 37
38 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 38
39 Exercise: LL(1) prediction table Terminals: id. num $ (1) S E $ (2) E A B (3) E B (4) A id B (5) B. id A (6) B num FIRST(S) = FIRST(E) = FIRST(A) = FIRST(B) = S E A B id. num $ 39
40 Extending LL(1) Parsing for epsilon productions 40
41 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 } 41
42 Computing the NULLABLE set Lemma: NULLABLE( 1 k ) = NULLABLE( 1 ) NULLABLE( k ) If X 1 k then we have the following equation: NULLABLE(X) = NULLABLE( 1 ) NULLABLE( k ) 1. Initially NULLABLE(X) = false 2. Iterate to fixpoint: for each production Y 1 k if NULLABLE( 1 k ) then NULLABLE(Y) = true 42
43 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( ) 43
44 FIRST with epsilon productions How do we compute FIRST( 1 k ) when epsilon productions are allowed? FIRST( 1 k ) =? 44
45 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 ) 45
46 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) = {a} S A c b A a What should we predict for input acb? What should we predict for input cb? 46
47 FOLLOW sets FOLLOW(X) = set of terminals that can follow X in some derivation FOLLOW(X) = {t S * X t } 47
48 FOLLOW sets if X α Y then FOLLOW(Y)? if NULLABLE( ) or = then FOLLOW(Y)? p
49 FOLLOW sets if X α Y then FOLLOW(Y) FIRST( ) if NULLABLE( ) or = then FOLLOW(Y)? p
50 FOLLOW sets if X α Y then FOLLOW(Y) FIRST( ) if NULLABLE( ) or = then FOLLOW(Y) FOLLOW(X) p
51 FOLLOW sets if X α Y then FOLLOW(Y) FIRST( ) if NULLABLE( ) (or = ) then FOLLOW(Y) FOLLOW(X) Allows predicting nullable productions: X α where NULLABLE(α) when the lookahead token is in FOLLOW(X) p. 189 S A c b A a c What should we predict for input cb? What should we predict for input acb? 51
52 Filling the prediction table Table[N, t] = N α if 1. t FIRST(α) or 2. NULLABLE(α) and t FOLLOW(N) 52
53 LL(1) conflicts 53
54 Conflicts FIRSTFIRST conflict X α and X and If FIRST(α) FIRST(β) {} FIRSTFOLLOW conflict X α NULLABLE(α) If FIRST(α) FOLLOW(X) {} 54
55 LL(1) grammars A grammar is in the class LL(1) when its LL(1) prediction table contains no conflicts A language is said to be LL(1) when it has an LL(1) grammar 55
56 LL(k) grammars 56
57 LL(k) grammars Generalizes LL(1) for k lookahead tokens Need to generalize FIRST and FOLLOW for k lookahead tokens 57
58 Agenda Understand role of syntax analysis Parsing strategies LL parsing Building a predictor table via FIRST/FOLLOW/NULLABLE sets Handling conflicts 58
59 Handling conflicts 59
60 Problem 1: FIRSTFIRST conflict term ID indexed_elem indexed_elem ID [ expr ] FIRST(indexed_elem) = { ID } How can we transform the grammar into an equivalent grammar that does not have this conflict? 60
61 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) 61
62 Exercise: apply left factoring S if E then S else S if E then S T 62
63 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 63
64 Problem 2: FIRSTFOLLOW conflict S A a b A a FIRST(S) = { a } FOLLOW(S) = { } FIRST(A) = { a } FOLLOW(A) = { a } How can we transform the grammar into an equivalent grammar that does not have this conflict? 64
65 Solution: substitution S A a b A a Substitute A in S S a a b a b 65
66 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 66
67 Problem 3: FIRSTFIRST conflict E E  term term Left recursion cannot be handled with a bounded lookahead How can we transform the grammar into an equivalent grammar that does not have this conflict? 67
68 Solution: 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 68
69 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 69
70 Next lecture: bottomup parsing
Fall 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 informationFall Compiler Principles Lecture 3: Parsing part 2. Roman Manevich BenGurion University
Fall 20142015 Compiler Principles Lecture 3: Parsing part 2 Roman Manevich BenGurion University Tentative syllabus Front End Intermediate Representation Optimizations Code Generation Scanning Lowering
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationCOMP 181. Prelude. Next step. Parsing. Study of parsing. Specifying syntax with a grammar
COMP Lecture Parsing September, 00 Prelude What is the common name of the fruit Synsepalum dulcificum? Miracle fruit from West Africa What is special about miracle fruit? Contains a protein called miraculin
More informationFall Compiler Principles Lecture 5: Intermediate Representation. Roman Manevich BenGurion University of the Negev
Fall 20162017 Compiler Principles Lecture 5: Intermediate Representation Roman Manevich BenGurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation
More informationFall Compiler Principles Lecture 6: Intermediate Representation. Roman Manevich BenGurion University of the Negev
Fall 20152016 Compiler Principles Lecture 6: Intermediate Representation Roman Manevich BenGurion University of the Negev Tentative syllabus Front End Intermediate Representation Optimizations Code Generation
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 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 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 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 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 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 informationChapter 2 Syntax Analysis
Chapter 2 Syntax Analysis Syntax and vocabulary are overwhelming constraints the rules that run us. Language is using us to talk we think we re using the language, but language is doing the thinking, we
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 informationCSE302: Compiler Design
CSE302: Compiler Design Instructor: Dr. Liang Cheng Department of Computer Science and Engineering P.C. Rossin College of Engineering & Applied Science Lehigh University February 20, 2007 Outline Recap
More informationA programming language requires two major definitions A simple one pass compiler
A programming language requires two major definitions A simple one pass compiler [Syntax: what the language looks like A contextfree grammar written in BNF (BackusNaur Form) usually suffices. [Semantics:
More informationAutomatic generation of LL(1) parsers
Automatic generation of LL(1) parsers Informatics 2A: Lecture 12 John Longley School of Informatics University of Edinburgh jrl@staffmail.ed.ac.uk 14 October, 2011 1 / 12 Generating parse tables We ve
More informationSyntactic Analysis. Chapter 4. Compiler Construction Syntactic Analysis 1
Syntactic Analysis Chapter 4 Compiler Construction Syntactic Analysis 1 Contextfree Grammars The syntax of programming language constructs can be described by contextfree grammars (CFGs) Relatively simple
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 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. 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 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 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 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 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 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 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 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 informationChapter 2 Syntax Analysis
Chapter 2 Syntax Analysis Syntax and vocabulary are overwhelming constraints the rules that run us. Language is using us to talk we think we re using the language, but language is doing the thinking, we
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 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 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 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 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 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 informationEarlier edition Dragon book has been revised. Course Outline Contact Room 124, tel , rvvliet(at)liacs(dot)nl
Compilerconstructie najaar 2013 http://www.liacs.nl/home/rvvliet/coco/ Rudy van Vliet kamer 124 Snellius, tel. 071527 5777 rvvliet(at)liacs(dot)nl college 1, dinsdag 3 september 2013 Overview 1 Why this
More informationSyntax Analysis. The Big Picture. The Big Picture. COMP 524: Programming Languages Srinivas Krishnan January 25, 2011
Syntax Analysis COMP 524: Programming Languages Srinivas Krishnan January 25, 2011 Based in part on slides and notes by Bjoern Brandenburg, S. Olivier and A. Block. 1 The Big Picture Character Stream Token
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 informationParsing #1. Leonidas Fegaras. CSE 5317/4305 L3: Parsing #1 1
Parsing #1 Leonidas Fegaras CSE 5317/4305 L3: Parsing #1 1 Parser source file get next character scanner get token parser AST token A parser recognizes sequences of tokens according to some grammar and
More information