You are on page 1of 29
12:34 |20.8KB/s Zi § EE OQ % geeksforgeeks.org/co + (5) [Ef ottase npneergtsnenaic; oeteisnenats Gpentngstem OBIS. Cann Wehnnspllageandtedpn CPs Compiler Design | Syntax Directed Definition Preroquiste—nacutiont Sntne Anaais Smt Dusted Tasinton Stax Dect Definition (SDD) a kn of abstract spect, is generalization of contest Grammar production X-> eis eszotted with Ra se of production ‘aes of the forms = fb, bp.) where sis the attrbute obtained fram funtion The abut can bea sting, number typeof a memery location. Semantic ules are fagment of code which are ‘ombodded ually tthe ond of procton and onelored in eur brace (I Example Foe fet (eval: eval + taal ‘Annotated Parse Tree The pase wee containing the values of attributes t each nade fo even input orng is aed annotated or decorated pares to. ool TESTING TIERS” What Level Tester Are You? Software Tester Certified List APSA (pen > + High tevel speciation ation date + Expl order ofevaluatlon I nt specied + Hides imptemer ‘Type ofatributes There ae two typer of attbuter nodes ie. value of synthesized atuibut at node ie computed from the values of atbibutes children nodes in parse tre, Example Eom get (eval = eval + Tel In this, Eval derive Rs vlues from Exval and Tval Computation of Synthesized attributes — + rite the SOD using spproprine semantic rules for exch production n given grammar. «Tne annotated parse esis generated and ctinaute values ae computed in bttom up manner. + Thevalveebtained a oot node i the final output Example: Consider the following grammar ‘The SOO for the above grammar canbe witen as fellow Production ‘Semantic Actions REE IEA Ce | iptnde Exgucingaenatis utente QpaaagSyien OMS Campers i Production ‘Semantic Actions SE Print(E.val) ESE tT Eval = Ey.val + Tal E>T Eval = T.val TTF Tval = Ty.val* Fval TSF Tal = Eval F> digit F.val = digitlexval Lotus assume en input string 4* 5 + 6 for computing syntresiced atibutes The annotated parse Hee fore input ting ie For computation of attributor wo start tom leftmost bottom node, The rle F-> dig is weed to eye Elo Fand the vale of ig ta igi lewal. Hence, Fv (ge Tal = from semantic ation Tal {rom xia onalaer which becomes wlve of F and since Tis parent nade of Fa, we va Then, for T-> Ts" F precision the corresponding from semante action Fal ‘semantic aeton i Twat = Tivol * Fal. Hence, Twat = 4*5= 20 Sint, combination of Eval + Tval becomes Eval le, Eval = Eyal + Tval= 26. Then, the procution S-> Eis applied to rece Eval = 26 and sementic action associated witht prints the resutt Eval Hence, the output wl be 26, 2 inherited Attrbutes - These are the atuibutes which deve the values from thelr parent or sibling nodes ie. vlue of inherte atbutes are computed by value of parent or siting nodes. Example > acd { Cain = Ain, C.type = 8.type } ‘Computation of inverted Atwibutes ~ + Constructthe SDD using semantic ations + Tae anaotated pase ee is generated and tribute values ae computed in too down manne Example: Consider the following grammar float double lie id id ‘The SDO fer the above grammar canbe writen as fellow Production ‘Semantic Actions S>TL Lins Type Tht Tiype = int TF teat T > double Leu Lo SPURL i OQ 2% geeksforgeeks.org/co + (5) [El votese npseergsnenaic; oerteisnenaies Gpentngitem ONS Cann Nehnns pllageantzedpn CPs Ine SUU torte above grammar canoe writen allows Production Semantic Actions STL Lin= Type Tint Type = int T= oat “Laype = float T= double “Type = double ttn | enc apetety Lin tid Entry type(id.enty Lin) Let us assume an input sting lat, efor computing inherited attibutes. The annotated parse ee forthe input tng ie ‘The value of Lnodes Is obtained fom Type (sbling| whichis basically lexical value obtained as int. lator double, Then L nada give type af identiers 8 anc The computation of typ ie done top down manner or preorder traversal Using fonction Enter type the typeof identifiers # anc fs ineortad in symbol table scorerperding i.enry {et 80% Course fee refund in just 80 Days! Also gt 1:1 Mock Interview Job assistance and "GecksforGecks helped me ace the GATE exam! Whenevor hac any douts egaring any topic ‘Anshika Modi AIR 23 ‘choose Geekstorceeks as your perect GATE 2025 Preparation partner wit hese newly Launched ‘GATE Offine DatnuNCR (Over 125000+ students steady bust usto be ther GATE Exam guid. Join them & let us help you In opening the GATE to top-tech ITs & NIT ou 2 Suggest imorouement < Previous Next > FOLLOW et in Syntax Analyse ‘open Shortest Path Fist (OSPF protocol states Share ur ght In econ C= SP Master Frontend/Backend/Full Steck > Build Projects -> Keep Applying to Jabs ‘And why go anywhere eee when our DSA to Development: Cosing Guide helps you do thein 8 Single program! Apply now to our DSA ta Devtonment Pras and our counselors wil connect with yeu for further guicance& supaort on 2 Suggsstimorovement < Previous Next > What ls shingled Magnetic Recording (MR)? hot sa Wireless neces Pint? 12:37|15.4KB/s i 6 @6092360 een coma ofa (0) B Introduction Also red shout Sedans of Tekan a Conaiec esa. Lentel ana n Dependency Graphs Ordering the Evaluation of Attributes {topological orto raph isn aden topalagie ceer en continue th the ‘Alo Sen, Spo Table Open 12:3710.2KB/s i © HH @LLCKO aes contrasts esionpep Race Rew x Sita (0) B ‘S-Attributed Definitions L-Attributed Definitions f'S00. The pine beat LLatbuted SOT e-atrtutes ‘oT ‘Semantic Rules with Controlled Side Effects 12:38 |97.6KB/s Zi § EB SMe) ioliet ss Nie) (5) Intermediate Code Generation in Compiler Design Inthe anes thesis modes of compiler the frontend of come leansates 0 source rogram into sn independent intermecat cod, thon the back ond ofthe compiler Uso thie intermediate code to generate the target cee (which canbe understood bythe machine). The bonefts of using machine independent intermediate cade ae + Because ofthe machine independent intermediate code, portabiy wl be enhanced. For ex suppose, if compile vanslates the source language te its target machine language withou having the option for generating intermediate cade, then for eech new machine, a fll native compiler i requted, Because, cbvicusy there were some meditations in the camper set according tothe machine specications, + Retorgetng i faitate, + fis waster to apply scurce code modification to improve the performance of soure code by optimizing the interment code aes | = a ae = | ~ ifwe generate machine code arety from source code then form target machine we wil have coptiniaars and a code generator but f we wil have & machine-independent intermediate code, we wll nave only one optimize. Itermadlate code can be ether Language-specic (eg, Bytecode for Java or tangunge. ndepandent (throe-address code). Tho felling are common ured termediate code representations 2. Postfix Notation + Also known as reerse Polish notation or sufi notation. + Inthe infc notation the operators placed between operands, og, 2 & Postfix notation postions the operator atthe ight end asin ab + + For any postfix expressions af and e2 witha binary operator (applying the operator elds eres + Postfocnettin eliminates the need fer parentheses, asthe aperatr’s poston and ay + In postfix notation, the aperatr consistently fllows the operand Example I: The posi representation af the expression (2 +B) “ele ab + e* Example 2: The posix representation ofthe expression fab) er) ¢ (0B) is: ab—ed Rend more: lito Posie 2, Theee-Address Code + A.trrec adeross statement involves a maximum of the references, consisting ef two fr operands an one forthe result + A sequence of tvee addres ectively forma tee adérees code + The plea form of thre adress statement expressed as reprosent memory addressee + Each vaiale (x;y 29a tee eds satementis associoted with 9 specie memory location + While a standard theee address statement includes three references there are instances winra 3 statement may contin fewer than three referoncs, ye i tl eategorized 35 3 a 1) Resa GY tots cretion; Beetanents Ope BSpiem ONS Canpertnane igllgcanedm Ch 2, Theee-Address Code + Ath aderass statement involves a maximum of the references, consisting ef two fr operands an one fr the result + A sequence of tives address staterent collectively forms a thee address code + The piel form of thre odstess statements exoressed as «= yop 2 where x yan 2 reprosent memory addoes0= + ach viable fx yin tree adores satementis associated vith a specie memory location + While » standard three adsresestatementincludes three references there ate instances winere a statement may contin fener than three references, yeti til nkegorized 953 Example: The tee aderess code forthe expression + b* ed: Th=bYeT2=94T113= T2+6:T 1.12, T3ae temporary ver ables. There ae 3 ways to representa Tnee-Addiess Coden comer design Qusdrapies i) Tips in Inciect Tralee ead more: The-adiess code 3. Syntax Tee + syntax toe serves as a condensed representation ofa pars tee, + The eparator anc keyword nodes present in the parse tree undergo a relocation process to become part ef thei respective parent nedesin he syntax wee the intemal nedes ae + Creating a syntax tree involves strategically placing parentheses within the expression. The technique contributes to 8 more intuitve representation, meking Kt easier to seer the sequence in which aperands shoul be procaesed + The syntax Hee nt only condenses te parse te but aso offers an improved vsuat reprozentation ofthe program’ syntactic tructra, Example:x= [a+ bea /le-b° a 7 Gt ere/@-(bFe)) Operator Root ‘Advantages of Intermediate Code Generation: Easlor to implomer coin the comply ofthe input ode, making i oasier to implement. termediate code generation can simply the cde generation process by Faettates code optimization: incermediate code generation ean enable the Us of various ede ‘eptinzation techniques, leading to improved performance and efficiency of the generated code ALG ee a Quadruple representation 2. Teplas~ This representation doesn't make us of extra temporary variable to represent single Cperatoninstoud when a reference to another tiles valu is needed, a pointe to that ples used So, consist of only tree fel namely ep argh and arg2. Dicsdvantage + Temporaris are imple and ifculto rearra coe. Be eed EP eee eyectgten ptagspien OMS Campers Bi Disadvantage + Temporaris re implicit ane fel to rearrange code + ris citicut to optinize because ootimizaion involves moving intetmediate code, When a tple ie moved, ny other tiple refering tof must direty sccosseymbot table entry, updated also, With help of pointer one en Example ~ Consider expression a=b*—e+b # | Op | Argt | Arg? @) | ominus [o O 2 o. b @)_| amin | o @) a @ b (a) + oe ©) = a 4) ‘Triples representation 23. Indirect Triples ~This representation makes use of pointer tothe listing of al ferences ta ‘computations which s made separately and store. similar in uiity 2 compare to quadumie ‘epresentation butraquires less space than. Temporaies ae impli and easier to rearrange code, Example ~ Consider expression a=b*—c+b*— F_ [op [art [Age] [# Bienen (19) | ons |e Foo a o_o] 16)_| onina[— @_| ter i [an e+ 08a [os (19, ae) a Indirect Triples representation {question = write quadrupoles and indirect trips fr following expression (c+ yl" (y+ 21+ oye Explanation ~The theo aderose code mist (2) 1f 4 10 goto (@) G) goto rext (tex? xe aster Mize (8) goto (2) next: // next Line after (€)¢h stotenent # Op | Argt | Arg2 | Result o + x y tt 2) + y z 2 ® = tt 2 8 @ + tt z 4 © + 8 4 6 ‘Quadruple representation r @ 4 REE 0 @O GE) Tees ue eeu oar aeetieud aescice ats) eee gee au eee Re Pets uo ouRSe ease usher eeu tee eee) Pees Meare A declaration of a variable tells the compiler that the Meee Ree gett ray Meee a eee eure toed Se okie ioc Type specifiers in deciarations define the type of a variable and function. It tells the compiler what type of Ce ere een a eke BS Tele Bollea] oto} Re cue eens eee Ue ee float, and void. @ Cees : Cee Other types and declarations in compiler Perl Rate lad cg Dees ee aR ene Cn Proce Rar Reon et stuart oe Attribute grammar A special form of context-free grammar that provides semantics to the language. Ouran Pe eee Ecce aud ele eee eas oe eae aN tarsus Undeclared variables, and Reserved identifier Tract aes (Ce Ce rea (Coco PPL e<8 Bin eB fa Me nre(e = rheo2/7) a coer) Co pooner eet] Oa ere mere een Tre ee ‘Types: Se a es eee ere ae ee es a en ee et ee ed Senne eran eras ee en eee eee ery eer eee Ce ee fore eteeein eee snare anctapedet Peed eee eee eee eee nS ee ee eee eee ee eee ea] ee eee et eee ec etd cant G=z Forecaroi 12:46 |77.7KB/s Zi Fa ey Foleo] MoCo T=r-1Ko2¢ i CGC 2@ C=) ee eee eas Prec eae Rea tere source code using a parser, which uses a con- rie eure kone a uaet sec aed Reames karte io RU aec age an ice cack lation is to construct a parse tree or syntax tree Bena a een Anau nae tou Ne Ree on cu ieikecul ek oake ante) Poa Me cece ee SS | ead The translation scheme for the grammar is given below: § + id:=E,E + £1+E2,E + Et,andE Pele The expressions can be of type real, integer, array, and records. © eee me ee eeu Caso eee ret nanan: ie isso aeaa See eras ‘Translation of Expressions Se ee eee FE EA ee SO Translation of Assignment Statements In the syntax directed translation, assignment statement is mainly deals with expressions. The expression can be of type real, integer, array and records. Consider the grammar © ee r- © ew The translation scheme of above grammar is given below: re Si (p= eokspodraray ipentihen kent (9=Ea) , (Eioce = newer: tit (Ealace = zplac) , Etplace (ace =rewtenp0 Emit (Eplace Ezploeo , Etpleos (Covace = place) cod (9 leak upgarane) pe then mk 9 =E ce) , ee RE -9 (lace =nevterote Emit (Esloee = Elploce Expl) , E-ET2 ——tEplne=nemenso: mt (Epuce = Crplce place) , e-@) (Eploce =e lee) co (0 ook petra protien sit (p= epee) tre no , o The p returns the entry for id.name in the symbol table. © The Emit function is used for appending the three address code to the output file. Otherwise it will report an error. © The newtemp() is a function used to generate hew temporary variables. E.place holds the value of E. “raslaton OF Expressions 1B Tobit contnts > Introduction Operations Within Expressions ©xO) Sits Oo AAR e » inthe syntoaleted defen nthe fue + top cenote the current symbol table {Funston topget ereves the entry 1 Attribute Eads denotes the egerese tt wil lathe vue et + new Temp) cectes th. 2 genkey 2) represents the 3 {8eressinetson xyz, Eepresson ppearingin place of verti they ‘nd 2 ore evaluat when pasted to Aasvantoge:No code generate for vrile Disadvontoge: Not good with sid ffocts Eete3) InFig. 619, he operators + ae uncry Feet the operators in typiealanguege Ie semontirules for=—> EL «£2 create ode to cmp = vl rom EL ond £2 = voles. vais ete computed and toed i temporory names thot oe formed onthe fh EI E2tronsiates ot = E1,od + €2. oder were tis ere temporary name EL omputed as Cid and £2 computes as vad The velueof Eat i set tot By repactedy perfoming new Temp a ‘uccession of seperate temporery names Tedenot the thre: oxeressinstrcton x= yz, wove the ratoten gens = y" {nen proves to gon, expressions tht Wile constructed nthe same wey. 5 By applying gen t.a combination of Whe we Wanalte E> E62. the semantic resin Fig. 629 combine Eicode E2cooe © Free Guided path hand pitedferyoul A 12:47 | 0.4KB/s Zi hE - ay naukri.com/code360/ COKE360 vec comics Sosearines Example 6.1%: in figs above Get the tech career you deserve, foster! SPP LC Bin OQ 2% geeksforgeeks.org/typ + [Ef vouese pneergsnenaic; citeisnenas Gpintngstem OBIS Cann Wehnns pllageandtedpn CPs ‘Type Checking in Compiler Design ‘Type checking isthe process of verying and enforcing constraints of types in values. A compiter rust eheek tht the Source Program should follow the syatce and semantic conventions of the source language and It should aso check the type rues ofthe language. It allws the programmer te Umit what types may be uted in ertin circumstances and assigns types to values. The type checker determines whether these values ae used appropriately oF nat Ie checks the type of objects and reports @ type erorin the case of a violation, and incorect types are corected, Whatever the compiler we use, while tis compiling the progam, thas fll the type rules ofthe Language. Every language hes is wa se af type rules fr the Language. We know that he information about datatypes i maltained and computed by te comper. The information shout datatypes Uice INTEGER, FLOAT, CHARACTER, and all the other datatypes 6s maintained anc computed by the compile. The compiler contains modules, where the type choctor ies module of compiler and ts tz i typo checking, conversion Conversion fom one type te another type Is known as impltt iis to be done automatically by the compiler. Implicit type conversions ate aleo called Coercion and ceason i inten many languages. Example: An Integer may be converted oa rea but real Is not converted tan integer Conversion ssid tobe Explicit the programmer wtrtes somthing todo the Conversion. Tonks: 1. to alow “indexing is only on an aay 2. has tw check the renge of datatypes used 2 INTEGER {int hae a range of -32,768 to +32767 4. FLOAT has a ange of 126-38 10 3.46738 ‘Types of Type Checking: Theta are twn kinds of type checking 1. Static Type Checking 2. Dynamic Type Checking ‘Static Type Checking Static tyne checking is defined ns type checking performed at compile time. checks the type vanes at rmpe-time, whieh means the type of te variable ie known at the compe tne. I _senersly examines the progam txt during the translation ofthe pragram: Using the type rules of 4 system, a compiler can infer ftom the source text that function (fun) will be applied to an ‘operand (of the right type each Kime the expression fun] is evalate “Type-checkst A comoler should report en errr if an operator fs applied to an incompatioe operand, For example, en array variable and function variable ae added togetet, +The flow of cntral checks Statements tha eau the low of contralto Lene # construct mus a @ 4 DE Eee GF tons rynestntinente: Beeman Op e5piem Oc Examples of Static cheeks nctude: “Type-checks: A comaler should report an errr if an operator fe applied to an incompatile operand, For example, fn ary vorible an function vrable are added together “The flow of antral checks Statements tha cue the lor of cone to leave = construct mus weoloce to whieh to tener the flow of eontel. For exemple, 8 break statement in C causes contralto leave the smallest encosing while, for, © sitch statement, an errr occurs such an enclosing statement does nt exis Uniqueness chacke: There are uations in which an objet must be defined only once. For example n Pascal an identifier must be declared uncuely, labels ina case statement must be distinct and alee 3 statorren in a eelar yoo may not bo reprecented Name-rolated checks: Sometimes the same name may appear to or more times. For example in Ado, » loop may have e nome that appears at the baginning and and af the construct. The ‘compiler must check thatthe seme name Is use at both places. ‘The Benefits of Static Type Checking 2. Runtime Error Protection. 2.tteatches syntactic eror tke spurious wores or extra punctuation, 3 entehes wrong names like Math an Predefined Naming 4, Detects incorrect ergument types 5 eatches the wrong number of arguments 6.tteatches wong retun types, ke return "70% rom a function that's declared to return anit Dynamic Type Checking: Dynamic Type Checking is tines as te type checking Belg done at ran time. In Dynamic Type (Checking, types are associated with values, not variables. Implementations of dynamically type checked languages runtime objects te generally associated with each other through # ype tag which Is 2 reference toa type containing its type Information. Dynamic typing is more flexible. A static type system always retrets what ean be conveniently expressed, Dynamic typing result in moce compact programs since I is mere Rendle ard does not reaire types fo be spelled out Programming witha state type system often requires mare design and implementation effort. Languages Uke Pescal end € have state (pe checking. Type checking is used to check the correctness ofthe program before ie execution, The main purpose of type-chesking eto check the comectness and data type assigaments and type-csting of the data types. whether it Is syntactically corrector not before their xeon ‘State Type-Checkng is alsa Used te determine the amount of memory nase to store the variable. ‘Tho design ofthe type-chocker depends on 2, SyntaetieStractare of tanguoge constrts 2, Tae Bresson of languges ‘3. The les for assigning types to constructs semantic rules) ‘The Postion ofthe Type enecker in the Compiter: ‘Tne token streams fom he Leslea analyzer ae passed tothe PARSER. The PARSER will generate 3 stax vee. When 3 program {sourcecode} econvertd into a syntax tre, thetype-checkerplaye corset varisble or not. Tho Type- Checker will check and i any modifatone are present, thon wil modiy R produces 2 syntax tee, and ater that. INTERMEDIATE CODE Genevetien is done. Overtonding: {An Overiaging symbol sone that na diferent oparations dopending on its conto overtoading is of two types: 1. Operator Overto ing 2, Function Overtooing ‘Operator Overloading: In Mathematics, the arithmetic expresion “x+y” has the addon operator + is overoaed because" inc” have fepperatcs when's’ andy ate integers, complex Pee nin GE tote rynetrtnente; Beene Op BSpiem OMS Canperctnane ighllgcanteim Ce ‘The token streams from the Lesca analyzer ae passed tothe PARSER. The PARSER will gonerate 2 syntax vee. When 9 program {sourcecode} s converted into a syntax tre. the type-checker plays 4 Crucat Role. So, by seeing the syntne tee, you can tll whether each datatype Is handling the correct vareble of not. The Type-Checker will check and if any modifiations ore present, then i will medliy ht produces a syntae tee and after that, INTERMEDIATE CODE Genevaten is dane Overtoading: {An Overloading symbol is one tha ha diferent operations depending on ts conte, Overtanding is of two types: 1. Operator veroading 2. Funeton Ovetading ‘operator Overloading: In Mathematics, the athmetic expression “xty" has the adlon operator “is everioaded bocaus0"* in “ey” have efferent operators whens andy a integers, complex numbers rls and Matrices, Example: In 8a, the parenthers (sre overiondce the element of the expression Af of an Artoy has a ciferent meaning such as a all to funtion 7° with argument oF on expt conversion of expression ito type’ In most languages the arthmeti operates ave everieaded, Function Overloading: The Type Checker resolves the Function Overloading based on types of arguments and Numbers. Example peice2) E-typar= iF E2.type = = Elatype = 5 --3t chen t else type_error {Get 90% Course fee refund in just 90 Daya! Als gt 1:1 Mock Interview, Job ssvctance and ‘more aceional benefit on selected course. Tako up the Three 90 challenge today! Here's a complete reacmap fr you to become a developer: Learn DSA -> Mastar Frontend/Backend/Fll Stack > Bull Projects > Keep Applying to Jobs And why go anywhere else when our DSA ta Development Ceding Guise helps you do this in single program! Apply now to our DEA ta Development Program and our counselors wl connect wlth you for further guidance & supoort ou 2 Suggest imorowement & Previous Nxt > What is shingled Magnetic Recording (SHRP Protocol Data Unit (POU) Share your thug neces cD si Reads dsntage cf lps Carpe Ovens Compler fea buteen Rate comprar rt compler

You might also like