CS 406/534 Compiler Construction Parsing Part I

Size: px
Start display at page:

Transcription

1 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. Linda Torczon s teaching materials at Rice University. All rights reserved. 1

2 What We Did Last Time The cycle in lexical analysis RE NFA NFA DFA DFA Minimal DFA DFA RE Engineering issues in building scanners CS406/534 Fall 2004, Prof. Li Xu 2 2

3 Parsing Part I Today s Goals Context-free grammars Sentence derivations Grammar ambiguity Left recursion problem with top-down parsing and how to fix it Predictive top-down parsing LL(1) condition Recursive descent parsing CS406/534 Fall 2004, Prof. Li Xu 3 3

4 Compilers Front Middle End Back End 4 Register Allocation Instruction Scheduling Instruction Selection IR Optimization n Optimization 2 Optimization 1 IR CSA Parser Scanner Infrastructure: symbol tables, trees, graphs, intermediate representations, sets, tuples CS406/534 Fall 2004, Prof. Li Xu 4 Analysis

5 The Front End Source code Scanner tokens Parser IR Parser Errors Checks the stream of words and their parts of speech (produced by the scanner) for grammatical correctness Determines if the input is syntactically well formed Guides checking at deeper levels than syntax Builds an IR representation of the code Think of this as the mathematics of diagramming sentences CS406/534 Fall 2004, Prof. Li Xu 5 5

6 The Study of Parsing The process of discovering a derivation for some sentence Need a mathematical model of syntax a grammar G Need an algorithm for testing membership in L(G) Need to keep in mind that our goal is building parsers, not studying the mathematics of arbitrary languages Roadmap 1 Context-free grammars and derivations 2 Top-down parsing Hand-coded recursive descent parsers LL(1) parsers LL(1) parsed top-down, left to right scan, leftmost derivation, 1 symbol lookahead 3 Bottom-up parsing LR(1) parsers LR(1) parsed bottom-up, left to right scan, reverse rightmost derivation, 1 symbol lookahead CS406/534 Fall 2004, Prof. Li Xu 6 6

7 Specifying Syntax with a Grammar Context-free syntax is specified with a context-free grammar SheepNoise SheepNoise baa baa This CFG defines the set of noises sheep normally make It is written in a variant of Backus Naur form Formally, a grammar is a four tuple, G = (S,N,T,P) S is the start symbol (set of strings in L(G)) N is a set of non-terminal symbols (syntactic variables) T is a set of terminal symbols (words) P is a set of productions or rewrite rules (P : N (N T) + ) CS406/534 Fall 2004, Prof. Li Xu 7 7

8 The Big Picture Chomsky Hierarchy of Language Grammars (1956) recursive enumerable context sensitive grammar CFG LR(1) LL(1) RE CS406/534 Fall 2004, Prof. Li Xu 8 8

9 Deriving Syntax We can use the SheepNoise grammar to create sentences use the productions as rewriting rules Rule Sentential Form SheepNoise 2 baa Rule Sentential Form SheepNoise 1 SheepNoise baa 2 baa baa Rule Sentential Form SheepNoise 1 SheepNoise baa 1 SheepNoise baa baa 2 baa baa baa And so on... While it is cute, this example quickly runs out of intellectual steam... CS406/534 Fall 2004, Prof. Li Xu 9 9

10 A More Useful Grammar To explore the uses of CFGs, we need a more complex grammar 1 Expr Expr Op Expr 2 number 3 id 4 Op * 7 / Rule Expr Sentential Form 1 Expr Op Expr 2 <id,x> Op Expr 5 <id,x> Expr 1 <id,x> Expr Op Expr 2 <id,x> <num,2> Op Expr 6 <id,x> <num,2> * Expr 3 <id,x> <num,2> * <id,y> Such a sequence of rewrites is called a derivation Process of discovering a derivation is called parsing We denote this derivation: Expr * id num* id CS406/534 Fall 2004, Prof. Li Xu 10 10

