COMP 181. Prelude. Next step. Parsing. Study of parsing. Specifying syntax with a grammar

Size: px
Start display at page:

Download "COMP 181. Prelude. Next step. Parsing. Study of parsing. Specifying syntax with a grammar"

Transcription

1 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 In an acidic environment, binds to sweet receptors in taste buds Sour becomes sweet Lemons and limes, Tabasco sauce, stinky cheese, dark beer Flavor tripping lasts about an hour Tufts University Computer Science Next step Parsing text chars Lexical analyzer tokens Parser IR text chars Lexical analyzer tokens Parser IR Errors Errors Parsing: Organize tokens into sentences Do tokens conform to language syntax? Good news: token types are just numbers Bad news: language syntax is fundamentally more complex than lexical specification Good news: we can still do it in linear time in most cases Parser Reads tokens from the scanner Checks organization of tokens against a grammar Constructs a derivation Derivation drives construction of IR Tufts University Computer Science Tufts University Computer Science Study of parsing Discovering the derivation of a sentence Diagramming a sentence in grade school Formalization: Mathematical model of syntax a grammar G Algorithm for testing membership in L(G) Roadmap: Contextfree grammars Topdown parsers Ad hoc, often handcoded, recursive decent parsers Bottomup parsers Automatically generated LR parsers Tufts University Computer Science Specifying syntax with a grammar Can we use regular essions? For the most part, no Limitations of regular essions Need something more powerful Still want formal specification (for automation) Contextfree grammar Set of rules for generating sentences Expressed in BackusNaur Form (BNF) Tufts University Computer Science

2 Contextfree grammar Example: Formally: contextfree grammar is G = (s, N, T, P) T : set of inals (provided by scanner) N : set of noninals (represent structure) sheepnoise sheepnoise baa baa Alternative (shorthand) s N : start or goal symbol P : N (N T)* : set of production rules produces or generates Language L(G) Language L(G) L(G) is all sentences generated from start symbol Generating sentences Use productions as rewrite rules Start with goal (or start) symbol a noninal Choose a noninal and expand it to the righthand side of one of its productions Only inal symbols left sentence in L(G) Inediate results known as sentential forms Tufts University Computer Science Tufts University Computer Science Expressions Language of essions Numbers and identifiers Allow different binary operators Arbitrary nesting of essions op number op + * / Tufts University Computer Science Language of essions What s in this language? op number op + * / We can build the string x * y This string is in the language op <id,x> op <id,x> <id,x> op <id,x> <num,> op <id,x> <num,> * <id,x> <num,> * <id,y> Tufts University Computer Science 0 Derivations Using grammars A sequence of rewrites is called a derivation Discovering a derivation for a string is parsing Different derivations are possible At each step we can choose any noninal Rightmost derivation: always choose right NT Leftmost derivation: always choose left NT (Other random derivations not of interest) Left vs right derivations Two derivations of x * y op <id, x> op <id,x> <id,x> op <id,x> <num,> op <id,x> <num,> * <id,x> <num,> * <id,y> op op <id,y> * <id,y> op * <id,y> op <num,> * <id,y> <num,> * <id,y> <id,x> <num,> * <id,y> Leftmost derivation Rightmost derivation Tufts University Computer Science Tufts University Computer Science

3 Derivations and parse trees Two different derivations Both are correct Do we care which one we use? Represent derivation as a parse tree Leaves are inal symbols Inner nodes are noninals To depict production α β γ δ show nodes β,γ,δ as children of α Tree is used to build internal representation Example (I) Rightmost derivation op op <id,y> * <id,y> op * <id,y> op <num,> * <id,y> <num,> * <id,y> <id,x> <num,> * <id,y> Concrete syntax tree Shows all details of syntactic structure What s the problem with this tree? Parse tree op op * y x Tufts University Computer Science Tufts University Computer Science Abstract syntax tree Parse tree contains extra junk Eliminate inediate nodes Move operators up to parent nodes Result: abstract syntax tree op op * y x Tufts University Computer Science x Problem: Evaluates as (x ) * y * y Example (II) Leftmost derivation op <id, x> op <id,x> <id,x> op <id,x> <num,> op <id,x> <num,> * <id,x> <num,> * <id,y> op x Parse tree Solution: evaluates as x ( * y) op * y Tufts University Computer Science Derivations Derivations and semantics x * y Leftmost derivation * y x Rightmost derivation Problem: Two different valid derivations One captures meaning we want (What specifically are we trying to capture here?) Key idea: shape of tree implies its meaning Can we ess precedence in grammar? Notice: operations deeper in tree evaluated first Solution: add an inediate production New production isolates different levels of precedence Force higher precedence deeper in the grammar Tufts University Computer Science Tufts University Computer Science

