Compiler Design Quantum
Compiler Design Quantum
whith recognizes language C- a ° 1 ja, Then the DEADcan be constricted fr language Las +4, 49 49, aaa | eee ert ag, aa, | aem aa 49.9 ana, | gam | qaaasc | Lsaag, CMa or each tate in @ find the posible sot of states fr each input ‘symbol using transition fnetionof NFA. this set ofstaesis nt in Q ad ittog.csi | ‘Transition diagram for DFA | yee | = Tia | 1 : B vig | ¢ ¢ D c “D 7 ton ableinto 2288 08 ‘For mummintn die the rows of a ‘SoetsTrconans of on Sal ate Noto rows ae smi. Ss the FA isalready miniiaed BETTE] how dos ite atoms ntl oles analysis? f 1 Lexical analysis the proces of eading the source text ofa program sad converting tino a sequence of akens tpvaroglar language, common ray to implement alexieal analyzer Specify regular expressions for all ofthe kinds of tokens inthe Iangusge ‘The disjunction ofall ofthe rglar expressions thus describes ny possible token in the language Convert the overall regular expression specifying all possible tokensinto a Deterministic Finite Automaton (DEA ‘Translate the DEA intoa program tht simulates the DEA. This program isthe lexial analyze. Introduction to Compiler sms called lexical analyzer nie the entire pence Write down the regular expression for “The set ofall string over {a,b auch that fifth symbol from right ibe. {Te set ofall string over {0,1} aveh that every block of four consecutive aymbol contain at least two een DFA oral strings over abi such that fifth syrabol fom ight is a Regular expression (a +B)" (a «bila +b)(a+ blab Rogular expression : [0010+ (0+ 140+ 1)00+ 1)+ 00 6 1110+ 1402101, 000-1) H0+1M0¢ 0610-110" 140) 14] Convert following NFA to equivalent DFA and hence imize the number of states in the DFA. “Answer ‘The lea structure of every programming language canbe specified Transition table for NFA: we *[* % + [oa Ce @ Ou) Teva telvure ta «ah our oft «tah elwure lag)Teo ee as | Rede ed | Me oat? | eee) | Weert Fig 342. Implementation of Leica Analyzers. Lexical Anal LEX Compiler. 1 ——— _—_ GiaTTE ova he implementation of exe ansizer. newer Lexical analyzer canbe implemented in fllowing step: 1. oput tothe lexieal analyzer is source program. 2, By using input buffering heme it scans the source program. Regular expressions are weed to represent the input patterns. [Now hsinput pattern is converted into NFA by using finite automation machine ‘Tokenind utp fle np program —] = Symbol abe Fig. 1.161. Implementation aerial analyzer. 15. ThisNA are thon converted into DFA and DFA are minimized by using diferent method o minimitaton. {6 Theminimized DPA are used to recognize the pattern and brokea into Jexemes Ech minimized DPA is asueated with a phase in programming language which will evaluate the lexeanes that match te regular expression. 8. The tool then constructs a state able fo the appropriate ini state ‘machine and ereates program code which contains the table, the ‘evaluation phase, and routine which uses hem appropmstely ‘Que LA] Write short notes om lexical analyzer generator. ‘Answer 1. For efficient design of eompile, various tol are used to automate the phases of compiler The lexical analysis phase cane automated sig 8 toolealled LEX,eat oper Des 1A9CCSTESem 6) ea analy. say whieh govern 8 at pedi biel sla At jhandrtten Leese iver fasting eke a compare LEX program in {LEN ans the sue thew tokens can Be CRecte ech a exe ere canbe reo GETTT] ean te ntomatie eneraion or | utomatic generation of Txial cena al ea ee antennae © proswunced as dot L Toco sc * Risin gree LEX Teele eee wor taxieatinne ‘elena anal Intra of tokens and prorat froctures order program ino — Felt together «that wales Tt sn, ork staerent, 6° of tesieal analyzer, ‘are Lestat) txsye + cer [Teele me Mig tats. 4. The LEX speciation le oresthe regular exresins fr the taken nd tbe leeyy file consi of te tabular representation of ‘Punition diagrams cnstrotdfar the regular expression Inspection fie, LEX ations are sscatd with every regula 11. These cine are simpy the ees ofCcodetha are directly caried rortothe ny Finally, ce Ccompler compiles this generated lene and produces an object program aout asshownin Fig L172 9 When some input stream is given to aout then sequence of tokens ses generated The described seni shawn in ig, 117 2. 1-206 (CS1TSem-6) Introduction to Compiler tue [6 | not compiler J aeeutable program Inpat_ Toy [_Steam “ing trom *| Tokens source program Fig. 1372, Generation oleriel analyzer wing LEX. Gas taBs | Explain different parts of LEX program. Tower | ‘The LEX program consists of three parts 1 I Deslaration section 8) ee ale section ee Assia procedure setion| Declaration section + ‘a Inthedeelaration section declaration of variable constants can be done, Some regular definitions can also be wetten inthis section. ¢ The regular definitions are basically components of regular expressions 2 Rule section: a The rule section consists of regular expressions with associated actions These translation rules ean be given in the formas R lation.) Ration | 2, tation) Where cach, ia replr expen seach aig rg fragnentdteng mat aon tbe taken or coresponing reqular expression 1 These actions can be apecied by peered Ausitiary procedure section 4 athissectin.l he pocdaresare defined which re reuired by the actions in the rule section. aOlt {AC (CMT Som.6) compiler Deen wo fotos seta coe ‘aint feton ean fonction FeRTAR] writes EX perms laneuae ewe | = program 6 Feng entity fee reserved word of e the besos") or nore ashi pater a | else | it | par |e dese ps indcates 0 sgnoring he white it) static | break switch | cba | 0D “egnd | vod | wale Ter keyed cunt pratnne int the keyword 768 | strut | case | ant | ons | oat | sale ve ‘Bee THR | Woot ar the various LEK actions that are wsed in LEX programming? ‘aaower | ‘There are following LEX actions that can be wed fr ese of programming sng LEX ol 1. BEGIN: Itindctethetart state The esl naar starts at tate o 2 CHO: Itemitstheinput sits 3 yytento %sxtext isa null terminated string that stores the Jxemes when lever repens the aken fom ng then Wher tend he nts yet ar aed BY ‘pew token. ee ces sem) Introdurtion vo Compile Thien an important function. The function yylex) ix called vr mart wanning the sore programm sles ‘Shen anne yserapt: ‘The function ypwrapl is clled when scanner encounter end of fie Iyywrapl) turns O then scanner continues scanning {yywrap) return 1 hat means end of file is encountered Sint isthe standard input ile that stores int ure program Joleng:yelengstoresthe length or numberof characters ia the iput Eng srken ina aicnsiting of ake name and an optional tribute ae The token name ia abstr symblrepreseting kind of xl unens can be Metitirs, keswords, constants, operators and anon sls eh a conmas an parents. ‘Alexeme isa sequence of charatersin the source program that matches the pattern fr atoken Lexeme identified bythe lescal analyzer as an instance ofthat ken ‘Aaternis a description of the form that the lexemes ofa token may take 12 Regularexpresions play an important role for specifying pater {8 akeywordisconsideredas token, pater sjust sequence of characters PARTS Formal Grammars and their Applicaton to Syntax Analysts ‘BNF Notation.pan CSTE Sem 8) ‘Compiler Desi Fa] peste om Tomer A amma ete fan be represen a A 4 oti sf fur te soctugeamima TPs Whe : ater 8 FC erally 0 fed cata et rina sometimes eae 250.619 Where wand Th ahasat le roducti Vis finte none terminal arereprest resented by ite nonempty set oft ere “Seoul terms are re tsar the forma -* Pat wet wbonecemens rent? act juctions oF ‘Soe san come cad prananr ees serminal known as starting symbol VT <4 ie.noterming siege ‘a shoudbe ota that ‘Ailsa po non-termina 4 Siespecal vara ‘Wale wrsaea ran GTR] wat is Content Pree Grammar (CFG)? Explain tomer] Contert free grammar: 1 AcRG dribess language by recursive rules called productions 3 Ac cant dsb sa combination four tuples and represented beueres tere, sae of sariables or noe terminal represented by A,B, oY Tos set of terminals represented by a, 8, on # Je 2s + + staring symbol. Ps set productions ‘he production vain CFC must ein the form ofA >a, where Ais vanable and ais string of aymbols Vo 7" The example of CFG is GaW.TB.S) 1240 CMT Bem 61 Introduction to Compiler snhere = IBLP = i. {UB and production in given an Boke bokee Row e vid ‘QaetG | Explain formal grammar and its application to syntax analyzer. Taawer | 1. Formal grammar represents the specification of programming tvth the use of production rales, eee 2. Thesyntax analyzer basically checks the syntax of the language 3. Asyntax analyzer takes the tokens from the esc analyzer and groups ‘them insuch away that some programming structure canbe reogniid [After grouping the tokens if tall eny syntax cannot be recognized then syntactic error wil be generated 5, This overall process is called syntax checking of the language, ‘This eyntaxcan be checked in the compiler by writing the specications. Specification tells the compiler how the syntax ofthe program Inne shoul be eee ‘Que 125, | Write short note on BNF notation. ‘Answer BNF notation + |. The BNF (Backus-Naur Form) ia notation technique fr context ere grammar. This notation is useful for specifying the syntax of the language ‘The BNF specification isas <!= Expl |Exp2| Exp. ‘Where isa non terminal, and Expl, Exp2 isa sequence of symbols. These symbols ean be combination of terminal or non terminals,rrr Lab (COSTE Sem 8) crass Desa 1 xa wer ipod “eres = fe? a names” cena ‘olame> = is caret stent name? <8 i mane, sre 8 we ean spect frat name, re mate. Sapeede by eal stn ope often no fo sa an in tua readable 4 RE ony rotations in BNF ae se onal eyelet IE ec repating the sb foro more mumDET canbe usd mes asterisk ‘ or example: [ael™ pt for tras ope lore mame of For repeating fumes sis sed Forexample nal” 4d Theater aes oreseparatdby eal pus be eeloed within Brackets Abii, YACC- The groopof items — Soe = Tony Answer Type and Medium Answer Type Questions Gee TG] What is an ambiguous grammar? Is the folowing rammaris ambiguous? Prove RE + |E(E) |i. The grammar should bbe moved tothe next line, centered. ‘Anawer Ambiguous grammar: A contest fe grammar Gis ambiguous if there {sat leas one strings L1G) having two or more distinct derivation tree, Proof: Let production ales give as: B+EE® 1-266 (CATT Sem-6) Introduction to Compile po kRY Bod rae tre for id #8 AL Hevies ao pone or iid Write short note on : i. Context free grammar fi YACC parser generator rte a short note on YACC parser generator, awe | 1. Context free grammar : Refer Q, 1.28, age 1-230. Unit Ji, YACC parser generator: 1L. YACC (Yet Another Compiler - Compiler isthe standard parser tgeneraor for the Unix operating system, 2, An opensource program, YACC generates cde forthe parser in the C programming language. 8. IeisaLook Ahead Lef-to Right LALR) parser generator, geerating ‘aparer, the part of compiler that tres tomake syntactic sense of ‘the sourcecode ‘Que138 | Consider the grammar G given as follows: 8+ ABloaB A-salda Bob Determine whether the grammar G is ambiguous or not. If ambiquous then consrut an wnanbiquosframmar equivalent1-97 C (CMT Sem 6) Intredetion to Compl (ARNT Sem 8) Long Answer Type and Medium Answer Type Questions Compiler Desi ‘ast s+ AB|oaB sama tet Let wt rate string ob from the ee wneren N A et te . I production's ight hand side. ! caesar tape etter cele oe Soe nts cr - snditions for constructing a parse tree from a CFG: Fach vertexofthe tee must have label. The labelisanon-erminal or than one pare tree. Hence, ing, eae ging mar than one Pe terminal ar nll. Sacer ‘Theroot ofthe re isthe start symbol, eS. cc sa ‘Thelabel of the internal vertices is non-erminalsyrabos <¥’, Aamo there is production +X)... Then for artes label A the Bab Children ofthat node wile XX, ammat bas nly, 4 vertex mi called laf ofthe parse ire isa terminal isan unambiguous grammar equiralent to 6, Now hi Symbol « Ear mll oe parse re for sting ob 5 ‘Goo 0 | How derivation is defined in CFG? 1. Adevivation is a sequence of tokens that i used to Find out whether 3 & No wages) sequence of string is generating valid statement not 2 Wecan define the notations a representa derivation Sane. 3. Firs, wedefine two notations => and ‘he SymatcSpifcaton of Prog i 4 Tfa-+ ie production of Pin CFG and a and b are strings in ion of Programming Languages Contest © (yoy Free Grammar (CFG), Derivation and Parse Tres, Youve tn Copabiliesof CF ub = oft—_— Comper Dosen pwnd te Wenay tat he praaction = 8a . ena ety des caer ie aanmar Go aren arm ceer 38 soto GEERT wd you mam ty tt eto eer ceaten wth name? Tower | Tene eration Tr dersin Utes pin agar art ei Puree fee tet mot derivation, Setontermina a ton scale poster seaeiersrs) gnc bE 0B cee aon Ei lahe (an civic ei right mst derivation, mont Aderinatin siecle Right mont derivation :AdervatinaS. aeration {fpr apbed nly to the Fight most variable non Example Let us consider a grammar having production E-+Eok|E eB |i Star with production E+E+E Ee ESE (Replace B+ E+E) Be Bed (heplace Bid) + Be idvid (Replace E>) oid « id id (Replace B+ id) FHT] write he copies of 6 400 (CMT Sem 5 Intredution to Compiler ‘aower | Various eapabilition of CFG are ener tre qrammar is nef to describe most of the programming Foun srrvearammar is properly designed then an ficient parser can be onstrated automaticaly ua the features af associatively and precedence information, Ten are for expressions can be constructed aoaren Ire grammar i capable of describing nested strctures like Can erenthesis, matching berin-nd, corresponding if then-ls's and so, — ‘VERY IMPORTANT QUESTIONS Following questions are very important. These questions ‘may be asked in your SESSIONALS as well as UNIVERSITY EXAMINATION. 1. Explain in detail the process of compilation. Mustrate the ‘output of each phase of compilation ofthe input Saab renbser2". ‘ie Refer Q.11 2, Define and ditferentiate between DEA and NEA with an ‘example. ‘wae Refer Q.16. @-%. Construct the minimized DFA for the regular expres (orn0+ 1110, ‘ane Refer Q. 111 Q4. Explain the implementation of lexical analyzer. Aue Refer Q. 115. Q5. Convert following NFA to equivalent DFA and hence ‘minimize the number of states in the DEA.1-916 (CSITSem-) Compile esis Zs | Q Rw , 7 a Basic Parsing unit . ‘naw Refer @Q 1.14 = Techniques (Qe Explain the term tole lexeme and pattern a Refer. 12 (Q7. What sansmiguous grammars thefollowin apt SS nbigeous? L sou ya saw Beer Q 138 " CONTENTS Qh Define parse ree What are the conitons for constructing ‘ose Parsing Technique 220 w 24C fares tre from aPC? Parsee Shit Redue Posing ax Fer 13 e900 | parca + Operator Precedence Persag 2c wo 280 | | Parts + Top-down Parsing 2-8 to 2150 Pree Pavers Part + Automate Generation of. 2-160 2170 Bitcent Parser LR Parra | ‘The Canoes! Calletone | orn heme Parts + Constructing SLR 211e w221¢ Paring Tables Parts: Constrvting canna LR 2.270 w 2-240 | ne Ta Part + Contacting LALR 280 9 2310 Paring Tables Using atalaald Aiguous Grammars | | An Avtomie Parser | Generster Implementation Parsing Table } 21 CICSIT-Sem-5)asic ars Testis oe ‘Basic Porsing Pechniques :Parwers Shift 2. 2CCSTT Sem) Answer Type Questions ‘ong Anwwer Typ and Medium Anewer TPS le of parser. What are the QeeBA | What ic parser 2 Write ther ‘most popular parsing techniaues tin baths paring gue Wt itonsows Euininoent ae cenuren open tt tein ge Aree ft Sian ae source yan teri sa ay base and recover from those errors. 2 Per ep oepr ny sta er 4 Pare ep coset pare oe a8 connie ‘Tere are basically two type of parsing tecniaues 1. Topedown parsing: sean 2 Topdor arg atop find the eto deren an in ring that start fom the rotor start seb, and treat noes in pe defied order 1 Tntop-down parsing the inp trig is sanned bythe parser ffom to igh one syminsken ta tine ¢ Theletmost derivation generates theleavesofpars tree inlet tori order which athe othe ipl ean order. 4 Inthe topdown parsing parsing decisions are based on the Iookabeed sym or sequence af symbols), 2 Rottom-up paring 4 Raton pasng canbe defined aan tempt reduc the inp string the stat symbol grammar ding oat the igh ‘oa derivation own reverse pases it ta rst of phases of Compiler Design 2.C(CSITSem-5) Parsing nvoves seeing for the subatring that mates the right side at any of the prodactiona of he gramme pce bythe left hand side non-terminal ofthe Thineubatring production 4 Process of replacngthe night sd ofthe production by thet side hon-terminal called “edction” War | Discuss bottom-up p: parsing techniques? ring. What are botto Bottom-up parsing techniques are : 1. Shift-reduce parser Shit-reduce parser attempts to construct parse tree from leaves torootand uses a stack to hold grammar symbols b Aparsergoeson shifting the input symbols onto the stack until handle comes on the top ofthe stack, ‘& When s handle appears on the top ofthe stack, it performs reduction iad § Tapa ape rite bead Seeking eat | shit dace pacer jem ‘ep Same lg. 22:1. Sit rece parser This parser performs following basic operations i Shin B parser i he most efit method of baton Barsog which can te used to prs the lage case ofentent fee frammars Thismetiod sao LR parsing Here_— i # i ~~ cut em cits acicarrsons) ‘ “eas tmurer of put symbols ‘When kis omitted it BT wna rthecomen conan tenure innit per? al a One a a nce anes fuction rule in the grammar recep » Sekai Beomeeste stares Rees ane toute int arte nanan opt “entiation = «eters prea ca be racer cay be eased when the same rl isonet Operator Precedence Paring. onic encounter in sit reduce PRESET common type oeoniic fund rammar allows 800" ete, fo he sa the grammar becomes ambiquos since @ pore than one 2 js reached by more Tetons Anewers Long Answer Type and Medium Answer Type Questions GeeBA | Explain operator precedence parsing with example. ‘answer 1A grammar Gis sad tobe operator preedence iit posses following opertis & Noproductionon the right sides Compiler Desi 25 C(CSIT-Sem-5) 1b There should not be any praiyetin rule prmsesing two adjacent tm ternal at her hand ie enna we 12 Inoperatr precedence parsing, we wife defce gevordence relations and > between par ofterminals The meanings ofthese relations ye ‘Ries more precedence than 9 nn ‘haw same precedence as ae Piakes precedence over q Forexample: Consider the grammar for arithmetic expressions B+EA| BE] id Ase ITLS 1, Now consider the string id + id * id 2. Wewillinsert $ symbols at the start and end ofthe input string. We will also insort precedence operator by referring the precedence relation table Seid >terid-> ted 98 4 Weil fellow fellowing steps to parse the given string Scan the input from left to right until fist-> is encountered 1b Scan backwards over = until <- is encountered, The handleis a string between <- and > 44 The parsing can be done as follows $< ld- 9+ id->* cid >] Handle id ieobtained between <> Reduce this by Evid E+ * 8 | Handle ids obtained between <> Reduce this by Eid E+E* S | Handle id obtained between “> [eee ra Insert at the benning and at the fend. Alo nuert the precedence pera. Seve SE |The * operator is surrounded by | (25 satin tah ieee mca we he [ce Bopeaton ae | Sets | Now + becomes handle. ‘Hence, we Sanat ss Parsingis doneye Techies Basic Parsi peccstTsemS) FeaaE | ive he algorithm for computing Precedence consider the following operator precedence mat coord compute te precedence fund fence function: -Agorithm for computing preeed Input: An operator precedence matt pet Perens otis presnig i PU DATS that noe ess or anindication = or tho aps ante,eonhettinateeiat ors Fee pete leit many oun aero Pari en and ay eine se °D s sertrecd qrashuhoe nears theo bun ste? For Gere dete rae an ee om he rou ff tHe OUP Sr eee cc neg to th roe of, ota 4 le raph eta in sep 3 bas acc, the no, prcedece ca ete tere armen tf the leat ofthe ones. cat en e)btbe engtino he lget path rm li group af, Then there exist a precedence fonction Precedence graph for above matrix is: 27 C(CSIT-Sem-5) compiler Desa ~ From the precedence graph, the precedence function us ‘igorithm calculated as fllows i (Teo Ts) TERE Fe GueTE | Give operator precedence parsing algorithm. Consider ‘he following grammar and build up operator precedence table, Also Piie the input string da(idvid)) Pp oEATINT PERE > @)lid Taswer ‘Operator precedence parsing algorithm : {Lecthe input string be e122. an, Initially, the stack contains 8. 1 Set pto point tothe first symbol ofS Repeat: Leto be the topmost terminal symbol on the stack and let b be : the current input symbol. Pe crnly fis on the sack and oly $8 te input then accep and freak teria Tre» boraé tens ont the stack and inrement po ext Japa symbol St ce ifae then rece rom the tack in Repeat cee po the ack + Untthe top stack terminalis related by » tothe terminal most recent popped te si Callthe ror correcting outing end Operator precedence table: wet as wes >er ssts—Ss hou Teh es i DAE (CSTE Sem) compiler Deen ee Secondly in backtracking we ned to mare some levels upward in tinder ta check the Puree sed bersene” >| ihilities This increases lot of overhead in 7 S08 Hann wai ‘phmenttione paring r ese betwee <> “a Hence it becomes necesnry o eliminate the backtracking by a fee ges ett " jane id vob A The left recursive grammar in represented a2 ap Tinea . ert at tbe Bonnar st |b. Here = means deriving the input in one or more steps. sel fe Here,A is non-terminal and a denotes some inpt string Frans we have € becomes handle shat bcome en a [Lang Answer Type and Medium Answer Type Questions QeeRA | What are the problems with top-down parsing? newer Problems with top-down parsing are 1. Backtrackin 1 Backtrakig i eehiquein which fr expansion of non terminal symbol, we choot alternative and ifsome mismatch occurs then very another alternative any. > ffranon-trminal, there are multiple production rules beginning ‘wth the same input symbol then to et the correct derivation, we . eed etry al these alternatives. {4 tfleft recursion is present in the yrammar then tp-down parser can eter int ante lop @ a Yea Q ® a ® @® ® ig. 224, Lt recursion. ‘This causes major problem in top-down parsing and therefore limination of eft recursion is must. Left factoring: Left factoring occurred when tis not clear that which ofthe two alternatives isused to expand the non-teminl. bb Ifthe grammaris not lft factored then it comes difclt forthe argertomake decision. ‘QueBA, | What do you understand by left factoring and left eliminated ? recursion and how it ‘Answer Left factoring and left recursion : Refer Q.27, Page 2-80, Unit-2 Left factoring can be eliminated by the following scheme: a Ingeneralit A> a8, la, Lolo bob ica production then snot pesibl for parser totake a decision whether to chose fire rule oF second 'b_Insuch situation, the given grammar can be lft factored as210CCSTSem.s) Basie Parsing Techniques Asad Hel ASK IBL IB, {Left recursion canbe eliminated by folowing acheme : © Ingeoeral if A+ Ag lA, (1A, HBB, srhere no f bein with an A In auch stuaton we replace the productions hy ABABA oD Asolo] [0A le ‘QeeRS | Etiminate left recursion from the following grammar S+AB,A-+BSIb,B-+SAla | Saas AsBSIb Bs SAlo saan s-as0|60 5+ $A5B1 aS 188 9-688 5+ ASBS| Bosnia B+ BABBA|SBA\e ba (as B+ ABBA Bc A+ BS|0 A~SAS|aSla A+ ABAAB|aAB|o As aABA’ Jas! A+ BAABA' | ‘The production ae lef recursion is S088 [68S ASBS| A+ aABA at LU CCT Sem) 19 aan, 2 Bo BHA jay Bs ARBAB. ‘GeeBIO|] Wee shor noes on opdown paring, What are op down parsing techniques ? Taower | ‘Top-down parsing Refer @ 24, Page 2-2, n.d ‘Top-down parsing techniques are: Recursive-descent parsing i top-down parser tat executes eof rere procedures to proce th np without acktaeing side nee farerand parsing sealed recrsedexen oe ik Terecv parece etka set iC writen in angage tat plement ine pda al efficiently, " ia 2 Predltive parsing: i Ameditie pringisan eticen ma ofiaplenentng recursive despre by handing he ak a ote ee ji Thepreditive parser hasan iapu,astack a parsing abe and an output The input contains the string tobe parse flowed by 8, therightend-narker, GEE Prodan Parsing | rahe ig 2101, Mad opie pr i The stack contsint sequence of grammar symtrs with $ indicating button of he tack Italy, the sack contains the Sart symbol fhe grammar pce 8 iv. The parsing able isa wo dimen array M A] where's ‘on tera and terminal the eybol ‘The pase contrat ya program that behave a fliws Fe ostput Stacksna Tecnign BARC (CSTE Sem 8) He senate; the Pr Tyee naire he Palen eth pies ss teks asf the pane tsa ame tevieoel rane he tarkan aances the b WN eo $.theparer pope puts eee pean onset MI alo 1 Nien eternal te 108 ms at ASRS cy teter ane BAIT pire henen open and pion PPA. “Under which conditions predictive parsngcan be constructed grammar? opener Bottom parser] Topdown parser | __ Bottom-up parser om moe |r T down parser left) In bottom-up parser right-most eaten pre | eter 2 Backtrackingis psible. | Barktracking is not possible “nti. npwttokenare popped Inti. it token ae puabed on Campi De aie: CAT Sem5) ‘Aigorithm for FIRST nnd FOLLOW. 1. FIRST funetion FINES (Xin tof terminal eymbols that ar first symbols appearingat RH. sn dervvatnot a Following are the rales wed to compute the FIRST fun 1 IfX determine terminal symbol then the FIRST 2 a 1h Ifthere isa rule then FIRST contin © UXianon-terminal ad X-¥, ¥,¥,.. 7, a production and ieisinall of FIRST. FIRST Y, thee FIRST) =(FIRSTY,) FIRSTY,) UFIRST'Y,... FIRST, 2 FOLLOW function FOLLOWA)is defined asthe set of terminal symbols that appear immediately tothe ight of A FOLLOWIA)= la |S S0.AaB where a and fare somegrammar symbols maybe terminal or non terminal, ‘The rules fr eomputing FOLLOW function ar as fllons 1 Forthe start symbol place in FOLLOWS), bb Ithere isa production +08 f then everything in FIRST without cis tobe placed in FOLLOW ¢Ifthere sa production A+ aor A Band FIRST\B) contain « then FOLLOW(B) = FOLLOW). That means ‘everything in FOLLOW) sn FOLLOWS), ofthe stack the tack First and follow ave deinedin| Firat and follow are used ia) topedown parser. trp pase. Shit-reduce parser, operator 15 Predicve parser and recursive meer precedence parser, and LR pase | dosent parser are top-down GoeBis | Ditterentinte between recursive descent parsing and predictive parsing. Taswer |] | parsing techniques. l are bottom-up parsing technique. S.No. Recursive descent parsing] Predictive parsing Predictive parsing can be constructed if the following condition Lf ee ‘build recursive | Recursive routine is not build folie | a 1 Brey rammar mt be recursitin tre [iso reduction rl [racinut omer | 2. Each grammar must be left factored. converted into program. into program. 3 [Parsing table iv ot [Paing tabloid ‘WeeRIE] wnt are the problems with opdown parsing ? Write Peri 1 | Fistandflowisnotsed. [Fest and flow is wved to (he algoritha for FIRST and POLLOW. ‘Answer Problems with top-down parsing : Refer Q 27, Page 2-80. Uni-2 constrct parsing table.Pia Paring Teehniguey DAAC UCSMTSem 8) BERIT retain non rcursive predictive parsing: Conair the fotlowing grammar and construct the predictive parsing thle ray B seTE lc Tart porn |e FaPlalb iow | Noo recursive descent parsing Predictive parsing Hels 210 Penne tse Sener rat Fate ror rer PaPiai Fox eee it ein rarely Posh iF Pari asn)= FIRS = FAST =. sr. RS asm Fouowe=18) POUOWE (8) FOLLOW =I", 4,8) LSC CHIT Sem-5) ‘GHRTAT Discus working of L parser with ts ok diagram, Wy ie most common ued parte? Tamer] Workingof LR parser: 1. Theworkngof Lt pare cane understood by sng bok gram an ‘shown in Fig. 2.15.1 bibmchranin F] pot ape BS TR pariog |e ostpt ste! rs Set ni ting a Cs ig. 2181, Modelo as LR pare.ace i avtark LITCWCSMTSem-5) snow are TRIE] We sort nto my sti tm Fe rammae ever aetna a pgrome sae forall LR pare tains stack, Kernel and non-kernel tema 4 Punetions clowure and gota cat te and stint following SNSUS Se \scramiar nyt cach the state abd, statis top The atthe drier program dpe econ npat sake care pose fr MPA, “a hi Ste parser che input symbol, then tack tateS Now current input symbol son action 8.0) whereas Following SiN aston Sen the stk a teens ‘The pructionS-+ generates only oneitem $+ 2 Augmented grammar: Iris dishing arom ten ttgmented puma Os whchS vance sts ee Input sea S55 The pup the ae ; eee ‘Panmaris wind cepa SMS Aa Sedy SS arr ‘gut That is when parser is about tw sedsee $6 ka 1 Reduce acon 5,» rede Ate parser exeeute scceptance tat ease Caan 2A p pitino te amma A=. 4 Kernelitemtsclciooftns + Sand alte tse Fi arpa ew pte ore eso Ur aesota thet me endo RS oF ir state symbol and r grammar symbol). So, the top = Non-kernel items : The collection of all the items in which © are att ‘now becomes S,, then A is pushed on the stack, and then state left end of RHS. ofthe rule hich © are atthe fouls, assed nh lack Te caveat apt symbol i 4 Panction lure and gto Tee are inp tone eet Inquest cline anne oan fuck Input SM Sen May SyeS as (PaRrs] ers $= Gata Sa Constructig SLR Paring Tables {tates ae psig completed {action |S, =eeor the parser has discovered a syntax LR parser is widely used fr following reasons 1. Li parsers an be contracted to resngize mast ofthe programming language for which context fe gramsnar can be write. — QueZI7] Explain SLR parsing techniques. Also write the 2 Theelasofgrammar that canbe parsed by LR parser ia superset of clas ofgrammars that cane parsed using predictive parsers, algorithm to construct SLR parsing table 8 LRparer works using no backtrackiag shit reduce techni. ‘Answer 4 LRparserisanefcen pare ast dtetssytacticerror very quickly ‘The SLR parsing can be done aDISC (CST Sem) eee Tonsiraction of SLR parsing th strat ‘ig. 2171. Working of SLR pare. sgnstruction ofan SLR parsing table: Algorithm for ‘atu the canna clctonofsetsfitemsfor ab augmented rummar ¢ Gotpu:poanible,an LR parsing abl consisting of parsing ation function ACTION and goto fanction GOTO. Method : Tene iy fy not The state ofthe parser are, oon state (ing onstroted from |, ‘The parsing action for state is determined as follows then st ACTION li, 0 1 IF|A-+aeapl i in/, and GOTO U0? eft Hevea ia terminal UA ve] is anf the set ACTION [ato “reduce >a" forall‘ FOLLOW (A). f(s -» Sis in then et ACTION i, $0 accept”. ‘The goto transitions for tae ae constructed using the rue, 41160701, 4)=1, then GOTO li, Al =) &Allentries not defined by eles (1) trough rue (4) are made “error” ‘The inital state of the paser is the one constructed from the set of items containing |S *S) “The parsing abl consisting ofthe parsing ACTION and GOTO function ‘determined by this algorithm iacalled the SLR parsing table for @. An LU parser using the SLR parsing table for C iscelled the SLR parser for Gand grammar having an SLR parsing table i suid tobe SLR) WRTRT consrvt an SLR) paring table fo the flowing 2 ‘S-+A) SOAPL PP P-+(oum, sum) ([Rmro ROT To Marks 10) Compiler Design C (CST Sem-5) gente grammar (for an sag Mere mma Ci Soa) sone SonP acai? canonical collection of sts of U0 mi nats of LH tem or grammar area lows Sosa) Sacap 33: P+ (enum, num} Saaye SoA? Po slau, num) =GOTO (ly P) SPP GOTO Uy nm) P-> um +, sum) i) =GOTOU,,P) h SAPO T,=GOTOU,) a S40 eP P+ foun, num) 1, =G0T0U, ty P-+ (num, + num) 1, = GOTO, PP S4(P.Pe 14,=GOTO (1, num) a 'P-» (num, num *) I= GOTOU, 1 he P+ foum, num *i secre asic Parsing Techniques NC CHT sem) —r ry datuine Seppe] ey | ttm ea I Sane LS | tt el So eAslo5 74 + {accom AO *SAl eg ; Liss 1=conbin, : ioSabe {-— 1,= 00704, 0) |— [odors @ fgeCOT0 21, Let wenunbered th etn enh rama [ 1 S+AS 2 sab FERED cote teres rime a S-4syb {Ave alee Construct te SLR prs abl forthe grammar Show the atone ouoesrae ofthe parser forthe input string “bo, [ARTUOIGI7 Mark 5 FOLLOWA)~ia6) | ae 19:1, SLR parsing able The augmented amare ‘eon Gore a8 aaimle | 8 [els [a S45)6 ese 4 aoe tL S| 8 | et 5 ‘The canonical cleton of LO items are a re ran a TS S+eAsiob i ua a fy AseSAlea u iA te core, 5 a 18-480 SA3|eb 7, TOL | Anse Iasic Paring Techniques Compiler Desin pacicetnsens) | secicurans, ae ans tones ret ae BS 1 <00701, h se are Boker Table 218.2: Parse the inpot abab using parse abe =COTOU,0) — h eon) Foeeee sik alt |__| Eke tab | Reduce Avo E+) mit | Sh Boia ost | Reda 5-9 1<60T0 uid 4 2 Eide = =— [= GOTOU,, +) ott Shit | t BoE oe | Rete a0 Powe Eoepee Rede A-2A 8 B+ 4B) os an Bond 1-coro4," | $ Reduce Sb | k gen 3 | Rede SAS pace L eltEE as 7 | er nS - Bstid ‘TeBBE consider the tolowing grammar B+ BEB) frond, BS Consrut the SLR parsing table end evggtt your fn parting Evers BletE table [ARTO a0; Mars 1y=GoT0uye) z sks be “Aawer | Babe ‘The augmented grammar iat BORE BoE ty=Gorou,.£) EOEsE h Bs BSB rae | Ea Be Boe) EGEVE Baud 1y=G0T0U, ‘The set of LR) items i a flloms n: Bs Be| le asi Paring Tech | Compiler Design 2480 (Carr Sem) le | 5 Gae2BE] Construct Lo) ° srammar = > eBlecd Avedle ‘TeEBT] Petr sin cede psn forthe given ip ering * aig the grammar SD ]e-+ SIS ae newer] i (aia) lao =” ‘Te sugmented grammarie Sas - S25 Tiack contents] Tnpat airing | __ Actions so etica ‘aie.0)8 Shit la ‘ Geos Suite Boel fe “a.0)8 Reduce +e ‘Te canoical election of LR (Oem are ss Hedacs 98 sas SL a, Sunt $4 ¥eBleceh si Shine AsscAloa sie | Reduce S-+¢ Bos seeb ob es Reduce LS SL Shit seit, suite Side Reduce Sa SLs Redvce Lo bsS oTO a Shit) 1SorerBlerea ses Reduce $9 (L) Aves sis Radice £9 E.8 Bosc wi he ob Alve Redce S-»(L) Asal - accep Bs vB2.960 CTT Sems) 1. GoW, « 1 haat 1,000, 5) 1 Rane 1.200701, 8 1 See 1. eaBe,§ Sr ebde8 Ashe Bos efdleNa MA slam 2.910 1087 Sem) rr 1 sem, § cust 7s Ssennus i Samet J fo ett os ate 1, 200, pr : Satna. L_ satedes Ct pad = pote 1, <00oTO, A) i Sates 1 scoror, ® : t Sooapeas s f= GoTO, 9 “ ty Ao iid re Bape ; = ss GOTOH, ‘i ad ‘GeeFaE] Show that the flowing grammar ome $-+Aaldde|Be|bBa secon i f:=CoT0H, LRU) but not LALR 4 Aoind Bowe = 1y:= GOTO, 4 a ‘ as Augmented granma G forthe pven grammar Ss . sos So+Ae S-rtde S-rBe Ssh‘ao arsine Teenie aed 1, .G0T Uy) 1 Sa8e8 1,260, 1, S-sAte§ GoTo) 18-4 bee 8 SbeBo,§ Ashe 1, Bate 1=GOTO UB) 15-9 Bee 8 1=GOTO yd) IsAsds, Badne 1,=00TO (1a) 1S Aas, 1,=C0TOU,A) TS bate,$ {,=GOTOU, B) 128-4 bB00,$ 1,=00704,2 athows Compiler Design a WA dee Noten Nye GTO fy 8 oes hy GOTO Ny Sov bhena 1-607 ta Ip 8+ be, ‘Theat tabl wil be desi sons Table 281, state ‘Action a ei |aikes] ay 6 | ePaper] < Ss Ss 1 26 Z accept 2s 3 s ral 7 & t steppe — 8 a 7 Ss os 1 ol a 0 a t 2 nh | -] Since the table doesnt have any confi. So, itis LR, For LALR/1 table item set and tem set 9are same. Ths we merge both theitem sets 1) item sey Now, the resultant pring able BecomesGoto e{sfa Jalal —__| ee] - i|s 2 | nm Since the table contains redce-reduce confit, itis not LALR(), GeedT| Construct the LALR parsing table for following SAA Asak ash {LR (1) butnot LALRAD). awe | ‘Toe given grammar is: ‘SusAA Assaalb ‘The aygmonted grammar will be s48 S444 A-vaalb - BAC (CHTSem-5) "The LID) items wil be se s SAA A> saAals Ao hal GOTO 4,8) 189 S09 1,=GOTO UA) IpS-+ AvA,S A aal,$ Aves = GOTO U,,a) TyA>a0d,o An eah, ah As ebab 1,=G0TO,,) TA beat 1=GOTO yA) [pS+ Ades 1,=GOTOU,.0) TeA-va0a,$ An wads Aa as 1,=GOTOU,,6) TA be8 iy=GOTOU,, A) TA ahevob . [pA aes 1,=GoT0 4,2.26 C (CST Sem.8) ase Parsing Techniquen Table 227.1 a L a | esr .cstt sms) sic LA ie dnp ens sm non Sn | i) so LAL) ‘VERY IMPORTANT QUESTIONS Since table doesnot contain any coat. So is ERO) ‘The goto table will befor LALR J, and /, will be unioned, I, and, wil be unioned, and fy and 7 wil be unioned. So Tyg Acta¥A,a/b/8 As eat.a/b/$ Anvab,a/ BIS Ig: Abe, 0/B/8 Tg: A sade, a/b/$and LALR table willbe Table2.27.2 IMPORTANT QUESTIONS | Following questions are ery important Thee quction maybe ashe in our SESSTONALS on ellos UUNIvansiry mxauinATION, Q-1. What is parser ? Write the role of parser. What are the most popular parsing techniques ? ‘aww, Refer Q.2.1 Explain operator precedence parsing with example, Refer Q.24. What are the problems with top-down parsing ? Refer Q.27 a2 sux Qs. aa @4, What do you understand by left factoring andleft recursion, and how itis eliminated? ane Refer Q. 28. Q5. Eliminate left recursion from the following grammar S-+AB,A + BS|b,B > SAla Aue Refer Q 29. Q.6. What are the problems with top-down parsing ? Write the algorithm for FIRST and FOLLOW. ‘Ang, Refer Q.212asc Parsing Techni 2.386 (CSITSem-8) Qs. wwe parsing, Consider the Wve predict Explain non-recurive predictive parsing, Covent Oe following grammar and constr table eoTe Bo eTe le rrr TET |e FoPlol® Refer 214 Construct an SLR(1) parsing table for the following grammar: Soa) SAPIPP P > (num, num) Refer@ 218. Consider the following grammar E-> E+E | B*B|(E)|id. Construct the SLR parsing table and suggest your final parsing table. Perform shift reduce parsing for the given input strings ‘using the grammar > (Z)|a +L, S|S (aaa) faa) Refer Q. 2.21 600 unit Syntax-Directed Translations ( CONTENTS) Beretta Part tn sacs | Parte + Parts + Parva: Parts Part Syntax Directed Trenaation S Implementation of Syatax-Directed Translators Intermediate Code, Past Fix 3-60 to 3-96 Notation, Parse Trees and Syntax Trees ‘Three Address Code, 8-90 w 8.130 Quadruple and Triples Translation of Assignment, Statements S43C to 3-18C Boolean Expressions Statements that Alter the Flow of Contel SAKE to 216 Poatfie Translation» Array Reference in Arithmetic Expressions BIC to a9 Procedures Call B:290 w 3-250 Declarations Statements 3-280 to 3-260 S-1C(CSITSem-5)S2C EMIT Sem) Synan Directed Translations PAR’ ‘Syntan-Dirwted Pransation Syntax Directed Translation ‘Schemes, Implementation of Syntax-Directed Translator, ‘annotated parse tree for the expression (4* 7 + 1) * 2, using the simple desk calculator grammar, faewer | 1 Syntax directed definition/translation isa generalization of context {eee grammar in which each grammar production X >a is astociated with ase ofemanticrulesof the forma:= by bb), where ais tn attribute obtained from the function Synta directed translation sa kind of abtraet specication. ie done for static analysis ofthe language It allows subroutines or semantic actions to be attached to the productions af «context fre grammar. These subroutines generate Interme ‘ate cde when called at appropriate time by a parser fr that rammar, 5. Thesyntax directed translation is partitioned int two subsets called the synthesized and inherited atributesaf grammar. ‘Token stream Dependency graph Syotax directed + Tronaation 4 valuation order fr semantic rules + ‘Translation of constructs Pig 34. yiler Design oe SC (CSITGem5) Annotated tree fr the expression 475 1x3 a1 @ ter + @ Alert «2 ‘lewal=7 Figs, ‘Gee | Whats aya rca translation? Hw ae semati sctons attached tothe production ? Explain with an esampe, Tower] Syntax directed translation: Refer Q 3.1, Page 3-2C, Unie.3 ‘Semantic actions are attached with every node of annotated parse tree. ‘Example: A parse tre along with the values ofthe attributes at mses (calledan “annotated parse tree" fran expression 2+ 3S with synthesized sttibutesis shown inthe Fig 32.1, Evrae ® BF ales trate (8) Feate(®) Aligtexvale2 Aigtlewales| Fig. 821.sean Devt Traine hese camper Desi BSC CMT Sem) S4CUCSTT Sem 8) Inherited attribute rae aherited attribute ce whe ied and inherit whataresymuhesired ed we a ee in pare tr spain atribtes EJ Mane intrtw of olibstes athe pret eer aea tts eoe saci 2 Ir airconn hoeg io (ergranmena langues eta = Ficaample:Syntaseid Stns tht wes inert atte ‘ere eon wth ange O84 by tonne an se tin bon SDSS SS ome Pit pst arth lb 4 ebony tcrated hth amma mb el Tread Topesereal tare aren Hoantan zoate sich a ing. 4 4 5 More ca eps anne rane ah a tring cherie. Lip serine oe Ciena sede age Lovid covert pL ope Fe LEST panetree des define by asemantc rae ‘eps tre slog wih be atsibue ales the pare we er 22 4 TRING EIN protacton se at hat nde Input tring int id, and di shown nthe Fig. 992 syeteszed athe Sener nies sadto be atone its vals computed “ feat ade inte pre te fom the atstd values ofthe cen A optan directed defizitin that waes the synthesized attributes is acusely sandto be Sttributed defining. ed definition can always be annotated forthe atrbutes at each node from 3. Thus, a pase tee for attrib by evaiatng tbe semantic rules learestoroct 4 be translations are spied using Sateiboted definitions, then the snan rules cant conveniently evaluated by the parser itself during the parsing For example: parse tre slong with the values ofthe attributes at Fig. 2, Parse tre with inherited dee called wn "entated parse tree" for an expression 2+ 3°S with tributes forthe sting ity ‘these attributes i shown inthe Fig 33. enien ‘Queda, | What is the difference between S-attributed and Leattributed definitions? I ‘B.No| Sattributed definition | Lrattributed definition 1. | Ttuses synthesized attributes, | It uses synthesized and inberited wae 7 y 2 | Semantics actions are placed at | Semanties actions are placed at Seana | seers 2 Seca ortcan) carne cabana] 2. 2. sate fae tepis ‘Fig 3.3.1. An annotated parse tree for expression 2 + 3*5 iret, left to right.yl fe Syntax Directed Translationy 6C(C8TT Sem) PART-2 Intermediate Code, Pots Notation, Parse Trees an Questions Answert ‘Long Answer Type and Medium Answer Type Questions d Syntax Treen, jon and discuss benefits of intermediate code? Taewer Intermediate code generation is the fourth phase of compiler which takes pars tree aban input from semantic phase and generates an intermediate fede as ouput. The benefits of intermediate code are: 1 Intermediate code is machine independent, which makes it easy ty ‘target the compiler to generat code for newer and diferent process, 2. Intermediate code is nearer tothe target machine as compared tothe source language st is eascr to generate the abject code 4. Theintermadiate cade allows the machine independent optimization of the cde by using specialized techniques. 4 Syntax directed translation implements the intermediate code ‘generation, thus by augmenting the parser, st can be folded into the parsing. GeeRR | Wnat is postfix translation ? Explain it with suitable example. Postfix reverse polish translation: isthe typeof translation in which ‘the operator symbols placed after itstwo operande For example: Consider the expression : (20+ (-5)°6 +12) Posts for above expression ca be calculate as (2044, "6612) tys8- abst o12 henge perry te Now putting values oft 4 tt, hehe Compiler Desien B1C(CSIT Sem) Dyes mere. (205-626 Fe inte cre? Tomer] Pere: a enh it hd io rps arn ea shan te ee ee ee er crea pees tem ser es ennai tesa ea ee raat er ea arnt idbaleel cal . Eobbelt nie rane eat, , Moewisapndenead one tos betere ata nl ‘elaeaed eas beat te dal nsf dll recs enemnsrtn et pete he O Tite ene perio cee ‘GeEBBT] what is eyatas tee ? What are the rales to construct, sytax eee fran expresion? Aawwer | 1. Asyntax trois a tee that shows the syntactic structure of a program while omitting irrelevant details present n parse tee 2 Syntax tee is condensed form ofthe parse tree 3. The operator and keyword nodes ofa parse tree are moved to their Parent and a chain of single production is replaced by single link ‘ules for constructing a syntax tree for an expression : 1. Bach nde in asyntax tree canbe implemented asa record with several fields. 2 In the node for an operator, one field identifies the operator and the Femaining field contains pointer to the nodes forthe operands 3. The operator often is calle the abe ofthe node 4. The fllowing functions ar used to create the nodes of syntax trees for ‘expressions with binary operators. Each function returns pointer to newly created node. -Minode(op ef, right): 11 creates an operator node with label op ‘and two field containing pointers to lft and rightwe OO BSC (CNTT Sem 8) Syntax Directed Translations compiler Desixn P SC CHT-Sem.5) 1 Mhleaftid, entry): I creates an identifier nove with label i and the feld containing entry.n pointer to the symbol table entry the identifier Mikloafinum, val): It creates a number node with label num oti notation fora *(b +6) are 7 ‘field containing val, the value of the number fatal” . 1 value of, For example : Construct a syntax tree for an expression a —4/+¢, In bs this sequence. >. Pare pointers to nodes, and entry a and ‘entry ¢ are pointers to the symbol table entries for ident ‘a’ and respectively = meal id entey a y= mkleaf (num 4, Dis minode (pot [Parrs} Pi mkleat id, enter Three Address Code, Quadruples Pe mknode Cy py) ae and Triples The tree is constructed in bottom-up fashion The function calls moat a ud, entry a) and mkleaf (num, 4) construct the leaves for a and 4. The Questions-Answers, Pointers to these nodes are saved using p, and p,. Call mknode Ds-p.) then constructs the interior node with theives fore ad 4 Long Answer Type and Medium Answer Type Questions aschlidren. The eyntax tree will be fez |e sa) ‘Wee AHOT] Explain ehreeaddrens code with examples = antl 1. Three address code isan abstract form of intermediate code that ean be ey peal implemented ara record withthe address fete 7 2 The general formof thre addres code repreentation ie vaca fora @=bope he eptan ten a4. » eRe where a, 6 and c are operands that can be names, constants and op GeeRRT] Draw syntax tree for the arithmetic expressions ‘preents he operator 427 (b +6) di. Also write the given expression in postfix notation. 3 The operator canbe ied of Moan point arithmetic operator orl aperators or boolean valued data: OMY cage operation a gh ical = the expression allowed ta tine. Syntax tee for given expredsion:a*(b +e)—d2 ‘There are at most three addresses ar allowed two for operands and ces = ‘one for result). Hence, the name of this representation is three address cote For example: The three address code for the expression =b eu ae | Qsbee tated Here t, and ¢, are the temporary names generated by the compi10C(CSITSem8) ‘Syntax Directed Tranlations S11 CC8TSem.5) GeeRAT] What are dierent ways to write three address code? ‘Answer Different ways to write three address code are : 1. Quadruple representation ‘The quadruple isa stuctre with at most fur felds such sop, arg arg, real 1b The op ld ie wed to represent the internal code for operator the fang and are2 represent the two operands used and result fil is ‘sed to store the result ofan expression, A> Cand B- 1# irc trplesrepresetation Tie init leepenstion + peitialnpe dread ponerse oedinsed fasne atone Forexample:s Teint iereprsettions atbe-atb following expression Gey yesisteayery = ‘The three addres code for gvem expression tyexey eyes Lent {The quadruple representation | Eocation | Operator | Operand | Operand? | Result im 1) 3) 6) + |i lll ae cape Ds S12 (CSTSem-5) ‘Syntax Directed Translations On —_—_——_—. _ F130 (CHIT Sey Tee trperepreeotation GERTE] Generate tree addren code to el Location rat rand! | Operand? | i, 12 Bl dV + TALE 115 Dt, ou an, ey ae ee Over] Ging aoestion, i cede) Asani get te ay datfor » | ¢ : : integer Let an 410 20 erat em aman zt Goer tor #1404 =n « 0,020 Titres pe repeat Beets hee stan teeny tree ‘ocaton| Operator Operand Opera) [Laaiion] Same Bde xd spats toe tt ao mt | SP Re] | cctet MATET Owen ae a | | a |g | & |) & os cia ices 2s ta 80 ef | dy) a |} a) im OMNES ce Ls 1 L_] L. = = 4% (204 +) +(base 84) [1+ 1+ 1) ‘GeeHIE] Generate thre addres code forthe lowing code: s4ede@hispenancsocs 2: ase 3 Therefore, three adress ode wil be PART-4 = Questions Long Answer Type and Mediums Answer Type ‘Bgoto 113 Poet woes ‘TR tw weltpecetefaoig ime ues oateneriuanelane Be Sassi mae 1 Case statements ‘ARTO DIT, Marks 18) 6: 117: Nest statementCompiler Design Sec (CTT Sem) syotan Directed Transations ewer Assignment statement ‘Semantic actions al (Cad entry = Ik upid. name), id etry ail then fppend vid entry Eplace) coe errr, "i ot declared? BISCICSTT Sem) 1 BEE, TV Bplace = newtemp, , LER ppend place ='B, place’, place) 1 | Boplace = newtem Sppend pace» E place place) stem i ‘Switeh E ‘Braloate Finto¢ such that = sppend place '="minus’ place) ’ foto check ceases, | Ly: coders, (E.place'=B, place) ame | pal ai (ident: = lok pid name, enact, ie, | Pe = ifid_entey nl then aetauli', oe I | ‘Slane Eola) ) entrar danaecare item goto, 1. Thelookypretumns the entry forid namein the symbol table it exists ; rei L, there. i} ‘a | 2 The function append is used for appending the three address code to the last etek, | Durr fle Others, aneror il be reported. a 4 Newtemp) iste futon wed fr generating new temporary varias. stchexpesion 4, E_place is used to hold the value of B. 1 Brample:x (0+ bole +d) Sieve atewent We wll assume al thee deters ae ofthe same type, Lt ws Bae totam paring method case ale etatement default: statement ’SECT Sem 8) Beample: seth Sontas Diet Ty latione ewe liceaeh, bre case? ¢0- break The thre adress cde can be ifok= 10, ifoh= 2 goto, Ly: ymasd ‘otolact Ly enb otolast last ‘GeeBITT] Write down the translation procedure for control if-then-else, statement and switch statement, “Anewer | 1 Boolean expression are used along with ifthe while-do, do-whle statement construct, $+ FE then St | IFE then S1 else $2|while Edo 1 |do BL while All these statements correspond toa boolean expression evaluation ‘Ths expression E should be converted to three addres ode ‘Tiss then intograted inthe context of contro statement. ‘Translation procedure for ifthen and if-then-else statement: 1. Consider a grammar for if-else ‘S-+ HE hen S, |iE then S, ese S, 2. Syntax directed translation scheme fr ifthen i given as follows Sif Bthens, true = new label!) Balse = Seat Sext = S next ompier Dien Inthegiven translation heme ewe, ‘Th faction gen. code is sed ty a een ene cna bast seantnaran Scode:= Bode | gen coelE re) | Side gen_code goto, S next gen. codelB flee) |S, coe For example : Consider the statement i Forex ach thena sa 5 ese Le true bes, ‘The three adress code for ifelaeis 100 fa .The OR and AND areleft associat, ‘The highest precedence is NOT then AND end lastly OR. The translation scheme for boolean expressions having numerical representation is as given below we compiler Dien pr BORE, pee] Bplace semen) pend i, lac opp, set atte PP ype pace = 1), srpedigt net sat sone ge [este AEE Blac = semen open place =) . FSFAISE t Ecpace« nemenp) append lace) i PART-6 Postfix Translation : Array References in Arithmetic Expression. Queetins Anewers Long Answer Type and Medium Antwer Type Qutonssa2c CST) Syntax Direted Translationg BERIT wie sore nt pon rantlation , iene ecarrentpreis ample Design 2230 (CIT Sem) Schemes ween Be Bye VT cade Bode = Tee Tycode= 7,1 1P coe | Tr code» Fede F code code Feeode id.code where I sgn it ued for coneatenation ante faced at = 1 S+es (Part-7] 2 C2 WEde Procedures Call 3 Wowie = ___ Asutaic ranstnn hemes given a —— [[_ Production rate Semantie ation —" Long Answer Type and Medium, Ws while W.QUAD = NEXTQUAD Anever Type Questions caw ee CWEde ASIN ‘WeedaE | Explain procedure call with example $3CS1 BACKPATCH (SL.NEXT, ith exampl cquaD) SNEXT=CFALSE GEN (goto C QUAD) BBR] woes poets notations Transhte C+D) + int outs ing Sys Directed Transition Scheme S073) TKaswer | Postfix notation : Refer Q. 3.6, Page 8-6C, Unit. ‘Numerical: Syotas directed translation scheme to specify the translation of ‘anexpression into pastfx notation areas follow Production Boner oT ToTeP TF Food) Paid “hnswer |] Procedures call 4 rosa n imprtant nd requ ed programming centri for compiler 2. Tisusedtogenerat code fr procedure calls nd eturas 3, Queue is used to store the list of parameters inthe procedure call 4 The translation fora call includes a sequence fection aken on entry and exit from each procedure, Following actions ake place i acing sequence Wen proeduecal ocr then spice allied activation 'b Baluate tho argument ofthe called procedure © Bxtablsh the environment pointers tocnable thecalle procedure to access data in enclosing blocks. 4 Savethe state ofthe cling procedures that it can reuneexeaton after the ell. (© Also save the return addres. It isthe addr ofthe ation to ‘which the called routine must transfer after its inished {Finally generate a jump tothe begining of the code forthe elle procedurecomm \ F25C(CSIT-Sem.5) elm, and low, are lower bounds on tne S-seall sais) “Tat i, f hh, 18 the Upper bound onthe val sat ih ali then ay Bhst + Elst & . Jow,* Hh eae or 1 fing te a ha es nary ‘sitable transition achome for pro cll woul be ies eee ™ Production rule | Semantic action sriastem eterna nme alld Et) fr each item pon QUEUE da | eee Anyi GEN (param p) Wa Nea + hd my + Ly 6 base — 044 aE lone lm, clam) sarees Bist is. | pend PLACE tus ed of @URUE| PARTS Blist +5 EPLAZEQUEVE to contain only Declarations Statements. QS] Explain ene concept of array references in arithmetic = See al areas! Answer] ‘An array is a collection of elements of similar data type. Here, we assume: the static allocation of array, whose subscripts ranges {rom ane to some limit known at compile time. Ie width of each array element is ‘u' then the (* clement of array A. begins in location, base + (i — low) * ‘here low is the lower bound on the subseript and base is the relative ‘address of the storage allocated for an array ie, base isthe relative address of Allow. Atwo dimensional array is normally stored in one of two forms, either ‘row-major (row by row) or column-major (column by column). ‘The Fig. 9.22.1 for row-major and column-major are given as ATT Ata a First Row] [[ATE2I Sear] | Fist Colum All at AL} cond Column ALi azz] 9 Second Rove] [TATE 2) AMI] Faia cotuma Ala ALS) Pig. 3.22.1. Incase ofa two dimensional array stored in row-major form, the rlative address of Ali, i,] ean be calculated by formula, ‘Long Answer Type and Medium Answer Type Questions Gue335. | Explain dectarative statements with example, ‘answer Inthe declarative statements the data items along with their data types are declared, Foresampl i 330 [een Dovid lentr_tid name, Fy fa Stace Pei TF integer Tondiet Forel (ype = rea Tout TF arvavinunl oF | types arrayinum val, pe) MinamderT ehenom vated | n —4 7 Tiers pointer pe) Toeidth:=4 |