11 Derivations At each step, we choose a non-terminal to replace Different choices can lead to different derivations Two derivations are of interest Leftmost derivation replace leftmost NT at each step Rightmost derivation replace rightmost NT at each step These are the two systematic derivations (We don t care about randomly-ordered derivations!) The example on the preceding slide was a leftmost derivation Of course, there is also a rightmost derivation Interestingly, it turns out to be different CS406/534 Fall 2004, Prof. Li Xu 11 11

12 The Two Derivations for x 2* y Rule Sentential Form Expr 1 Expr Op Expr 3 <id,x> Op Expr 5 <id,x> Expr 1 <id,x> Expr Op Expr 2 <id,x> <num,2> Op Expr 6 <id,x> <num,2> * Expr 3 <id,x> <num,2> * <id,y> Leftmost derivation Rule Sentential Form Expr 1 Expr Op Expr 3 Expr Op <id,y> 6 Expr * <id,y> 1 Expr Op Expr * <id,y> 2 Expr Op <num,2> * <id,y> 5 Expr <num,2> * <id,y> 3 <id,x> <num,2> * <id,y> Rightmost derivation In both cases, Expr * id num * id The two derivations produce different parse trees The parse trees imply different evaluation orders! CS406/534 Fall 2004, Prof. Li Xu 12 12

13 Derivations and Parse Trees Leftmost derivation Rule Sentential Form G Expr 1 Expr Op Expr 3 <id,x> Op Expr E 5 <id,x> Expr 1 <id,x> Expr Op Expr 2 <id,x> <num,2> Op Expr E Op E 6 <id,x> <num,2> * Expr 3 <id,x> <num,2> * <id,y> x E Op E This evaluates as x ( 2* y ) 2 * y CS406/534 Fall 2004, Prof. Li Xu 13 13

14 Derivations and Parse Trees Rightmost derivation Rule Sentential Form Expr 1 Expr Op Expr 3 Expr Op <id,y> 6 Expr * <id,y> 1 Expr Op Expr * <id,y> 2 Expr Op <num,2> * <id,y> 5 Expr <num,2> * <id,y> 3 <id,x> <num,2> * <id,y> E G E Op E E Op E * y This evaluates as ( x 2 ) * y x 2 CS406/534 Fall 2004, Prof. Li Xu 14 14

15 Derivations and Precedence These two derivations point out a problem with the grammar: It has no notion of precedence, or implied order of evaluation To add precedence Create a non-terminal for each level of precedence Isolate the corresponding part of the grammar Force the parser to recognize high precedence subexpressions first For algebraic expressions Multiplication and division, first (level one) Subtraction and addition, next (level two) CS406/534 Fall 2004, Prof. Li Xu 15 15

16 Derivations and Precedence Adding the standard algebraic precedence produces: level two level one 1 Goal Expr 2 Expr Expr + Term 3 Expr Term 4 Term 5 Term Term * Factor 6 Term / Factor 7 Factor 8 Factor number 9 id This grammar is slightly larger Takes more rewriting to reach some of the terminal symbols Encodes expected precedence Produces same parse tree under leftmost & rightmost derivations Let s see how it parses x - 2 * y CS406/534 Fall 2004, Prof. Li Xu 16 16

17 Derivations and Precedence Rule Sentential Form Goal G 1 Expr E 3 Expr Term 5 Expr Term * Factor E T 9 Expr Term * <id,y> 7 Expr Factor * <id,y> T T * F 8 Expr <num,2> * <id,y> 4 Term <num,2> * <id,y> F F <id,y> 7 Factor <num,2> * <id,y> <id,x> <num,2> 9 <id,x> <num,2> * <id,y> This produces x ( 2* y ), along with an appropriate parse tree. Both the leftmost and rightmost derivations give the same expression, because the grammar directly encodes the desired precedence. CS406/534 Fall 2004, Prof. Li Xu 17 17

18 Ambiguous Grammars Our original expression grammar had other problems 1 Expr Expr Op Expr 2 number 3 id 4 Op * 7 / Rule Sentential Form Expr 1 Expr Op Expr 1 Expr Op Expr Op Expr 3 <id,x> Op Expr Op Expr 5 <id,x> Expr Op Expr 2 <id,x> <num,2> Op Expr 6 <id,x> <num,2> * Expr 3 <id,x> <num,2> * <id,y> This grammar allows multiple leftmost derivations for x -2* y Hard to automate derivation if > 1 choice The grammar is ambiguous different choice than the first time CS406/534 Fall 2004, Prof. Li Xu 18 18