4 Adding precedence Two levels: Level : lower precedence higher in the tree Level : higher precedence deeper in the tree Observations: Larger: requires more rewriting to reach inals But, produces same parse tree under both left and right derivations Tufts University Computer Science + * or / or or or number Expression example Rightmost derivation * or * <id,y> or * <id,y> <num,> * <id,y> <num,> * <id,y> or <num,> * <id,y> <id,x> <num,> * <id,y> Parse tree Now right derivation yields x ( * y) Tufts University Computer Science 0 x op op * y With precedence In class questions What if I want (x)*y? op * Some common patterns op * y * x y x Tufts University Computer Science Tufts University Computer Science Another issue Original ession grammar: op number op + * / Our favorite string: x * y Tufts University Computer Science Another issue op op op <id, x> op op <id,x> op <id,x> <num,> op <id,x> <num,> * <id,x> <num,> * <id,y> Multiple leftmost derivations Such a grammar is called ambiguous Is this a problem? Very hard to automate parsing Tufts University Computer Science 0 op <id, x> op <id,x> <id,x> op <id,x> <num,> op <id,x> <num,> * <id,x> <num,> * <id,y>

5 Ambiguous grammars A grammar is ambiguous iff: There are multiple leftmost or multiple rightmost derivations for a single sentential form Note: leftmost and rightmost derivations may differ, even in an unambiguous grammar Intuitively: We can choose different noninals to expand But each noninal should lead to a unique set of inal symbols What s a classic example? Ifthenelse ambiguity Ifthenelse Grammar: Problem: nested ifthenelse statements stmt if then stmt if then stmt else stmt other statements Each one may or may not have else How to match each else with if Tufts University Computer Science Tufts University Computer Science Ifthenelse ambiguity with two derivations: if then if then stmt else stmt if prod. prod. then else if stmt prod. then prod. stmt if then if then stmt else stmt Removing ambiguity Restrict the grammar Choose a rule: else matches innermost if Codify with new productions stmt if then stmt if then withelse else stmt other statements withelse if then withelse else withelse other statements Intuition: when we have an else, all preceding nested conditions must have an else Tufts University Computer Science Tufts University Computer Science Ambiguity Ambiguity can take different forms Grammatical ambiguity (ifthenelse problem) Contextual ambiguity In C: x * y; could follow typedef int x; In Fortran: x = f(y); f could be function or array Cannot be solved directly in grammar Issues of type (later in course) Deeper question: How much can the parser do? Parsing What is parsing? Discovering the derivation of a string If one exists Harder than generating strings Not surprisingly Two major approaches Topdown parsing Bottomup parsing Don t work on all contextfree grammars Properties of grammar deine parseability Our goal: make parsing efficient We may be able to transform a grammar Tufts University Computer Science Tufts University Computer Science

6 Two approaches Topdown parsers LL(), recursive descent Start at the root of the parse tree and grow toward leaves Pick a production and try to match the input What happens if the parser chooses the wrong one? Bottomup parsers LR(), operator precedence Start at the leaves and grow toward root Issue: might have multiple possible ways to do this Key idea: encode possible parse trees in an internal state (similar to our NFA DFA conversion) Bottomup parsers handle a large class of grammars Grammars and parsers LL() parsers Lefttoright input Leftmost derivation symbol of lookahead LR() parsers Lefttoright input Rightmost derivation symbol of lookahead Also: LL(k), LR(k), SLR, LALR, Grammars that they can handle are called LL() grammars Grammars that they can handle are called LR() grammars Tufts University Computer Science Tufts University Computer Science Topdown parsing Start with the root of the parse tree Root of the tree: node labeled with the start symbol Algorithm: Repeat until the fringe of the parse tree matches input string At a node A, select one of A s productions Add a child node for each symbol on rhs Find the next node to be expanded (a noninal) Done when: Leaves of parse tree match input string (success) Example Expression grammar Input string + * or / or or or number x * y (with precedence) Tufts University Computer Science Tufts University Computer Science 0 Example Current position in the input stream Backtracking Input string x * y + x * y + x * y or + x * y <id> + x * y <id,x> + x * y + Input string x * y + x * y + x * y or + x * y <id> + x * y? <id,x> + x * y Undo all these productions Problem: Can t match next inal We guessed wrong at step What should we do now? x If we can t match next inal: Rollback productions Choose a different production for Continue Tufts University Computer Science Tufts University Computer Science

7 Retrying Successful parse Input string x * y x * y x * y or x * y <id> x * y <id,x> x * y <id,x> or x * y <id,x> <num> x * y Problem: More input to read Another cause of backtracking x Input string x * y x * y x * y or x * y <id> x * y <id,x> x * y <id,x> * x * y <id,x> * x * y <id,x> <num> * x * y <id,x> <num,> * x * y <id,x> <num,> * <id> x * y x * y Tufts University Computer Science Tufts University Computer Science Other possible parses Problem: ination Input string x * y x * y x * y x * y x * y Wrong choice leads to infinite expansion (More importantly: without consuming any input!) May not be as obvious as this Our grammar is left recursive Left recursion Formally, A grammar is left recursive if a noninal A such that A * A α (for some set of symbols α) What does * mean? A B x B A y Bad news: Topdown parsers cannot handle left recursion Good news: We can systematically eliminate left recursion Tufts University Computer Science Tufts University Computer Science Notation Eliminating left recursion Noninals Capital letter: A, B, C Terminals Lowercase, underline: x, y, z Fix this grammar: foo foo α β Language is β followed by zero or more α Some mix of inals and noninals Greek letters: α, β, γ Example: A B + x A B α α = + x Rewrite as foo β bar bar α bar New noninal This production gives you one β These two productions give you zero or more α Tufts University Computer Science Tufts University Computer Science

