Compila(on* **0368/3133*(Semester*A,*2013/14)*
|
|
- Winifred Gaines
- 5 years ago
- Views:
Transcription
1 Compila(on 0368/3133(SemesterA,2013/14) Admin Lecture4:SyntaxAnalysis (Top/DownParsing) ModernCompilerDesign:Chapter2.2 NoamRinetzky Nextweek:Trubowicz101(Lawschool) Mobiles... Slidescredit:RomanManevich,MoolySagiv,JeffUllman,EranYahav 1 2 WhatisaCompiler? Acompilerisacomputerprogramthat transformssourcecodewri\enina programminglanguage(sourcelanguage) intoanotherlanguage(targetlanguage). Themostcommonreasonforwan(ngto transformsourcecodeistocreatean executableprogram. //Wikipedia( ConceptualStructureofaCompiler Compiler txt exe Frontend Semantic Backend Source Executable Representation text code Lexical Syntax Semantic Intermediate Code Analysis Analysis Analysis Representation Generation Parsing (IR) 3 words sentences 4 1
2 program(text( token(stream( Fromscanningtoparsing! ( LP Grammar: E... Id!!!Id! a... z ( LP ((23$+$7)$$x)$ syntax error 23 Num Lexical Analyzer + OP Parser Op() valid 7 Num ) RP OP x Id Abstract(Syntax(Tree( ) RP ContextFreeGrammars G=(V,T,P,S) V nonterminals(syntac(cvariables) T terminals(tokens) P deriva(onrules EachruleoftheformVt(T4V) S startsymbol Op(+) Id(b) Num(23) Num(7) 5 6 CFGterminology! CFGterminology S S;S S id:=e E id! E num! E E+E Symbols:! Terminals(tokens):;!:=!(!)id!num!print! Non:terminals:SEL Start(non:terminal:S Conven(on:thenon/terminalappearing inthefirstderiva(onrule Grammar(produc=ons((rules)( N μ Deriva(on/asequenceofreplacementsof non/terminalsusingthederiva(onrules Language/thesetofstringsofterminals derivablefromthestartsymbol Senten(alform/theresultofapar(al deriva(oninwhichtheremaybenon/ terminals 7 8 2
3 S S ; S id := E ; S id := id ; S id := id ; id := E id := id ; id := E + E ParseTree S S E S id := E Leomost/rightmostDeriva(on Leomostderiva(on alwaysexpandleomostnon/terminal Rightmostderiva(on Alwaysexpandrightmostnon/terminal id := id ; id := E + id id := id ; id := id + id x:= z ; y := x + z id := id ; E id + E id Allowsustodescribederiva(onbylis(ngthe sequenceofrules alwaysknowwhataruleisappliedto 9 10 LeomostDeriva(on Broadkindsofparsers x":="z;" y":="x"+"z" S t S;S S t id := E S S ; S id := E ; S id := id ; S id := id ; id := E id := id ; id := E + E id := id ; id := id + E id := id ; id := id + id x$:=$z$ ;$$y$$:=$$x$+$z$ E t id E + E E E ( E ) S t S;S S t id := E E t id S t id := E E t E + E E t id E t id 11 Parsersforarbitrarygrammars Earley smethod,cykmethod Usually,notusedinprac(ce(thoughmightchange) Top/Downparsers Constructparsetreeinatop/downma\er Findtheleomostderiva(on LinearBo\om/Upparsers Constructparsetreeinabo\om/upmanner Findtherightmostderiva(oninareverseorder 12 3
4 Intui(on:Top/DownParsing! Beginwithstartsymbol Guess theproduc(ons Checkifparsetreeyieldsuser'sprogram E ET E T T T+F T F F id F num F (E) Intui(on:Top/Downparsing! E T E Recall:Nonstandard precedence T T F F F +! 2!! 3! Intui(on:Top/Downparsing! Intui(on:Top/Downparsing! E ET E T T T+F T F F id F num F (E) Weneedthis ruletogetthe! E! E ET E T T T+F T F F id F num F (E) E! E T! +! 2!! 3! +! 2!! 3!
5 Intui(on:Top/Downparsing! Intui(on:Top/Downparsing! E ET E T T T+F T F F id F num F (E) E T! E E ET E T T T+F T F F id F num F (E) E T E T T! T F! +! 2!! 3! +! 2!! 3! Intui(on:Top/Downparsing! Intui(on:Top/Downparsing! E ET E T T T+F T F F id F num F (E) E T E E ET E T T T+F T F F id F num F (E) E T E T T T T F! F F F +! 2!! 3! +! 2!! 3!
6 Intui(on:Top/Downparsing! Intui(on:Top/Downparsing! E ET E T T T+F T F F id F num F (E) E T E E ET E T T T+F T F F id F num F (E) E T E T T T T F F F F F +! 2!! 3! +! 2!! 3! E ET E T T T+F T F F id F num F (E) Intui(on:Top/Downparsing! T E T E T Challengesintop/downparsing! Top/downparsingbeginswithvirtuallyno informa(on Beginswithjustthestartsymbol,which matcheseveryprogram Howcanweknowwhichproduc(onsto apply? F F F +! 2!! 3!
7 RecursiveDescent! Recursivedescent bool A(){ // A " A 1 A n pos = recordcurrentposition(); Blindexhaus(vesearch Goesoverallpossibleproduc(onrules Read&parseprefixesofinput Backtracksifguesseswrong Implementa(on Uses(possiblyrecursive)func(onsforevery produc(onrule Backtracks! rewind input for (i = 1; i n; i++){ if (A i ()) return true; rewindcurrent(pos); } return false; } bool A i (){ // A i = X 1 X 2 X k for (j=1; j k; j++) if (X j is a terminal) if (X j == current) match(current); else return false; else if (! X j ()) return false; return true; } current 25 token(stream( ( LP ( LP 23 Num + OP 7 Num ) RP OP x Id ) RP 26 Example Grammar E"T T+E T"int intt (E) Input:(5) Tokenstream:LPintRP Problem:LeoRecursion E E/term term inte(){ returne()&&match(token( / ))&&term(); } # Whathappenswiththisprocedure? # Recursivedescentparserscannothandleleo/recursivegrammars p. 127!
8 Leorecursionremoval p. 130! Challengesintop/downparsing! L(G 1 )=β,βα,βαα,βααα, L(G 2 )=same N Nα β E E/term term N βn N αn ε G 1 G 2 # Forour3 rd example: Canbedonealgorithmically. Problem:grammarbecomes mangledbeyondrecogni(on! E termte term TE >termte ε Top/downparsingbeginswithvirtuallyno informa(on Beginswithjustthestartsymbol,which matcheseveryprogram Howcanweknowwhichproduc(onsto apply? Wanted:Top/Downparsingwithout backtracking Predic(veparsing! GivenagrammarGandawordwderivewusingG Applyproduc(ontoleomostnonterminal Pickproduc(onrulebasedonnextinputtoken Generalgrammar Morethanoneop(onforchoosingthenext produc(onbasedonatoken Restrictedgrammars(LL) Knowexactlywhichsingleruletoapplybasedon Nonterminal Next(k)tokens(lookahead) Booleanexpressionsexample! E LIT (E OP E) not E LIT true false OP and or xor not ( not true or false )
9 Booleanexpressionsexample! E LIT (E OP E) not E LIT true false OP and or xor produc(onto applyknownfrom nexttoken! not ( not true or false ) E Problem:produc(onswithcommonprefix! term ID ID[expr] Cannottellwhichruletousebasedonlookahead(ID) E => not E => not ( E OP E ) => not ( not E OP E ) => not ( not LIT OP E ) => not ( not true OP E ) => not ( not true or E ) => not ( not true or LIT ) => not ( not true or false ) not E ( E OP E ) not LIT or LIT true false Solu(on:leofactoring RewritethegrammartobeinLL(1) term ID ID[expr] Leofactoring anotherexample! S ifethenselses ifethens T term IDaoer_ID Aoer_ID [expr] ε S ifethenss T S elses ε Intui(on:justlikefactoringxy+xzintox(y+z)
10 LL(k)Parsers LL(k)parsingviapushdown automataandpredic(ontable! Predic(veparser Canbegeneratedautoma(cally Doesnotuserecursion Efficient Incontrast,recursivedescent Manualconstruc(on Recursive Expensive 37 Pushdownautomatonuses Predic(onstack Inputtokenstream Transi(ontable nonterminalsxtokens/>produc(onalterna(ve EntryindexedbynonterminalNandtokent containsthealterna(veofnthatmustbe predicatedwhencurrentinputstartswitht 38 Nonterminals Exampletransi(ontable! (1) E LIT (2) E ( E OP E ) (3) E not E (4) LIT true (5) LIT false (6) OP and (7) OP or (8) OP xor (! )! not! true! false! and! or! xor!! $! E LIT 4 5 Input tokens OP Which!rule! should!be!used! Non/RecursivePredic(veParser! Stack! X! Y! Z! $! a! +! Predic(veParsing program! Parsing Table! b! $! Output! Table
11 LL(k)parsingviapushdown automataandpredic(ontable! Twopossiblemoves Predic(on WhentopofstackisnonterminalN,popN,lookuptable[N,t]. Iftable[N,t]isnotempty,pushtable[N,t]onpredic(onstack, otherwise syntaxerror Match Whentopofpredic(onstackisaterminalT,mustbeequalto nextinputtokent.if(t==t),poptandconsumet.if(t T) syntaxerror Parsingterminateswhenpredic(onstackisempty Ifinputisemptyatthatpoint,success.Otherwise, syntaxerror Runningparserexample! aacbb$ A t aab c Input!suffix! Stack!content! Move! aacbb$ A$ predict(a,a)=ataab aacbb$ aab$ match(a,a) acbb$ Ab$ predict(a,a)=ataab acbb$ aabb$ match(a,a) cbb$ Abb$ predict(a,c)=atc cbb$ cbb$ match(c,c) bb$ bb$ match(b,b) b$ b$ match(b,b) $ $ match($,$) success 41 a! b! c! A AtaAb Atc 42 FIRSTsets FIRST(α)={t α"tβ} {X" } FIRST(α)=allterminalsthatαcanappearas firstinsomederiva(onforα + ifcanbederivedfromx Example: FIRST(LIT)={true,false} FIRST((EOPE))={ ( } FIRST(notE)={not} 43 Compu(ngFIRSTsets! FIRST(t)={t}// t nonterminal FIRST(X)if X" or X"A 1..A k and FIRST(A i )i=1 k FIRST(α) FIRST(X)if X"A 1..A k αand FIRST(A i )i=1 k 44 11
12 12 FIRSTsetscomputa(onexample! STMT ifexprthenstmt whileexprdostmt EXPR; EXPR TERM zero?term notexpr ++id //id TERM id constant! TERM! EXPR! STMT! 45 1.Ini(aliza(on! TERM! EXPR! STMT! id constant! zero? Not ++ //! if while! 46 STMT ifexprthenstmt whileexprdostmt EXPR; EXPR TERM zero?term notexpr ++id //id TERM id constant! TERM! EXPR! STMT! id constant! zero? Not ++ //! if while! zero? Not ++ //! 47 2.Iterate STMT ifexprthenstmt whileexprdostmt EXPR; EXPR TERM zero?term notexpr ++id //id TERM id constant! 2.Iterate2! TERM! EXPR! STMT! id constant! zero? Not ++ //! if while! id constant!! zero? Not ++ //! 48 STMT ifexprthenstmt whileexprdostmt EXPR; EXPR TERM/>id zero?term notexpr ++id //id TERM id constant!
13 2.Iterate3 fixed/point! FOLLOWsets p. 189! STMT ifexprthenstmt whileexprdostmt EXPR; EXPR TERM zero?term notexpr ++id //id TERM id constant! STMT! if while! zero? Not ++ //! id constant! EXPR! zero? Not ++ //! id constant!! TERM! id constant! FOLLOW(X)={t S" αxtβ} FOLLOW(X)=setoftokensthatcanimmediatelyfollowXin somesenten(alform NOTrelatedtowhatcanbederivedfromX Intui(on:X"AB FIRST(B) FOLLOW(A) FOLLOW(B) FOLLOW(X) IfB" εthenfollow(a) FOLLOW(X) FOLLOWsets:Constraints $ FOLLOW(S) FIRST(β) { } FOLLOW(X) ForeachA"αXβ FOLLOW(A) FOLLOW(X) ForeachA"αXβand FIRST(β) Example:FOLLOWsets E"TX X"+E T"(E) intyy"t Terminal! +! (!! )! int! FOLLOW int,( int,( int,( _,),$,),+,$ Non.! Term.! E! T! X! Y! FOLLOW ),$ +,),$ $,) _,),$
14 A"α Predic(onTable Problem:NonLLGrammars S Aab A a ε T[A,t]=αift FIRST(α) T[A,t]=αif FIRST(α)andt FOLLOW(A) tcanalsobe$ Tisnotwelldefined!thegrammarisnotLL(1) bools(){ returna()&&match(token( a ))&&match(token( b )); } boola(){ returnmatch(token( a )) true; } # Whathappensforinput ab? # Whathappensifyoufliporderofalterna(vesandtry aab? Problem:NonLLGrammars Solu(on:subs(tu(on S Aab A a ε S Aab A a ε FIRST(S)={a} FIRST(A)={aε} FOLLOW(S)={$} FOLLOW(A)={a} S aab ab Subs(tuteAinS FIRST/FOLLOWconflict S aaoer_a aoer_a ab b Leofactoring
15 LL(k)grammars AgrammarisLL(k)ifitcanbederivedvia: Top/downderiva(on Scanningtheinputfromleotoright(L) Producingtheleomostderiva(on(L) Withlookaheadofktokens(k) Tiswelldefined AlanguageissaidtobeLL(k)whenithasan LL(k)grammar LL(k)grammars AgrammarisnotLL(k)ifitis Ambiguous Leorecursive Notleofactored EarleyParsing Dynamicprogramming InventedbyEarley[PhD.1968] HandlesarbitraryCFG Canhandleambiguousgrammars ComplexityO(N 3 )whenn= input Usesdynamicprogramming Compactlyencodesambiguity 59 BreakaproblemPintosubproblemsP 1 P k SolvePbycombiningsolu(onsforP 1 P k Memo/ize(store)solu(onstosubproblems insteadofre/computa(on Bellman/Fordshortestpathalgorithm Sol(x,y,i)=minimumof Sol(x,y,i/1) Sol(t,y,i/1)+weight(x,t)foredges(x,t) 60 15
16 EarleyParsing Dynamicprogrammingimplementa(onofa recursivedescentparser S[N+1]Sequenceofsetsof Earleystates N= INPUT Earleystate(item)sisasenten(alform+auxinfo S[i]Allparsetreethatcanbeproduced(bya RDP)aoerreadingthefirstitokens S[i+1]builtusingS[0] S[i] EarleyStates s=<cons(tuent,back> cons(tuent(do\edrule)fora"αβ A" αβpredicatedcons(tuents A"α βin/progresscons(tuents A"αβ completedcons(tuents backpreviousearlystateinderiva(on EarleyParser Input=x[1 N] S[0]=<E " E,0>;S[1]= S[N]={} fori=0...ndo un(ls[i]doesnotchangedo foreachs S[i] ifs=<a" a,b>anda=x[i+1]then S[i+1]=S[i+1] {<A" a,b>}//scan ifs=<a" X,b>andX"αthen S[i]=S[i] {<X" α,i>}//predict ifs=<a",b>and<x" A,k> S[b]then S[i]=S[i] {<X" A,k>}//complete S0 S E,0 E E + E,0 E n,0 Example n + n S1 S2 S3 E n, 0 S E, 0 E E +E,0 E E + E,0 E E + E,2 E n,2 E n, 2 E E + E, 0 E E +E,2 S E, 0 FIGURE 1. Earley sets for the grammar E E + E n and the input n + n.itemsinboldareoneswhichcorrespondtothe input s derivation
THEORY OF COMPILATION
Lecture 04 Syntax analysis: top-down and bottom-up parsing THEORY OF COMPILATION EranYahav 1 You are here Compiler txt Source Lexical Analysis Syntax Analysis Parsing Semantic Analysis Inter. Rep. (IR)
More informationSyntax Analysis Part III
Syntax Analysis Part III Chapter 4: Top-Down Parsing Slides adapted from : Robert van Engelen, Florida State University Eliminating Ambiguity stmt if expr then stmt if expr then stmt else stmt other The
More informationCS415 Compilers Syntax Analysis Top-down Parsing
CS415 Compilers Syntax Analysis Top-down Parsing These slides are based on slides copyrighted by Keith Cooper, Ken Kennedy & Linda Torczon at Rice University Announcements Midterm on Thursday, March 13
More informationCSE302: Compiler Design
CSE302: Compiler Design Instructor: Dr. Liang Cheng Department of Computer Science and Engineering P.C. Rossin College of Engineering & Applied Science Lehigh University February 27, 2007 Outline Recap
More informationSyntax Analysis Part I
1 Syntax Analysis Part I Chapter 4 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2013 2 Position of a Parser in the Compiler Model Source Program Lexical Analyzer
More informationSyntactic Analysis. Top-Down Parsing
Syntactic Analysis Top-Down Parsing Copyright 2015, Pedro C. Diniz, all rights reserved. Students enrolled in Compilers class at University of Southern California (USC) have explicit permission to make
More informationTop-Down Parsing and Intro to Bottom-Up Parsing
Predictive Parsers op-down Parsing and Intro to Bottom-Up Parsing Lecture 7 Like recursive-descent but parser can predict which production to use By looking at the next few tokens No backtracking Predictive
More informationIntroduction to Bottom-Up Parsing
Outline Introduction to Bottom-Up Parsing Review LL parsing Shift-reduce parsing he LR parsing algorithm Constructing LR parsing tables Compiler Design 1 (2011) 2 op-down Parsing: Review op-down parsing
More informationIntroduction to Bottom-Up Parsing
Introduction to Bottom-Up Parsing Outline Review LL parsing Shift-reduce parsing The LR parsing algorithm Constructing LR parsing tables Compiler Design 1 (2011) 2 Top-Down Parsing: Review Top-down parsing
More informationCompiler Principles, PS4
Top-Down Parsing Compiler Principles, PS4 Parsing problem definition: The general parsing problem is - given set of rules and input stream (in our case scheme token input stream), how to find the parse
More informationIntroduction to Bottom-Up Parsing
Outline Introduction to Bottom-Up Parsing Review LL parsing Shift-reduce parsing he LR parsing algorithm Constructing LR parsing tables 2 op-down Parsing: Review op-down parsing expands a parse tree from
More informationn Top-down parsing vs. bottom-up parsing n Top-down parsing n Introduction n A top-down depth-first parser (with backtracking)
Announcements n Quiz 1 n Hold on to paper, bring over at the end n HW1 due today n HW2 will be posted tonight n Due Tue, Sep 18 at 2pm in Submitty! n Team assignment. Form teams in Submitty! n Top-down
More informationSyntax Analysis Part I
1 Syntax Analysis Part I Chapter 4 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2013 2 Position of a Parser in the Compiler Model Source Program Lexical Analyzer
More informationIntroduction to Bottom-Up Parsing
Introduction to Bottom-Up Parsing Outline Review LL parsing Shift-reduce parsing The LR parsing algorithm Constructing LR parsing tables 2 Top-Down Parsing: Review Top-down parsing expands a parse tree
More informationSyntax Analysis: Context-free Grammars, Pushdown Automata and Parsing Part - 3. Y.N. Srikant
Syntax Analysis: Context-free Grammars, Pushdown Automata and Part - 3 Department of Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler
More informationCompiling Techniques
Lecture 5: Top-Down Parsing 26 September 2017 The Parser Context-Free Grammar (CFG) Lexer Source code Scanner char Tokeniser token Parser AST Semantic Analyser AST IR Generator IR Errors Checks the stream
More informationExercises. Exercise: Grammar Rewriting
Exercises Text adapted from : Alessandro Artale, Free University of Bolzano Exercise: Grammar Rewriting Consider the following grammar for Boolean expressions: Bexp Bexp or Bterm Bterm Bterm Bterm and
More informationCreating a Recursive Descent Parse Table
Creating a Recursive Descent Parse Table Recursive descent parsing is sometimes called LL parsing (Left to right examination of input, Left derivation) Consider the following grammar E TE' E' +TE' T FT'
More informationCONTEXT FREE GRAMMAR AND
CONTEXT FREE GRAMMAR AND PARSING STATIC ANALYSIS - PARSING Source language Scanner (lexical analysis) tokens Parser (syntax analysis) Syntatic structure Semantic Analysis (IC generator) Syntatic/sema ntic
More informationCMSC 330: Organization of Programming Languages. Pushdown Automata Parsing
CMSC 330: Organization of Programming Languages Pushdown Automata Parsing Chomsky Hierarchy Categorization of various languages and grammars Each is strictly more restrictive than the previous First described
More informationLL(1) Grammar and parser
Crafting a Compiler with C (XI) 資科系 林偉川 LL(1) Grammar and parser LL(1) grammar is the class of CFG and is suitable for RDP. Define LL(1) parsers which use an LL(1) parse table rather than recursive procedures
More informationAnnouncement: Midterm Prep
Announcement: Midterm Prep Midterm is Tuesday, 3/13 at 11 in three classrooms - Last name A-C Van Vleck B115 - Last name D-J Van Vleck B135 - Last name K-Z CS1240 List of topics Up to and including lecture
More informationComputing if a token can follow
Computing if a token can follow first(b 1... B p ) = {a B 1...B p... aw } follow(x) = {a S......Xa... } There exists a derivation from the start symbol that produces a sequence of terminals and nonterminals
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 7: LL(1) Parsing Zheng (Eddy) Zhang Rutgers University February 7, 2018 Class Information Homework 3 will be posted this coming Monday. 2 Review: Top-Down
More informationBottom-up syntactic parsing. LR(k) grammars. LR(0) grammars. Bottom-up parser. Definition Properties
Course 9-10 1 Bottom-up syntactic parsing Bottom-up parser LR(k) grammars Definition Properties LR(0) grammars Characterization theorem for LR(0) LR(0) automaton 2 a 1... a i... a n # X 1 X 1 Control Parsing
More informationContext free languages
Context free languages Syntatic parsers and parse trees E! E! *! E! (! E! )! E + E! id! id! id! 2 Context Free Grammars The CF grammar production rules have the following structure X α being X N and α
More informationContext-Free Grammars (and Languages) Lecture 7
Context-Free Grammars (and Languages) Lecture 7 1 Today Beyond regular expressions: Context-Free Grammars (CFGs) What is a CFG? What is the language associated with a CFG? Creating CFGs. Reasoning about
More informationCompiling Techniques
Lecture 5: Top-Down Parsing 6 October 2015 The Parser Context-Free Grammar (CFG) Lexer Source code Scanner char Tokeniser token Parser AST Semantic Analyser AST IR Generator IR Errors Checks the stream
More informationLecture 11 Context-Free Languages
Lecture 11 Context-Free Languages COT 4420 Theory of Computation Chapter 5 Context-Free Languages n { a b : n n { ww } 0} R Regular Languages a *b* ( a + b) * Example 1 G = ({S}, {a, b}, S, P) Derivations:
More informationSyntax Analysis Part I. Position of a Parser in the Compiler Model. The Parser. Chapter 4
1 Syntax Analysis Part I Chapter 4 COP5621 Compiler Construction Copyright Robert van ngelen, Flora State University, 2007 Position of a Parser in the Compiler Model 2 Source Program Lexical Analyzer Lexical
More informationParsing -3. A View During TD Parsing
Parsing -3 Deterministic table-driven parsing techniques Pictorial view of TD and BU parsing BU (shift-reduce) Parsing Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1) Problems with
More informationBottom-up syntactic parsing. LR(k) grammars. LR(0) grammars. Bottom-up parser. Definition Properties
Course 8 1 Bottom-up syntactic parsing Bottom-up parser LR(k) grammars Definition Properties LR(0) grammars Characterization theorem for LR(0) LR(0) automaton 2 a 1... a i... a n # X 1 X 1 Control Parsing
More informationAmbiguity, Precedence, Associativity & Top-Down Parsing. Lecture 9-10
Ambiguity, Precedence, Associativity & Top-Down Parsing Lecture 9-10 (From slides by G. Necula & R. Bodik) 2/13/2008 Prof. Hilfinger CS164 Lecture 9 1 Administrivia Team assignments this evening for all
More informationCompiler Principles, PS7
Top-Down Parsing Compiler Principles, PS7 Parsing problem definition: The general parsing problem is - given set of rules and input stream (in our case scheme token input stream), how to find the parse
More informationParsing Algorithms. CS 4447/CS Stephen Watt University of Western Ontario
Parsing Algorithms CS 4447/CS 9545 -- Stephen Watt University of Western Ontario The Big Picture Develop parsers based on grammars Figure out properties of the grammars Make tables that drive parsing engines
More informationFollow sets. LL(1) Parsing Table
Follow sets. LL(1) Parsing Table Exercise Introducing Follow Sets Compute nullable, first for this grammar: stmtlist ::= ε stmt stmtlist stmt ::= assign block assign ::= ID = ID ; block ::= beginof ID
More informationBottom-up syntactic parsing. LR(k) grammars. LR(0) grammars. Bottom-up parser. Definition Properties
Course 8 1 Bottom-up syntactic parsing Bottom-up parser LR(k) grammars Definition Properties LR(0) grammars Characterization theorem for LR(0) LR(0) automaton 2 a 1... a i... a n # X 1 X 1 Control Parsing
More informationSyntactical analysis. Syntactical analysis. Syntactical analysis. Syntactical analysis
Context-free grammars Derivations Parse Trees Left-recursive grammars Top-down parsing non-recursive predictive parsers construction of parse tables Bottom-up parsing shift/reduce parsers LR parsers GLR
More informationPredictive parsing as a specific subclass of recursive descent parsing complexity comparisons with general parsing
Plan for Today Recall Predictive Parsing when it works and when it doesn t necessary to remove left-recursion might have to left-factor Error recovery for predictive parsers Predictive parsing as a specific
More informationSyntax Analysis - Part 1. Syntax Analysis
Syntax Analysis Outline Context-Free Grammars (CFGs) Parsing Top-Down Recursive Descent Table-Driven Bottom-Up LR Parsing Algorithm How to Build LR Tables Parser Generators Grammar Issues for Programming
More informationEXAM. CS331 Compiler Design Spring Please read all instructions, including these, carefully
EXAM Please read all instructions, including these, carefully There are 7 questions on the exam, with multiple parts. You have 3 hours to work on the exam. The exam is open book, open notes. Please write
More informationLR2: LR(0) Parsing. LR Parsing. CMPT 379: Compilers Instructor: Anoop Sarkar. anoopsarkar.github.io/compilers-class
LR2: LR(0) Parsing LR Parsing CMPT 379: Compilers Instructor: Anoop Sarkar anoopsarkar.github.io/compilers-class Parsing - Roadmap Parser: decision procedure: builds a parse tree Top-down vs. bottom-up
More informationCompiling Techniques
Lecture 6: 9 October 2015 Announcement New tutorial session: Friday 2pm check ct course webpage to find your allocated group Table of contents 1 2 Ambiguity s Bottom-Up Parser A bottom-up parser builds
More informationSyntax Directed Transla1on
Syntax Directed Transla1on Syntax Directed Transla1on CMPT 379: Compilers Instructor: Anoop Sarkar anoopsarkar.github.io/compilers-class Syntax directed Translation Models for translation from parse trees
More informationThe Parser. CISC 5920: Compiler Construction Chapter 3 Syntactic Analysis (I) Grammars (cont d) Grammars
The Parser CISC 5920: Compiler Construction Chapter 3 Syntactic Analysis (I) Arthur. Werschulz Fordham University Department of Computer and Information Sciences Copyright c Arthur. Werschulz, 2017. All
More informationComputer Science 160 Translation of Programming Languages
Computer Science 160 Translation of Programming Languages Instructor: Christopher Kruegel Top-Down Parsing Top-down Parsing Algorithm Construct the root node of the parse tree, label it with the start
More informationCompiler Construction Lent Term 2015 Lectures (of 16)
Compiler Construction Lent Term 2015 Lectures 13 --- 16 (of 16) 1. Return to lexical analysis : application of Theory of Regular Languages and Finite Automata 2. Generating Recursive descent parsers 3.
More informationCA Compiler Construction
CA4003 - Compiler Construction Bottom Up Parsing David Sinclair Bottom Up Parsing LL(1) parsers have enjoyed a bit of a revival thanks to JavaCC. LL(k) parsers must predict which production rule to use
More informationCompiler Construction Lent Term 2015 Lectures (of 16)
Compiler Construction Lent Term 2015 Lectures 13 --- 16 (of 16) 1. Return to lexical analysis : application of Theory of Regular Languages and Finite Automata 2. Generating Recursive descent parsers 3.
More informationContext-Free Grammar
Context-Free Grammar CFGs are more powerful than regular expressions. They are more powerful in the sense that whatever can be expressed using regular expressions can be expressed using context-free grammars,
More informationEXAM. CS331 Compiler Design Spring Please read all instructions, including these, carefully
EXAM Please read all instructions, including these, carefully There are 7 questions on the exam, with multiple parts. You have 3 hours to work on the exam. The exam is open book, open notes. Please write
More informationAutomata Theory CS F-08 Context-Free Grammars
Automata Theory CS411-2015F-08 Context-Free Grammars David Galles Department of Computer Science University of San Francisco 08-0: Context-Free Grammars Set of Terminals (Σ) Set of Non-Terminals Set of
More informationTop-Down Parsing, Part II
op-down Parsing, Part II Announcements Programming Project 1 due Friday, 11:59PM Office hours every day until then. ubmission instructions will be emailed out tonight. Where We Are ource Code Lexical Analysis
More informationTalen en Compilers. Johan Jeuring , period 2. October 29, Department of Information and Computing Sciences Utrecht University
Talen en Compilers 2015-2016, period 2 Johan Jeuring Department of Information and Computing Sciences Utrecht University October 29, 2015 12. LL parsing 12-1 This lecture LL parsing Motivation Stack-based
More informationINF5110 Compiler Construction
INF5110 Compiler Construction Parsing Spring 2016 1 / 84 Overview First and Follow set: general concepts for grammars textbook looks at one parsing technique (top-down) [Louden, 1997, Chap. 4] before studying
More informationCS153: Compilers Lecture 5: LL Parsing
CS153: Compilers Lecture 5: LL Parsing Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Proj 1 out Due Thursday Sept 20 (2 days away) Proj 2 out Due Thursday Oct 4 (16 days away)
More informationBottom up parsing. General idea LR(0) SLR LR(1) LALR To best exploit JavaCUP, should understand the theoretical basis (LR parsing);
Bottom up parsing General idea LR(0) SLR LR(1) LALR To best exploit JavaCUP, should understand the theoretical basis (LR parsing); 1 Top-down vs Bottom-up Bottom-up more powerful than top-down; Can process
More informationShift-Reduce parser E + (E + (E) E [a-z] In each stage, we shift a symbol from the input to the stack, or reduce according to one of the rules.
Bottom-up Parsing Bottom-up Parsing Until now we started with the starting nonterminal S and tried to derive the input from it. In a way, this isn t the natural thing to do. It s much more logical to start
More informationProf. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan
Language Processing Systems Prof. Mohamed Hamada Software Engineering La. The University of izu Japan Syntax nalysis (Parsing) 1. Uses Regular Expressions to define tokens 2. Uses Finite utomata to recognize
More informationCompiler Design. Spring Syntactic Analysis. Sample Exercises and Solutions. Prof. Pedro C. Diniz
Compiler Design Spring 2015 Syntactic Analysis Sample Exercises and Solutions Prof. Pedro C. Diniz USC / Information Sciences Institute 4676 Admiralty Way, Suite 1001 Marina del Rey, California 90292 pedro@isi.edu
More informationCSC 4181Compiler Construction. Context-Free Grammars Using grammars in parsers. Parsing Process. Context-Free Grammar
CSC 4181Compiler Construction Context-ree Grammars Using grammars in parsers CG 1 Parsing Process Call the scanner to get tokens Build a parse tree from the stream of tokens A parse tree shows the syntactic
More informationTheory of Computation - Module 3
Theory of Computation - Module 3 Syllabus Context Free Grammar Simplification of CFG- Normal forms-chomsky Normal form and Greibach Normal formpumping lemma for Context free languages- Applications of
More informationParsing. Unger s Parser. Laura Kallmeyer. Winter 2016/17. Heinrich-Heine-Universität Düsseldorf 1 / 21
Parsing Unger s Parser Laura Kallmeyer Heinrich-Heine-Universität Düsseldorf Winter 2016/17 1 / 21 Table of contents 1 Introduction 2 The Parser 3 An Example 4 Optimizations 5 Conclusion 2 / 21 Introduction
More informationCompiling Techniques
Lecture 3: Introduction to 22 September 2017 Reminder Action Create an account and subscribe to the course on piazza. Coursework Starts this afternoon (14.10-16.00) Coursework description is updated regularly;
More informationLecture 11 Sections 4.5, 4.7. Wed, Feb 18, 2009
The s s The s Lecture 11 Sections 4.5, 4.7 Hampden-Sydney College Wed, Feb 18, 2009 Outline The s s 1 s 2 3 4 5 6 The LR(0) Parsing s The s s There are two tables that we will construct. The action table
More informationCompiler Construction Lectures 13 16
Compiler Construction Lectures 13 16 Lent Term, 2013 Lecturer: Timothy G. Griffin 1 Generating Lexical Analyzers Source Program Lexical Analyzer tokens Parser Lexical specification Scanner Generator LEX
More informationCompiling Techniques
Lecture 7: Abstract Syntax 13 October 2015 Table of contents Syntax Tree 1 Syntax Tree Semantic Actions Examples Abstract Grammar 2 Internal Representation AST Builder 3 Visitor Processing Semantic Actions
More informationΕΠΛ323 - Θεωρία και Πρακτική Μεταγλωττιστών. Lecture 7a Syntax Analysis Elias Athanasopoulos
ΕΠΛ323 - Θεωρία και Πρακτική Μεταγλωττιστών Lecture 7a Syntax Analysis Elias Athanasopoulos eliasathan@cs.ucy.ac.cy Operator-precedence Parsing A class of shiq-reduce parsers that can be writen by hand
More informationUNIT II REGULAR LANGUAGES
1 UNIT II REGULAR LANGUAGES Introduction: A regular expression is a way of describing a regular language. The various operations are closure, union and concatenation. We can also find the equivalent regular
More informationSyntax Analysis (Part 2)
Syntax Analysis (Part 2) Martin Sulzmann Martin Sulzmann Syntax Analysis (Part 2) 1 / 42 Bottom-Up Parsing Idea Build right-most derivation. Scan input and seek for matching right hand sides. Terminology
More informationCFLs and Regular Languages. CFLs and Regular Languages. CFLs and Regular Languages. Will show that all Regular Languages are CFLs. Union.
We can show that every RL is also a CFL Since a regular grammar is certainly context free. We can also show by only using Regular Expressions and Context Free Grammars That is what we will do in this half.
More information5/10/16. Grammar. Automata and Languages. Today s Topics. Grammars Definition A grammar G is defined as G = (V, T, P, S) where:
Grammar Automata and Languages Grammar Prof. Mohamed Hamada oftware Engineering Lab. The University of Aizu Japan Regular Grammar Context-free Grammar Context-sensitive Grammar Left-linear Grammar right-linear
More informationBottom-Up Syntax Analysis
Bottom-Up Syntax Analysis Mooly Sagiv http://www.cs.tau.ac.il/~msagiv/courses/wcc13.html Textbook:Modern Compiler Design Chapter 2.2.5 (modified) 1 Pushdown automata Deterministic fficient Parsers Report
More informationBottom-Up Parsing. Ÿ rm E + F *idÿ rm E +id*idÿ rm T +id*id. Ÿ rm F +id*id Ÿ rm id + id * id
Bottom-Up Parsing Attempts to traverse a parse tree bottom up (post-order traversal) Reduces a sequence of tokens to the start symbol At each reduction step, the RHS of a production is replaced with LHS
More informationEDA045F: Program Analysis LECTURE 10: TYPES 1. Christoph Reichenbach
EDA045F: Program Analysis LECTURE 10: TYPES 1 Christoph Reichenbach In the last lecture... Performance Counters Challenges in Dynamic Performance Analysis Taint Analysis Binary Instrumentation 2 / 44 Types
More informationAdministrivia. Test I during class on 10 March. Bottom-Up Parsing. Lecture An Introductory Example
Administrivia Test I during class on 10 March. Bottom-Up Parsing Lecture 11-12 From slides by G. Necula & R. Bodik) 2/20/08 Prof. Hilfinger CS14 Lecture 11 1 2/20/08 Prof. Hilfinger CS14 Lecture 11 2 Bottom-Up
More informationEXAM. Please read all instructions, including these, carefully NAME : Problem Max points Points 1 10 TOTAL 100
EXAM Please read all instructions, including these, carefully There are 7 questions on the exam, with multiple parts. You have 3 hours to work on the exam. The exam is open book, open notes. Please write
More informationCompiler construction
Compiler construction Martin Steffen February 20, 2017 Contents 1 Abstract 1 1.1 Parsing.................................................. 1 1.1.1 First and follow sets.....................................
More informationCompilerconstructie. najaar Rudy van Vliet kamer 124 Snellius, tel rvvliet(at)liacs.
Compilerconstructie najaar 2012 http://www.liacs.nl/home/rvvliet/coco/ Rudy van Vliet kamer 124 Snellius, tel. 071-527 5777 rvvliet(at)liacs.nl werkcollege 9, dinsdag 27 november 2012 SLR Parsing / Backpatching
More informationParsing. Context-Free Grammars (CFG) Laura Kallmeyer. Winter 2017/18. Heinrich-Heine-Universität Düsseldorf 1 / 26
Parsing Context-Free Grammars (CFG) Laura Kallmeyer Heinrich-Heine-Universität Düsseldorf Winter 2017/18 1 / 26 Table of contents 1 Context-Free Grammars 2 Simplifying CFGs Removing useless symbols Eliminating
More informationDefinition: A grammar G = (V, T, P,S) is a context free grammar (cfg) if all productions in P have the form A x where
Recitation 11 Notes Context Free Grammars Definition: A grammar G = (V, T, P,S) is a context free grammar (cfg) if all productions in P have the form A x A V, and x (V T)*. Examples Problem 1. Given the
More informationINF5110 Compiler Construction
INF5110 Compiler Construction Spring 2017 1 / 330 Outline 1. Parsing First and follow sets Top-down parsing Bottom-up parsing References 2 / 330 INF5110 Compiler Construction Parsing Spring 2017 3 / 330
More informationh>p://lara.epfl.ch Compiler Construc/on 2011 CYK Algorithm and Chomsky Normal Form
h>p://lara.epfl.ch Compiler Construc/on 2011 CYK Algorithm and Chomsky Normal Form S à N ( N S) N ( N ) S S Parsing an Input N S) à S N ) N ( à ( N ) à ) 7 6 5 4 3 2 1 ambiguity N ( N ( N ) N ( N ) N (
More informationEng. Maha Talaat Page 1
El-Shorouk Academy Acad. Year : 2013 / 2014 Higher Institute for Computer & Term : 2nd Information Technology Year : 4th Computer Science Department Supervisor: Prof. Dr. Ahmed Abbassy Section contents:
More informationLanguages. Languages. An Example Grammar. Grammars. Suppose we have an alphabet V. Then we can write:
Languages A language is a set (usually infinite) of strings, also known as sentences Each string consists of a sequence of symbols taken from some alphabet An alphabet, V, is a finite set of symbols, e.g.
More informationCourse Script INF 5110: Compiler construction
Course Script INF 5110: Compiler construction INF5110, spring 2018 Martin Steffen ii Contents Contents 4 Parsing 1 4.1 Introduction to parsing........................ 1 4.2 Top-down parsing...........................
More informationCS 406: Bottom-Up Parsing
CS 406: Bottom-Up Parsing Stefan D. Bruda Winter 2016 BOTTOM-UP PUSH-DOWN AUTOMATA A different way to construct a push-down automaton equivalent to a given grammar = shift-reduce parser: Given G = (N,
More informationCYK Algorithm for Parsing General Context-Free Grammars
CYK Algorithm for Parsing General Context-Free Grammars Why Parse General Grammars Can be difficult or impossible to make grammar unambiguous thus LL(k) and LR(k) methods cannot work, for such ambiguous
More informationMA/CSSE 474 Theory of Computation
MA/CSSE 474 Theory of Computation CFL Hierarchy CFL Decision Problems Your Questions? Previous class days' material Reading Assignments HW 12 or 13 problems Anything else I have included some slides online
More informationLecture VII Part 2: Syntactic Analysis Bottom-up Parsing: LR Parsing. Prof. Bodik CS Berkley University 1
Lecture VII Part 2: Syntactic Analysis Bottom-up Parsing: LR Parsing. Prof. Bodik CS 164 -- Berkley University 1 Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient
More informationCS Pushdown Automata
Chap. 6 Pushdown Automata 6.1 Definition of Pushdown Automata Example 6.2 L ww R = {ww R w (0+1) * } Palindromes over {0, 1}. A cfg P 0 1 0P0 1P1. Consider a FA with a stack(= a Pushdown automaton; PDA).
More informationSyntax Analysis, VII The Canonical LR(1) Table Construction. Comp 412
COMP 412 FALL 2018 Syntax Analysis, VII The Canonical LR(1) Table Construction Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights
More information60-354, Theory of Computation Fall Asish Mukhopadhyay School of Computer Science University of Windsor
60-354, Theory of Computation Fall 2013 Asish Mukhopadhyay School of Computer Science University of Windsor Pushdown Automata (PDA) PDA = ε-nfa + stack Acceptance ε-nfa enters a final state or Stack is
More informationI 1 : {S S } I 2 : {S X ay, Y X } I 3 : {S Y } I 4 : {X b Y, Y X, X by, X c} I 5 : {X c } I 6 : {S Xa Y, Y X, X by, X c} I 7 : {X by } I 8 : {Y X }
Let s try building an SLR parsing table for another simple grammar: S XaY Y X by c Y X S XaY Y X by c Y X Canonical collection: I 0 : {S S, S XaY, S Y, X by, X c, Y X} I 1 : {S S } I 2 : {S X ay, Y X }
More informationLR(1) Parsers Part III Last Parsing Lecture. Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved.
LR(1) Parsers Part III Last Parsing Lecture Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. LR(1) Parsers A table-driven LR(1) parser looks like source code Scanner Table-driven Parser
More informationRecursive descent for grammars with contexts
39th International Conference on Current Trends in Theory and Practice of Computer Science Špindleruv Mlýn, Czech Republic Recursive descent parsing for grammars with contexts Ph.D. student, Department
More informationOutline. CS21 Decidability and Tractability. Machine view of FA. Machine view of FA. Machine view of FA. Machine view of FA.
Outline CS21 Decidability and Tractability Lecture 5 January 16, 219 and Languages equivalence of NPDAs and CFGs non context-free languages January 16, 219 CS21 Lecture 5 1 January 16, 219 CS21 Lecture
More informationMildly Context-Sensitive Grammar Formalisms: Embedded Push-Down Automata
Mildly Context-Sensitive Grammar Formalisms: Embedded Push-Down Automata Laura Kallmeyer Heinrich-Heine-Universität Düsseldorf Sommersemester 2011 Intuition (1) For a language L, there is a TAG G with
More informationChapter 1. Formal Definition and View. Lecture Formal Pushdown Automata on the 28th April 2009
Chapter 1 Formal and View Lecture on the 28th April 2009 Formal of PA Faculty of Information Technology Brno University of Technology 1.1 Aim of the Lecture 1 Define pushdown automaton in a formal way
More informationCISC4090: Theory of Computation
CISC4090: Theory of Computation Chapter 2 Context-Free Languages Courtesy of Prof. Arthur G. Werschulz Fordham University Department of Computer and Information Sciences Spring, 2014 Overview In Chapter
More information