19 Two Leftmost Derivations for x 2 * y The Difference: Different productions chosen on the second step Rule Sentential Form Expr 1 Expr Op Expr 3 <id,x> Op Expr 5 <id,x> Expr 1 <id,x> Expr Op Expr 2 <id,x> <num,2> Op Expr 6 <id,x> <num,2> * Expr 3 <id,x> <num,2> * <id,y> Original choice Both derivations succeed in producing x - 2 * y Rule Sentential Form Expr 1 Expr Op Expr 1 Expr Op Expr Op Expr 3 <id,x> Op Expr Op Expr 5 <id,x> Expr Op Expr 2 <id,x> <num,2> Op Expr 6 <id,x> <num,2> * Expr 3 <id,x> <num,2> * <id,y> New choice CS406/534 Fall 2004, Prof. Li Xu 19 19

20 Definitions Ambiguous Grammars If a grammar has more than one leftmost derivation for a single sentential form, the grammar is ambiguous If a grammar has more than one rightmost derivation for a single sentential form, the grammar is ambiguous The leftmost and rightmost derivations for a sentential form may differ, even in an unambiguous grammar Classic example the if-then-else problem Stmt if Expr then Stmt if Expr then Stmt else Stmt other stmts This ambiguity is entirely grammatical in nature CS406/534 Fall 2004, Prof. Li Xu 20 20

21 Ambiguity This sentential form has two derivations if Expr 1 then if Expr 2 then Stmt 1 else Stmt 2 if if E 1 then else E 1 then if S 2 if E 2 then E 2 then else S 1 S 1 S 2 production 2, then production 1 production 1, then production 2 CS406/534 Fall 2004, Prof. Li Xu 21 21

22 Removing the ambiguity Ambiguity Must rewrite the grammar to avoid generating the problem Match each else to innermost unmatched if (common sense rule) 1 Stmt WithElse 2 NoElse 3 WithElse if Expr then WithElse else WithElse 4 OtherStmt 5 NoElse if Expr then Stmt 6 if Expr then WithElse else NoElse Intuition: a NoElse always has no else on its last cascaded else if statement With this grammar, the example has only one derivation CS406/534 Fall 2004, Prof. Li Xu 22 22

23 Ambiguity if Expr 1 then if Expr 2 then Stmt 1 else Stmt 2 Rule Sentential Form Stmt 2 NoElse 5 if Expr then Stmt? if E 1 then Stmt 1 if E 1 then WithElse 3 if E 1 then if Expr then WithElse else WithElse? if E 1 then if E 2 then WithElse else WithElse 4 if E 1 then if E 2 then S 1 else WithElse 4 if E 1 then if E 2 then S 1 else S 2 This binds the else controlling S 2 to the inner if CS406/534 Fall 2004, Prof. Li Xu 23 23

24 Deeper Ambiguity Ambiguity usually refers to confusion in the CFG Overloading can create deeper ambiguity a = f(17) In many Algol-like languages, f could be either a function or a subscripted variable Disambiguating this one requires context Need values of declarations Really an issue of type, not context-free syntax Requires an extra-grammatical solution (not in CFG) Must handle these with a different mechanism Step outside grammar rather than use a more complex grammar CS406/534 Fall 2004, Prof. Li Xu 24 24

25 Ambiguity - The Final Word Ambiguity arises from two distinct sources Confusion in the context-free syntax (if-then-else) Confusion that requires context to resolve (overloading) Resolving ambiguity To remove context-free ambiguity, rewrite the grammar To handle context-sensitive ambiguity takes cooperation Knowledge of declarations, types, Accept a superset of L(G) & check it by other means This is a language design problem Sometimes, the compiler writer accepts an ambiguous grammar Parsing techniques that do the right thing i.e., always select the same derivation CS406/534 Fall 2004, Prof. Li Xu 25 25

