Top-Down Parsing

Total Page:16

File Type:pdf, Size:1020Kb

Top-Down Parsing Outline • Recursive Descent Parsing • Predictive Parsers Top-Down Parsing Originated from Prof. Aiken CS 143 Modified by Yu Zhang 1 2 Intro to Top-Down Parsing: The Idea Recursive Descent Parsing (递归下降的分析) • Consider the grammar • The parse tree is constructed 1 E T |T + E –From the top T int | int * T | ( E ) – From left to right t2 3 t9 • Token stream is: ( int5 ) • Terminals are seen in order of 4 7 appearance in the token • Start with top-level non-terminal E stream: t5 t6 t8 – Try the rules for E in order t2 t5 t6 t8 t9 3 4 Recursive Descent Parsing Recursive Descent Parsing E T |T + E E T |T + E T int | int * T | ( E ) T int | int * T | ( E ) E E T ( int5 ) ( int5 ) 5 6 1 Recursive Descent Parsing Recursive Descent Parsing E T |T + E E T |T + E T int | int * T | ( E ) T int | int * T | ( E ) E E T T Mismatch: int is not ( ! int Backtrack … ( int5 ) ( int5 ) 7 8 Recursive Descent Parsing Recursive Descent Parsing E T |T + E E T |T + E T int | int * T | ( E ) T int | int * T | ( E ) E E T T Mismatch: int is not ( ! int * T Backtrack … ( int5 ) ( int5 ) 9 10 Recursive Descent Parsing Recursive Descent Parsing E T |T + E E T |T + E T int | int * T | ( E ) T int | int * T | ( E ) E E T T Match! Advance input. ( E ) ( E ) ( int5 ) ( int5 ) 11 12 2 Recursive Descent Parsing Recursive Descent Parsing E T |T + E E T |T + E T int | int * T | ( E ) T int | int * T | ( E ) E E T T Match! Advance input. (E) (E) T T ( int5 ) ( int5 ) 13 14 int Recursive Descent Parsing Recursive Descent Parsing E T |T + E E T |T + E T int | int * T | ( E ) T int | int * T | ( E ) E E T T Match! Advance input. End of input, accept. (E) (E) T T ( int5 ) ( int5 ) 15 16 int int A Recursive Descent Parser. Preliminaries A (Limited) Recursive Descent Parser (2) • Let TOKEN be the type of tokens • Define boolean functions that check the token – Special tokens INT, OPEN, CLOSE, PLUS, TIMES string for a match of – A given token terminal • Let the global next point to the next token bool term(TOKEN tok) { return *next++ == tok; } – The nth production of S: bool Sn() { … } – Try all productions of S: bool S() { … } 17 18 3 A (Limited) Recursive Descent Parser (3) A (Limited) Recursive Descent Parser (4) • For production E T • Functions for non-terminal T bool T1() { return term(INT); } bool E1() { return T(); } bool T2() { return term(INT) && term(TIMES) && T(); } • For production E T + E bool T3() { return term(OPEN) && E() && term(CLOSE); } bool E2() { return T() && term(PLUS) && E(); } • For all productions of E (with backtracking) bool T() { TOKEN *save = next; bool E() { return (next = save, T ()) TOKEN *save = next; 1 || (next = save, T2()) return (next = save, E1()) || (next = save, T3()); } || (next = save, E2()); } 19 20 Recursive Descent Parsing. Notes. Example • To start the parser E T |T + E ( int ) –Initialize next to point to first token T int | int * T | ( E ) –Invoke E() bool term(TOKEN tok) { return *next++ == tok; } • Notice how this simulates the example parse bool E1() { return T(); } bool E2() { return T() && term(PLUS) && E(); } bool E() {TOKEN *save = next; return (next = save, E1()) • Easy to implement by hand || (next = save, E2()); } bool T () { return term(INT); } – But not completely general 1 bool T2() { return term(INT) && term(TIMES) && T(); } – Cannot backtrack once a production is successful bool T3() { return term(OPEN) && E() && term(CLOSE); } – Works for grammars where at most one production can bool T() { TOKEN *save = next; return (next = save, T1()) succeed for a non-terminal || (next = save, T2()) || (next = save, T3()); } 21 22 When Recursive Descent Does Not Work Elimination of Left Recursion • Consider a production S S a • Consider the left-recursive grammar bool S1() { return S() && term(a); } S S | bool S() { return S1(); } •Sgenerates all strings starting with a and •S()goes into an infinite loop followed by a number of • A left-recursive grammar has a non-terminal S • Can rewrite using right-recursion S + S for some S S’ • Recursive descent does not work in such cases S’ S’ | 23 24 4 More Elimination of Left-Recursion General Left Recursion • In general • The grammar S A | S S | … | S | | … | 1 n 1 m A S • All strings derived from S start with one of is also left-recursive because + 1,…,m and continue with several instances of S S 1,…,n • Rewrite as • This left-recursion can also be eliminated S 1 S’ | … | m S’ S’ 1 S’ | … | n S’ | • See Dragon Book for general algorithm –Section 4.3 25 26 Summary of Recursive Descent Predictive Parsers (预测分析器) • Simple and general parsing strategy • Like recursive-descent but parser can – Left-recursion must be eliminated first “predict” which production to use – … but that can be done automatically – By looking at the next few tokens –No backtracking • Unpopular because of backtracking (回溯) • Predictive parsers accept LL(k) grammars – Thought to be too inefficient –Lmeans “left-to-right” scan of input –Lmeans “leftmost derivation” • In practice, backtracking is eliminated by –kmeans “predict based on k tokens of lookahead” restricting the grammar – In practice, LL(1) is used 27 28 LL(1) vs. Recursive Descent Predictive Parsing and Left Factoring • In recursive-descent, • Recall the grammar – At each step, many choices of production to use E T + E | T – Backtracking used to undo bad choices T int | int * T | ( E ) • In LL(1), – At each step, only one choice of production • Hard to predict because –That is • When a non-terminal A is leftmost in a derivation –For T two productions start with int • The next input symbol is t –For E it is not clear how to predict • There is a unique production A to use – Or no production to use (an error state) • We need to left-factor the grammar • LL(1) is a recursive descent variant without backtracking 29 30 5 Left-Factoring Example Left-Recursion & Left-Factoring Example • Recall the grammar • Recall the grammar E T + E | T E E + T | T -- +: left assoc. T int | int * T | ( E ) T int | int * T | ( E ) • Factor out common prefixes of productions • Eliminate left-recursion & factor out common E T X prefixes X + E | E T X T ( E ) | int Y X + T X | Y * T | T ( E ) | int Y Y * T | 31 32 LL(1) Parsing Table Example LL(1) Parsing Table Example (Cont.) • Left-factored grammar •Consider the [E, int] entry E T X X + E | – “When current non-terminal is E and next input is T ( E ) | int Y Y * T | int, use production E T X” • The LL(1) parsing table: next input token – This can generate an int in the first position int * + ( ) $ E T X T X •Consider the [Y,+] entry X + E – “When current non-terminal is Y and current token T int Y ( E ) is +, get rid of Y” Y * T –Ycan be followed by + only if Y rhs of production to use leftmost non-terminal 33 34 LL(1) Parsing Tables. Errors Predictive Parsing • Blank entries indicate error situations 输入 a + b $ •Consider the [E,*] entry – “There is no way to derive a string starting with * 预测分析程序 from non-terminal E” 栈 X 输出 Y Z $ 分析表M 36 35 6 Using Parsing Tables LL(1) Parsing Algorithm • Method similar to recursive descent, except initialize stack = <S $> and next – For the leftmost non-terminal S repeat – We look at the next input token a case stack of – And choose the production shown at [S,a] <X, rest> : if T[X,*next] == Y1…Yn then stack <Y1… Yn rest>; • A stack records frontier of parse tree else error (); – Non-terminals that have yet to be expanded <t, rest> : if t == *next ++ – Terminals that have yet to matched against the input then stack <rest>; – Top of stack = leftmost pending terminal or non-terminal else error (); until stack == < > • Reject on reaching error state • Accept on end of input & empty stack 37 38 LL(1) Parsing Algorithm LL(1) Parsing Example $ marks bottom of stack initialize stack = <S $> and next Stack Input Action repeat For non-terminal X on top of stack, E $ int * int $ T X lookup production case stack of T X $ int * int $ int Y <X, rest> : if T[X,*next] == Y1…Yn int Y X $ int * int $ terminal then stack <Y1… Yn rest>; Y X $ * int $ * T else error (); Pop X, push * T X $ * int $ terminal <t, rest> : if t == *next ++ production T X $ int $ int Y For terminal t on top of then stack <rest>; rhs on stack. stack, check t matches next else error (); Note int Y X $ int $ terminal input token. until stack == < > leftmost Y X $ $ symbol of rhs X $ $ is on top of the stack. $ $ ACCEPT 39 40 Constructing Parsing Tables: The Intuition Computing First Sets • Consider non-terminal A, production A , & token t Definition • T[A,t] = in two cases: First(X) = { t | X * t} { | X * } * •If t Algorithm sketch: – can derive a t in the first position –We say thatt First() 1. First(t) = { t } 2. First(X) •IfA and * and S * A t •if X – Useful if stack has A, input is t, and A cannot derive t •if X A1 … An and First(Ai) for 1 i n – In this case only option is to get rid of A (by deriving ) 3. First() First(X) if X A1 … An •Can work only if t can follow A in at least one derivation –and First(A ) for 1 i n –We sayt Follow(A) i 41 42 7 First Sets.
Recommended publications
  • Derivatives of Parsing Expression Grammars
    Derivatives of Parsing Expression Grammars Aaron Moss Cheriton School of Computer Science University of Waterloo Waterloo, Ontario, Canada [email protected] This paper introduces a new derivative parsing algorithm for recognition of parsing expression gram- mars. Derivative parsing is shown to have a polynomial worst-case time bound, an improvement on the exponential bound of the recursive descent algorithm. This work also introduces asymptotic analysis based on inputs with a constant bound on both grammar nesting depth and number of back- tracking choices; derivative and recursive descent parsing are shown to run in linear time and constant space on this useful class of inputs, with both the theoretical bounds and the reasonability of the in- put class validated empirically. This common-case constant memory usage of derivative parsing is an improvement on the linear space required by the packrat algorithm. 1 Introduction Parsing expression grammars (PEGs) are a parsing formalism introduced by Ford [6]. Any LR(k) lan- guage can be represented as a PEG [7], but there are some non-context-free languages that may also be represented as PEGs (e.g. anbncn [7]). Unlike context-free grammars (CFGs), PEGs are unambiguous, admitting no more than one parse tree for any grammar and input. PEGs are a formalization of recursive descent parsers allowing limited backtracking and infinite lookahead; a string in the language of a PEG can be recognized in exponential time and linear space using a recursive descent algorithm, or linear time and space using the memoized packrat algorithm [6]. PEGs are formally defined and these algo- rithms outlined in Section 3.
    [Show full text]
  • A Typed, Algebraic Approach to Parsing
    A Typed, Algebraic Approach to Parsing Neelakantan R. Krishnaswami Jeremy Yallop University of Cambridge University of Cambridge United Kingdom United Kingdom [email protected] [email protected] Abstract the subject have remained remarkably stable: context-free In this paper, we recall the definition of the context-free ex- languages are specified in BackusśNaur form, and parsers pressions (or µ-regular expressions), an algebraic presenta- for these specifications are implemented using algorithms tion of the context-free languages. Then, we define a core derived from automata theory. This integration of theory and type system for the context-free expressions which gives a practice has yielded many benefits: we have linear-time algo- compositional criterion for identifying those context-free ex- rithms for parsing unambiguous grammars efficiently [Knuth pressions which can be parsed unambiguously by predictive 1965; Lewis and Stearns 1968] and with excellent error re- algorithms in the style of recursive descent or LL(1). porting for bad input strings [Jeffery 2003]. Next, we show how these typed grammar expressions can However, in languages with good support for higher-order be used to derive a parser combinator library which both functions (such as ML, Haskell, and Scala) it is very popular guarantees linear-time parsing with no backtracking and to use parser combinators [Hutton 1992] instead. These li- single-token lookahead, and which respects the natural de- braries typically build backtracking recursive descent parsers notational semantics of context-free expressions. Finally, we by composing higher-order functions. This allows building show how to exploit the type information to write a staged up parsers with the ordinary abstraction features of the version of this library, which produces dramatic increases programming language (variables, data structures and func- in performance, even outperforming code generated by the tions), which is sufficiently beneficial that these libraries are standard parser generator tool ocamlyacc.
    [Show full text]
  • Adaptive LL(*) Parsing: the Power of Dynamic Analysis
    Adaptive LL(*) Parsing: The Power of Dynamic Analysis Terence Parr Sam Harwell Kathleen Fisher University of San Francisco University of Texas at Austin Tufts University [email protected] [email protected] kfi[email protected] Abstract PEGs are unambiguous by definition but have a quirk where Despite the advances made by modern parsing strategies such rule A ! a j ab (meaning “A matches either a or ab”) can never as PEG, LL(*), GLR, and GLL, parsing is not a solved prob- match ab since PEGs choose the first alternative that matches lem. Existing approaches suffer from a number of weaknesses, a prefix of the remaining input. Nested backtracking makes de- including difficulties supporting side-effecting embedded ac- bugging PEGs difficult. tions, slow and/or unpredictable performance, and counter- Second, side-effecting programmer-supplied actions (muta- intuitive matching strategies. This paper introduces the ALL(*) tors) like print statements should be avoided in any strategy that parsing strategy that combines the simplicity, efficiency, and continuously speculates (PEG) or supports multiple interpreta- predictability of conventional top-down LL(k) parsers with the tions of the input (GLL and GLR) because such actions may power of a GLR-like mechanism to make parsing decisions. never really take place [17]. (Though DParser [24] supports The critical innovation is to move grammar analysis to parse- “final” actions when the programmer is certain a reduction is time, which lets ALL(*) handle any non-left-recursive context- part of an unambiguous final parse.) Without side effects, ac- free grammar. ALL(*) is O(n4) in theory but consistently per- tions must buffer data for all interpretations in immutable data forms linearly on grammars used in practice, outperforming structures or provide undo actions.
    [Show full text]
  • Efficient Recursive Parsing
    Purdue University Purdue e-Pubs Department of Computer Science Technical Reports Department of Computer Science 1976 Efficient Recursive Parsing Christoph M. Hoffmann Purdue University, [email protected] Report Number: 77-215 Hoffmann, Christoph M., "Efficient Recursive Parsing" (1976). Department of Computer Science Technical Reports. Paper 155. https://docs.lib.purdue.edu/cstech/155 This document has been made available through Purdue e-Pubs, a service of the Purdue University Libraries. Please contact [email protected] for additional information. EFFICIENT RECURSIVE PARSING Christoph M. Hoffmann Computer Science Department Purdue University West Lafayette, Indiana 47907 CSD-TR 215 December 1976 Efficient Recursive Parsing Christoph M. Hoffmann Computer Science Department Purdue University- Abstract Algorithms are developed which construct from a given LL(l) grammar a recursive descent parser with as much, recursion resolved by iteration as is possible without introducing auxiliary memory. Unlike other proposed methods in the literature designed to arrive at parsers of this kind, the algorithms do not require extensions of the notational formalism nor alter the grammar in any way. The algorithms constructing the parsers operate in 0(k«s) steps, where s is the size of the grammar, i.e. the sum of the lengths of all productions, and k is a grammar - dependent constant. A speedup of the algorithm is possible which improves the bound to 0(s) for all LL(l) grammars, and constructs smaller parsers with some auxiliary memory in form of parameters
    [Show full text]
  • Conflict Resolution in a Recursive Descent Compiler Generator
    LL(1) Conflict Resolution in a Recursive Descent Compiler Generator Albrecht Wöß, Markus Löberbauer, Hanspeter Mössenböck Johannes Kepler University Linz, Institute of Practical Computer Science, Altenbergerstr. 69, 4040 Linz, Austria {woess,loeberbauer,moessenboeck}@ssw.uni-linz.ac.at Abstract. Recursive descent parsing is restricted to languages whose grammars are LL(1), i.e., which can be parsed top-down with a single lookahead symbol. Unfortunately, many languages such as Java, C++, or C# are not LL(1). There- fore recursive descent parsing cannot be used or the parser has to make its deci- sions based on semantic information or a multi-symbol lookahead. In this paper we suggest a systematic technique for resolving LL(1) conflicts in recursive descent parsing and show how to integrate it into a compiler gen- erator (Coco/R). The idea is to evaluate user-defined boolean expressions, in order to allow the parser to make its parsing decisions where a one symbol loo- kahead does not suffice. Using our extended compiler generator we implemented a compiler front end for C# that can be used as a framework for implementing a variety of tools. 1 Introduction Recursive descent parsing [16] is a popular top-down parsing technique that is sim- ple, efficient, and convenient for integrating semantic processing. However, it re- quires the grammar of the parsed language to be LL(1), which means that the parser must always be able to select between alternatives with a single symbol lookahead. Unfortunately, many languages such as Java, C++ or C# are not LL(1) so that one either has to resort to bottom-up LALR(1) parsing [5, 1], which is more powerful but less convenient for semantic processing, or the parser has to resolve the LL(1) con- flicts using semantic information or a multi-symbol lookahead.
    [Show full text]
  • A Parsing Machine for Pegs
    A Parsing Machine for PEGs ∗ Sérgio Medeiros Roberto Ierusalimschy [email protected] [email protected] Department of Computer Science PUC-Rio, Rio de Janeiro, Brazil ABSTRACT parsing approaches. The PEG formalism gives a convenient Parsing Expression Grammar (PEG) is a recognition-based syntax for describing top-down parsers for unambiguous lan- foundation for describing syntax that renewed interest in guages. The parsers it describes can parse strings in linear top-down parsing approaches. Generally, the implementa- time, despite backtracking, by using a memoizing algorithm tion of PEGs is based on a recursive-descent parser, or uses called Packrat [1]. Although Packrat has guaranteed worst- a memoization algorithm. case linear time complexity, it also has linear space com- We present a new approach for implementing PEGs, based plexity, with a rather large constant. This makes Packrat on a virtual parsing machine, which is more suitable for impractical for parsing large amounts of data. pattern matching. Each PEG has a corresponding program LPEG [7, 11] is a pattern-matching tool for Lua, a dy- that is executed by the parsing machine, and new programs namically typed scripting language [6, 8]. LPEG uses PEGs are dynamically created and composed. The virtual machine to describe patterns instead of the more popular Perl-like is embedded in a scripting language and used by a pattern- "regular expressions" (regexes). Regexes are a more ad-hoc matching tool. way of describing patterns; writing a complex regex is more We give an operational semantics of PEGs used for pat- a trial and error than a systematic process, and their per- tern matching, then describe our parsing machine and its formance is very unpredictable.
    [Show full text]
  • Syntactic Analysis, Or Parsing, Is the Second Phase of Compilation: the Token File Is Converted to an Abstract Syntax Tree
    Syntactic Analysis Syntactic analysis, or parsing, is the second phase of compilation: The token file is converted to an abstract syntax tree. Analysis Synthesis Compiler Passes of input program of output program (front -end) (back -end) character stream Intermediate Lexical Analysis Code Generation token intermediate stream form Syntactic Analysis Optimization abstract intermediate syntax tree form Semantic Analysis Code Generation annotated target AST language 1 Syntactic Analysis / Parsing • Goal: Convert token stream to abstract syntax tree • Abstract syntax tree (AST): – Captures the structural features of the program – Primary data structure for remainder of analysis • Three Part Plan – Study how context-free grammars specify syntax – Study algorithms for parsing / building ASTs – Study the miniJava Implementation Context-free Grammars • Compromise between – REs, which can’t nest or specify recursive structure – General grammars, too powerful, undecidable • Context-free grammars are a sweet spot – Powerful enough to describe nesting, recursion – Easy to parse; but also allow restrictions for speed • Not perfect – Cannot capture semantics, as in, “variable must be declared,” requiring later semantic pass – Can be ambiguous • EBNF, Extended Backus Naur Form, is popular notation 2 CFG Terminology • Terminals -- alphabet of language defined by CFG • Nonterminals -- symbols defined in terms of terminals and nonterminals • Productions -- rules for how a nonterminal (lhs) is defined in terms of a (possibly empty) sequence of terminals
    [Show full text]
  • Lecture 3: Recursive Descent Limitations, Precedence Climbing
    Lecture 3: Recursive descent limitations, precedence climbing David Hovemeyer September 9, 2020 601.428/628 Compilers and Interpreters Today I Limitations of recursive descent I Precedence climbing I Abstract syntax trees I Supporting parenthesized expressions Before we begin... Assume a context-free struct Node *Parser::parse_A() { grammar has the struct Node *next_tok = lexer_peek(m_lexer); following productions on if (!next_tok) { the nonterminal A: error("Unexpected end of input"); } A → b C A → d E struct Node *a = node_build0(NODE_A); int tag = node_get_tag(next_tok); (A, C, E are if (tag == TOK_b) { nonterminals; b, d are node_add_kid(a, expect(TOK_b)); node_add_kid(a, parse_C()); terminals) } else if (tag == TOK_d) { What is the problem node_add_kid(a, expect(TOK_d)); node_add_kid(a, parse_E()); with the parse function } shown on the right? return a; } Limitations of recursive descent Recall: a better infix expression grammar Grammar (start symbol is A): A → i = A T → T*F A → E T → T/F E → E + T T → F E → E-T F → i E → T F → n Precedence levels: Nonterminal Precedence Meaning Operators Associativity A lowest Assignment = right E Expression + - left T Term * / left F highest Factor No Parsing infix expressions Can we write a recursive descent parser for infix expressions using this grammar? Parsing infix expressions Can we write a recursive descent parser for infix expressions using this grammar? No Left recursion Left-associative operators want to have left-recursive productions, but recursive descent parsers can’t handle left recursion
    [Show full text]
  • Parser Generation Bottom-Up Parsing LR Parsing Constructing LR Parser
    CS421 COMPILERS AND INTERPRETERS CS421 COMPILERS AND INTERPRETERS Parser Generation Bottom-Up Parsing • Main Problem: given a grammar G, how to build a top-down parser or a • Construct parse tree “bottom-up” --- from leaves to the root bottom-up parser for it ? • Bottom-up parsing always constructs right-most derivation • parser : a program that, given a sentence, reconstructs a derivation for that • Important parsing algorithms: shift-reduce, LR parsing sentence ---- if done sucessfully, it “recognize” the sentence • LR parser components: input, stack (strings of grammar symbols and states), • all parsers read their input left-to-right, but construct parse tree differently. driver routine, parsing tables. • bottom-up parsers --- construct the tree from leaves to root input: a1 a2 a3 a4 ...... an $ shift-reduce, LR, SLR, LALR, operator precedence stack s m LR Parsing output • top-down parsers --- construct the tree from root to leaves Xm .. recursive descent, predictive parsing, LL(1) s1 X1 s0 parsing Copyright 1994 - 2015 Zhong Shao, Yale University Parser Generation: Page 1 of 27 Copyright 1994 - 2015 Zhong Shao, Yale University Parser Generation: Page 2 of 27 CS421 COMPILERS AND INTERPRETERS CS421 COMPILERS AND INTERPRETERS LR Parsing Constructing LR Parser How to construct the parsing table and ? • A sequence of new state symbols s0,s1,s2,..., sm ----- each state ACTION GOTO sumarize the information contained in the stack below it. • basic idea: first construct DFA to recognize handles, then use DFA to construct the parsing tables ! different parsing table yield different LR parsers SLR(1), • Parsing configurations: (stack, remaining input) written as LR(1), or LALR(1) (s0X1s1X2s2...Xmsm , aiai+1ai+2...an$) • augmented grammar for context-free grammar G = G(T,N,P,S) is defined as G’ next “move” is determined by sm and ai = G’(T, N { S’}, P { S’ -> S}, S’) ------ adding non-terminal S’ and the • Parsing tables: ACTION[s,a] and GOTO[s,X] production S’ -> S, and S’ is the new start symbol.
    [Show full text]
  • CSCI 742 - Compiler Construction
    CSCI 742 - Compiler Construction Lecture 12 Recursive-Descent Parsers Instructor: Hossein Hojjat February 12, 2018 Recap: Predictive Parsers • Predictive Parser: Top-down parser that looks at the next few tokens and predicts which production to use • Efficient: no need for backtracking, linear parsing time • Predictive parsers accept LL(k) grammars • L means “left-to-right” scan of input • L means leftmost derivation • k means predict based on k tokens of lookahead 1 Implementations Analogous to lexing: Recursive descent parser (manual) • Each non-terminal parsed by a procedure • Call other procedures to parse sub-nonterminals recursively • Typically implemented manually Table-driven parser (automatic) • Push-down automata: essentially a table driven FSA, plus stack to do recursive calls • Typically generated by a tool from a grammar specification 2 Making Grammar LL • Recall the left-recursive grammar: S ! S + E j E E ! num j (E) • Grammar is not LL(k) for any number of k • Left-recursion elimination: rewrite left-recursive productions to right-recursive ones S ! EE0 S ! S + E j E E0 ! +EE0 j E ! num j (E) E ! num j (E) 3 Making Grammar LL • Recall the grammar: S ! E + E j E E ! num j (E) • Grammar is not LL(k) for any number of k • Left-factoring: Factor common prefix E, add new non-terminal E0 for what follows that prefix S ! EE0 S ! E + E j E E0 ! +E j E ! num j (E) E ! num j (E) 4 Parsing with new grammar S ! EE0 E0 ! +E j E ! num j (E) Partly-derived String Lookahead parsed part unparsed part S ( (num)+num ) E E0 ( (num)+num ) (E)
    [Show full text]
  • 1 Top-Down Parsing
    Section - Top-Down Parsings: 1 Top-Down Parsing 1 Top-Down Parsing ❍ Top-down vs. bottom-up ● less powerful ● more complicated to generate intermediate code or perform semantic routines ● easier to implement, especially recursive descent ❍ Top-down parser ● builds the parse tree from the root down ● follows leftmost derivation; herefore, it is called LL(k) ● we always expand the topmost symbol on the stack (leftmost in derivation) ❍ Top-down procedure (k=1 lookahead) ● utilize stack memory ● start with pushing initial nonterminal S ● at any moment ❍ if a terminal is on the top of the stack ■ if it matches the incoming token, the terminal is popped and the token is con- sumed ■ error otherwise ❍ if a nonterminal is on the top of the stack ■ we need to replace it by one of its productions ■ must predict the correct one in a predictive parser (if more than one alternative) ■ errors possible in a predictive parser if none predicted ● successful termination ❍ empty stack and EOFtk incoming ❍ empty styacj is an error otherwise ❍ Some other properties ● actual program tokens are never on the stack ● the stack contains predicted tokens expected on input ● we must make correct predictions for efficiently solving alternatives 2003 Cezary Z Janikow 1 Section - Top-Down Parsings: 2 Left Recursion Example 1.1 Use the unambiguous expression grammar to top-down parse id+id*id. ❍ Problems to handle in top-down parsing ● left recursive productions (direct or indirect) ❍ infinite stack growth ❍ can always be handled ● non-deterministic productions (more than one production for a nonterminal) ❍ may be handled, or not, by left-factorization ❍ verified by First and Follow sets 2 Left Recursion ❍ Top-down parsers cannot handle left-recursion ● any direct left-recursion can be removed with equivalent grammar ● indirect left-recursions can be replaced by direct, which subsequently can be removed ❍ Removing direct left recursion: ● separate all left recursive from the other productions for each nonterminal ● A → Aα | Aβ | ..
    [Show full text]
  • Top-Down Parsing
    CS 4120 Introduction to Compilers Andrew Myers Cornell University Lecture 5: Top-down parsing 5 Feb 2016 Outline • More on writing CFGs • Top-down parsing • LL(1) grammars • Transforming a grammar into LL form • Recursive-descent parsing - parsing made simple CS 4120 Introduction to Compilers 2 Where we are Source code (character stream) Lexical analysis Token stream if ( b == 0 ) a = b ; Syntactic Analysis if Parsing/build AST == = ; Abstract syntax tree (AST) b 0 a b Semantic Analysis CS 4120 Introduction to Compilers 3 Review of CFGs • Context-free grammars can describe programming-language syntax • Power of CFG needed to handle common PL constructs (e.g., parens) • String is in language of a grammar if derivation from start symbol to string • Ambiguous grammars a problem CS 4120 Introduction to Compilers 4 Top-down Parsing • Grammars for top-down parsing • Implementing a top-down parser (recursive descent parser) • Generating an abstract syntax tree CS 4120 Introduction to Compilers 5 Parsing Top-down S → E + S | E E → num | ( S ) Goal: construct a leftmost derivation of string while reading in token stream Partly-derived String Lookahead parsed part unparsed part S ( (1+2+(3+4))+5 → E+S ( (1+2+(3+4))+5 → (S) +S 1 (1+2+(3+4))+5 → (E+S)+S 1 (1+2+(3+4))+5 → (1+S)+S 2 (1+2+(3+4))+5 → (1+E+S)+S 2 (1+2+(3+4))+5 → (1+2+S)+S 2 (1+2+(3+4))+5 → (1+2+E)+S ( (1+2+(3+4))+5 → (1+2+(S))+S 3 (1+2+(3+4))+5 → (1+2+(E+S))+S 3 (1+2+(3+4))+5 6 Problem S → E + S | E E → num | ( S ) • Want to decide which production to apply based on next symbol (1) S
    [Show full text]