8 Back to essions Eliminating left recursion Two cases of left recursion: + How do we fix these? + * or / or or or * or / or Resulting grammar All right recursive Retain original language and associativity Not as intuitive to read Topdown parser Will always inate May still backtrack There s a lovely algorithm to do this automatically, which we will skip 0 + or * or / or or number Tufts University Computer Science Tufts University Computer Science 0 Topdown parsers Rightrecursive grammar Problem: Leftrecursion Solution: Technique to remove it What about backtracking? Current algorithm is brute force Problem: how to choose the right production? Idea: use the next input token (duh) How? Look at our rightrecursive grammar 0 + or * or / or or number Two productions with no choice at all All other productions are uniquely identified by a inal symbol at the start of RHS We can choose the right production by looking at the next input symbol This is called lookahead BUT, this can be tricky Tufts University Computer Science Tufts University Computer Science Lookahead Goal: avoid backtracking Look at future input symbols Use extra context to make right choice How much lookahead is needed? In general, an arbitrary amount is needed for the full class of contextfree grammars Use fancydancy algorithm CYK algorithm, O(n ) Fortunately, Many CFGs can be parsed with limited lookahead Covers most programming languages not C++ or Perl Topdown parsing Goal: Given productions A α β, the parser should be able to choose between α and β Trying to match A How can the next input token help us decide? Solution: FIRST sets (almost a solution) Informally: FIRST(α) is the set of tokens that could appear as the first symbol in a string derived from α Def: x in FIRST(α) iff α * x γ Tufts University Computer Science Tufts University Computer Science