26 Parsing Techniques Top-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 pick may need to backtrack Some grammars are backtrack-free (predictive parsing) Bottom-up parsers (LR(1), operator precedence) Start at the leaves and grow toward root As input is consumed, encode possibilities in an internal state Start in a state valid for legal first tokens Bottom-up parsers handle a large class of grammars CS406/534 Fall 2004, Prof. Li Xu 26 26

27 Top-down Parsing A top-down parser starts with the root of the parse tree The root node is labeled with the goal symbol of the grammar Top-down parsing algorithm: Construct the root node of the parse tree Repeat until the fringe of the parse tree matches the input string 1 At a node labeled A, select a production 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 production in step 1 That choice should be guided by the input string CS406/534 Fall 2004, Prof. Li Xu 27 27

28 The Expression Grammar Version with precedence derived last lecture 1 Goal Expr 2 Expr Expr + Term 3 Expr Term 4 Term 5 Term Term * Factor 6 Term / Factor 7 Factor 8 Factor number 9 id And the input x 2* y CS406/534 Fall 2004, Prof. Li Xu 28 28

29 Example Let s try x 2* y : Rule Sentential Form Input Goal Goal x 2 * y Expr 1 Expr x 2 * y 2 Expr + Term x 2 * y Expr + Term 4 Term + Term x 2 * y Term 7 Factor + Term x 2 * y 9 <id,x> + Term x 2 * y Fact. 9 <id,x> + Term x 2 * y <id,x> Leftmost derivation, choose productions in an order that exposes problems CS406/534 Fall 2004, Prof. Li Xu 29 29

30 Let s try x 2* y : Example Goal Rule Sentential Form Input Goal x 2 * y Expr 1 Expr x 2 * y Expr + Term 2 Expr + Term x 2 * y 4 Term + Term x 2 * y Term 7 Factor + Term x 2 * y 9 <id,x> + Term x 2 * y Fact. 9 <id,x> + Term x 2 * y <id,x> This worked well, except that doesn t match + The parser must backtrack to here CS406/534 Fall 2004, Prof. Li Xu 30 30

31 Continuing with x 2* y : Example Goal Rule Sentential Form Input Goal x 2 * y Expr 1 Expr x 2 * y 3 Expr Term x 2 * y Expr Term 4 Term Term x 2 * y 7 Factor Term x 2 * y Term 9 <id,x> Term x 2 * y 9 <id,x> Term x 2 * y <id,x> Term x 2 * y Fact. <id,x> CS406/534 Fall 2004, Prof. Li Xu 31 31

32 Example Continuing with x 2* y : Goal Rule Sentential Form Input Goal x 2 * y Expr 1 Expr x 2 * y 3 Expr Term x 2 * y Expr Term 4 Term Term x 2 * y 7 Factor Term x 2 * y Term 9 <id,x> Term x 2 * y 9 <id,x> Term x 2 * y <id,x> Term x 2 * y Fact. <id,x> This time, and matched We can advance past to look at 2 Now, we need to expand Term -the last NT on the fringe CS406/534 Fall 2004, Prof. Li Xu 32 32

33 Example Trying to match the 2 in x 2* y : Goal Rule Sentential Form Input <id,x> Term x 2 * y Expr 7 <id,x> Factor x 2 * y Expr Term 9 <id,x> <num,2> x 2 * y <id,x> <num,2> x 2 * y Term Fact. Fact. <num,2> <id,x> CS406/534 Fall 2004, Prof. Li Xu 33 33

34 Example Trying to match the 2 in x 2* y : Goal Rule Sentential Form Input <id,x> Term x 2 * y Expr 7 <id,x> Factor x 2 * y Expr - Term 9 <id,x> <num,2> x 2 * y <id,x> <num,2> x 2 * y Term Fact. Where are we? 2 matches 2 Fact. <id,x> We have more input, but no NTs left to expand The expansion terminated too soon Need to backtrack <num,2> CS406/534 Fall 2004, Prof. Li Xu 34 34

