0% found this document useful (0 votes)
11 views

Compiler Design

Compiler design quantum For btech fifth sem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
11 views

Compiler Design

Compiler design quantum For btech fifth sem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 89
pram sing renuisieD BY: Qyntum Publications® ‘Dai of Quantum Page Pvt Sanat, Ghaziabad 201010 . Phone 0120-10047 mal: pagequanrum Delhi Office: 18580, F © Au Ric: Reserve pf te paletion may be reread or tancmitd rr om by ony maa, witha! permison maiLcom _ Website: www.quantumpage cain ast Robtas Nagar, Shahdara, Delhi-1 10039 | Tromasan conned ins works derived fom sources] | Rteredtbe ruber efforthas been made to ensure | securacy, however nether the publisher nor the authors | franc the accuracy completes of any information ‘ub herein and nether the publisher nor the authors ‘hel be rsponle for any errors, omission, or damages sing out of use of this information. ler Design (CSIT : Sem-5) 1 Baiton » 2010-11 2 Bdition : 2011-12 5 Baiton + 2012-13, © Béition 2013-14 5° Réition : 2016-15 © Béition : 2015-16 7 Béition : 2016-17 8° Baiton : 2017-18, 9 Baiton : 2018-19 10° Béiion : 2019-20 11" Baition : 2080-21 (Thoroughly Revised Edition) Price: Rs. 21101-on Printed at Gia Piers, DOTS —<—<—==C ONTENTS ‘KCS-502/KIT-052: COMPILER DESIGN, UNIT; INTRODUCTION TO COMPILER (-1Cw1-310) Tass and pases, Bootstrapping, Bate state machines and regular ‘lpeeaions and their applitions to lea analy, Optimization ‘Ea toed Pottern Mathers implementation of excl analyze, {fxkalaneyzcr geneeator, LEX compiler, Formal grammar and thar application fo syntax analy BNP notation, ambiguly, YACC ‘The practic spencation of pogrom languages Context Re [Famumars, derivation ad patse tes, apabiitis of CEG LUNIT2; BASIC PARSING TECHNIQUES. 21Cw2-380) Taner, Sift reduce parsing operator precedence parsing top down parsing predictive parsers Avtomatic Construction o efficent Parser UR parsers, the canonical Collection of UR(O) items, covtocing SUR parsing ables, constructing Canonical LR parsing Uibten, Constructing LAUR parsing tables, using ambiguous ammars, an nutomatic parser generator, implementation of LR paring tables. UNIT; SYNTAX-DIRECTED TRANSLATION (@-1C13-270) ‘Staedireced Translation schemes, Implementation of Syntax ‘dete Translators nlermedote code poste notation Pane ee {eSymas tes, thee address code, quadruple & wipls, tarslation of assignment statements Boolean expressions, statements that alter the How of canto, posta tanlation anslation with op down passer Mote about Wanslaton. Array references in arithmetic ‘Expressions, procedures call declarations and case statements UNIT-4: SYMBOL TABLES. (1Ct04220 ata struct fr symbol tables repesenting scape infrmaton Run-Time Adminstration Implementation of simple stack Slezaton scheme, torage lcaton nck sated language Error Deeton Recovery: Leica Phase entry hse UNITS: CODE GENERATION (10105260 asg tus the Tapet Language: Address in the Trg! Code $s Hacks and Fow Craps, Opinuation of Basic Bork, Cae Generar Code opiate: Machine Iniandent Opin Lop optimization, DAG representation obi Boks, value ner and slab ans, Cloal Dat ow anys ‘SHORT QUESTIONS (6Q1C189-16¢) ‘SOLVED PAPERS (2015-1670 2018-19) ($P.1.CtwsP.13¢) Pert Parts Parer s Compiler jourdvcion to Compile © Phases and Passes uote apping ete State Machine and Regaar Expressions i ‘ht pean ene heal, Optimizatio of Da Based Patera Matchers Implementation of ese Azaleer Lexical Analyzer Generator, LEX Compiler Formal Gramoars and hele Application to Syatax ‘Analy, BNP Notation Ambiguity, YACC. The Syatatic Specification of Programming Languages ‘omest Pree Grammar «CFC, Dersation and Parse Teees, Copabiies of CFG 1-1 C(CSIT-Sem-5) 1-2C to 1-60 1-6C to 1-70 1-86 to L170 1-17€ to 1-220 1-220 to 1-280 1-25€ to 1-21C 1-a7€ t0 1-900 Introduction to | Introduction t Compiler 1 2C(CNIT Sem.) ‘Que Ld. ] Explain in detail the process of compilation. Ilustrate the output of each phase of compilation of the input tax bo erebroded” Taawer ‘Acompiler contains 6 phases which are a follows i, Phase 1 (Lexical analyz 4 Theloxical analyzer is also called seanner. 'b. Thelesical analyzer phase takes souree program as an input and separates characters of source language into groups of strings called token These tokens may be keywords identifiers operator symbols and punctuation symbols, AL Phase 2 (Syntax analyzer) ‘4 Thesyntax analyzer phase is also called parsing phase. 1b The syntax analyzer groups tokens together into syntactic © The output ofthis phase is parse tree. iil, Phase 3 (Semantic analyzer) 4 The somantic analyzer phase checks the source program for semantic errors and gathers type information fr subsequent code feneration phase, 'Reuses parse tree and symbol table to check whether the given program i semantically consistent with language definition ‘© The output ofthis phase is annotated syntax tree, iv. Phase 4 (Intermediate code generation) : 4 The intermediate code generation takes syntax tree as an input from semantic phase and generates intermediate cade b. Ttgenerates varity of code such a three address code, quadruple, triple CMT Sem-5) Introduction to Compiler | (Pans | Introduction to Introduction to Compiler, Phases and Passes. | Compiler ‘Long Answer Type and Medium Answer Type Questions ‘QuoLA, | Explain in detail the process of compilation. Illustrate the output of each phase of compilation of the input — cama ceeerovone ntrodactin to Compiler Phe and Passes newer 1-4C to1-2¢ | | Acompiler contains phases which are as follows stspping meee i. Phate t (Lexical analyzer): parc + Pat Sit Muti Hew Lie 4 Theleicalanalyeris als clled canner Zee Ee oa 1 Thelericl analyzer phase taker source program as an input and ek bate separates characters of soarse language into groups of tings ENB Patera Motehers called ken, «© These tokens may be keywords identifiers, operator symbols and {Implementation of. TATE to 1-220 punetuation symbols, Ue a Phase 2 (Syntax analyzes): ve Aer 7 4 Theoyalax analyzer phat is also called parsing phase The syntax analyzer groups tokens together into syntactic Part + Formal Gramars and 1-200 to 1-260 coe aot Sa The output ofthis phase i parse treo, iii, Phase 3 (Semantic analyzer) Anmbigaiy, VAC: 1-25C to 1-270 ‘The semantic analyzer phase checks the source program for semantic errs andgathers tye nfnmatio saben oe ‘The Syntactic Specification, 1-27€ to 1-300 | generation phase. 7 — oo 7 of Proprammiog Languages qcrramming Languages |b Tuses parse tre and symbol table to check whether the given Derivation and Parse Trees, rogram is semantically consistent with language def \ Capa of CF « Bae ‘The output ofthis phase is annotated syntax tee 1%. Phase 4 (Intermediate code generation) ‘The intermediate code generation takes syntax tree from semantic phase and generates intermediate code, generates variety of ode such as three address code, quadruple hom -quadrpl an input MC(CSTT-Sem.5) (ren LAC (CMT Sem) conte Don ela {weal aatvaer} — —s ‘Syntax analyser | = Etat Target program, Fig LL. ‘y. Phase 5 (Code optimization) : This phase is designed to improve the termediavecodeso tet the ultimate object program runs faster and takes les space vi. Phase 6 (Code generation) + ‘a Ttis the final phase for compiler. ‘Te generates the astembly code as target language. ‘cTn this phase, the address inthe binary code is translated from login adres Symbol table/table management: A symbol table is data structure ‘containing record that allows us to find the record foreach identifier ‘icky and to store or retrieve date from that record quickly. Error handler: The error handler is invoked when a flaw in the source program is detected. Compilation of Wsernbsen2" 1-4C(CMITSem.8) nrc Coie Onipa [es nr sdjetidgsudhouayeatyeg | EMO Pane | “Annotated syntax tree | habe tenon Intermed cte ‘pointed 2) Se Compiter Design = | — II == — | ‘Que TR | What are the typos of passes in compiler? ‘Knewer ‘Types of passer: 1. Single-pass compiler: ‘a Ine single-pass compiler, when a line source ie processed ite canned andthe tokens are extracted 1b. Then the syntax of the line is analyzed andthe tre strc, hme tables containing information about each token are bail 2 Multipars compiler: In mlti-pasrcompller it ean the inet sours ete es adaces rot modified form. then sans the edie frm rea second mudd form and san, ntl he abject orm prodaced Taw TS. ] Discwes the role of compiler writing tools Desri various compiler writing tools Taewer | Rote of compiler writing tools: eect for autosntie design of compilt 1 Compiter writing tool are vse f 2 Every tool uses specialized langue = iting tote are woed as debuggers version Manske erat eat ree gmat sa yotes directed tranation sa ae nmeiated with each node of parse te Te pradace se sien nodes inte te : verator These tolt take a collection of rales 4 Automatic codt Eom ofeach operation of thelntermedate ANSE ‘at dein pe tangunge fo target mackie - sine data ow eng wet oping he co Data fo oR che information about now values (rans) Bootetropping Quostions-Anewers “Long Answer Type and Medium Answer Type Questions | Gueia | Detine bootstrapping with the help of an exampl What ros compiler? How it ootsrapping of compiler done “Knewer | (Crome compiler: crosacompier ea compiler capable ofereating executable ‘ole for platform other than the one on which the compiler running Bootstrap Bootstrapping othe proctor of writing a compiler or assembler) in the source programming language that tintendto comple {ail minima cre wrt hecompler ingested nadir ee lle 1-TCICNIT Sem.) Compiler Desi seer a ae ae irre aco fr Source Tart. plemented ny me Fig 141. ‘ocrete anew language, for machine A create *C{ acompiler fo subset, Sof the desired language, 2, rin angusge A which ren on machine A. Language A maybe ‘smb language) B retan 1 hea "6 aon treaun ein in inf Fig 143. © Comite "Cf sing “Ci taobtan “Ci, compiler for language 1, which runs on machine A and produces code for machine A. chs Sch-s'ch ‘The proces ilastrated by the Tdagramsisclled bootstrapping and canbe summarized by the equation LAS ALA (ates LE J Inteodetion to Compiler LAC(CSIT Sem) [ParT-3) Fite State Machines and Regular Expressions and their "Apolcaton to Lexical Anat, Optimization of DEA ‘Based Pattern Matches Questions Answers ‘Long Answer Type and Medium Answer Type Questions GaeTET] What do you mean by regular expression ? Write the formal recursive definition ofa regular expression. Taawer 1. Regular expression is formula a special language that is sed for peciving simple classes of strings. 2. Atring is «sequence of symbols; for the purpose of most text-based Search techniques, a string is any sequence of alphanumeric characters {Teters, numbers, space, tab, and punctuation) fe definition of regular expression : Formal ree Formally, a regular expression isan algebraic notation for characterizing a tof striogs 1. Any terminal, i, the symbols belong to are regular expression. [Null etring (o,«) and null set (are also regular expression 2 If P and Q are two rogular expressions then the union of the two regular expressions denoted by P + Q is alo a regular expression 3. MPandQ aretwo regular expressions then their concatenation denoted boy PQ in ala a regular expression 4. IEP isa rogular expression then the iteration (rept denoted by Ps also a regular expression, LI Pisarogular expression then P, ia regular expression. 6 The expressions gt by repeated application of the rules fom (1) to (5) over are also regular expression, ‘Ques, ] Define and differentiate between DFA and NFA with an example. jon oF closure) ic fee have ony one senate abe determine ti Aa es poi rom some sate ec uesand represented at weQ Esco (Qe Ant of oc-empty ite tates = Asetofnoempty iit input sa p= Inia tate of DFA ‘Fe Anocempy finite stot inal tate 52Qurn@ sa senza do be non determinnic we hav ata Se onic same np sab rom sone a 1 Roatan Ste ntomata sete tples and represen 1 M=QE8.49F) sere, = Aset of non-empty Finite states ‘+ Initial state of NFA and member of @ FA non-empty finite set of final states and set of non-empty finite input symbls TOCOME A 1-10CCMT ems) “ pifterence between DFA and NFA: SNo| DFA £ = NPA stands for deverminitie finite Tt stands for non-deverministic automata ute tomann ‘Only one transition is pomble| More than one transition = from one state to anather on porsible from one state to same input symbol. ‘other on same inpat symbol “Transition function 5 is written | Transition function 6 written | 5x2 +g B:QaiEe lena —j __8: 0s ____ 2:0 te GIDEA ctransition snot posite | In NFA, ciransition pane [4_fnprecernten os | NP tin 5 DEA cana be cnvered into) NFA ean be conver iio aT = ‘Example: DFA forthe language tht contains the strings ending with NFA or the language L which accept al the strings in which the third symbol fom right end i alwayea over = lab) Oo -O= OO Fig. 16.3. member of Q Se ‘GeT | Eeplain Thompeon's construction with example ian _ a =] Qe Thompson's construction + mart 1 isan or asoring sear expen a ‘ Itistransition fanetion that takes astate om @and an input symbol from © and returns & fubset of The sis represented 35 BQ EVI 428 Following rules are defined fora regular expression asa basis forthe construction The NFA representing the empty string is @ @ EWSTT Sem Compiler Dosen Inteoducton to Compiler <. abe reqular exe jt carter tusceanbe rete troduction to Compiler o vd any ase tions om | 1h The ian erator i se ha [can be represented a¢ v ives comneeting one NFA tothe other te Concatenation simply inva thos ob can be represented as See «peace orb mer Tre eter rom the inp: thas loos ike : py using Thompson's constru: eo ee | Etmetee Construct NFA forr=(a)6)"= | = sept: G8} Step2: ‘The NFA ferry =iry)* —_— 1-136 (CTEM. apie Deen 7 L4G (CRITSem-6) Introduction to Compiler eselar expression 06° [th in Final vate of Final state of DPA willbe al states which contain Final states of step a ee | Que LAL | Construct the minimized DFA for the regular expression Woe nrO41)10. Tawer | Given regular expression :(0-+ 190+ 110 [NFA for given regular expression : @2¥"2-,@ SP OMGLOMG patil : &0-6-© areola Now, we convert above NFA into DFA. ‘Transition table for NFA: Fig. 19: NPA of ab ab GaeTAO] Discuss conversion of NFA into a DFA. Also give the | coiie ncn ccmneion — STESTTSINATT Conversion from NFA to DFA: Suppose thre isan NFAX <@, 3,8 F> which ognize language 2a, Thon the DPAD ean be constracted fo language La Step Intl | 2a an | am ayaa. 4% aa, | aa | 49,088 Step2: Adda, t06 aia, | aad | aaa | anna | nae, | an | ame | aasasd | ‘Step: For each wate in Q find the possible set of states fr each input symbol sing transition function of NEA. thi set of states is notin Qa tog Compile Dosen “Tramsiion diagram for DEA 1 semaine ei Seed Trcoanete afta tae FO" [Nooo sows are sim Se theDFA is already inimied ‘GeeTAE] tow does finite automata useful for lexical analysis ? ‘daswer 1. Lexical analysis the proces of reading the soure texto a program sod converting tite a sequence of tokens. 2 Thelexia structure of every programming language canbe specitied Transition table for ¢NF, tye regular language, common way to implemeatalexieal analyzer 4 Specify regular expressions fr alo the kinds of tokens in the Ianguage The disjunction ofall of the regular expressions thus deseribes| ‘any possible token inthe language, Convert the overall regular expression specifying all possible tokens into a Deterministi Finite Automaton (DFA). Translate the DPA ito program that simulates the DFA, This rogram isthe lexical analyzer CRIT Hom 6) Intrrduetion to Compiler ld lexieal analyzer “This appromeh 0 80 useful that programs mratorv ie te atterate tbe ootre proveee Write down the regular expression for ‘The set ofall string over [ab auch that fifth ymbol from right erties ret Receeneerarett acre DA forall strings over lb such that fifth symbol fama right is Regular expression :(0 +5)" a(a+bila+b)\a+biia-b Regular expression : [000 + 11604 100+ 1/004 1). 041)10+10+10+ 1 090-1) +10+ 100+ 104107 1)10 + 100) Convert following NFA to equivalent DFA and hence Tawwer | Ti “Answer ee 1 % % | Mya Ce a fey} pf ‘eelosure of ll = Wo dy) closure of ay! =a) ‘closure of yl =) 1-17 (CST Sem. {GEATAR] sora the implementation of eric nays Tnswer {Lexical analyzer can be implemented in following step 1 Input tothe lexical analyzer is a source program, 2, By sing input buffering scheme, it scans the source program (Regular expressions are used to represent the input patterns, [Now tis input patter is converted into NFA by using init automation aya) machine. Regular expression Pinte sutomata Input prowram <—[ Lesicalanaer |» Tekan a a ‘Symbol able Fig. 1.15.1 Implementation ofescal analyzer. 5. ThisNPA are then converted into DFA and DPA are minimized by using different method of minimization, (6, The minimized DBA are used to recognize the pattern and broken into lexemes, Each minimized DPA is astocated with a phase in a programming language which will evaluate the lexemes that match the regular expression 8. The tool then constructs a sate table forthe appropriate finite state ‘machine and creates program code which contains the table, the ‘evaluation phases, anda routine which uses them appropriately. ‘Que 165] Write short notes on lexical analyzer generator. PART-4 area senarany * For eficient design of eompiler, various tools are used to automate the Implementation of Leicl Analyzers Lexical Analyser General” phases ofeompier The lel ali phase canbe automated using LEX Compiler. toolealled LEX Fig. 1142. —-—_—_—~ 119 CSATSem.5) Comper Deen sea anlar which goers “on atthe hep el expressions rd to handwritten Nien 3 generated #1 heen ae mt rer atin est om URN cameron eel 5 Uke ‘that various programming se td tte = ‘yew sh ken nen ne eae ca sess canereeno “GeeTAE roan the antomatic ner iyzer is done vsing LEX| Automatic generation of lexical anal a extension (of ER canted gt enone - as dot L'. enact, « Soateeearentetemee ea halve pros (pee ce nett gcc ets rele eh ak 5 LE eae abr represen of he cet Srammstrated oeear expression 6 genio ee, LEX ars are auc wth very rua] ‘soon Thee arteries cole hat rediety acied powtewne '8 Finally the C compiler compiles this generated lex. and produces an object program act as shown in Fig. 1.172. jon oflesical analyzer 1 8 When some input stream is given to aout then sequence of tokens sts generated. The described scenario is shown in Fig. 1.17.2, Introiaction to Compiler c |__ ame compiter | eecutable program! Inpot_ FL Stream of “ainge trom | tokens source program Fig. 117.2 Generation of eseal analyzer wing LEX. Que Lis | Explain different parts of LEX program. Taewer | ‘The LEX program consists of three parts %I Dedaration section w ae Rule section %% Asiliary procedure section 1. Declaration section : f, Inthedeclaration section, declaration of variable constantscan be done, ‘b Some regular definitions canals be written in this section The regular definitions are basically components of regular expressions. 2 Rule section: 4 Therule section consists of regular expressions with associated ‘actions. These translation rules ean be given inthe form as R, [action] R,laction,) R, action) ‘Where each R, is regular expression and each action isa program ‘fragment deseribing what actions tobe taken for corresponding regular expression ‘These actions can be specified by piece of C code. & Ausiliary procedure sect 1. Inthiesection all the procedures are defined which are required by the actions inthe rule section Neo . rarecestTsem6) | ocewrtsem-s Introduction wo Compiler compe BS plex): This ean portant funtion The fntion yet led = ilejeanner starts neanning the souree program This ecton consi oni fant ‘c Srerany fonction ae Beran: FE] Write a LE sn toidentiy few reserved words Me function yywrap() is called when scanner eneounter end of Fee] Write a LEX proers le 1h fyyweap) returns 0 then seanner continues seanning = — 2 yyerah returns 1 tht means end file is nevuntered = Spin: inthe standard input file that storesinpt source programs eng: spleng stores the length or number of haraters inthe pat peu to recognize the Kermode sinne moe Tai. | Explain the term token, lexeme and pattern. a inteates ero mora ti pve@at #6 OF a mori jue spaces"! cee wt | case | faicapconitig ten saad an opin rte seu da nae |e 6 HL | BAe Bee et ear [enter | a end | |e | orb) esate ‘The token name is an abstract symbol representing a kind of lexical pent 7 identifiers, keyword: aa aera keyeord\ 0 37t@1 ‘Tokens can be identifiers, keywords, constants, operators and + ‘ak De pi: iat te here 7 punctuation symbols such as commas and parenthesis pa ‘Alexemeisa sequence of characters inthe souree program that matches the pattern fora token, ses Lexeme ieidentfied by the lexical analyze tern: ‘Apattera isa description ofthe form thatthe lexemes of a token may take |2 Regular expressions play an important role for specifying patterns ‘Answer | Makeywordisconsderedas token, patternisjust sequence of characters ‘There ae following LEX ations that canbe used fr ease of programming ieee PART-S Formal Grammars and their Application to Syntax Analysis, 2 ECHO: Ieemits theinput sits BNF Notation. 8 yytext0: | yytext is ull terminated string that stones the lexemes when lexer recognizes the taken from np akon. an instance ofthat token. ‘QoeT90_] What are the various LEK actions that are used in LEX programming ? When new tokens found the antes fret are replaced by ,4¢ (CST Sem 5) Compiler Desi TRE] esrb gramme cm ninsin ff EDT ex pra sia amma # Aa ed BW TPS) WOT Cat eer nt to vateann term MT 1 Ve ite noe edna ier ike RSC ne tetera et 2 Tonite eae epee a ETO ar geantbeforma of Whercaand ohn Tia has at les Pinfinentwboe rah Pink at ee a cae tino duct Seen nab seminal known as starting symbol ‘ sete a noted that V ie.,noterming ‘eee ena dronosermina can bint ee oat of ortermial FETE] wat icContent Fre Grammar (CPG) Pepin ower | Contes fre grammar: 1 ARG dari language by recursive rales called productions 2 ACPGcante described as a combination offour tuples and represented wOnTPS: sere, sae of variables or aon-trminal represented by A, B, ue YoZ: To set of terminals represented by a, by oF I BH S-sartng smb. P set of productions. 4. The production used in CPG mast bein the frm of A +, where Ais ‘able and ie string of symbole VT 4 The example of CG is: Vines [S60 (CTT Hem) Introduction to Ce nore WUBI = 18.4 1 [an prodetion Pie given Babe BokOE Bo Bod ‘Que B4 | Kxplain formal grammar and its application to syntax analyzer. ‘Answer 1. Formal grammar represents the specification of programm ‘with th us of production rules, anes 2 The syntax analyzer basically checks the syntax ofthe language 3. Anytaxanlyer takes the tole th lexical analyzer and ‘hom insuch away Sat some programming structure canbe eagad 4 After grouping the tokens if at all any syntax cannot be recoga then syntactic error willbe generated a 5, Thisoverall process is called syntax checking ofthe language ‘This syntaxcan be checked in the compiler by writing the specifations ‘Specification tells the compiler how the 3 Section tlle the comple how the eat oft programing ‘Que 135.] Write short note on BNF notation, “Tarwer | BNP notation: 1 The BNF Backus Nowe. ur Form) sa notatinteehiqu for grammar. This notation is usef me via a he fLimnar. Ths ttn lr sein the sao The BNF speciation sas “oymbol> = Exp Exp2| Ee. Wher symbol is a non terminal, and Expl Bxp2 is a equence of sym. These symbole ‘gmt Then syle can be combination of terial tan ——_~——S—e asc (CMITSem 6) comple Desa 280 (CRT Sem) Introduction to Compiler orexap ; er eqtreets zipcode coun “exsirese> = sftiname sremes XX, .Mg. Then fora vertex, label A. the children ofthat node, wil BK ‘A vertex mis called a leaf ofthe parse ire symbol ¢ Bor nul (0) ‘Que 130: ] How derivation is defined in CFG? foorse is a terminal 1 Aderivation ie sequence of tokens that is used to find out whether a sequence of string i generating valid statement or not 2 Weean define the notations to representa derivation 3. First, we define twonotations = and > If is.a production of P in CFG and @ and 6 are strings in (Woy then —_ “ ub = oft rrr ects easccomrTsen a1 secu rapt tree ya be pe Wey tha hea dea (peer ane inate of ren wear hat, 3 0,14 Rea 4 AH _ingrannar ven rnc tepc rans 28 and viet by et mont deivaion x nica ie et evn Leh mort derivation: Te ders eater a Tre ner apne 0h i of ir Pobee Feels ‘eae pdt FabeE Ee EOE (Repace BE * 8) ad ek (Replace Bi) suede place Bid sige did else Eid dren sical derivation Set dri ie ‘right most variable (non-terminal) at {prada apie el the ‘Example: Let us considera grammar Gavin rouction E+ EsE| BoE |id Start ts reduction BOBO EH EGE place B+ +8) oe Bed eplace Bia) + Beidsid (epace E+ id) side idvid epace Bid) 1-900 (OTT Sem Intretion to Comper TTR serine tne capaien oc fnew | Various expablltien of CPO mre orient re grammar etl to describe mont ofthe programming Tne «puke arammar ic propery designed then an ficient pase can be oagtrated tomate 4. Uning the features of associat ively and precedenes informatio, reat nar incapable of describing nested stractures Uke hing bin ond, corresponding if-then-else’ (rms forexpressions ca | 4 Cant fee era felanced parenthesis mate ndsoon (@.1, Explain in detail the process of compilation. Illustrate the outrat ofeach phage if complltion ofthe np Santbseynb+ee2™ ae Refer Q 11, 2. Define and diferente between DEA and NFA with an ‘example aa Refer 16 3. Construct the minimized DFA for the regular expression + D%0+1)10. i a Bete 1h @.4. Explain the implementation of lexical analyzer. ‘Rue Reter QU, . 5. Convert following NPA to equivalent DF 1 equivalent DFA and hence ‘minimize the number of states in the DFA. we 1-31 CCT Sem) ©. et a (Qe Explain the term token, lexeme and pattern. aus Refer 12 (Q7. Whatisan ambiguous grammar? Is thefollowi "rove EE + [EU The ram [bemoved to the next line centered. ama Beer 1.28 ig grain mar should (8, Deine parse tree What arethe contin for consirucing pare tre from aCFG? me MeaI® Boe Basic Parsing ae Techniques ~~ CONTENTS Part + esi Parsing Tecniques Parers Shift Reduce Parsing 220 tw 240 arta + Operator Precedence Prsing 240 9280 Peres + gomunaing SUt are w 2210 Pert + Con C rtretng eapenical LE. 2.270 wo 2-280 Paring Table Past? : Constructing LALR aan te aare | | Aatigons Gramma Generator Impemantation CLK Paring Tables D1 C(CSTTSem.5) Toes ee ‘Base Parsing Techniques Pare Shit BAC CMTTSem praee, What are the SRT wei prer we seri ton polar persing chine? ‘Eeplain about basic parsing schatgoes What intopdown paring? euuniwanah — wed ce it i as eamme pan ti same Scape am ity of a source ringer ce at 2 howe Pera cmtre = ‘There are basically two type of parsing techniques Ponders pardag a Topdown paring attest find te eet deri Input sing at start fos tho otra smi), eat the nes in redefined ode. Into dow parsing, the apa strng wi scanno by the parser fun eft to nght, one symbaoken ane. © Toelefamont derivation generates the leaves ofpars teen et (aright order, which mashes othe input scan order. In the top-down parsing, parsing dessions are based on the lookahead eymbal or requence af sya) 2 Bottom-up parsing Bottom. paring canbe defied a an altempt to ee teint sHeingwtothe sar symbal of arama by Ending ot the right rst erination of win revere reporters and rere fn the es uses ito rst of pases of Compiler Desi 2AC(CSITSem-5) Paring nvnvesseachna ir the stating tebe the ight fide athny ofthe predtions of te grammar 1 Thissuatring replaced hy the left hand side no trmil ofthe pretctn 4 Process replacing right eo the production by hele sie tm terminal called rection” BRET dine ‘parsing techniques ? Bottom-up parsing: Kefer@ 2.1, Page 2-20, Uit.2 otom-up parsing techniques are 1. Shiftreduce parse Shift reduce parser attormpt a construct parse tree fom leaves {root and ueea stack ob grammar oyabols parser goes on shin the input symbols oto the tack until a andl comer onthe top ofthe stack When a handle appears on the top of the stack, it performs reduction What are bottom. ttom-up p oid § aut cape ig. 221. Sti reduce parser. 4 Thisparser performs following basic operations i shit Reduce Anco Error 2 LR parser LR parser isthe most efficent method of buttam-up ‘Parsing which ean be sed to pare the large ease af contest fre ‘Srammars Thismethod sealed LRU) parsing ere errr et ii Parsi pac estT sem) Latandsore ont seni Ketan fr nghtnt eseation ene tse Whe ists ‘ enunedtob — - FE] va arechecommon contin ean bem alee eeu roost common conflict encountered i shift-redvce Parser PS ti cnt vie production rule inthe STaDa ae rb sone recta in Dsante he Taseraruntencmedh ee Ea Seman Re en erm (Sesh jst started Medco Achat ru tobe reduced the same OH hee the happens the grammar becomes ambious Snet & Ferree merpreted mar tha 08 2 «PORE canbe caused when the same rule reached by more asco Operator Precedence Parsing. ‘Gocstons Answers {ang Aner Type and Medium Anew ‘Type Questions ple. Wee | Explain operator precedence parsing with Taewer 1 Agrammar (ssid ob operat properties 2 Noproductionon the right sess precedence fit posses following npler Design ould me any prt re pmessing two adjacent atthe right had we 12 Inoperator precedence parsing, me wil fst defice precedence relations| oad > between prof wenunals Me meaning these eltions be Then ee ives more precedente than aie as same precedence a pe Pakes precedence aver g Forexample: Consider the grammar for arithmetic expressions BEA |B |-E id Asti tte 1) Now consider the tring © id 2. Wevsllicert symbols atthe start andendof the input tring We will tla nuert precedence operator by relerrng the precedence relation table Seid >t ccid->teid->$ 4, Wewsl flow ellowing step to parse the given string 1 Scanthe input fom lf to rght until fist > is encountered, 1k Scan backward over = util 44, The parsing can be done as fellows Food > ee id-> "cid: 8] Handed ntaied eeweon >] |edit by ni ode id taneabincen o> Reduce this by E+ id. | Ev Et cid->3 [Handled ieottained between <> Reduce this id EVER [Remove all the non terminal. + Insert $at the beginning anda the | lend, Also insert the precedence Serer os ‘The * operator is surrounded by | <> tmieindiates that © becomes handle. That means, we have to reduce E*B operation first teoot ee ew [eo eetinteee eer 8 as asc Parsing Testor ae ws tence function. “Fee iets compan edence Consider the fllowing operator sei dro tgaph and compute the tapas sera or penne tins nore am pave) Method: 1 Crsteombo 2 Pain theretedsrbns ert ia te Gort dicted raph whos dese be eee Ppt plce an ee fom the group of 0 t EONP Piet plc ane rom te group otha oA 4&1 the graph constr in step 3 has exc, then, no precedence io ere thre are ces lab the length fhe anges Neen te prupof fee gt) bs the length te angst ath om, rraupofe, Ten tore exstaprcedece faction Precedence graph or above matrix is sean ects tain cial nto many ous arsse,suche athe sae ee. pope anit FOE 27C(CMTSem-5) the precedence function using rs 1s z[2 10 “Gass | Give operator precedence parsing algorithm. Consider the following grammar and buld up operator precedence table. Also ‘hefeth input string dvd) BoE SP|LT OPER EBD Tamron ‘Operator precedence parsing algorithm : Ta theinputsiringtbe el, e2,. on italy, the stack cotais 8 1 exp topoint tothe Set symbol oo. 2b Repeat Let be the topmost terminal symbol on the stack and et be the earrent input jm. ‘only $ iv the stack and only 8s the input then accept and rose ole ‘ein Ite» bora then shifta onto the tack and increment ptonext inpat symbol. i loc ifa ~e Handle ne bene ease Reduce thietn Foi cities eres terial va the noe tite bese ms [ong Ansmer Type and Mediam Answer Type Questions QeeRT | What are the problems with top-down parsing ? ‘reer | Problems with op down parsing are 1 Backtracking 4.” Backachng ea tshaque ia which or expansion ofr terminal sym we choo alteratve and ifsome mismatch ocurs then Wetey anatber slterativ any 1h Méranootermina. there are multiple production roles begining ‘ithe same input yl then tet the erect derivation, ee ed tote athe lteratives amen Dein OC (CHIT Sem) Seca. nicked une ne eves pad i tvchack the poitine This iron of ever the backtracking by rings gear a Left recursion: the eft recursive grammar ie epreented a AS Ae bb Here means deriving the input in ane of mae tps Here, A sn nonterminal and denotes some input string eft recursion i present in the grammar then tp-down parser fan enter iat infinite lop, ‘ @ BC Yer a @ Q ® ® ® Fig. 221. Le eeursion. This causes major problem in top-down parsing and therefore mination fle recursion mast. Left factoring: Left factorings ocurred when iis notclear that which fhe tw ‘ternativess sed to expand the non-erina 1 Ifthe grammars ot eft factored then it becomes dificult forthe ree ta make decisions Gaets | What do you understand by left factoring and left liminated ? recursion and how “raewer_ | Left factoring and left recursion : Refer Q 27, Page 2-80. Unit-2 ‘Left factoring can be eliminated by the following scheme: a ngenera i Ama, [oe ita production then int pose for parser to take a decision whether tochnose fir role or second 'bInsuch situation, the given grammar ean be left factored as CCST Sem 8) airing Techniqas A-sat' Iybohal ARIA, Left recursion can be eliminated by following scheme: a Ingeoeral it AAA, A018 BS sehen eps witha 1h tnsuch situation we replace the A productions by ABABA ABA’ Asa Alo Alloa ‘Geek | Etiminate et recursion from the following grammer SABA BS}0,B-9 Ala eee] Saas Anasie 2 SAle a) 5-7 838)88 5-+ $ASBlaSB168 Sasa S488 bale 2 ABBA|B4\0 tA ale > ABBAB | A BS|e A+ SAS|SIo A+ ABAAB|aAB a AaB ad A BABA |e ‘The prodecton afte let recursion ie S-+08B8 [68s S488" |e A+ ABW Jat compile Design PUCICSIT Sem) A Maanne BAA a Bs Anu GRAB] Write short notes on topdown par tor down parsing techniques? Pantie Tower | ‘Top-down parsing ReferQ.21,Pae2 26, Unica. ‘Top-down parsing techniques are: 1. Recursive-descent parsing: 4, top-down parser that executes eto recursive procedures proces theinpu without backtracking elled eran decent ase and patingiscalled recursive descent eng ‘Therecursvproedurescante ens townte and ul effient if wen a8 langage hat inplenene he ee efficiently. ' Sees | 2 Predictive parsing: | 1 Apreditive parsing san een way ofimplementng recursive descent parsing by handling the stack of activation recards cenit ii Thepreictive parserhas an input, astack, parsing al, nd an ‘output. The input contains the strings ke parsed followed 8 thoright end-marker, Prodan | sua fT] parsing Le Output propa i Paring Table Pig 2102, Model ota pete parser fi, The stack contsins a sequence af grammar symbols with § Sndicating button ofthe sac niall, the stack cain the Start symbol ofthe grammar preceded by 8 1k. The prsngtable isa two dimensional aray MLA, where Ais ‘anon trminal and’ terminal the symbol. ‘The parser contrlled by pogram that behaves as flows raring Tenis B12CCSIT Sm 8) The preva determines Xero ere Thee ine si s_ollewang are the psi announcer steel EN eae $ the purer hate at Whe § the pare ope Xie sal rg Rien sab wet nat Sand ae anes the eee eset itcontey MX. e] of ee eho 20. prt eX aon termina tee ‘he parang tate M Tit tbe pomina an ra sae heeen top-down and BOOB-ED APSE eens parsingcan deconstructed fora Under which conditions predictive ranmar? mee Betton parser | SNe) Towdownpener | Se topdows paver Tet) Tatton parser Figi-most Th lopeden parser ef ; Aeration doe. rears Compile Desian scicMT sem) lgorthen for FIRST and FOLLOW. 1 FIRST function 4 FIRST (Xi st of terminal sybaisthat are fist sible ppearingst HHS in ders Following are trues und to compute the FIRST fusctins 4 MX determine terial sms th te FIRST X= a) Hehe isa X sehen FIRST cinta 6 UXisnomterminal and X-+F¥,¥,¥,.¥ ia production and SeloimallofFIRSTIY,) FIRST, thes FIRSTUX)«(FIRSTY))FIRSTY,) FIRST... FIRST, 2 FOLLOW function: i FOLLOWA)isdefinedastheset of terminal syns that appar immediately tthe ight of i FOLLOWA)=(a| 8 SoAepwhere wand) are some grammar symbole may be terminal or n-tersinal Theres for eompatng FOLLOW fanctin re allows ‘2 Forthe start symbal Space in FOLLOWS 1h tfthereisa production Aap then everthing in FIRST) without cistobe placed in FOLLOW ¢ Mthere isa profuction A +a B Bor a Band FIRST'B cntain «then FOLLOW) = FOLLOW A) That meant ‘versthing in FOLLOW) isin FOLLOWB) 2 iatikapipee | Baia ot ble | ra qi put token are pushed on| Th nae onthe a sate an 1d First and fellow are defined in| First and follow are used in| tup-ow parser tmp parser [5 Prt parerandrcersve] Shif-reduce parser, operator [decent parser te top-dora| pecedence parser, and LR parse] [parsing techniques. Srbedom upparsingecique We] Diterentate between recursive descent parsing and a [SNe] Recursive descent parsing| Predictive parsing Predictive parsing can be constructed if the fllowing condition holds: 1. very grammar mast be resursvein nature, 2 Bach grammar must be eft factored ‘BERR wnt ae te problems with top don pri the arith for FIRS nd FOLLOW, Aasver | Problems with top-down parsing Refer 27, Page 28¢, Uni 2 TT | OF ir ued to build recursive | Resurive routine fot bald 2 [RUS of production rule is [Production ues at converted [comertedint program. ita program. 3 [Parsing table is not |Parsingtableisconsructed constricted, “| First and flow isnot sed as LAACCSTT Sem 8) BEATE nc pet ping Cale he Heaney rnonara the pre prin he ore Femi fire Pri. Faria Page DC. Vat Namerical FIRST = FOLLOWE) =|$) FOLLOWE)«($) FOLLOW « 1,8) POLLOWT) = (6,81 FOLLOW) =(*,«,$1 FOLLOWE="*,5,$) Compiler Desi LSC (CMT Sem-6) FID) cn ergot pre ‘Why ite most commonly used parser? Aaower | Working of LR parser 1 The working LR parser canbe undertod by using lc gram at shown in Fig 2.18. te Block diagram. ae PS] toe tape S|] emer 1 oun saa x, |-—|_eseim ig. 2161. Mol of Li parser LR parser is widely used fr following reason on atsng Teles WeSTT Sem 8) " Forsovng the na 8.80 fo LR parser thas Ryu Terese adever program an oe ae eer cel at atin and maint a atc Tie sng SNSMS MaaSerteSy ach isthe state andS, state stop srammar sl Fete pres ete + St one Rome a a ee sua top cel a otedae A th per xtatees nee eta a ppatctn the pena A> SES Eaw a ae mi peo tt a a eran ul oe opt he ck SEES MICE icp the ah anthem ate fo, ispsed nthe tack Th caret symbol i Se sack Taps SMS Boa SaeAS were $= Gata 1 tain cae pati peed {Kaw Se cera he per dcoverd aaa af LR parsers canbe constructed to recone mast ofthe programming language fr which context ee grammar can be writen The clasof grammar that canbe parsed by LE parser isa superset of clas grammars that canbe parsed uring predictive pases “i parser woes sing non ockrackng shire echigue [parser ieanefcen parser ast dette satcticero very ikl. Compiler Desi LITCUSTT Sem) FRE Wt te ting 1 LRaDiteme 2 Augmented grammar 41. Kernel nnd non-kernel items Funetionsclomure and gots s-raice The production $+ geertesonyoneitem 4 Augmented grammar: ita anvarGishvig artsy ten tented grammar Gin which Soa new a op een S558 The pry of hs gramaris wnt Oe seo input Tat whe prs abet vduae $8 rea pine te 4 Herelitems: I scalltonf tna -+ Sandal tte wine dhesareotat the st ao RS chee Nonkernelitems:The cleo alte temin wich art the left end of RHLS. of the rule at : 4 anetions closure and goo: Tew ar tw imparts in requtedto create lect ave et of LR tons PARTS Constructing SLR Parsing Tables, Questions-Answers ea 4 ‘Long Answer Type and Medium Answer Type Questions Que27] Explain SLR parsing techniques. Also write the algorithm to construct SLR parving table. ‘xawwer | The SLR parsing canbe dane as osc Parsing Technine BAS (CATT Sem) conta fe erat osteat ig 2174 Waking of SUR prs “igrihm fr coneretin of n SUR parsing abe: nee sP ite cannial winoef es iens fr an segmented amar peep; fuse, an psing ble consisting pring ation Faction |NCHON and eot function GOTO, Method = Let C= Ut onstrated fom ‘The parsing action fo Pa eval in and GOTO U2 ‘hun Hee ois terminal 2 A sae nnd, theset ACTION fie] o "reduce Ara foal in POLLOWA Ir 15 Sel isin hen set ACTION i, 810 "acen ‘Th goto transition for stat ‘are constructed using the rule 4 1G0TOr, A)=t, then GOTO [Al ‘Allentries nt defined by rales (D rough rule are made “errr” ‘Toc ntl tae ofthe parser isthe oe constructed from the set of ‘ems cotaing > +S. "The parsing table consinting ofthe parsing ACTON and GOTO foto eeomined ty thislgoitim ical the SLR parsing tablefr ©. An 1 purer unin the SL paring table for Cistalled the SLR parser for Gand grammar baving an SLR parsing table ssid tobe SLR, BaERTA] constract an SUR) paring table for he altoming franmar Sa) SOAP PP P+ (oum, ou) 1) Thesttes ofthe parser are, Ln sat eig state ix determined as follow [then set ACTION i, (Rar aon Te Mas 10) compiler Desi D19C (CMT Sem) mugen grain or the ide 4 0 rte above grammar Gis a8 Soap Solbe Pm, 2am) canonical election of eto i es aa nt of tem for grammar areas lew Satay Soap SoeRp P+ (om, ou) 1,=G0T0 ty 8) ih Sse LecoT0ya) t saae SoANP 1,=GOTO Uy) q Sane PS sou, us 1,=GOTO Uy) t P+ num, gum) =GoT0u,.) t soaye =coT0u,.) t SoA? slau, mum 1.00701, P) t SocPP 1. =coT0d, mm) t "P->(aum », nam) 1 =6oT0U, PI SAP Soke Poo fn, mum) P+ (num, aun SotPPs 1=60T0U,,.n0m) 4 P+ fou, um +} y= 6070.) he P+ foam, num) + ing Techniques 2.200 (CITB ae a |p Tee consider te eoing wammar Sasi peri Contr in ER pre ale forthe ranma Show th tions fhe parser forthe inp string “abel. ARTUBOT, Marks 16] Toower_] ‘The augmented grammar is Sas Saas AS Sala ‘Toe canonical election of LR) tere are T8408 SeAs|*b AseSAise 1,-00T0U, 8) 18-484" S+Asieb AaSea compiler Desi a A) 1-000, 4) ISoaee Sn eagies Aaediiee [ss Ta nts T& 1 fe a i BPs TS§ oe ae nh fe Alon fe La cy a | a eee asc Parsing Tengu Table 2182 Pare thesnput obab wpa ale, c as SwRS AS ss os Sat sosiet as Reduce Ara SUS, os Reduce A> AS ue as Sit ants 8 Reduce S > was 8 Rede 5A wi = eco ‘Woe FRN Consider the folowing grammar E+ B +B | E*E| (5). Construct the SLR parsing table and ruggest your final parsing boas Kaower ] The augmented gamma is ae eae BO EVE ESESE Ene) Baud ‘The set of LO) items i flows bok Boke mn Bone 1,000.4, 6) 1, Bose Boker Boner 1,=00704,.0) ky Ete) rae Bo eese Bn) Bid h=Gor0U, id) hy: Bove 1,=00700,«) h Bo bvek ras EEE Paar BoB BaEVE 1,=60T0U,.) a "Ee OE 228C(C9TSem.5) ‘BaPRR] Peto truce parsing forthe iveninpst sing ching the grammer 8-1) [o-+ 1818 Leia) ii (aa) ‘Answer ‘Beck contente [Input wiring [Actions rs (at Shit x (ata,a)6 Shite ge Reduce S+a 3s Reduce L +S SL Shit) gt Shit Sui x Shia aL. ans Reduce +0 SLs ans Reduce L-+ 5 Sid as Sait Shib, as shite Sita ns Reduce S-v0_| SLLs ng Reduce L-+.8 | Rae EE esi) aL 8 | Reduce S910 abs 8 | Reduce LL, % 8 | shiny” | Su) § | Reduce +12) | is § Aecest | eee — ‘The augmented grammar i sas SoeBlcd AseAla B+ Bb ‘The canonical election of LR 0items are 18-408 Sebo coa Asteaiea Bae ecdeb 1,=00T0U, $) 1osose 1,=C0TOU,«) [Sree Blewed Ased Bosca Aspalen B+ eo *b hc Parsing Tchniquey 296 CNITSem ase 12007, oor 8 1 Soe 1.200701, i kaels 1-070, 1 Seed Bac Baceed BovaBeb 1,-c0TOU.A) TeS-reea Aaede 100708) 1 BoeBe 1426070 Ue) TysBaceeB Aaa Boeeed Boecedl +b Aneellee 1, = GOTO Uy A) TysAveA DPA for set items: CE Sa Compiler Desian ECCT Sem 5) Lat ue nunbered the prodeton len the grammar So S seed vk Ave Bch Hob eo [ace ats s a | 1 E wtutatale | Elan lean nail ae saline Pee | ES ape [S| Se ny ‘GFT ive the artim for construction of enol UR parsing abe asc Pring Tees 2 aNC CATT Sem) io Sa aoe ACHIN MH TON a rere iene ue Hat Mt in co i sie are determined as fellow ete Uy 2) = Uy then set rr ap i and GOTO Uy 0) = ee eh Sag Hare aired tbe ena cone ein, A eS. then set ACTION Halt “educe eg -oSe Shain J then et ACTION $1 2eeen” ‘het rants rate are deter as filo 2 GOTO TA) then GOTO LA Allenton find hy ules (1 4) 4 Ten tate of pare athe oe contre from tet ontinng ems S288 Ire paring acti Suton bas wo mallets then reser x sade be LR dlorLR. virvcion of canonical LR paring table are aero (Constructing LALR Parsing Tables Using Ambiguots Grammars, An “Automate Parser Generator, Implementation of LR Parsing Tables. Questions Answers hae ‘Te aorta for construtin of LALR parsing tbl i Input : An augmented grammar. ‘Output The LALK parsigg table function ACTION and GOTO for Hee eee mete gn Pec icutaens) me inet tt) : me ma Cor, and replace thw met tte le hang tat UO Senne rt ping actions for sate arenas nt es LD) tem, The rated om there rma te ce mene tclian iin ro spar a 4 The goo table construtt aston isofLR(D items ce dono 8 eine or more ty Boon co tb se aller tes cas kcisthatemm an cot ‘Thetable produced by thi alpwrithm cle LALR orsing aie or tte ty tin Siam tamu untesces ern ent ee ‘The callectonof sets of tems cna Called LALRI collections, = wt at Toth alge x ‘TERE Por the prema aad |abe | She Aff Construct LR parsing table. Als raw the LAL table frm the dere LR pring al =a ips ee and ete aor ar cui etn ae eres fosaat ane Sonate soeues ree ae asc Parsi Tchnigeg compiler Des 21 C CMT Sem 5) <00T0, 8 sabes sanetet Aaetd Boete =GoTo, A! [ as | QeeFAET] show that the following grammar S-+AalbAe Be|bBa rer Boa LHC) but not LALR 1) Tanwer Augmented grammar G fr the given grammar sas S+a0 Ste SoBe SBa ac Tn, saxecernaees 7 Follows Least santas Sosehet Soe § Ss eh8a 8 Ante sede 1,=0OT0 Uy) 18388 1, =00T0 Ud) teaoeas, Boa },eCOT0U,.0) PC CMT Som 5, WA vine Wden Ips OOM O05 fe S oes coro Ny Sobhees 1,*00T01h.0) hy 8 sha Teclontabe ile died aes Tobe 2981 ua ‘Aeton on Bienen) 6 fae capac] ® s % vas T = [ets 3 8 Te] + So ofa t 7 Su ® [Sa | ot, a 10 I an 2 a I Since the tale doesnot have any confit. 8, itis LA). For LALRID table, item set 5 an item stare same, Thus we merge ‘both the item sets, =itemset ys Now, theresa parsing le ‘comes «| 8 fe] te Sie the tbl contains rede edu oii, it isnot LAL), WeeBRT] Construct the LALR parsing table for following rammar: ‘SAA Anak Ab {LR but not ALR. Tawer | ‘The given grammars: ‘Sad peers ‘The augmented grammar wll be ss Saat A-vaals ARTO 016-16, Mark 1) Campi Design Lac eNT Sem.5) 1 tem il be 184 ’ Soveaas Ao 0A, Arsh 1,=GOTOU, 8) 184508 1,=G0T0 Uy) 1p S-+ Ads perry Asses 1,=60TOU, 0) ByAsesAob As eadat Ao abo GOTO U6) TA beat 1,=c0T0U,, a) 1p SAae 1,=C0T0U,.0) TeAsaas. Asaaas Aves 1, =60T0U,6) TAvba8 0070 5) 1pA-saeab 1,=00T041,.4) IyA-vanes 2.96 CCSTTSom 8) nc Parsing Techniques Veblen a7 @ = ce ale does ot contain any cont SOE ‘Te gtotable wl be fr LALR tecntoneds a & ile unoned 2nd wil | end willbe uso Ty: Ava0d,a/bI$ Awa 0//8 A-rebo/b/8. 1 A-sbe,0/8/8 Ig: A-vade,a/b/$and LALR able willbe ‘rable 2272. Goto . sla A able does net contain, a “oe deta | What is parser? Write the role of parser. Whet are the ‘mont popular parsing techniques’? Refer @.21 Explain operator precedenen parsing with example, ‘What are the problems with op down parsing? ReterQ.27 an. ame a2 ane ReferQ.24 as. a ‘What do you understand by left factoring andleft recursion and how it eliminated ? aa Refer. 28 5. Eliminate ltt recursion from the following grammar SAB,A-9 BS]b,B-9 SAla aa Reter@ 29 6. What are the problems with top-down parsing ? Write the algorithm for FIRST and FOLLOW. aux Refer Q.212 predictive parsing, Consider the 97, Bopla mfammnar and contract she predictive parsing following eraminar an tani BTR le Tarr rrr. Paria same eer 24, unit Syntax-Directed Translations SLR(1) parsing table for the following sc Parsing Technique psec centr sem) QA Com — cc Schnee, CONTENTS | naw Refer Q2i8, — 7 — | rart-l + Syotax Directed Translation 240 wae 9. Consider the folowing grammar B > & +B | BYE|(E)|id. : Syatax Directed Traslton Schema Construct the SLR parving table and suggest your final Implementation of Satay iret parsing table, ‘rane saws Bator Q220, | Part + Intermediate Coe, Post Fix 3-6¢ to 2-00 10, Perform shift reduce parsing for the given input strings ‘Notation, Pare Teer ond sing the grammar (L)]aL>L,3|5 Syntas Tres lawned dee Part. 3+ Three Addee» Code, 3-96 vo 296 nak HetorQ 221 Quedruple and Triples Part: Translation of Assignment 2130 w ase ose ‘Statements PartS + Boslean Expressions see te 21e the Flow of Cone | Parte + Posta Teanton: Array 3.210 wa. 21¢ Reterene tn Arithmetic Expressions Pare7 + Procedures Call 2-290 w o-ase 3-250 we 2-280 SACCSIT Sem) S2C0CSTT Sem) Sy Diet PAR’ ‘Sonta Dine Translation Syma Directed Translation ‘Schemes, Implementation of Syntax Directed Translators, BEET] Derine syntax directed tea annotated parve tee fr the expression (4 * 7+ 1)*2, using the simple dea caleultor grammar. Tarwer | 1 Syntax directed deinitiontrasltion is a geeralinaion of content feee rama in which ech gamma production X-+ eis asecated sth ofeemanti res ofthe forma {by by. where i {ttre obtained fromthe Fanetin Srater ected trenlation wa kind of aera speciation, Wie dne for stati analysis of the language 11 allows subroutines or semantic actions tobe attached to the productions a context fee grammar These sbroutnes generate terme iat ode when called at appropriate ie bya parser fr that ‘he syntax directed translation is partitianed nto wo subsets called ‘hcoyatheaed and inherted attributes of grammar, ‘Token team Pare eee — t Srataxdreted Trenton 9 Evaluation order for semantics Meta, ‘Gee | What is syntax directed translation? How ae semantic sections attached tothe production ? Explain with an example. iaewer | Syntax directed translation: Refer Q 3.1, Page-20. Units ‘Semantic ations ar itched with very ode of annotated pars tee sample A parse tee along withthe Values of theatres toes (caledan annotated parse reer anexpesson +3 i suested bates isabown nthe Pig 3.21, @ev0 dignenals Fig 321. ant tse Trains CSTE Sms) a ee = rps ar smcted se ected estibe rane ET apes anti tombe a ing 9 SSIS ate se ratte CNET LSIST0 sin ens dtr asemantrie TEDL Spader dt de Sythesied atte: Se reprise nthe mated fits vale compated SS STESGEATMUSIER Tale ort ote tte pane te SSE etic enc ue she tend trate is SISSIES aioe 4 Punter anted dentin can alnars be aot BESET SSLE resets at ach ode om nataresymibesived and inherited re peering that cops Tonle ar the lab | tfbetrasltions are specied using S.ateibted definitions, then the Sant res cab convient evahated bythe parser itself during the pare Por example parse re along with che values of the attributes at ‘heeled "asta pare tre” fran expression 2+ 3*5 with ‘Sothesed etnbtessbownun the Fig. 28.1 * * egrets pe eat ieee ig, 23.1. An anotted pare tre fr exprsin «38. omer een 250 IMT Hem 6) pneritd attribute denen ibered atte ne whose ve at ee a prs tee msi ate ihe ret it srg ihre nrc Forenampe: Syntax ireteddefntins that wes inher trite 2 bom Liye The ro Tigges eer Tora Tye sre fare Ite ote stor pe Lo boi herd pe Ls ‘tpeparse tre, log withthe atribute value a the parse tenes, {Bput steing iti ad id is shown inthe Fig 332 vom Gere Fig. 832, Pre tree with ered ststbte forthe raga yy ‘GaedA] What is the difference between S-attributed and attributed definitions? Taawer SNe] Satiributeddefinition | Lattributed definition 1 uessynthesied attributes | Tease waihisined and ered seit 7 | Semana wend] Senusret [Sektewetrohete "| anyon on trina rid atibus ae eae by |femagarace tera ep footer “Lang Anewer Type and Medium Answer Type Questions ee al GeeTR | What is intermediate code generation and discusy ‘benefits of intermediate code? Taewer letermate code generation is the fourth phase of compiler which takeg pure tre san gp rm seman phase ad oneates an intermedia fede as output The benefit of intermediate code are 1 Intermediate coe machine dependent, which makes it easy ty ‘target he copier opneatecoe for ewer ad diferent process, 2 Intermediate code ie nearer othe target mache s compared tothe source lanugs ot isease to peerate the get cde 4 Thetntermetae code allows the machine independent optimization of ‘he nde yung pecialied techniques, 4 Syntas directed translation implements the intermediate code ezeration, thus by augmenting the parser, ican be fled no the ‘GeeTA | What is posts translation ? Explain it with suitable example, Posfiarevere pls ranaation: iste ye of ranlatinin which ‘broperatar ali paced aero operade Forcuample (reser tbr expretin: 20-6 641 ear awe eapeson cant elt a nen seein Bente reer Now patting values typ ty eqs compiler Deen __S1CVC8T Sem) Disite Biersiae (ao) s-ees ine ‘GEERT pete pen re Why pase re consirection sly mile or CFG? Parse tree: A parse te i an ordered ‘rein which ead! ide of production represents parent node ad children tes re roprsesed by production rat hand ide ‘Conditions for constructing» pare tree from + CFG are Each vertexofthe tre must have label The iit rina or terminal or nul ‘Toe roto the tre i the start symbl,S fi Tholabef the internal vertices no termina symbol «¥, fs) there ina production +XX,..X,. Then fora vere label A, the ‘duldren nde, willbe, ve Avertex mi allo ala ofthe parse te iis lab is stern Stl © Lornal et Pare tre constructions only pase CP Tis beau eprops een match with the properties of CP ‘BeRRT] wat i yates toe? What ae the rules to construct yas ve fran expression? 1. Anyntat tree isa tro that shows the amas strotur a prograsn hile omiting irlevant deal preset in pare roe 2 Syntax rei condensed form ofthe pareve. The operator and eyword nade of parse tee are moved to their paren anda chai of ingle prodtion ie eplaced by sage ik ales for constructing a nyntax tee for an expression: 1. Eachnode in asyata re can be mplemented as record with several fel 2 Inthe node fran operator one field identifies he operator and the ‘emining fed contain pointer to the nds forthe operands 5. The operator often called te lb ofthe nde ‘4 Thefollowing functions are used to creat the nodes of eta res far cxpresions with binary operators Each fuetionretare pote nowy erated node |% Mode(op lef right) lt reales an operator node with abe op ‘nd two eld containing pointers tole and right. SACOM Sem) Syotan Dect ranalations For example: Contract syta tree fran eapressio @— 4+. Seer care pone the weber nent a crbol acento or sear end ss clivon The natn tree wilt "Pig. 881. The yan te TeeBT] Draw eyatas tre for the arithmetic expressions: a to 0)-d/ Alea write the given expression in postfix notation, Sytax ee forgiven expression a (b+<)—We retain 8 0a -—___Sieetervern {Lang Answer Type and Medivm Anewer Type Questions es Se ee | ‘GeeIOT] explain tare adress code with examples Tomer] 1 Ty adres code san abstract orm finteredte cde hat cn te Impcmened ac record with te odors 2 The general frm ote aren code rpreecation mbope where and are pert tat can be names costs and op ‘Thar are at most tes addres ae allowed io for operas ad sng frre Honey, te name fs represen hen ere and are the tesiporary names eneratd bythe compile. B10C CSTTSems) Syntae Dircted Translations ee QeeBATT] What are ditterent ways to write three address code ? ‘answer |] Different ways to write three address code are: [minus | a @ [umes] a : A . @ | pan ‘The qundropl a trace wit t mos four fda sucha op CO a A) ang arg. rau of= | 1. Theos erst ital er oprta he ng and rg? represent te two operands used snd ret feds ‘turec adress code of given satement the eso the result ofan expression, 1 WA>Cand B id relopid + TRUE E+ FALSE ere the rlop is denoted <2, «>The OR and AND are lef assniate ‘The highest precedence is NOT then AND and lastly OR. ‘The translation scheme for boolean expressions having numerical "Tepresentation sas give below Foid,eop id, spend pase" sppend to net sate «2, append pla = 1 i Eo TRUE EFA PART-6 Pout Translation : Array References Arihnatc Expresions ‘Long Answer Type and Medium Anewer Type Questions sarc (est sem 8) Suntan Diet Tamsin, BET eestor eon pont easton cei nee Proc canbe astro aeieve posts orm Postfis translation of while statement Production: -+ while MIF do 421 ample Desi Sacicuttsems) semen: — ee ee Vee cade Tere Tyco = 7 ee Pee Tyeole= Fee Peas Rede Peode= ido tere‘ seis ed or erin, Canbe faa a — IS test [Part-7] tote imi 3 eae ee 4 ntl rion shea — ong Answer Type and Medium ‘W.QUAD = NEXTQUAD Answer Type Questions wea = a TACRPATCH SL NE ‘GEE Hapan procedure cal with example cquaD, Toone] SNEXT-CPALSE eames: GEN gto CQUAD) 1 Prcdire i ninptnt neque bed raining cst EBB epee arioest aan csr ke pert ng pt Drcod Prin Shnme GOTS). awwer | Postfix notation Reler@- 46, Page 3-6 Uni. ‘Numerical: Sata drei translation heme to specify the tansationo tnexpressin io post notation areas alla Production bons Bat TotyxP T9F Foe Paid fracampler 2 Tinused to gonerat coe for procedure cal and eturas 3 Queve fused to tore thelist of garameters in the procedural, 4 The translation fora call include sequence factions taken on ety ‘dei from each peocedare.Folwing actin ake lens caling sequence When procedure call ocur then pce allisted fer activation record 1 Bvaluate the argument ofthe called procedure © Bstablsh the envionment otro otal the cle procedure toaccessdatain enclosing hacks, 4 Savethe stato cling pre so thittcanrenne execution after the el (Ala cave the etn res Ie the adda ofthe ation to hich the elle routine must rane ater isis Finally generates jumpto the beiasing athe coder the clad procedare. ae ae |, ween iineretntntaeere sta ht ewe a come meee fm map a ide) ia Declarations Sitements J ie @eectioneAnawers "EE | |" Long Answer Type and Medium Anewer Type Questions {he aticallcation af array, whos arg aes be as ‘For RaS. | explain declarative atoms ah eeac ara ment Ww hn he len way & =) ee Eee: | BE — ay nc 4. The Fig. 322.1 for row-major and column-major are given as aie | [Foret Seond Can | Seon nae in Con |_| Fosrosinant oF | tripe sanaraan a Festa [fam sxec\eSTT Sem) Syntan Phot Tatiana revo The comptalon oft ean ‘ict swath nal the val fot es ie byte the forma ie Ine above tnslation scheme, Type. Tih are the sy thesind Stebetes The tse ineats the datatype ofeorerpning entifor Gnd wath ed to ince the memory uit asoiated with ‘Sheer of coreapoding type For natance steer has wilh and frlban The rule D +d Tie adeclaratve statment ori declaration, The Enter tab ie function wed for eeating the symbol table entry for denier slong with t tse snot. Thewidth ofarayiecbained by multiplying the width ofeach element tymumber of elements the aay ‘Tae wsthof pointer types of apposed tae ame Fer 2. Explain attributes, What are rynthesized and inherited @A. What is postfix translation ? Explain it with suitable example. ame Refer 3.3. QA. Whatisoyntaxtree? What are the rules to construct syntax tree for an expression? sax Hofer 38, 5. What are ditferent ways to write three address code? se Refer 3.1, 6, Write the quadruples, triple and indirect triple for the following expression: Gentgerrieyes) ue fer 312 - Sct) see aap 1 No Folvecace fle nn nerd Sigaen cee ‘ i Case statements ae olor 025, Qa, Define backpatching and semantic rue expression. Derivethe three addrens code fore (a Seiction cag sate ad or the alwing ans afer Q 3.17 7 eee NIT Symbol Tables Parts» CONTENTS Symbol Tables Data Strctre for Symbol Tables Storage Alain Block Structured Language Error Detection and Recovery eseal Phase Brors Syntactic Phase Erors ‘Semantic Errore +1 C(C8IT Sms) 420 tw 470 100 wo 4186 4180 wo 4160 4-100 wo 4210 sare Goa Dn eymba abe with capitis owe | ipo laid heres ep 1 fe eandbndgifraati bursa AP mkt ‘sheared ine ware pe at evan 2 econ ever ee Tene | Nombtable mare loving cabs LT Tentn Trt wh res a he £ Koetrtstenwreae cuenta Asmar To srt inna pea san 4 Moai: sow strat sets ne Deas Ts itera wept ans a Ge] Wea are che yb ale requirement? What are ihe sewers inthe uifrm srr a obo! be? ‘ae buerequrmeats of symol alae as fos 1 srr sibling tener es (iva at lan fever shoe 2 Fut oouplcarch: Theta depends he ‘Senator tbe gala peda ead ui epee {Aiea tation space: Te snl ble mus bso fv orth yumi fort ect ac 4 Ali bandleanguge haat Ta cares ‘ing nw nel np crs doe Denerisin uniform atructre of embel able: 1"Te ufo rca cant hl enone length eed ‘rerun rir ume Bll Ie lgghota neostigmine ESCLESTT Sem) GEER] How names can be looked! up in the symbol table 2 Dicom Tower] trum wu fet 2 Whee «new eamew ifort hat an ing ei coeds ee alee 3 Then terete mt vem cet echnian raeig efron belt tuhe sre eter ndangserenne ‘symbol table, ee [nance the stabs ase abtcin ltl ‘Serta and eri semi rng see 5 Temas te cope mor tent et le det ae fepatediodueer ebay posed rae Fererample:Consr te levngetine ss hacen void seopee i tnta.be level 1+ fl latest Peel 247 i C oat & Phevel3*7 int Pevel 47 1 1 ‘The symbol able could be represented by an upwards growing stack as: 1 Initially the symbat tabl empty. LL ii Arte frst three declarations, the symel table wil be fi AMerthe second delaratin of Level 2 scant Sem 5) vac! a si After entering into Level 4 | «| 6 fan ‘i, Oo Leaving the conto rm Level * ' Onleaving the funtion entirely the sya tbl will be sainemps ‘Que | What i the role of symbol able? Discus diferent data steuctures used for symbol table. ‘OR Discuss the various data structures used for symbol table with suitable example 4SCC8TT Sem.) Role of symbol able 1. Teepe te track of semantics of variables 2 eetaresinformation about ope, 3. Ithelpto achieve compile ime efcieney Different data structures used in iplementing symbal table are: 1. Unordered list ‘© Simpleto implement symbol table. . Wisimplemented as an aray or linked is ‘© Linked lst an grow dynamically that eliminate the problem ofa fard sie aray ‘4 nsertion of variable take 011 time but oka is ow or tablesie on 7 = 2 Orderedtist: ‘an array is sorted it can he searched using binary search in Otog laid 1 Insertion nt sorted array is expensive that it takes Oi) time on average © Ordered list is useful when set of names is known , table of reserved words 3 Search tree: 2 Search re operation and lokwp is dein artic ime 1b Search tre is balanced by usiag algorithm of AVL and Rd Mack 4 Hash tables and hash functions : ‘4 Mash tabletranshte the elements inthe xed range of valve called Ina value and this vale ued by sh anetin, Hash able can be sed to minimize the movement of elements in the symbol table © Thehash function helps in uniform distribution ofaames in sya} table, For example Consider part fC program nag 1. Unorderd tit acest sem) Ordre a iw 1 ay. Search te 4 His tble Names] — Hahate Stage tate ‘Geet | Describe symbol table and its entries, Also, discuss varios data structure used for symbol table dasver | ‘Symbol table: fer @ 41, Page 4-20, Unit atresn the yb table areas follows: 1 Variables 4 Variables are identifiers whose value may change between executions apd during angle xeaton program 1 They represent the contents of ome memry loin. The symbol able needs torcordbththevarablesame as welos isaloeated storage space st runtime Compile Desi 4 TCU Sem.) 2 Constance 4 Constante ae idenifersthat representa finale tha an never ean 1 Cale variables of procedures, no runt lication need be ore for constants «© These are ty land riht into the code star the compiler compilation time A Types user defined): | A.wser defined type is combination of ane or more existing types 1b Types are accessed by name and reference a type definition 4 Cases : | Clases are abetrct data type which restrict aces ois members ‘nd provide convenient language level plymarpie, 1b. Thsineudes the oeatonof the dela contrutr and destracto, nd the adres of the virtual funtion table, & Records: Records represent acoletonof posi heterogeneous members which ca be aecesed by name, The symbol table probaly needs to record each of the reorls embers ‘Various data structure used for symbol able: ofr G44, Page +40, Unie PART-2 | Representing Scope Information Questions Anewers Long Answer Type and Medium Answer Type Questions ‘Que 48. | Discuss how the scope information is represented in symbol table. ‘Taswer 1. Scope information characterize the declaration fidenifies and the Durtion of the program where it sallowed to use each sentir. 2 Different languages have different spe fr declarations. Fr example. in FORTRAN, the scope of name sa single subroutine, whereas cst Sem5) se * ia ‘a0 the COPE of 8 NAN the seo oy “ie delet Proce mich rd en a ee Fa ener dace nen en dati SS 5 ae de am le se a sums ee « Sem ed et Seer ees i ae een ‘cannot be declared within the same lexical scope, aaa ee moment cae ee ca rcgice the empath bener oid amg 0 = ens Sines: See of abe oi Write a short note on sping. LCST Sem gy Scoping i eth of Keeping variable in rent part of program dant fom ne nether 2. Senge grr dds todas: 2°" Sac scoping: States ale alee sping. tnt sop avanahlesieay Wier etctoplewloerene 1% Dynamic scoping: Invonani png sobbed eg ‘sthe denier acted withthe ea reece ‘QeeART] Ditterentiate between lexical (or ati) seope and dynamic cope. Tower | SNe] Lexical scope Dynamicscope | The Windig. of name |The Hating ope scores

You might also like