9 Topdown parsing Building FIRST sets We ll look at this algorithm later The LL() property Given A α and A β, we would like: FIRST(A α) FIRST(A β) = Parser can make right choice by with one lookahead token..almost.. What are we not handling? Topdown parsing What about ε productions? Complicates the definition of LL() Consider A α and A β and α may be empty In this case there is no symbol to identify α Example: What is FIRST(#)? = { ε } What would tells us we are matching production? S A z A x B y C Tufts University Computer Science Tufts University Computer Science Topdown parsing If A was empty S A z A x B y C What will the next symbol be? Must be one of the symbols that immediately follows an A Solution Build a FOLLOW set for each symbol that could produce ε Extra condition for LL: FIRST(A β) must be disjoint from FIRST(A α) and FOLLOW(Α) FOLLOW sets Example: FIRST(#) = { x } FIRST(#) = { y } FIRST(#) = { ε } S A z A x B y C What can follow A? Look at the context of all uses of A FOLLOW(A) = { z } Now we can uniquely identify each production: If we are trying to match an A and the next token is z, then we matched production Tufts University Computer Science Tufts University Computer Science More on FIRST and FOLLOW Notice: FIRST and FOLLOW are sets FIRST may contain ε in addition to other symbols Question: What is FIRST(#)? = FIRST(B) = { x, y, ε }? and FIRST(C) Question: When would we care about FOLLOW(A)? Answer: if FIRST(C) contains ε Tufts University Computer Science S A z A B C D B x y C... LL() property Key idea: Build parse tree topdown Use lookahead token to pick next production Each production must be uniquely identified by the inal symbols that may appear at the start of strings derived from it. Def: FIRST+(A α) as FIRST(α) U FOLLOW(A), if ε FIRST(α) FIRST(α), otherwise Def: a grammar is LL() iff A α and A β and FIRST+(A α) FIRST+(A β) = Tufts University Computer Science 0

10 Parsing LL() grammar Given an LL() grammar Code: simple, fast routine to recognize each production Given A β β β, with FIRST + (β i ) FIRST + (β j ) = for all i!= j /* find rule for A */ if (current token FIRST+(β )) select A β else if (current token FIRST+(β )) select A β else if (current token FIRST+(β )) select A β else report an error and return false Topdown parsing Build parse tree top down A β γ δ G A α B ζ B ε C? D t t t t t t t t t token stream Is CD? Consider all possible strings derivable from CD What is the set of tokens that can appear at start? G A α B ζ A β γ δ B C D F t FIRST(C D) t FIRST(F) t FOLLOW(B) disjoint? Tufts University Computer Science Tufts University Computer Science FIRST and FOLLOW sets FIRST(α) The righthand side of a production For some α (T NT)*, define FIRST(α) as the set of tokens that appear as the first symbol in some string that derives from α That is, x FIRST(α) iff α * x γ, for some γ Note: may include ε FOLLOW(A) For some A NT, define FOLLOW(A) as the set of symbols that can occur immediately after A in a valid sentence. FOLLOW(G) = {EOF}, where G is the start symbol Computing FIRST sets Idea: Use FIRST sets of the right side of production Cases: A B B B FIRST(A B) = FIRST(B ) What does FIRST(B ) mean? Union of FIRST(B γ) for all γ What if ε in FIRST(B )? FIRST(A B) = FIRST(B ) What if ε in FIRST(B i ) for all i? FIRST(A B) = {ε} Why =? repeat as needed leave {ε} for later Tufts University Computer Science Tufts University Computer Science Algorithm Algorithm For one production: p = A β if (β is a inal t) FIRST(p) = {t} else if (β == ε) FIRST(p) = {ε} else Given β = B B B B k i = 0 do { i = i + ; FIRST(p) += FIRST(B i ) {ε} } while ( ε in FIRST(B i ) && i < k) Why do we need to remove ε from FIRST(B i )? if (ε in FIRST(B i ) && i == k) FIRST(p) += {ε} Tufts University Computer Science For one production: Given A B B B B B Compute FIRST(A B) using FIRST(B) How do we get FIRST(B)? What kind of algorithm does this suggest? Recursive? Like a depthfirst search of the productions Problem: What about recursion in the grammar? A x B y and B z A w Tufts University Computer Science 0

11 Algorithm Algorithm Solution Start with FIRST(B) empty Compute FIRST(A) using empty FIRST(B) Now go back and compute FIRST(B) What if it s no longer empty? Then we recompute FIRST(A) What if new FIRST(A) is different from old FIRST(A)? Then we recompute FIRST(B) again When do we stop? When no more changes occur we reach convergence FIRST(A) and FIRST(B) both satisfy equations This is another fixpoint algorithm Using fixpoints: forall p FIRST(p) = {} while (FIRST sets are changing) pick a random p compute FIRST(p) Can we be smarter? Yes, visit in special order Reverse postorder depth first search Visit all children (all righthand sides) before visiting the lefthand side, whenever possible Tufts University Computer Science Tufts University Computer Science Example 0 goal + or * or / or or number FIRST() = { + } FIRST() = { } FIRST() = { ε } FIRST() = { * } FIRST() = { / } FIRST() = { ε } FIRST() =? FIRST() = FIRST() = FIRST() = FIRST(0) FIRST() = { number, identifier } Computing FOLLOW sets Idea: Push FOLLOW sets down, use FIRST where needed Cases: A B B B B B k What is FOLLOW(B )? FOLLOW(B ) = FIRST(B ) In general: FOLLOW(B i ) = FIRST(B i+ ) What about FOLLOW(B k )? FOLLOW(B k ) = FOLLOW(A) What if ε FIRST(B k )? FOLLOW(B k ) = FOLLOW(A) extends to k, etc. Tufts University Computer Science Tufts University Computer Science 0 Example Example 0 goal + or * or / or or number FOLLOW(goal) = { EOF } FOLLOW() = FOLLOW(goal) = { EOF } FOLLOW() = FOLLOW() = { EOF } FOLLOW() =? FOLLOW() += FIRST() += { +,, ε } += { +,, FOLLOW()} += { +,, EOF } 0 goal + or * or / or or number FOLLOW() += FOLLOW() FOLLOW(or) =? FOLLOW(or) += FIRST() += { *, /, ε } += { *, /, FOLLOW()} += { *, /, +,, EOF } Tufts University Computer Science Tufts University Computer Science

12 Computing FOLLOW Sets LL() property FOLLOW(G) {EOF } for each A NT, FOLLOW(A) Ø while (FOLLOW sets are still changing) for each p P, of the form A β β β k FOLLOW(β k ) FOLLOW(β k ) FOLLOW(A) TRAILER FOLLOW(A) for i k down to if ε FIRST(β i ) then FOLLOW(β i ) FOLLOW(β i ) { FIRST(β i ) { ε } } TRAILER else FOLLOW(β i ) FOLLOW(β i ) FIRST(β i ) TRAILER Ø Def: a grammar is LL() iff A α and A β and FIRST+(A α) FIRST+(A β) = Problem What if my grammar is not LL()? May be able to fix it, with transformations Example: A α β α β α β A α Z Z β β β Tufts University Computer Science Tufts University Computer Science Left oring Expression example Graphically A α β α β α β A αβ αβ αβ After left oring: or identifier [ ] ( ) First+() = {identifier} First+() = {identifier} First+() = {identifier} A α Z Z β β β A αz β β β or identifier post post [ ] ( ) In this form, it has LL() property First+() = {identifier} First+() = { [ } First+() = { ( } First+() =? = Follow(post) = {operators} Tufts University Computer Science Tufts University Computer Science Left oring Left oring Graphically or identifier identifier [ ] Question Using left oring and left recursion elimination, can we turn an arbitrary CFG to a form where it meets the LL() condition? Answer No basis for choice identifier ( ) Given a CFG that does not meet LL() condition, it is undecidable whether or not an LL() grammar exists ε Example or identifier [ ] {a n 0 b n n } {a n b n n } has no LL() grammar Next word deines choice ( ) aaa0bbb aaabbbbbb Tufts University Computer Science Tufts University Computer Science

13 Limits of LL() No LL() grammar for this language: {a n 0 b n n } {a n b n n } has no LL() grammar Predictive parsing Predictive parsing The parser can predict the correct expansion Using lookahead and FIRST and FOLLOW sets G a A b a B bb A a A b 0 B a B bb Problem: need an unbounded number of a characters before you can deine whether you are in the A group or the B group Two kinds of predictive parsers Recursive descent Often handwritten Tabledriven Generate tables from First and Follow sets Tufts University Computer Science Tufts University Computer Science 0 Recursive descent Example code 0 goal + or * or / or or number ( ) This produces a parser with six mutually recursive routines: Goal Expr Expr Term Term Factor Each recognizes one NT or T The descent refers to the direction in which the parse tree is built. Goal symbol: main() /* Match goal > */ tok = nexttoken(); if (() && tok == EOF) then proceed to next step; else return false; Toplevel ession () /* Match > */ if (() && ()); return true; else return false; Tufts University Computer Science Tufts University Computer Science Example code Match () /* Match > + */ /* Match > */ if (tok == + or tok == ) tok = nexttoken(); if (()) then if (()) return true; else return false; /* Match > empty */ return true; Check FIRST and FOLLOW sets to distinguish Example code or() /* Match or > ( ) */ if (tok == ( ) tok = nexttoken(); if (() && tok == ) ) return true; else syntax error: expecting ) return false /* Match or > num */ if (tok is a num) return true /* Match or > id */ if (tok is an id) return true; Tufts University Computer Science Tufts University Computer Science

14 Topdown parsing So far: Gives us a yes or no answer Is that all we want? We want to build the parse tree How? Add actions to matching routines Create a node for each production How do we assemble the tree? Building a parse tree Notice: Recursive calls match the shape of the tree main or Idea: use a stack Each routine: Pops off the children it needs Creates its own node Pushes that node back on the stack Tufts University Computer Science Tufts University Computer Science Building a parse tree Generating a topdown parser With stack operations () /* Match > */ if (() && ()) _node = pop(); _node = pop(); _node = new Node(_node, _node) push(_node); return true; else return false; 0 goal + or * or / or or number Two pieces: Select the right RHS Satisfy each part First piece: FIRST+() for each rule Mapping: NT Σ rule# Look familiar? Tufts University Computer Science Tufts University Computer Science Generating a topdown parser Tabledriven approach 0 goal + or * or / or or number Second piece Keep track of progress Like a depthfirst search Use a stack Idea: Push Goal on stack Pop stack: Match inal symbol, or Apply NT mapping, push RHS on stack Encode mapping in a table Row for each noninal Column for each inal symbol Table[NT, symbol] = rule# if symbol FIRST+(NT > rhs(#)) +, *, / id, num error error error or error or error error (do nothing) Tufts University Computer Science Tufts University Computer Science 0

15 Code push the start symbol, G, onto Stack top top of Stack loop forever if top = EOF and token = EOF then break & report success if top is a inal then if top matches token then pop Stack // recognized top token next_token() else // top is a noninal if TABLE[top,token] is A B B B k then pop Stack // get rid of A push Bk, Bk,, B // in that order top top of Stack Missing else s for error conditions Next time Bottomup parsers Why? More powerful But, more complex algorithm (cannot write by hand) Widely used yacc, bison, JavaCUP Tufts University Computer Science Tufts University Computer Science Left oring Algorithm: A NT, find the longest prefix α that occurs in two or more righthand sides of A if α ε then replace all of the A productions, A αβ αβ αβ n γ, with A α Z γ Z β β β n where Z is a new element of NT Repeat until no common prefixes remain Tufts University Computer Science

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

Compilers. 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 information

Prelude COMP 181 Tufts University Computer Science Last time Grammar issues Key structure meaning Tufts University Computer Science

Prelude 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 information

Syntactic Analysis. Top-Down Parsing

Syntactic Analysis. Top-Down Parsing Syntactic Analysis Top-Down 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 information

CS 406/534 Compiler Construction Parsing Part I

CS 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 information

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

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing Roadmap > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing The role of the parser > performs context-free syntax analysis > guides

More information

CSCI312 Principles of Programming Languages

CSCI312 Principles of Programming Languages Copyright 2006 The McGraw-Hill 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 McGraw-Hill

More information

Parsing. 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. 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 information

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

Parsing Part II (Top-down parsing, left-recursion removal) Parsing Part II (Top-down parsing, left-recursion removal) Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Students enrolled in Comp 412 at Rice University have explicit

More information

CS415 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 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 information

3. Parsing. Oscar Nierstrasz

3. 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 information

Introduction to Parsing. Comp 412

Introduction 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 information

Types of parsing. CMSC 430 Lecture 4, Page 1

Types of parsing. CMSC 430 Lecture 4, Page 1 Types of parsing Top-down parsers start at the root of derivation tree and fill in picks a production and tries to match the input may require backtracking some grammars are backtrack-free (predictive)

More information

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

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Parsing III (Top-down parsing: recursive descent & LL(1) ) (Bottom-up parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,

More information

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

Parsing III. (Top-down parsing: recursive descent & LL(1) ) Parsing III (Top-down parsing: recursive descent & LL(1) ) Roadmap (Where are we?) Previously We set out to study parsing Specifying syntax Context-free grammars Ambiguity Top-down parsers Algorithm &

More information

Introduction to Parsing

Introduction 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 information

More on Syntax. Agenda for the Day. Administrative Stuff. More on Syntax In-Class Exercise Using parse trees

More on Syntax. Agenda for the Day. Administrative Stuff. More on Syntax In-Class 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 information

Top down vs. bottom up parsing

Top 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 information

Syntax Analysis, III Comp 412

Syntax 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 information

Parsing II Top-down parsing. Comp 412

Parsing II Top-down parsing. Comp 412 COMP 412 FALL 2018 Parsing II Top-down 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 information

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

Syntax 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 information

CS1622. Today. A Recursive Descent Parser. Preliminaries. Lecture 9 Parsing (4)

CS1622. 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 information

Wednesday, September 9, 15. Parsers

Wednesday, 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 information

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

Parsers. 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 information

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

Parsers. 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 information

CS 314 Principles of Programming Languages

CS 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 information

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

Top-Down Parsing and Intro to Bottom-Up Parsing. Lecture 7 Top-Down Parsing and Intro to Bottom-Up Parsing Lecture 7 1 Predictive Parsers Like recursive-descent but parser can predict which production to use Predictive parsers are never wrong Always able to guess

More information

Syntax Analysis, III Comp 412

Syntax 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 information

Monday, September 13, Parsers

Monday, 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 non-terminals S is the start symbol P is the set of productions

More information

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

Parsing Part II. (Ambiguity, Top-down parsing, Left-recursion Removal) Parsing Part II (Ambiguity, Top-down parsing, Left-recursion Removal) Ambiguous Grammars Definitions If a grammar has more than one leftmost derivation for a single sentential form, the grammar is ambiguous

More information

8 Parsing. Parsing. Top Down Parsing Methods. Parsing complexity. Top down vs. bottom up parsing. Top down vs. bottom up parsing

8 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 information

CA Compiler Construction

CA Compiler Construction CA4003 - Compiler Construction David Sinclair A top-down 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 information

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

Top-Down Parsing and Intro to Bottom-Up Parsing. Lecture 7 Top-Down Parsing and Intro to Bottom-Up Parsing Lecture 7 1 Predictive Parsers Like recursive-descent but parser can predict which production to use Predictive parsers are never wrong Always able to guess

More information

Chapter 3. Parsing #1

Chapter 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 information

Wednesday, August 31, Parsers

Wednesday, 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 information

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

Syntactic Analysis. Top-Down Parsing. Parsing Techniques. Top-Down Parsing. Remember the Expression Grammar? Example. Example Syntactic Analysis op-down Parsing Parsing echniques op-down 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 information

Computer Science 160 Translation of Programming Languages

Computer Science 160 Translation of Programming Languages Computer Science 160 Translation of Programming Languages Instructor: Christopher Kruegel Top-Down Parsing Parsing Techniques Top-down parsers (LL(1), recursive descent parsers) Start at the root of the

More information

CS2210: Compiler Construction Syntax Analysis Syntax Analysis

CS2210: 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 information

CS 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 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 information

Syntax Analysis. The Big Picture. The Big Picture. COMP 524: Programming Languages Srinivas Krishnan January 25, 2011

Syntax 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 information

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

COP4020 Programming Languages. Syntax Prof. Robert van Engelen COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview n Tokens and regular expressions n Syntax and context-free grammars n Grammar derivations n More about parse trees n Top-down and

More information

Chapter 4: LR Parsing

Chapter 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 information

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

Syntax Analysis, V Bottom-up Parsing & The Magic of Handles Comp 412 Midterm Exam: Thursday October 18, 7PM Herzstein Amphitheater Syntax Analysis, V Bottom-up Parsing & The Magic of Handles Comp 412 COMP 412 FALL 2018 source code IR Front End Optimizer Back End IR target

More information

SYNTAX 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 information

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

COP4020 Programming Languages. Syntax Prof. Robert van Engelen COP4020 Programming Languages Syntax Prof. Robert van Engelen Overview Tokens and regular expressions Syntax and context-free grammars Grammar derivations More about parse trees Top-down and bottom-up

More information

Lexical and Syntax Analysis. Top-Down Parsing

Lexical and Syntax Analysis. Top-Down Parsing Lexical and Syntax Analysis Top-Down 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 information

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing Abstract Syntax Trees & Top-Down 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 information

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing Review of Parsing Abstract Syntax Trees & Top-Down 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 information

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing Review of Parsing Abstract Syntax Trees & Top-Down 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 information

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

Bottom-up parsing. Bottom-Up Parsing. Recall. Goal: For a grammar G, withstartsymbols, any string α such that S α is called a sentential form Bottom-up parsing Bottom-up 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 information

Compiler Construction 2016/2017 Syntax Analysis

Compiler Construction 2016/2017 Syntax Analysis Compiler Construction 2016/2017 Syntax Analysis Peter Thiemann November 2, 2016 Outline 1 Syntax Analysis Recursive top-down parsing Nonrecursive top-down parsing Bottom-up parsing Syntax Analysis tokens

More information

Lexical and Syntax Analysis

Lexical and Syntax Analysis Lexical and Syntax Analysis (of Programming Languages) Top-Down Parsing Lexical and Syntax Analysis (of Programming Languages) Top-Down Parsing Easy for humans to write and understand String of characters

More information

Concepts Introduced in Chapter 4

Concepts Introduced in Chapter 4 Concepts Introduced in Chapter 4 Grammars Context-Free Grammars Derivations and Parse Trees Ambiguity, Precedence, and Associativity Top Down Parsing Recursive Descent, LL Bottom Up Parsing SLR, LR, LALR

More information

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

Compilers. Bottom-up Parsing. (original slides by Sam Compilers Bottom-up Parsing Yannis Smaragdakis U Athens Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Bottom-Up Parsing More general than top-down parsing And just as efficient Builds

More information

Administrativia. WA1 due on Thu PA2 in a week. Building a Parser III. Slides on the web site. CS164 3:30-5:00 TT 10 Evans.

Administrativia. WA1 due on Thu PA2 in a week. Building a Parser III. Slides on the web site. CS164 3:30-5:00 TT 10 Evans. Administrativia Building a Parser III CS164 3:30-5: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 information

MIT Specifying Languages with Regular Expressions and Context-Free Grammars

MIT Specifying Languages with Regular Expressions and Context-Free Grammars MIT 6.035 Specifying Languages with Regular essions and Context-Free Grammars Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Language Definition Problem How to precisely

More information

CS 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). 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 information

How do LL(1) Parsers Build Syntax Trees?

How do LL(1) Parsers Build Syntax Trees? How do LL(1) Parsers Build Syntax Trees? So far our LL(1) parser has acted like a recognizer. It verifies that input token are syntactically correct, but it produces no output. Building complete (concrete)

More information

CMSC 330: Organization of Programming Languages

CMSC 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 information

A programming language requires two major definitions A simple one pass compiler

A 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 context-free grammar written in BNF (Backus-Naur Form) usually suffices. [Semantics:

More information

Part 5 Program Analysis Principles and Techniques

Part 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 information

MIT Specifying Languages with Regular Expressions and Context-Free Grammars. Martin Rinard Massachusetts Institute of Technology

MIT Specifying Languages with Regular Expressions and Context-Free Grammars. Martin Rinard Massachusetts Institute of Technology MIT 6.035 Specifying Languages with Regular essions and Context-Free Grammars Martin Rinard Massachusetts Institute of Technology Language Definition Problem How to precisely define language Layered structure

More information

Context-free grammars

Context-free grammars Context-free grammars Section 4.2 Formal way of specifying rules about the structure/syntax of a program terminals - tokens non-terminals - represent higher-level structures of a program start symbol,

More information

4. Lexical and Syntax Analysis

4. 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 information

4. Lexical and Syntax Analysis

4. 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 information

LL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012

LL(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 information

Front End. Hwansoo Han

Front End. Hwansoo Han Front nd Hwansoo Han Traditional Two-pass 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 information

Building a Parser III. CS164 3:30-5:00 TT 10 Evans. Prof. Bodik CS 164 Lecture 6 1

Building a Parser III. CS164 3:30-5:00 TT 10 Evans. Prof. Bodik CS 164 Lecture 6 1 Building a Parser III CS164 3:30-5: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 information

Compiler Construction: Parsing

Compiler Construction: Parsing Compiler Construction: Parsing Mandar Mitra Indian Statistical Institute M. Mitra (ISI) Parsing 1 / 33 Context-free grammars. Reference: Section 4.2 Formal way of specifying rules about the structure/syntax

More information

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

EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised: EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 2017-09-11 This lecture Regular expressions Context-free grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)

More information

Syntax Analysis/Parsing. Context-free grammars (CFG s) Context-free grammars vs. Regular Expressions. BNF description of PL/0 syntax

Syntax Analysis/Parsing. Context-free grammars (CFG s) Context-free grammars vs. Regular Expressions. BNF description of PL/0 syntax Susan Eggers 1 CSE 401 Syntax Analysis/Parsing Context-free grammars (CFG s) Purpose: determine if tokens have the right form for the language (right syntactic structure) stream of tokens abstract syntax

More information

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

Syntax 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. Hernandez-Campos, and D. Stotts. The Big Picture Character

More information

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

Syntax. Syntax. We will study three levels of syntax Lexical Defines the rules for tokens: literals, identifiers, etc. Syntax Syntax Syntax defines what is grammatically valid in a programming language Set of grammatical rules E.g. in English, a sentence cannot begin with a period Must be formal and exact or there will

More information

Parsing II Top-down parsing. Comp 412

Parsing II Top-down parsing. Comp 412 COMP 412 FALL 2017 Parsing II Top-down 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

More information

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

PART 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 information

Compilers. Predictive Parsing. Alex Aiken

Compilers. Predictive Parsing. Alex Aiken Compilers Like recursive-descent but parser can predict which production to use By looking at the next fewtokens No backtracking Predictive parsers accept LL(k) grammars L means left-to-right scan of input

More information

Parsing #1. Leonidas Fegaras. CSE 5317/4305 L3: Parsing #1 1

Parsing #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

Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing. Lecture 11-12 Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient

More information

Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay Syntax Analysis (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay September 2007 College of Engineering, Pune Syntax Analysis: 2/124 Syntax

More information

CS502: Compilers & Programming Systems

CS502: Compilers & Programming Systems CS502: Compilers & Programming Systems Top-down Parsing Zhiyuan Li Department of Computer Science Purdue University, USA There exist two well-known schemes to construct deterministic top-down parsers:

More information

EECS 6083 Intro to Parsing Context Free Grammars

EECS 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 information

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

CSE 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 information

Bottom-up Parser. Jungsik Choi

Bottom-up Parser. Jungsik Choi Formal Languages and Compiler (CSE322) Bottom-up Parser Jungsik Choi chjs@khu.ac.kr * Some slides taken from SKKU SWE3010 (Prof. Hwansoo Han) and TAMU CSCE434-500 (Prof. Lawrence Rauchwerger) Bottom-up

More information

CS 321 Programming Languages and Compilers. VI. Parsing

CS 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 information

Ambiguity, Precedence, Associativity & Top-Down Parsing. Lecture 9-10

Ambiguity, Precedence, Associativity & Top-Down Parsing. Lecture 9-10 Ambiguity, Precedence, Associativity & Top-Down Parsing Lecture 9-10 (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 information

VIVA QUESTIONS WITH ANSWERS

VIVA 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 language-the

More information

Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich Ben-Gurion University of the Negev

Fall Compiler Principles Lecture 2: LL parsing. Roman Manevich Ben-Gurion University of the Negev Fall 2017-2018 Compiler Principles Lecture 2: LL parsing Roman Manevich Ben-Gurion University of the Negev 1 Books Compilers Principles, Techniques, and Tools Alfred V. Aho, Ravi Sethi, Jeffrey D. Ullman

More information

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

Compilerconstructie. 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. 071-527 2876 rvvliet(at)liacs(dot)nl college 3, vrijdag 22 september 2017 + werkcollege

More information

Note that for recursive descent to work, if A ::= B1 B2 is a grammar rule we need First k (B1) disjoint from First k (B2).

Note 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 information

4 (c) parsing. Parsing. Top down vs. bo5om up parsing

4 (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 information

Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing. Lecture 11-12 Bottom-Up Parsing Lecture 11-12 (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 information

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

Parsing Wrapup. Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing. This lecture LR(1) parsing Parsing Wrapup Roadmap (Where are we?) Last lecture Shift-reduce parser LR(1) parsing LR(1) items Computing closure Computing goto LR(1) canonical collection This lecture LR(1) parsing Building ACTION

More information

Chapter 4. Lexical and Syntax Analysis

Chapter 4. Lexical and Syntax Analysis Chapter 4 Lexical and Syntax Analysis Chapter 4 Topics Introduction Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing Copyright 2012 Addison-Wesley. All rights reserved.

More information

Lecture 8: Deterministic Bottom-Up Parsing

Lecture 8: Deterministic Bottom-Up Parsing Lecture 8: Deterministic Bottom-Up Parsing (From slides by G. Necula & R. Bodik) Last modified: Fri Feb 12 13:02:57 2010 CS164: Lecture #8 1 Avoiding nondeterministic choice: LR We ve been looking at general

More information

1 Introduction. 2 Recursive descent parsing. Predicative parsing. Computer Language Implementation Lecture Note 3 February 4, 2004

1 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 information

3. 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 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 information

Lexical Analysis. Introduction

Lexical 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 information

Defining syntax using CFGs

Defining syntax using CFGs Defining syntax using CFGs Roadmap Last time Defined context-free grammar This time CFGs for specifying a language s syntax Language membership List grammars Resolving ambiguity CFG Review G = (N,Σ,P,S)

More information

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

A left-sentential form is a sentential form that occurs in the leftmost derivation of some sentence. Bottom-up parsing Recall For a grammar G, with start symbol S, any string α such that S α is a sentential form If α V t, then α is a sentence in L(G) A left-sentential form is a sentential form that occurs

More information

Lecture 7: Deterministic Bottom-Up Parsing

Lecture 7: Deterministic Bottom-Up Parsing Lecture 7: Deterministic Bottom-Up Parsing (From slides by G. Necula & R. Bodik) Last modified: Tue Sep 20 12:50:42 2011 CS164: Lecture #7 1 Avoiding nondeterministic choice: LR We ve been looking at general

More information

Building Compilers with Phoenix

Building Compilers with Phoenix Building Compilers with Phoenix Syntax-Directed Translation Structure of a Compiler Character Stream Intermediate Representation Lexical Analyzer Machine-Independent Optimizer token stream Intermediate

More information