35 Example Trying again with 2 in x 2* y : Goal Rule Sentential Form Input <id,x> Term x 2 * y Expr 5 <id,x> Term * Factor x 2 * y Expr Term 7 <id,x> Factor * Factor x 2 * y 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 time, we matched & consumed all the input Success! CS406/534 Fall 2004, Prof. Li Xu 35 35

36 Another Possible Parse Other choices for expansion are possible Rule Sentential Form Input Goal x 2 * y 1 Expr x 2 * y 2 Expr + Term x 2 * y 2 Expr + Term +Term x 2 * y 2 Expr + Term + Term +Term x 2 * y 2 Expr +Term + Term + +Term x 2 * y consuming no input! This doesn t terminate (obviously) Wrong choice of expansion leads to non-termination Non-termination is a bad property for a parser to have Parser must make the right choice CS406/534 Fall 2004, Prof. Li Xu 36 36

37 Left Recursion Top-down parsers cannot handle left-recursive grammars Formally, A grammar is left recursive if A NT such that a derivation A + Aα, for some string α (NT T ) + Our expression grammar is left recursive This can lead to non-termination in a top-down parser For a top-down parser, any recursion must be right recursion We would like to convert the left recursion to right recursion Non-termination is a bad property in any part of a compiler CS406/534 Fall 2004, Prof. Li Xu 37 37

38 Eliminating Left Recursion To remove left recursion, we can transform the grammar Consider a grammar fragment of the form Fee Fee α β where neither α nor β start with Fee We can rewrite this as Fee β Fie Fie α Fie ε where Fie is a new non-terminal This accepts the same language, but uses only right recursion CS406/534 Fall 2004, Prof. Li Xu 38 38

39 Eliminating Left Recursion The expression grammar contains two cases of left recursion Expr Expr + Term Term Term * Factor Expr Term Term / Factor Term Factor Applying the transformation yields Expr Term Expr Expr + Term Expr Term Expr ε Term Factor Term Term * Factor Term / Factor Term ε These fragments use only right recursion They retain the original left associativity CS406/534 Fall 2004, Prof. Li Xu 39 39

40 Eliminating Left Recursion Substituting them back into the grammar yields 1 Goal Expr 2 Expr Term Expr 3 Expr + Term Expr 4 Term Expr 5 ε 6 Term Factor Term 7 Term * Factor Term 8 / Factor Term 9 ε 10 Factor number 11 id 12 ( Expr ) This grammar is correct, if somewhat non-intuitive. It is left associative, as was the original A top-down parser will terminate using it. A top-down parser may need to backtrack with it. CS406/534 Fall 2004, Prof. Li Xu 40 40

41 Eliminating Left Recursion The transformation eliminates immediate left recursion What about more general, indirect left recursion? The general algorithm: arrange the NTs into some order A 1, A 2,, A n for i 1 to n for s 1 to i 1 Must start with 1 to ensure that A 1 A 1 β is transformed replace each production A i A s γ with A i δ 1 γ δ 2 γ δ k γ, where A s δ 1 δ 2 δ k are all the current productions for A s eliminate any immediate left recursion on A i using the direct transformation This assumes that the initial grammar has no cycles (A i + A i ), and no epsilon productions And back CS406/534 Fall 2004, Prof. Li Xu 41 41

42 Eliminating Left Recursion How does this algorithm work? 1. Impose arbitrary order on the non-terminals 2. Outer loop cycles through NT in order 3. Inner loop ensures that a production expanding A i has no non-terminal A s in its rhs, for s < i 4. Last step in outer loop converts any direct recursion on A i to right recursion using the transformation showed earlier 5. New non-terminals are added at the end of the order & have no left recursion At the start of the i th outer loop iteration For all k < i, no production that expands A k contains a non-terminal A s in its rhs, for s < k CS406/534 Fall 2004, Prof. Li Xu 42 42

43 Example Order of symbols: G, E, T G E E E + T E T T E ~ T T id CS406/534 Fall 2004, Prof. Li Xu 43 43

44 Example Order of symbols: G, E, T 1. A i = G G E E E + T E T T E ~ T T id CS406/534 Fall 2004, Prof. Li Xu 44 44

