Parsing II Topdown parsing. Comp 412


 Harvey Parrish
 3 years ago
 Views:
Transcription
1 COMP 412 FALL 2017 Parsing II Topdown parsing Comp 412 source code IR Front End OpMmizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit permission to make copies of these materials for their personal use. Faculty from other educamonal insmtumons may use these materials for nonprofit educamonal purposes, provided this copyright nomce is preserved. Chapter 3 in EaC2e
2 Ambiguity Review Defini9ons A contextfree grammar G is ambiguous if there exists has more than one letmost derivamon for some sentence in L(G) A contextfree grammar G is ambiguous if there exists has more than one rightmost derivamon for some sentence in L(G) The letmost and rightmost derivamons for a sentenmal form may differ, even in an unambiguous grammar However, they must have the same parse tree 1
3 Ambiguity Review We talked about syntac9c ambiguity Ambiguity in the contextfree syntax Classic example is the ifthenelse grammar 0 Stmt if Expr then Stmt 1 if Expr then Stmt else Stmt 2 other statements Fix ambiguity in contextfree grammar by rewrimng the grammar 0 Stmt if Expr then Stmt 1 if Expr then WithElse else Stmt 2 other statements 3 WithElse if Expr then WithElse else WithElse 4 other statements 3
4 Ambiguity We must also deal with seman9c ambiguity One syntax with two meanings Classic example arose in Algollike languages A = f(17,21) Is this a call to a funcmon f? or a reference to an element of an array f? DisambiguaMng this kind of confusion requires context Need the value of the declaramon for f An issue of type, not syntax Requires either: 1. An extragrammamcal solumon Manage the ambiguity by accepbng language and deferring disambiguabon unbl the compiler has enough context (e.g., type informabon) 2. A different syntax Fix ambiguity in meaning by changing the language (e.g., C s [ ] or BCPL s! ) 4
5 Order of OperaMons or Precedence Consider again the deriva9on of x 2 * y 0 Expr Expr Op Value 1 Value 2 Value number 3 idenmfier 4 Op plus 5 minus 6 Mmes 7 I divide Rule Senten*al Form Expr 0 Expr Op Value 0 Expr Op Value Op Value 1 Value Op Value Op Value 3 <id,x> Op Value Op Value 5 <id,x> Value Op Value 2 <id,x> <num,2> Op Value 6 <id,x> <num,2> * Value 3 <id,x> <num,2> * <id,y> LeHmost deriva9on 5
6 Order of OperaMons The lehmost deriva9on is unique, but it specifies the wrong precedence Rule Senten*al Form Expr 0 Expr Op Value 0 Expr Op Value Op Value 1 Value Op Value Op Value 3 <id,x> Op Value Op Value 5 <id,x> Value Op Value 2 <id,x> <num,2> Op Value 6 <id,x> <num,2> * Value 3 <id,x> <num,2> * <id,y> Expr Expr Op Mmes Expr Op Value Value minus <num,2> Value <id,y> Evaluates (x  2) * y <id,x> Elimina9ng ambiguity does not necessarily produce the desired meaning. It COMP produces 412, a Fall consistent 2017 meaning, but that meaning can be consistently wrong. 6
7 Order of OperaMons How do you add precedence to a grammar? To add precedence Decide how many levels of precedence the grammar needs Create a nonterminal for each level of precedence Isolate the corresponding part of the grammar Force the parser to recognize high precedence subexpressions first For algebraic expressions, including (), +,, *, and / Parentheses first (level 1 ) MulMplicaMon and division, next (level 2) SubtracMon and addimon, last (level 3) 7
8 DerivaMons and Precedence Adding the standard algebraic precedence produces: level 3 level 2 level 1 0 Goal Expr 1 Expr Expr + Term 2 Expr  Term 3 Term 4 Term Term * Factor 5 Term / Factor 6 Factor 7 Factor ( Expr ) 8 number 9 id The new grammar is larger (7 vs. 9) Takes more rewrimng to reach some of the terminal symbols Encodes expected precedence Produces same parse tree under letmost & rightmost derivamons Correctness trumps the speed of the parser Let s see how it parses x + 2 * y The classic expression grammar See also Figure 7.7 on p. 351 of EaC2e Both parentheses & precedence are beyond the power of an RE 8
9 DerivaMons and Precedence Rule Senten*al Form Goal 0 Expr 2 Expr Term 3 Term Term 6 Factor Term 9 <id,x> Term 4 <id,x> Term * Factor 6 <id,x> Factor * Factor 8 <id,x> <num,2> * Factor 9 <id,x> <num,2> * <id,y> The le9most deriva*on The classic expression grammar derives x ( 2 * y ) with the parse tree shown.. Both the letmost and rightmost derivamons give the same parse tree and value, because the grammar directly and explicitly encodes the desired precedence. E T F <id,x> G E T F <num,2> Parse tree for x 2 * y T * F <id,y> 9
10 DerivaMons and Precedence Rule Senten*al Form Goal 0 Expr 2 Expr Term 4 Expr Term * Factor 9 Expr Term * <id,y> 6 Expr Factor * <id,y> 8 Expr <num,2> * <id,y> 3 Term <num,2> * <id,y> 6 Factor <num,2> * <id,y> 9 <id,x> <num,2> * <id,y> The rightmost deriva*on The classic expression grammar derives x ( 2 * y ) with the parse tree shown.. Both the letmost and rightmost derivamons give the same parse tree and value, because the grammar directly and explicitly encodes the desired precedence. E T F <id,x> G E T F <num,2> Parse tree for x 2 * y T * F <id,y> 10
11 Parsing Techniques Topdown parsers (LL(1), recursive descent) Start at the root of the parse tree and grow toward leaves Pick a producmon & try to match the input Bad pick may need to backtrack Large class of grammars are backtrackfree E G E  T Bo[omup parsers (LR(1), operator precedence) Start at the leaves and grow toward root As input is consumed, encode possibilimes in an internal state Start in a state valid for legal first tokens We can make the process determinismc T T * F F F <id,y> <id,x> <num,2> Parse tree for x  2 * y COMP Boromup 412, Fall parsers 2017 can recognize a larger class of grammars than can topdown parsers. 11
12 TopDown Parsing We will examine two ways of implemen9ng topdown parsers Scanner <word, category> pairs Recursive Descent Parser IR RecursiveDescent Parser Highly efficient, highly flexible form of parser Typically implemented as a handcoded parser Set of mutuallyrecursive roumnes Works well for any backtrack free or predicmvely parsable grammar Easy to understand, easy to implement 12
13 TopDown Parsing We will examine two ways of implemen9ng topdown parsers Scanner <word, category> pairs Skeleton LL Parser Table IR Knowledge encoded in tables to drive skeleton specifica9ons (as a CFG) LL(1) Parser Generator Lab 2 Tabledriven LL(1) Parser LL(1) Parser Generator takes as input a CFG that is backtrack free Skeleton Parser interprets the table produced by the generator In Lab 2, you will implement an LL(1) table generator Your table generator will use a recursivedescent parser as its front end 13
14 Topdown Parsing The Algorithm A topdown parser starts with the root of the parse tree The root node is labeled with the goal symbol of the grammar Construct the root node of the parse tree Repeat unbl lower fringe of the parse tree matches the input string 1. At a node labeled with NT A, select a producbon with A on its LHS and, for each symbol on its RHS, construct the appropriate child 2. When a terminal symbol is added to the fringe and it doesn t match the fringe, backtrack 3. Find the next node to be expanded (label NT) The key is picking the right producmon in step 1 That choice should be guided by the input string 15
15 The Classic Expression Grammar Consider the Classic Expression Grammar 0 Goal Expr 1 Expr Expr + Term 2 Expr  Term 3 Term 4 Term Term * Factor 5 Term / Factor 6 Factor 7 Factor ( Expr ) 8 number 9 id And the input x 2 * y 16
16 Example Let s try to derive x 2 * y : Goal Rule Senten*al Form Input Goal x  2 * y Lower fringe of the parmally completed parse tree is the posibon in the input buffer Build a le9most derivabon, to work with a le\toright scanner. 17
17 Example Let s try to derive x 2 * y : Goal Rule Senten*al Form Input Goal x  2 * y Expr 0 Expr x  2 * y Expr + Term 1 Expr + Term x  2 * y 3 Term + Term x  2 * y Term 6 Factor + Term x  2 * y Fact. 9 <id,x> + Term x  2 * y <id,x> + Term x  2 * y <id,x> This worked well, except that doesn t match + The parser must backtrack to here is the posibon in the input buffer 18
18 Example Con9nuing with x 2 * y : Goal Rule Senten*al Form Input Goal x  2 * y 0 Expr x  2 * y Expr Expr Term 2 Expr Term x  2 * y 3 Term Term x  2 * y Term 6 Factor Term x  2 * y 9 <id,x>  Term x  2 * y <id,x> Term x  2 * y Fact. <id,x> <id,x> Term x  2 * y Now,  and  match Now we can expand Term to match 2 Now, we need to expand Term  the last NT on the fringe 19
19 Example Trying to match the 2 in x 2 * y : Rule Senten*al Form Where are we? 2 matches 2 Input <id,x>  Term x  2 * y 6 <id,x>  Factor x  2 * y 8 <id,x>  <num,2> x  2 * y <id,x>  <num,2> x  2 * y Expr Term Fact. <id,x> We have more input, but no NTs let to expand The expansion terminated too soon Need to backtrack Goal Expr Term Fact. <num,2> 20
20 Example Trying again with 2 in x 2 * y : Rule Senten*al Form Input <id,x>  Term x  2 * y Goal Expr 4 <id,x>  Term * Factor x  2 * y 6 <id,x>  Factor * Factor x  2 * y Expr Term 8 <id,x>  <num,2> * Factor x  2 * y Term Term * Fact. <id,x>  <num,2> * Factor x  2 * y <id,x>  <num,2> * Factor x  2 * y Fact. Fact. <id,y> 9 <id,x>  <num,2> * <id,y> x  2 * y <id,x> <num,2> <id,x>  <num,2> * <id,y> x  2 * y This The Mme, Point: we matched & consumed all the input For Success! efficiency, the parser must make the correct choice when it expands a NT. Wrong choices lead to wasted effort. 21
21 Another possible parse Other choices for expansion are possible Rule Senten*al Form Input Goal x  2 * y 0 Expr x  2 * y 1 Expr +Term x  2 * y 1 Expr + Term +Term x  2 * y 1 Expr + Term +Term + Term x  2 * y 1 and so on. x  2 * y Consumes no input! This expansion doesn t terminate Wrong choice of expansion leads to nonterminamon Nontermina*on is a bad property for a parser to have Parser must make the right choice 22
22 The Classic Expression Grammar 0 Goal Expr 1 Expr Expr + Term 2 Expr  Term 3 Term 4 Term Term * Factor 5 Term / Factor 6 Factor 7 Factor ( Expr ) 8 number 9 id Classic Expression Grammar The possibility of an infinite sequence of expansions in a parser is bad. disastrous The problem arises from le\ recursion in the grammar and a le\most derivamon 1 LHS symbol cannot appear at start of the RHS Cannot derive from it in mulbple steps, either Top down parsers build letmost derivamons, so grammars with let recursion are not suitable for topdown parsing 1 Similar problem arises with right recursion and a rightmost derivamon. 23
23 LeT Recursion Topdown parsers cannot handle lehrecursive grammars Formally, A grammar is leh recursive if A NT such that a derivamon A + Aα exists, for some string α (NT T ) + Our classic expression grammar is let recursive This can lead to nonterminamon in a topdown parser In a topdown parser, any recursion must be right recursion We would like to convert the let recursion to right recursion Nontermina*on is always a bad property in a compiler Fortunately, we can eliminate let recursion in an algorithmic way. COMP Right 412, recursion Fall 2017 is defined in a symmetric way. 24
24 EliminaMng LeT Recursion To remove leh recursion, we can transform the grammar Consider a grammar fragment of the form Fee Fee α β where neither α nor β start with Fee Language is β followed by 0 or more α s We can rewrite this fragment as Fee β Fie Fie α Fie ε where Fie is a new nonterminal The new grammar defines the same language as the old grammar, using only right recursion. New Idea: the ε producmon Added a reference to the empty string 25
25 EliminaMng LeT Recursion The expression grammar contains two cases of leh recursion Expr Expr + Term Term Term * Factor Expr  Term Term * Factor Term Factor Applying the transformamon yields Expr Term Expr Term Factor Term Expr + Term Expr Term * Factor Term  Term Expr ε / Factor Term ε These fragments use only right recursion 26
26 EliminaMng LeT Recursion Subs9tu9ng them back into the grammar yields 0 Goal Expr 1 Expr Term Expr 2 Expr + Term Expr 3  Term Expr 4 ε 5 Term Factor Term 6 Term * Factor Term 7 / Factor Term 8 ε 9 Factor ( Expr ) 10 number 11 id Rightrecursive expression grammar This grammar is correct, if somewhat counterintuimve. A topdown parser will terminate using it. A topdown parser may need to backtrack with it. It is let associamve, as was the original Why didn t we just rewrite it so Expr was at the right end of the RHS, rather than the let end? 27
27 EliminaMng LeT Recursion Subs9tu9ng them back into the grammar yields 0 Goal Expr 1 Expr Term Expr 2 Expr + Term Expr 3  Term Expr 4 ε 5 Term Factor Term 6 Term * Factor Term 7 / Factor Term 8 ε 9 Factor ( Expr ) 10 number 11 id Rightrecursive expression grammar This grammar is correct, if somewhat counterintuimve. NOTE: This technique eliminates direct let A topdown recursion parser when a will producmon s terminate RHS using begins it. with its own LHS. It A does topdown not address parser indirect may let need to recursion. backtrack We with will it. get there, in a couple of slides It is let associamve, as was the original Why didn t we just rewrite it so Expr was at the right end of the RHS, rather than the let end? 28
28 Associa9vity EliminaMng LeT Recursion No9ce that we do not use the naïve rightrecursive form Expr Term Expr Expr Term + Expr Expr + Term Expr  Term Expr ε Term  Expr Term Transformed grammar fragment Naïve rightrecursive form The naïve rightrecursive form generates a different associamvity (and parse tree) than did the original grammar. The transformed grammar fragment generates the same parse tree as the original grammar did. (See in EaC2e.) 29
29 Associa9vity EliminaMng LeT Recursion The naïve rightrecursive form changes the associa9vity Expr Term Expr Expr Term + Expr Expr + Term Expr  Term Expr ε Term  Expr Term Transformed grammar fragment Naïve rightrecursive form z w + + y x + w x y z ASTs for w + x + y + z 30
30 Parsing with the RR CEG 0 Goal Expr 1 Expr Term Expr 2 Expr + Term Expr 3  Term Expr 4 ε 5 Term Factor Term 6 Term * Factor Term 7 / Factor Term 8 ε 9 Factor ( Expr ) 10 number 11 id Right Recursive CEG Rule Senten*al Form x 2 * y, again Goal 0 Expr 1 Term Expr 5 Factor Term Expr 11 <id,x> Term Expr 8 <id,x> Expr 3 <id,x>  Term Expr 5 <id,x>  Factor Term Expr 10 <id,x>  <num,2> Term Expr 6 <id,x>  <num,2> * Factor Term Expr 11 <id,x>  <num,2> * <id,y> Term Expr 8 <id,x>  <num,2> * <id,y> Expr 4 <id,x>  <num,2> * <id,y> 31
31 Parsing with RR CEG Text of slide Rule Senten*al Form Goal Expr x 2 * y (again) Goal Term Expr 0 Expr 1 Term Expr minus Term Expr 5 Factor Term Expr 11 <id,x> Term Expr Factor Term ε 8 <id,x> Expr 3 <id,x>  Term Expr <num,2> 5 <id,x>  Factor Term Expr 10 <id,x>  <num,2> Term Expr Mmes Factor Term 6 <id,x>  <num,2> * Factor Term Expr 11 <id,x>  <num,2> * <id,y> Term Expr <id,y> ε 8 <id,x>  <num,2> * <id,y> Expr Factor Term 4 <id,x>  <num,2> * <id,y> <id,x> ε 32
Parsing 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 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 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 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 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 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 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 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 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 (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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationBuilding a Parser Part III
COMP 506 Rice University Spring 2018 Building a Parser Part III With Practical Application To Lab One source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda
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 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 informationEDA180: Compiler Construc6on Context free grammars. Görel Hedin Revised:
EDA180: Compiler Construc6on Context free grammars Görel Hedin Revised: 201301 28 Compiler phases and program representa6ons source code Lexical analysis (scanning) Intermediate code genera6on tokens
More informationDefining syntax using CFGs
Defining syntax using CFGs Roadmap Last 8me Defined contextfree grammar This 8me CFGs for syntax design Language membership List grammars Resolving ambiguity CFG Review G = (N,Σ,P,S) means derives derives
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 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 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 informationDerivations vs Parses. Example. Parse Tree. Ambiguity. Different Parse Trees. Context Free Grammars 9/18/2012
Derivations vs Parses Grammar is used to derive string or construct parser Context ree Grammars A derivation is a sequence of applications of rules Starting from the start symbol S......... (sentence)
More informationSyntax Analysis Check syntax and construct abstract syntax tree
Syntax Analysis Check syntax and construct abstract syntax tree if == = ; b 0 a b Error reporting and recovery Model using context free grammars Recognize using Push down automata/table Driven Parsers
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 informationCSE P 501 Compilers. Parsing & ContextFree Grammars Hal Perkins Spring UW CSE P 501 Spring 2018 C1
CSE P 501 Compilers Parsing & ContextFree Grammars Hal Perkins Spring 2018 UW CSE P 501 Spring 2018 C1 Administrivia Project partner signup: please find a partner and fill out the signup form by noon
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 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 informationCSE P 501 Compilers. Parsing & ContextFree Grammars Hal Perkins Winter UW CSE P 501 Winter 2016 C1
CSE P 501 Compilers Parsing & ContextFree Grammars Hal Perkins Winter 2016 UW CSE P 501 Winter 2016 C1 Administrivia Project partner signup: please find a partner and fill out the signup form by noon
More informationCSE 3302 Programming Languages Lecture 2: Syntax
CSE 3302 Programming Languages Lecture 2: Syntax (based on slides by Chengkai Li) Leonidas Fegaras University of Texas at Arlington CSE 3302 L2 Spring 2011 1 How do we define a PL? Specifying a PL: Syntax:
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 informationGenerating Code for Assignment Statements back to work. Comp 412 COMP 412 FALL Chapters 4, 6 & 7 in EaC2e. source code. IR IR target.
COMP 412 FALL 2017 Generating Code for Assignment Statements back to work Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights
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 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 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 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 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 informationFormal Languages and Compilers Lecture V: Parse Trees and Ambiguous Gr
Formal Languages and Compilers Lecture V: Parse Trees and Ambiguous Grammars Free University of BozenBolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/
More informationSyntax. In Text: Chapter 3
Syntax In Text: Chapter 3 1 Outline Syntax: Recognizer vs. generator BNF EBNF Chapter 3: Syntax and Semantics 2 Basic Definitions Syntax the form or structure of the expressions, statements, and program
More informationFront End. Hwansoo Han
Front nd Hwansoo Han Traditional Twopass Compiler Source code Front nd IR Back nd Machine code rrors High level functions Recognize legal program, generate correct code (OS & linker can accept) Manage
More informationComputing Inside The Parser SyntaxDirected Translation, II. Comp 412 COMP 412 FALL Chapter 4 in EaC2e. source code. IR IR target.
COMP 412 FALL 20167 Computing Inside The Parser SyntaxDirected Translation, II Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2017, Keith D. Cooper & Linda Torczon, all
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 informationLexical Analysis, V Implemen'ng Scanners. Comp 412 COMP 412 FALL Sec0on 2.5 in EaC2e. target code. source code Front End OpMmizer Back End
COMP 412 FALL 2017 Lexical Analysis, V Implemen'ng Scanners Comp 412 source code IR Front End OpMmizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights reserved. Students
More informationCSE P 501 Compilers. Parsing & ContextFree Grammars Hal Perkins Winter /15/ Hal Perkins & UW CSE C1
CSE P 501 Compilers Parsing & ContextFree Grammars Hal Perkins Winter 2008 1/15/2008 200208 Hal Perkins & UW CSE C1 Agenda for Today Parsing overview Context free grammars Ambiguous grammars Reading:
More informationLexical Analysis  An Introduction. Lecture 4 Spring 2005 Department of Computer Science University of Alabama Joel Jones
Lexical Analysis  An Introduction Lecture 4 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved.
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 informationCMSC 330: Organization of Programming Languages. Architecture of Compilers, Interpreters
: Organization of Programming Languages Context Free Grammars 1 Architecture of Compilers, Interpreters Source Scanner Parser Static Analyzer Intermediate Representation Front End Back End Compiler / Interpreter
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 informationContextFree Grammars
ContextFree Grammars Lecture 7 http://webwitch.dreamhost.com/grammar.girl/ Outline Scanner vs. parser Why regular expressions are not enough Grammars (contextfree grammars) grammar rules derivations
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 informationChapter 4. Lexical and Syntax Analysis. Topics. Compilation. Language Implementation. Issues in Lexical and Syntax Analysis.
Topics Chapter 4 Lexical and Syntax Analysis Introduction Lexical Analysis Syntax Analysis Recursive Descent Parsing BottomUp parsing 2 Language Implementation Compilation There are three possible approaches
More informationCS 406/534 Compiler Construction Parsing Part II LL(1) and LR(1) Parsing
CS 406/534 Compiler Construction Parsing Part II LL(1) and LR(1) Parsing Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof.
More informationHomework & Announcements
Homework & nnouncements New schedule on line. Reading: Chapter 18 Homework: Exercises at end Due: 11/1 Copyright c 2002 2017 UMaine School of Computing and Information S 1 / 25 COS 140: Foundations 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 informationAdministrativia. PA2 assigned today. WA1 assigned today. Building a Parser II. CS164 3:305:00 TT 10 Evans. First midterm. Grammars.
Administrativia Building a Parser II CS164 3:305:00 TT 10 Evans PA2 assigned today due in 12 days WA1 assigned today due in a week it s a practice for the exam First midterm Oct 5 will contain some projectinspired
More informationThe ILOC Virtual Machine (Lab 1 Background Material) Comp 412
COMP 12 FALL 20 The ILOC Virtual Machine (Lab 1 Background Material) Comp 12 source code IR Front End OpMmizer Back End IR target code Copyright 20, Keith D. Cooper & Linda Torczon, all rights reserved.
More informationCompilers Course Lecture 4: Context Free Grammars
Compilers Course Lecture 4: Context Free Grammars Example: attempt to define simple arithmetic expressions using named regular expressions: num = [09]+ sum = expr "+" expr expr = "(" sum ")" num Appears
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 informationPrinciples of Programming Languages COMP251: Syntax and Grammars
Principles of Programming Languages COMP251: Syntax and Grammars Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2006
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 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 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 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 informationMore on Syntax. Agenda for the Day. Administrative Stuff. More on Syntax InClass Exercise Using parse trees
More on Syntax Judy Stafford Comp 80 Meeting February, 00 Agenda for the Day Administrative Stuff Moodle Classlist at without waiting list More on Syntax InClass Exercise Using parse trees Last time Syntax
More informationCompiler Design Concepts. Syntax Analysis
Compiler Design Concepts Syntax Analysis Introduction First task is to break up the text into meaningful words called tokens. newval=oldval+12 id = id + num Token Stream Lexical Analysis Source Code (High
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 informationIntermediate Representations
Most of the material in this lecture comes from Chapter 5 of EaC2 Intermediate Representations Note by Baris Aktemur: Our slides are adapted from Cooper and Torczon s slides that they prepared for COMP
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 informationSyntax Analysis. Prof. James L. Frankel Harvard University. Version of 6:43 PM 6Feb2018 Copyright 2018, 2015 James L. Frankel. All rights reserved.
Syntax Analysis Prof. James L. Frankel Harvard University Version of 6:43 PM 6Feb2018 Copyright 2018, 2015 James L. Frankel. All rights reserved. ContextFree Grammar (CFG) terminals nonterminals start
More informationLexical Analysis. Introduction
Lexical Analysis Introduction Copyright 2015, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University of Southern California have explicit permission to make copies
More informationMIT Specifying Languages with Regular Expressions and ContextFree Grammars
MIT 6.035 Specifying Languages with Regular essions and ContextFree Grammars Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Language Definition Problem How to precisely
More informationBuilding a Parser II. CS164 3:305:00 TT 10 Evans. Prof. Bodik CS 164 Lecture 6 1
Building a Parser II CS164 3:305:00 TT 10 Evans 1 Grammars Programming language constructs have recursive structure. which is why our handwritten parser had this structure, too An expression is either:
More informationIntermediate Representations
COMP 506 Rice University Spring 2018 Intermediate Representations source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students
More informationThe Parsing Problem (cont d) RecursiveDescent Parsing. RecursiveDescent Parsing (cont d) ICOM 4036 Programming Languages. The Complexity of Parsing
ICOM 4036 Programming Languages Lexical and Syntax Analysis Lexical Analysis The Parsing Problem RecursiveDescent Parsing BottomUp Parsing This lecture covers review questions 1427 This lecture covers
More informationCS 406/534 Compiler Construction Putting It All Together
CS 406/534 Compiler Construction Putting It All Together 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
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 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 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 informationComputing Inside The Parser SyntaxDirected Translation, II. Comp 412
COMP 412 FALL 2018 Computing Inside The Parser SyntaxDirected Translation, II Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights
More informationCMPS Programming Languages. Dr. Chengwei Lei CEECS California State University, Bakersfield
CMPS 3500 Programming Languages Dr. Chengwei Lei CEECS California State University, Bakersfield Chapter 3 Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing
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 informationCompilers  Chapter 2: An introduction to syntax analysis (and a complete toy compiler)
Compilers  Chapter 2: An introduction to syntax analysis (and a complete toy compiler) Lecturers: Paul Kelly (phjk@doc.ic.ac.uk) Office: room 304, William Penney Building Naranker Dulay (nd@doc.ic.ac.uk)
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 informationIntroduction to Parsing. Lecture 5
Introduction to Parsing Lecture 5 1 Outline Regular languages revisited Parser overview Contextfree grammars (CFG s) Derivations Ambiguity 2 Languages and Automata Formal languages are very important
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 informationIntroduction to Parsing. Lecture 5
Introduction to Parsing Lecture 5 1 Outline Regular languages revisited Parser overview Contextfree grammars (CFG s) Derivations Ambiguity 2 Languages and Automata Formal languages are very important
More informationCMSC 330: Organization of Programming Languages. Context Free Grammars
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 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 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 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 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 information