45 Example Order of symbols: G, E, T 1. A i = G G E E E + T E T T E ~ T T id 2. A i = E G E E T E' E' + T E' E' ε T E ~ T T id CS406/534 Fall 2004, Prof. Li Xu 45 45

46 Example Order of symbols: G, E, T 1. A i = G G E E E + T E T T E ~ T T id 2. A i = E G E E T E' E' + T E' E' ε T E ~ T T id 3. A i = T, A s = E G E E T E' E' + T E' E' ε T T E' ~ T T id Go to Algorithm CS406/534 Fall 2004, Prof. Li Xu 46 46

47 Example Order of symbols: G, E, T 1. A i = G 2. A i = E 3. A i = T, A s = E 4. A i = T G E G E G E G E E E + T E T E' E T E' E T E' E T E' + T E' E' + T E' E' + T E' T E ~ T E' ε E' ε E' ε T id T E ~ T T T E' ~ T T id T' T id T id T' E' ~ T T' T' ε CS406/534 Fall 2004, Prof. Li Xu 47 47

48 Roadmap (Where are We?) We set out to study parsing Specifying syntax Context-free grammars Ambiguity Top-down parsers Algorithm & its problem with left recursion Left-recursion removal Predictive top-down parsing The LL(1) condition Simple recursive descent parsers CS406/534 Fall 2004, Prof. Li Xu 48 48

49 Picking the Right Production If it picks the wrong production, a top-down parser may backtrack Alternative is to look ahead in input & use context to pick correctly How much lookahead is needed? In general, an arbitrarily large amount Use the Cocke-Younger, Kasami algorithm or Earley s algorithm Fortunately, Large subclasses of CFGs can be parsed with limited lookahead Most programming language constructs fall in those subclasses Among the interesting subclasses are LL(1) grammars and LR(1) CS406/534 Fall 2004, Prof. Li Xu 49 49

50 Basic idea Predictive Parsing Given A α β, the parser should be able to choose between α & β FIRST sets For some rhs α G, 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 γ We will defer the problem of how to compute FIRST sets until we look at the LR(1) table construction algorithm CS406/534 Fall 2004, Prof. Li Xu 50 50

51 Predictive Parsing Basic idea Given A α β, the parser should be able to choose between α & β FIRST sets For some rhs α G, 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 γ The LL(1) Property If A αand A βboth appear in the grammar, we would like FIRST(α) FIRST(β) = This would allow the parser to make a correct choice with a lookahead of exactly one symbol! This is almost correct See the next slide CS406/534 Fall 2004, Prof. Li Xu 51 51

52 Predictive Parsing What about ε-productions? They complicate the definition of LL(1) If A αand A βand ε FIRST(α), then we need to ensure that FIRST(β) is disjoint from FOLLOW(α), too Define FIRST + (α) as FIRST(α) FOLLOW(α), if ε FIRST(α) FIRST(α), otherwise Then, a grammar is LL(1) iff A αand A βimplies FIRST + (α) FIRST + (β) = FOLLOW(α) is the set of all words in the grammar that can legally appear immediately after an α CS406/534 Fall 2004, Prof. Li Xu 52 52

53 Predictive Parsing Given a grammar that has the LL(1) property Can write a simple routine to recognize each lhs Code is both simple & fast Consider A β 1 β 2 β 3, with FIRST + (β 1 ) FIRST + (β 2 ) FIRST + (β 3 ) = /* find an A */ if (current_word FIRST(β 1 )) find a β 1 and return true else if (current_word FIRST(β 2 )) find a β 2 and return true else if (current_word FIRST(β 3 )) find a β 3 and return true else report an error and return false Of course, there is more detail to find a β i ( in EAC) Grammars with the LL(1) property are called predictive grammars because the parser can predict the correct expansion at each point in the parse. Parsers that capitalize on the LL(1) property are called predictive parsers. One kind of predictive parser is the recursive descent parser. CS406/534 Fall 2004, Prof. Li Xu 53 53

54 Recursive Descent Parsing Recall the expression grammar, after transformation 1 Goal Expr 2 Expr Term Expr 3 Expr + Term Expr 4 Term Expr 5 ε 6 Term Factor Term 7 Term * Factor Term 8 / Factor Term 9 ε 10 Factor number 11 id This produces a parser with six mutually recursive routines: Goal Expr EPrime Term TPrime Factor Each recognizes one NT or T The term descent refers to the direction in which the parse tree is built. CS406/534 Fall 2004, Prof. Li Xu 54 54

55 Recursive Descent Parsing A couple of routines from the expression parser Goal( ) token next_token( ); if (Expr( ) = true & token = EOF) then next compilation step; else report syntax error; return false; Expr( ) if (Term( ) = false) then return false; else return Eprime( ); looking for EOF, found token Factor( ) if (token = Number) then token next_token( ); return true; else if (token = Identifier) then token next_token( ); return true; else report syntax error; return false; EPrime, Term, & TPrime follow the same basic lines (Figure 3.7, EAC) looking for Number or Identifier, found token instead CS406/534 Fall 2004, Prof. Li Xu 55 55

56 Recursive Descent Parsing To build a parse tree: Augment parsing routines to build nodes Pass nodes between routines using a stack Node for each symbol on rhs Action is to pop rhs nodes, make them children of lhs node, and push this subtree To build an abstract syntax tree Build fewer nodes Put them together in a different order Expr( ) result true; if (Term( ) = false) then return false; else if (EPrime( ) = false) then result false; else build an Expr node pop EPrime node pop Term node make EPrime & Term children of Expr push Expr node return result; Success build a piece of the parse tree CS406/534 Fall 2004, Prof. Li Xu 56 56

57 Left Factoring What if my grammar does not have the LL(1) property? Sometimes, we can transform the grammar The Algorithm A NT, find the longest prefix α that occurs in two or more right-hand sides of A if α ε then replace all of the A productions, A αβ 1 αβ 2 αβ n γ, with A α Z γ Z β 1 β 2 β n where Z is a new element of NT Repeat until no common prefixes remain CS406/534 Fall 2004, Prof. Li Xu 57 57

58 Left Factoring A graphical explanation for the same idea αβ 1 A αβ 1 αβ 2 αβ3 A αβ 2 becomes αβ 3 A α Z Z β 1 β 2 β n A αz β 1 β 2 β 3 CS406/534 Fall 2004, Prof. Li Xu 58 58

59 Left Factoring: An Example Consider the following fragment of the expression grammar Factor Identifier Identifier [ ExprList ] Identifier ( ExprList ) FIRST(rhs 1 ) = { Identifier } FIRST(rhs 2 ) = { Identifier } FIRST(rhs 3 ) = { Identifier } After left factoring, it becomes Factor Identifier Arguments Arguments [ ExprList ] ( ExprList ) ε FIRST(rhs 1 ) = { Identifier } FIRST(rhs 2 ) = { [ } FIRST(rhs 3 ) = { ( } FIRST(rhs 4 ) = FOLLOW(Factor) It has the LL(1) property This form has the same syntax, with the LL(1) property CS406/534 Fall 2004, Prof. Li Xu 59 59

60 Graphically Left Factoring Identifier Factor Identifier [ ExprList ] No basis for choice Identifier ( ExprList ) becomes ε Factor Identifier [ ExprList ] Word determines correct choice ( ExprList ) CS406/534 Fall 2004, Prof. Li Xu 60 60

61 Recursive Descent (Summary) 1. Build FIRST (and FOLLOW) sets 2. Massage grammar to have LL(1) condition a. Remove left recursion b. Left factor it 3. Define a procedure for each non-terminal a. Implement a case for each right-hand side b. Call procedures as needed for non-terminals 4. Add extra code, as needed a. Perform context-sensitive checking b. Build an IR to record the code Can we automate this process? CS406/534 Fall 2004, Prof. Li Xu 61 61

62 Summary Parsing Part I Introduction to parsing grammar, derivation, ambiguity, left recursion Predictive top-down parsing LL(1) condition Recursive descent parsing CS406/534 Fall 2004, Prof. Li Xu 62 62

63 Next Class Table-driven LL(1) parsing Bottom-up parsing CS406/534 Fall 2004, Prof. Li Xu 63 63

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

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

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

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 &

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

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

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

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

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

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

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

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

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

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

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

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,

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/

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

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

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)

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

COMP 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

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

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

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

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

CS 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

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

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.

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

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

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

Syntax Analysis Part I

Syntax Analysis Part I Chapter 4: Context-Free Grammars Slides adapted from : Robert van Engelen, Florida State University Position of a Parser in the Compiler Model Source Program Lexical Analyzer Token,

Goals for course What is a compiler and briefly how does it work? Review everything you should know from 330 and before

CMSC 430 Today Goals for course What is a compiler and briefly how does it work? Review everything you should know from 330 and before > This looks like a lot of material (and it is), but most of this

Syntax 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

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

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

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

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)

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

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

CS415 Compilers. Lexical Analysis

CS415 Compilers Lexical Analysis These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Lecture 7 1 Announcements First project and second homework

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,

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

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

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

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

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

Compiler 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

Sometimes 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

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

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

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

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

Academic 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

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

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

CS415 Compilers Overview of the Course. These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University

CS415 Compilers Overview of the Course These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Critical Facts Welcome to CS415 Compilers Topics in the

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

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

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

Building 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

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

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

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:

Formal Languages and Compilers Lecture V: Parse Trees and Ambiguous Gr

Formal Languages and Compilers Lecture V: Parse Trees and Ambiguous Grammars Free University of Bozen-Bolzano Faculty of Computer Science POS Building, Room: 2.03 artale@inf.unibz.it http://www.inf.unibz.it/

Where We Are. CMSC 330: Organization of Programming Languages. This Lecture. Programming Languages. Motivation for Grammars

CMSC 330: Organization of Programming Languages Context Free Grammars Where We Are Programming languages Ruby OCaml Implementing programming languages Scanner Uses regular expressions Finite automata Parser

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

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

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

Syntax 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

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

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

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

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

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

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

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

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

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)

S Y N T A X A N A L Y S I S LR

LR parsing There are three commonly used algorithms to build tables for an LR parser: 1. SLR(1) = LR(0) plus use of FOLLOW set to select between actions smallest class of grammars smallest tables (number

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

CMSC 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

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

Parser Generation. Bottom-Up Parsing. Constructing LR Parser. LR Parsing. Construct parse tree bottom-up --- from leaves to the root

Parser Generation Main Problem: given a grammar G, how to build a top-down parser or a bottom-up parser for it? parser : a program that, given a sentence, reconstructs a derivation for that sentence ----

Homework & 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

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

The Parsing Problem (cont d) Recursive-Descent Parsing. Recursive-Descent Parsing (cont d) ICOM 4036 Programming Languages. The Complexity of Parsing

ICOM 4036 Programming Languages Lexical and Syntax Analysis Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing This lecture covers review questions 14-27 This lecture covers

EDAN65: Compilers, Lecture 04 Grammar transformations: Eliminating ambiguities, adapting to LL parsing. Görel Hedin Revised:

EDAN65: Compilers, Lecture 04 Grammar transformations: Eliminating ambiguities, adapting to LL parsing Görel Hedin Revised: 2017-09-04 This lecture Regular expressions Context-free grammar Attribute grammar

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

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

Syntax Analysis Prof. James L. Frankel Harvard University Version of 6:43 PM 6-Feb-2018 Copyright 2018, 2015 James L. Frankel. All rights reserved. Context-Free Grammar (CFG) terminals non-terminals start

Principles 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

Programming Language Syntax and Analysis

Programming Language Syntax and Analysis 2017 Kwangman Ko (http://compiler.sangji.ac.kr, kkman@sangji.ac.kr) Dept. of Computer Engineering, Sangji University Introduction Syntax the form or structure of

Syntax Analysis: Context-free Grammars, Pushdown Automata and Parsing Part - 4. Y.N. Srikant

Syntax Analysis: Context-free Grammars, Pushdown Automata and Part - 4 Department of Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler