Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
33 views
26 pages
Poc Syntax Directed
Principle of Compilers Syntax analysis
Uploaded by
borntoinfo2
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save poc syntax directed For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
33 views
26 pages
Poc Syntax Directed
Principle of Compilers Syntax analysis
Uploaded by
borntoinfo2
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save poc syntax directed For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save poc syntax directed For Later
You are on page 1
/ 26
Search
Fullscreen
3 SEMANTIC ANALYSIS + — Check semantics + Error reporting + Disambiguate overloaded operators + Type coercion + Static checking - Type checking ~ Control flow checking — Uniqueness ch Name checks if —— reac ge ee — int b 0 a b int int int int Figure 3.1: Parsing Assume that the program has been verified to be syntactically correct and converted into ate representation (a parse tree). One parse tree is available now some kind of interme: The next phase will be semantic analysis of the generated parse tree. Semantic analysis, also includes error reporting in case any semantic error is found out Semantic analysis is a pass by a compiler that adds semantic information to the parse tree and performs certain checks based on this information. It logically follows the parsing phase, in which the parse tree is generated, and logically precedes the code generation phase, in which (intermediate/target) code is generated. (In a compiler implementation, it may be possible to fold different phases into one pass.) A typical example of semantic information that is added and checked is typing information aby Tal arin Sots Po Lo par Bo ay bo repo 2= tng of variables and fnetion names 9 th defining, (type checking) and the aed some early code optimization is done jn this py ae ae ee i storys reece ne mames function names, ct.) Fer 0 a ach symbol (variable name ; : ings ave done in Sen Analysi ; owing things av ‘a ae operators: IF ah Opertor is everoaded, gy ‘ © Overloa rn perator Disambiguate C f fy the meaning of that particular operator because from one y like to specify the mea aa may ocr either at compile time (a sae check aan ipa check). Static type ee ‘ : ae task of : semantic analysis carried out by a compiler. If type rules are en, forced Strong) (that is, generally allowing only those automatic type conversions which do ny lose information), the process is called strongly ‘ped, if not, weakly typed ing: Whether a variable name is unique or not, in itg Scope + Uniqueness che * Type coercion: If some kind of mixing of types is allowed in languages, whcy are not strongly typed, This can be done dynamically as well as statically * Name Checks: Check whether any variable has a name, which is not alloy Ex. Name is same as an identifier( Ex. int in java). Beyond syntax ana 1. Parser cannot catch all the program errors 2. There isa level of correctness that is eeper than syntax analysis 3 Some language features cannot be modeled using context free grammar formalism Whether an identifier has been declared before use ~ This problem is of identifying a language {waw|w eds) This language 1S not context free A parser has something tha HS own limitations in catching program errors related to semantics, is deeper thai in syntax analysis, Typical features of semantic analysis cannot be modeled USING context free grammar formalism. If One tries to incorporate those features in the defi f ‘ion of @ language then th, sn't remaia n that language doesn’ Context free anymore, eae euag Example: string x;int y: Y=x43 the use of x isa int a, b; a=bte type error CIS not declaregAn ulentificr may refer to + Anidentifier may be usabi dhfferent variables in different parts of the program e in one part of the program but not another These are a couple of e iple of examples, which tell us that typically what a compiler has to do analysis, ae fg 2cty The third point can be explained like this: An identifier x ean WO Separate functions in the i then of the type char, Hence the same beyond syntax be declared in program, once of the type int ane pwo different MWentifier will have to be bound to these {Wo different contexts. ‘The fourth point can be explained in this manner’ A variable declared within one funetion cannot be used within the scope of other function unless declared there separately. This is just a ably you can think of many more examples in which a variable declared in one scope cannot be used in another scope properties in the the definition of the example. Prob. Compiler needs to know? + Whether a vari ible has been declared? + Are there variables which have not been declared? + What is the type of the variable? Whether a variable is a scalar, an array, or a function? + What declaration of the variable does each reference use? + Ifan expression is type consistent? + Ian array use like A[ij,k] is consistent with the declaration? Does it have three dimensions? What does a compiler need to know during semantic analysis? Fore variable and we have a statement like ample, we have the third question from the above list, ie., what is the type of a int a,b, ¢; Then we sce that syntax analyzer cannot alone handle this situation, We actually need to traverse the parse trees to find out the type of identifier and this is all done in semantic analysis phase. Purpose of listing out the questions is that unless we have ‘ie analyzer. This answers to these questions we will not be able to write a sema becomes a feedback mechanism. + How many arguments does a function take? + Are all invocations of a function consistent with the declaration? + Tfan operator/function is overloaded, which function is being invoked? + Inheritance relationship + Classes not multiply defined + Methods in a class are not multi pend upon the language ply defined + The exact requirements de s the answers to all these questions only then will it be able to If the compiler ha successfully do a semantic analysis by using the generated parse tree, These questions give a feedbacl " questions help in outlining the work of ik to what is to be done in the semantic analysis. These the semantic analyzer. se at i bea eo oS Ics]“STs verve by Taras Leng Sl How to answer these questions? art of semantic analysis phase 1 values like type information, number of These issues are Answers to these questions depend upon parameters ete. Compiler will have to do some computation to arrive at answers cd by computations may be non focal in some Cases compiler will have t0 keep information a particular function ete. It will The information requ In order to answer the previous questions the about the type of variables, number of parameters 1" have to do some sort of computation in order to gain this information, Most ymbol table to store but in a different scope altogether compilers keep a structure called sy this information. At times the information required is not available locally, Use formal methods Context sensitive grammars Extended attribute grammai + Use ad-hoc techniques Symbol table — Ad-hoc code + Something in between!!! — Use attributes Do analysis along with parsing ‘ode is developed in a systematic way ammar, Here we put lot of attributes around {tribute value computation Use code for — However, In syntax analysis we used context free 2 ammars along with extended attribute it. So it consists of context sensitive gra in it and the formal grammars, Ad-hoc methods also good as there is no structur method is simply just too tough. So we would like to use somethin ult that writing specifications itself may become tou 2 in between. Formalism may be so diffic than writing compiler itself. So we do use attributes but we do analysis along with parse tree itself instead of using context sensitive grammars. Why attributes? For lexical analysis and syntax analysis formal techniques were used. tions along with regular expressions However, we still had code in form of and context free grammar The attribute grammar formalism is important cult to implement — However, it is very diff But makes many points clear — Makes “ad-hoc” code more organized — Helps in doing non local computations ‘Attibute grammar is nothing but it is @ CFG and attributes put around all the terminal and non-terminal symbols are used. Despite the difficulty in the implementation of the atribute grammar formalism it has certain big advantages, which makes it desirable.reserved by THINKER Generali ation of CFG where each grammar symbol has an associated set of ‘Ive omton ir auascin essen D n ing semantic rules with productions = Syntax directed defi + High level specifications + Hides implementation details + Explicit order of evaluation is not specified — Translation schemes + Indicate order in which semantic rules are to be evaluated + Allow some implementation details to be shown An attribute grammar is the formal expression of the syntax-directed semantic checks associated with a grammar. It represents the rules of a language not explicitly imparted by the syntax. In a practical way, it defines the information that we will need to be in the abstract syntax tree in order to successfully perform semantic analysis. This information is stored as attributes of the nodes of the abstract syntax tree, The values of those attributes are calculated by semantic rule. There are two ways for writing attributes: ion in which 1. Syntax Directed Definition: It is a high level speci 2; /* does not give any implementation details are hidden, eg, SS = $1 + $2: / implementation details Translation scheme: Sometimes we want to control the way the attributes are evaluated, the order and place where they are evaluated. This is of a slightly lower level. Conceptually both: — Traverse the parse tree to ev + Evaluation may: — Generate code — Save information in the syn Issue error messages Perform any other activity jwate the semantic rules at the parse tree nodes mbol table parse tree, actions are taken simultaneously when a To avoid repeated traversal of the attributes goes along with the construction of the token is found. So calculation of parse tree. Along with th i generate code, save the informatt etc, at the same time while buildi Jes the compiler may simultaneously sue error messages es of the e evaluation of the semantic rul .n in the symbol table, and/or ing the parse tree. This saves multiple pass parse tree. ig Sas PN at DO YB wpe fan nH Te writen porns nee a Example: Number —ysign list sign > |- list —>list bit | bit . attribute grammar that annotates number Wi h the value it repre: ar that nt 7 Build attril Associate attributes with grammar symbols : Symbol “Attributes Number Value Sign Negative List position, value Bit position, value Production Attributes rule Number— sign list | list.position = 0 if sign.negative then number.value else number. value = list.value list.value sign > sign.negative = false sign > - Sign.negative = true list — bit bit position = list position list.value = bit.value Uist S Tist 1 bit list] position = list 0 position > 1 bit position = list 0 position list0 .value = listl value + bit. value bit 0 bitvalue bit 1 bit.value = 2bit position Explanation of attribute rules Num — sign list Negative of the Value of list*/ lea ‘an attribute (negative) for sign*/ is the sa sue s the same as list Position because this bit is tH List 5 bit List S List bit from attributes of LHS and vice versaIcsl Number Eee ao list sign neg = (ru ; Neat / A / eee valet V Pos=2 bit Val=4 4 0 1 Figure 3.2: Parse tree and the dependence g Dependence graph shows the dependence of attributes on other attributes, along with the syntax tree. Top down traversal is followed by a bottom up traversal to resolve the dependenc attribute . Number, val and neg are synthesized attributes. Pos is an inherited Attributes fall into two classes: synthesized and inherited Value of a synthesized attribute is computed from the values of its children nodes Value of an inherited attribute is computed from the sibling and parent nodes The attributes are divided into two groups, called synthesized attributes and inherited attributes. The synthesized attributes are the result of the attribute evaluation rules also using the values of the inherited attributes, The values of the inherited attributes are inherited from parent nodes and siblin Each grammar production A —>a has ociated with ita set of. semantic rules of the form3.3 ba f(el 020k) and either fA OR of the grammar symbols on the right where fis a function, — bis a synthesized attribute of i crited attribute of on! ~ bis an inherite tin a on attributes tae atibtes We Mee LO KROW befire fag 5 Dependence relation tells us wha cl bute. calculate a particular attril ofthe tribute b depends on the values ofthe tidus py, 1 belong to the cen nodes and b to A then b will be called synthe = ae ‘Aad if b belongs to one among a (child nodes) then it is an inherg aut ¥ attribute of one ofthe grammar symbols on the right. SYNTHESIZED ATTRIBUTES + A syntax directed definition that uses onl S- attributed definition * A parse tree for an S-attributed definition can be annota semantic rules for attributes S-atributed grammars are a class of attribute grammars, comparable with L. attributed grammars but characterized by having no inherited attributes at al Inherited attributes, which must be passed down from parent nodes to childr of the abstract syntax tree during the semantic analysis, pose a probl UP Parsing because in bottom-up parsing, the p are created after creation of all of their childre Erammars can be incorporated conveniently parsing. y synthesized attributes is said tobe ap ed by evaluating en nodes m for bottom ‘arent nodes of the abstract syntax tree n. Attribute evaluation in § attributed in both top-down Parsing and bottom-up Syntax Directed Defini ns for a desk calculator programs; cs| \ Print? Val 17 i Meta : : T Val=5 al<12 F Val=5 * Val=4 id yA F id Figure 3.3: Parse tree for 3*44 $n it here for 3 * Using the previous attribute grammar calculations have been work ng has been done 4+ 5n. Bottom up pa 34 INHERITED ATTRIBUTES ed in terms of attributes at the + An inherited attribute is one whose value is de parent andor siblings + Used for finding out the context in which it appears attributes but more natural to use inherited attributes + Possible to use only DoTL Lin = T-type T= real Taaype = real T— int Type = int L—L1,id Li n= Lin: addtype(id-entry, Lin) Lod addtype (id.entry,L.in) — p to find the context (yf Inherited attributes hel same variable n ofa token or scope when the tions. An inherited attribute mes in a pt laced by an S am in different func “iie inherited attributes 19 SOME cases Ri, inl I to use gystem but itis more natura attribute amp! 0 entry for the 1d a and attache, ‘example given above. xdds a symbol table entry for oe o nctions adds a S Hore adap B) fi ‘ the type of b. type in=teal aN UO in=real, real oe Y \__aietppe( reat addtype( x, real) Figure 3.4: Parse tree for real x, y, 2 Dependence of attributes in an inherited attribute system The value of in (an inherited attribute) at the three L. nodes gives the type of the three Identifiers x, y and z.. These are determined by computing the value of the attribute Type at the left child of the root and then valuating L.in top down at the three L nodes in the right subtree of the root. At each L node the procedure addtype is called ‘hich inserts the type of the identifier to its entry in the symbol table. The figure also Shows the dependence graph which ig introduced later Dependency Graph * Han attribute b depends on g evaluated after the semantic rule The dependencies among the nodes{cs} for each node n in the Parse tree do for each semantic rule b — E(e} , ¢2 ( associated with production at n } fori Ltokdo construct an edge from ci to b ves CK ) do An algorithm to construct the dependency graph. After making one node for every attribute of all the nodes of the parse tree, make one edge from each of the other attributes on which it depends, Example: . Suppose A.a-f(X.x,Y.y) 7 ‘ Va EN If ProductionA XY has the semantic ruleXx=g(A.a, Y-y) Ue Figure 3.5: Dependency Graph The semantic rule A.a = f(X.x , Y.y) for the production A — synthesized attribute a of A to be dependent on the attribute x of X and the attribute y of Y . Thus the dependency graph will contain an edge from X.x to A.a and Yy to Aa accounting for the two dependencies. Similarly for the semantic rule Xx = g(A.a, Y.y) for the same production there will be an edge from A.a to X.x and an edg ¢ from Y.y to X.x. > XY defines the Example: Whenever following production is used in a parse tree E>E1+E2 — Eval=E1 val+E2.val we create a dependency graph Eval Eval Eval Figure 3.6: Dependency Graph The synthesized attribute E.val depends on El.val and E2.val hence the two edges ‘one each from E 1 .val & E 2 .val | | | | eoere See Example: Dependency graph for real idl, id2, id3 put a dummy synthesized attribute b for a si D semantic rule that Consists of a procedure call type = real Type_lexeme in “real + Y Cie real) addtype(x,real) <_X id Figure 3.7: Dependency graph for real idl, id2, id3 The figure shows the dependency graph for the statement real id1, id2, id3 along with the parse tree. Procedure calls can be thought of as rules defining the values of dummy synthesized attributes of the nonterminal on the left side of the associated production. Blue arrows constitute the dependency graph and black lines, the parse tree. Each of the semantic rules addtype (id.entry, L.in) associated with the L productions leads to the creation of the dummy attribute. Evaluation Order Any topological sort of dependency graph gives a valid order in which semantic les must be evaluated a4 = real aS =a addtype(id3.entry, a5) a7=a5 addtype(id2.entry, a7 ) a9 == a7 addtype(idl entry, a9 ) : A topological sort of a directed acyclic graph is any ordering ml, m2, ™3- se g to lat the nodes of the graph such that edges go from nodes earlier in the orde nodes. Thus if mi ~ mj is an edge from mi to mj then mi appears before ™ in ®ordering. The of c topological sort ety siiements shown in the slide “pendency graph in the previous slide. ‘an’ stands for the attribute associated with the node cy pI Phe rumbering i 9s shown inthe previous ate (Ne epemene? graph, Th slide 5 obtained from the ABSTRACT SYNTAX TREE + Condensed form of parse tree + Useful for representing language constructs, +The production S —+ if B then st else s2 may appear as if-then-else B sl 82 Figure 3.8: Abstract Syntax Tree In the next few slides we will see how abstract syntax trees can be constructed from syntax directed definitions. Abstract syntax trees are condensed form of parse trees. Normally operators and keywords appear as leaves but in an abstract syntax tree they are associated with the interior nodes that would be the parent of those leaves in the parse tree. This is clearly indicated by the examples in these slides. + Chain of single productions may be collapsed, and operators move to the parent nodes E + vA VN E T * 3 i T + id3 idl id2 AN T F + + F id2 + idl Figure 3.9: Collapsed Production le with the operators moving up Chain of single production are collapsed into one nod to become the node a ern FE Nao ao ses FAN prof is bose thy ~2! "ighis reserved by Thinkcell Learning Solutions nomcod ing fields are POINIETS 10 operang 7 Gherators: one field for Ol inked oper) with label id and another pet symbol table «Identifier: one «to keep the value of the number caftid.entry) Ni : = one fie num and anothel umber: 0 mkleaftnum.val) Jd with label plemented as a record with severa t field identifies the operator (called the label of nters to the nodes for operands. Nodes of an iis to hold values (oF pointers to values) given in the slide are used to creat Each function retums a pointer to a an abstract symtax free cam be imi iis, In the node for an operator one fis ¢ remaining contain pol may have additional fiel fo the node. The functions Fach node in the node) and th abstract syntax tree of attributes attached t ‘he nodes of abstract syntax trees for expressions newly created note. Example: PS he following sequence of funetion calls creates a parse tree p3 forae4+c a PI =mkleaf{id, entry.a) P2=mkleaf{num, 4) P3=mknode(-,P1,P2) Pt z id [ay P4=mkleaftid,entry.c) we PS=miknode(+,P3,P4) entry of ¢ id Hl num] 4 entry of a Figure 3.10: parse tree for a-4 + ¢ An example showin th ig the formation of an abstract syntax tree by the given function calls for the exy f pression a-4+e.Th The call sequene: ee can be explai xplained as: I. Pl =mkleaftid aid entry.a): A lea ) +A leaf node made for the identifier a and an entry fora : is made in the symbol table . P= mkleal - ares ie ep ae made for the number 4 Oey ‘PLLP2) : An internal node for the ‘t ke ~ takes ne 4, P= mkleatlidentry aan es the previously ma is made in the symbo} Ita 5. P5 = mknode(+p3 ae ideAsyntax directed definition ¢, for ct eas Onstructing syntax tree Bp ee ‘Pir mknode(+, B1 ptr, T pts) anu Eptr=T ptr Lge T ptr = mknode(*, 11 ptr, F ptr) 7 Tptr = F.ptr F= (BE) Fptr = B.ptr Pid PF. F.ptr:= ei gas Ptr = mkleaftid, entry id) F.ptr = mkleat{num,val) BOTTOM-UP EVALUATION OF §-aT- + Canbe + Whenever reduction is m ade, value of 0 is fom 6 ae a '¢ of new synthesized attribute is computed + Extend stack to hold the values also INITIONS aluated while parsing | state | value stack | stack ptr > + The current top of stack is indicated by ptr top Synthesized attributes are evaluated using the attributes of the children nodes only So in a bottom up evaluation, if the attributes are maintained on a stack then the attributes of nodes higher up in the parse tree can be evaluated. The stack is extended to hold the state as well as the value, Top of the stack is maintained in a location pointed by the pointer top. Suppose semantic rule A.a = f(X-x, Y.y, Z.2) is associated with production A>XYZ + Before reducing XYZ to A, value of Z is in val(top), value of Y is in val(top-1) and value of X is in val(top-2) + [fsymbol has no attribute then the entry is undefined decremented by 2 and state covering A is put in + After the reduction, top #8 val(top) hile parsing of A.a= (X.x,Y.y,Z2). Top is jarser stack wh : ues viz. X,Y and Z are popped and value of A eval An example of @ decremented by two because thre has to be pushed in.sign «sign list cee, CS as ae i Fotki = OER AER (mete ——T then number.value Tivol SE 4 ae . Sign.negative —» false ere, | sign.negative ~* Fase sign negative —> true ares ~~ bit position — list-position list bit list.value — bit. value list 0 — list 1 bit list | position —+ list 0 position + 1 bit position — list 0 .position list 0 value — list 1 .value + bit.value bit 0 bit-value > 0 bit + 1 bit.value + 2 bit position Example: Desk Calculator Lorn print(val(top)) Tor t>——— Pot Foo di —— | Before reduction niop After cod The code | ¥allntop) = val(top-2) + valitopy | ¥al(ntop) = val(top- 2) * val(top) E) al(atop) = val(top-1y it _ °P = ntop fragments (like le reduction toics} Se eee = Input State Val Production 3514p *5+4n digit 3 *5+4n F 3 [*5+4n T 3 S+4n T* 3* an Trdigit 3*5 aaa TP 3*5 F— digit van c 15 ee +4n Is ee an IS+ a 344 : ised F— digit "i 15+4 a E 19 This shows the evaluation of the synthesized attributes of 3*5+4n by an LR parser g the input : The parser during a bottom up pass. Initial sequence of events on seein onto the stack. In the shifis the state corresponding to token digit (taken as digit he second move, the parser reduces by the production F -* digit It mplements the lexval. In the third move, the parser reduces by T + F. No semantic rule F val = d code fragment is associated so the val array is unchai goes on similar lines. Afler each reduction, the top of the val stack conta ed. Rest of the implementation attribute value associated with the left side of the reducing production 37 L-ATTRIBUTED DEFINITIONS * When translation takes place during parsing, order of evaluation is linked to the order in which nodes are created + A natural order in both top-down and bottom-up parsing is depth first-order © L-attributed definition: where attributes can be evaluated in depth-first order utes Leattributed definitions are a class of syntax-directed definitions where va . can always be evaluated in depth first order. (L is for left as attribute inform: not actually appears to flow from left to ght). Even if the parse tre constructed, it is useful to study translation dunng parsing by cons first evaluation of attributes at the nodes of a parse tree18 an L- attributed ifeach inherited attribute of X j a ed definition is hand side of «A syntax direct ) as the righ Xn depends only 0” x j-l and qsise Aa>XIX2 — Attributes o _ Inherited attribute of A sf symbols XI X2o- Consider translation scheme A>LM AaQR As= f6 (Qs) which means that attribute of a symbol nt node. Suppose for the production Yi can be a function of, in general, We assume that we have inherited attributes, will be defined in terms of its sibling and its pare! A+ XYZ, if we have to write a function of Yi - of A inherited attribute of X and attribute of Y. However, no matter what parsing we use (top-down or bottom up) we won't be able to evaluate Y in a single pass, as we can never have Z evaluated till then, Clearly, the general definition of attribute equation doesn't work. We, therefore have to modify the attribute equation, in effect limit it. This further restriction is such that we can evaluate a function in a left-first traversal order. To achieve this Yi should be a function of A (inherited) and X (inherited and eee The generalization of this rule is that inherited attribute of X will ne only on its left sibling and not on its right sibling, Note that we cannot use the s 7 Sent the parent, because these, in general, will be a function of all : . By this limitation, we ca Siti ee i = (in both top-down and bottom-up parsing) single pass. "0 functions which satisfy the conditions of L tae eae ees ef -attributed definitions, but in the second one the second function is usi ze e rule thal ing synthesiz r ea ieee i Of R, this violates the rule that definition, econd example is not an L-attributedA CFG where : ‘mantic actions oc ‘cur within the RHS of product luction Examp A translation sehen scheme to maj fi Aaa P infix to postfix R > addop T {print(addop)} R | € T — num {print(num)} ve ! T print (num) a Hi fu addop print (addop) Qs ) ) , i | addop print{num) wi, intima) () (3) : num 2) print(num) R 5 Figure 3.11: Parse tree for 9 + Assume actions are terminal symbols + Perform depth first order traversal 10 + When designing translation scheme, ensure referred to + Incase of synthesized attribute it obtain 9 5-2 + attribute value is available when is trivial (why?) mn, we have to explicitly ¢ actions inthe dealing with implementation ‘an now put in between the rules som order to control the order of traversal (mum and addop). It ean generally ® has to begin with ). The give? as we are f traversal. We ¢ Ina translation schem: worry about the order o} as part of the RHS. We put this rules two terminals (which necessarily 1d we need to convert it into tree is in black, without the red e actions. The actions are ever we &' fe seen as an addop) given example, we have number followed by R grammar is in infix notation am ignore all the actions, the P' a parse tree with th first traversal, and when postfix notation. UE if we include so far areated & © arse jon the red edges we get a counter #4 terminal, Now, if we do # d¢P'CS4TeForum S c vrata tasaton SRAM, WE HAVE Oke ay seta ptse some of the parts may be left undefined y-- ; sr eeu wll be obtained: ActONS are Something We yy, at actions, Tere ease note that translation scheme is different from rae action In the later, we do not have any evaluation order; jp tis ose enpiit evaluation order. By explicit evaluation order we have ty ga in order to get the desired output. Place of each action ind appropriate places, and that is that translation wee it, we of the evaluation order differen and we have to control it case we hav correct action at correct places, is very important. We have to fi a ame is all about. If we talk of only synthesized attribute, the translation scheme i, ‘vial. This is because, when we reach we know that all the children must h; very tri 7 been evaluated and all their attributes must have also been dealt with. This is because finding the place for evaluation is very simple, it is the rightmost place. + Incase of both inherited and synthesized attributes + An inherited attribute for a symbol on ths of a production must be computed in an action before that symbol S3AIA2 {Al in=1,A2.in=2} Asa {print(A.in)} depth first order traversal gives error undefined a print(A, in a vin) print(A, in) Figure 3.12: Translation Schema A synthesized attribute for non terminal attributes it ref ferences, havi Placed atthe end of the ce Comp on the ths can be computed after ell uted. The action normally should beich says that when we react e, then ever s left musi de, then everything on its left must I eft must have been computed. If we do this, we will a ee For such specific ve always have the attribute evaluated at the ¢ om eee a a “ne given example) calculating anywhere pe work, but genera ust be calcula eee aa culated immediately at the left. Example: Transta ‘Top down Translation Use predictive parsing to implement L-attributed definitions E>EI+T =E 1 val+ Tal E>EI-T E 1 .val—T.val E>T E.val == T.val T> (6) T.val = E.val T— num T.val = num_lexval how we use parse tree and L-attribute We now come to implementation. We decide st tree with a one-to-one correspondence. We fi Jblem is left recursion. If symbols, definitions to construct the parse ation scheme. The first major pro! our standard mechanism, we introduce new fh the existing actions. Also, we have to do the Jook at the top-down transl we remove left recursion by and new symbols will not work wit parsing in a single pass Eliminate left recursion Eo T {Ri=T.val} {Eval = Rs} (RI A=Ri+ Tallje of removing left recy, Slon To iemove Jeft recursion, we use our earlier rul rewrite fhe attribute equations in a systematic manner. We look at g solution for ths example, a general algorithm will be discussed late, Le Hula Tid, Some new symbols have been Ite Ou ~ added, w, "| Sy equations are no fonger V4 What we are trying (0 do is to take the attribut e Of the attribute attribute form the Teft subtree t0 a right ang et log R inherited is T val sabiree below, We just keep taking ist production. subtree until we hit the Ly Ri=Tva [aes Num 0) = N RLi=Ri-Tval Rs=RI I. num i. Ss R RS=RI Tal =5 l Rs= (2) | Figure 3.13: parse tree aft fer elimination of left recursion Num (2) Fiew We 3.14: Pay ree for 9.54.9aa jor tp-town parsing, We can assume that an action is executed at the time that a symbol in the same position would be expanded. Thus, in the second production in ure the Ist action (assignment to R1i) is done after T has been fully ond action is done after RI has been fully lation shove fi vanded 10 terminals, and the on tapanded: Also, as discussed in the previous lecture, for an L-attributed trar jn inherited attribule of a symbol must be computed by an action appearing before a synthesized attribute of the non-terminal on the left must be symbol and the computed alicr all the attributes it depends on, have been computed. sion Removal of left ree The ursive translation for predictive parsing shown below: Suppose we have the following translation scheme: sneral scheme for transforming left As=e(ALs, Ys) s = f(X.s)} Fach grammar symbol has a synthesized attribute written using the lower case letter «(Cand g are arbitrary functions.) After removing left recursion from the above smmar and taking semantic actions into account, the transformed scheme becomes: {Rin=f(Xs)} R {As — Rs} R {Rhin= eY¥s.Rin)} rR iRs— Ris} 9 BOTTOM UP EVALUATION OF INHERITED ATTRIBUTES + Remove embedded actions from translation scheme + Make transformation so that embedded actions occur only at the ends of their productions + Replace each action by a distinct marker nonterminal M and attach action at end of Me L-attributed definitions in the framework of mpleme’ In this section, the method to bottom-up parsing will be shown. To handle inher formed so that all embedded actions in the transformed ited attributes bottom up, the given translation scheme is transfi translation scheme occur at the right ends of thei each embedded action in the given scheme by a distinct marker M, a non-terminal productions. For this we replace and attach action at end of M + € Therefore, EssoTR R T {print} R R&T {print (-)} R Re T-+—num {print(num.val)} transforms toCeysateronuw E=TR R-++TMR R+-TNR Roe oe “arn | leds Moe” {print(+)} Noe print} ¢ productions, $0 they can be perfor, armed scheme terminate p Actions in the transform med before the right side is reduced during bottom-up par just before the right si it er stacks Inheriting attribute on parse , reduces RHS of A+ XY by removing XY fom stack ang + Bottom up parser reduces RHS putting A on the stack Synthesized attributes of Xs ean be inherited by Y by using the copy rule YieXs Example: String real p,q. [D>TL | iLin=Tiypey {Type = integer} eee T—real__ | (Ttype=real} Ls Lhid } {Lt in=Lin} Lt id {addtype(identry,L in )) Laid {addtypetid.entry.L in )} A bottom-up parser reduces the Y from the top of the attribute of X, X.s is the subtree below Y , this value ¢ Xs. Similarly, in the above Lin is the inherited Fight side of production A> XY by Parser stack and putting A on the st ready on the parser stack befor removing X and ack, Since the synthesized any reduction takes place in an be inherited by Y by using the copy rule Y Bien example T.type is the synthesized attribute and attribute, State stack Input Production real pq ana real P.qr p>————__| Par T real jess eae | Tp ar |__| fp TL qr Vow -———__ | qa | ———_ ——_—__|t TL a LoLid TL, r TL i : L— Lid 12} : D TL Every time a string is reduced to L, T.val is just below it on the stack Example: DoTL [point | val{top) =integer Fo real val[top] =real L— Lid ‘addtype(val{top}, val[top-3)) Lid ‘addtype(valltop], val[top-1]) «Every time a reduction to L is made value of T type is just below tt «Use the fact that T.val (type information) is at a known place in the stack + When production L —> id is applied, id.entry is atthe top of the stack and T.type is just below it, therefo addtype(valftop], val{top-1) addtype(id.entry, L.in) = => L 1, id is applied id.entry is at th + Similarly when production L stack and T.type is three places below it, therefore addtype(val[top},valltop-3)) ced as a pair of arrays, state and val. If holds a synthesized attribute X.s. T.val stack, relative to the top. Let top and ind just after a reduction he top of the addtype(id.entry, L.in)<> the parser stack is implement state(i} is grammar symbol X, then valli] (type information) is at a known place in the val atop be the indices of the top entry in the stack just before a When production Ld is applied, identey 's at the top of low it, therefore, Suppose that takes place, respectively. the val stack and T.type is just bel entry, Line adatypecvalltorh val{top - 1)) addtype(i plied identry is at the top of the stack duction L — LI, id is apy it where T is. Hence, val{top ~ 3)) Similarly, when pro‘ and T.type is three places addtype(id.entry, L.in below il ) <> addtype(valltop} Therefore, the translation scheme becomes: The value of T.value is used in place of Lin.6. A parse tree showing attribute value at each node is called (A) Conerete tree (B) Syntex tree (C) Annotated parse tree (D) Labeled tree ‘A context free grammar in which program fragments ealled semantic actions 27° embedded within right side of the production is called (A) Syntax directed definition (B) Translation scheme (C) Annotated parse tree (D) None of these Which of the following traversal method is used by translation scheme to execute the action ? (A) Depth first traversal (B) Breadth first search (C) In order traversal (D) Level order traversal 4. ] EXERCISET Which of the following checks are within static checking? Mela (A) Type checks (B) Flow checks (C) Uniqueness checks (D) All of these If an array variable and a function y, are added together, which type es error will be generated? (A) Name related checks (B) Uniqueness checks (C) Type checks (D) None of these iat St Type checking is normally done during (A) Syntax Analysis (B) Lexical Ana (C) Code optimization (D) Semantic Analysis | ANSWER KEYS EXPLANATIONS Type checking is part of semantic analy sis. te ter ter ten After ¢ will be (A)
You might also like
CD Unit - 2
PDF
100% (1)
CD Unit - 2
148 pages
Module-5-Syntax Directed Translation
PDF
No ratings yet
Module-5-Syntax Directed Translation
54 pages
Semantic Analysis
PDF
No ratings yet
Semantic Analysis
46 pages
cc-06 Semantic-Analysis Slides
PDF
No ratings yet
cc-06 Semantic-Analysis Slides
83 pages
Chapter 4 Syntax Directed Translation (SDT)
PDF
100% (1)
Chapter 4 Syntax Directed Translation (SDT)
6 pages
Compiler Design Semantic Analysis
PDF
0% (1)
Compiler Design Semantic Analysis
4 pages
Acknowledgements: The Slides For This Lecture Are A Modified Versions of The Offering by
PDF
No ratings yet
Acknowledgements: The Slides For This Lecture Are A Modified Versions of The Offering by
145 pages
Semantic Analysis
PDF
No ratings yet
Semantic Analysis
108 pages
Gmail - Infosys Springboard Pragati Path To Future - Cohort 4 - Jan'25 - Apr'25 - Registrations Are Now Open!
PDF
No ratings yet
Gmail - Infosys Springboard Pragati Path To Future - Cohort 4 - Jan'25 - Apr'25 - Registrations Are Now Open!
2 pages
Unit 4
PDF
No ratings yet
Unit 4
107 pages
Compiler Unit 2
PDF
No ratings yet
Compiler Unit 2
78 pages
9 - Syntax Analysis
PDF
No ratings yet
9 - Syntax Analysis
60 pages
Lec04 Sematic Analysis
PDF
No ratings yet
Lec04 Sematic Analysis
83 pages
Semantic Analysis: Instructor: Venkata Ramana Badarla
PDF
No ratings yet
Semantic Analysis: Instructor: Venkata Ramana Badarla
90 pages
Chapter 4 - 6
PDF
No ratings yet
Chapter 4 - 6
78 pages
Lecture 5 Sementic Analysis
PDF
No ratings yet
Lecture 5 Sementic Analysis
49 pages
Compiler Design
PDF
No ratings yet
Compiler Design
30 pages
Compiler Construction Chapter 6
PDF
No ratings yet
Compiler Construction Chapter 6
111 pages
Compiler Design 4
PDF
No ratings yet
Compiler Design 4
48 pages
Symmetric Ciphers
PDF
No ratings yet
Symmetric Ciphers
79 pages
CD Module 4new Full
PDF
No ratings yet
CD Module 4new Full
46 pages
Check Semantics - Error Reporting - Disambiguate - Type Coercion - Static Checking
PDF
No ratings yet
Check Semantics - Error Reporting - Disambiguate - Type Coercion - Static Checking
108 pages
Chương 4. Phân Tích NG Nghĩa
PDF
No ratings yet
Chương 4. Phân Tích NG Nghĩa
57 pages
Chapter 4
PDF
No ratings yet
Chapter 4
43 pages
11 Semantic Analysis
PDF
No ratings yet
11 Semantic Analysis
28 pages
Semantica HL
PDF
No ratings yet
Semantica HL
57 pages
Compi Desi CHP 04
PDF
No ratings yet
Compi Desi CHP 04
28 pages
05 Syntax-Directed Translation
PDF
No ratings yet
05 Syntax-Directed Translation
32 pages
Unit 4.1
PDF
No ratings yet
Unit 4.1
47 pages
CD Unit 3 - Merged
PDF
No ratings yet
CD Unit 3 - Merged
51 pages
Chapter 4 Syntax Directed Translation
PDF
No ratings yet
Chapter 4 Syntax Directed Translation
37 pages
Lecture 3 - CSC 303
PDF
No ratings yet
Lecture 3 - CSC 303
23 pages
Ch04 Semantic Analysis 4e
PDF
No ratings yet
Ch04 Semantic Analysis 4e
38 pages
Lec 4 Ibot
PDF
No ratings yet
Lec 4 Ibot
26 pages
Module 4
PDF
No ratings yet
Module 4
24 pages
Screenshot 2024-05-11 at 11.38.19 AM
PDF
No ratings yet
Screenshot 2024-05-11 at 11.38.19 AM
28 pages
Lecture 6 - Semantic Analysis
PDF
No ratings yet
Lecture 6 - Semantic Analysis
26 pages
Chapter 4 Semantic Analysis
PDF
No ratings yet
Chapter 4 Semantic Analysis
36 pages
Module 3 - Semantic Analysis
PDF
No ratings yet
Module 3 - Semantic Analysis
31 pages
Chapter 4 - Compiler Designnn 1 Compressed
PDF
No ratings yet
Chapter 4 - Compiler Designnn 1 Compressed
35 pages
Poc Intermediate Code Generation
PDF
No ratings yet
Poc Intermediate Code Generation
14 pages
Crypto Intro 2006
PDF
No ratings yet
Crypto Intro 2006
14 pages
Module-4 Syntax
PDF
No ratings yet
Module-4 Syntax
24 pages
4 Semantic Analysis
PDF
No ratings yet
4 Semantic Analysis
20 pages
Chapter-4 Semantic Analysis
PDF
No ratings yet
Chapter-4 Semantic Analysis
17 pages
Syntax Analysis: Presentation by
PDF
No ratings yet
Syntax Analysis: Presentation by
15 pages
Module 3 - Semantic Analysis
PDF
No ratings yet
Module 3 - Semantic Analysis
26 pages
Mod 1
PDF
No ratings yet
Mod 1
24 pages
Lecture4-Semantic Analysis
PDF
No ratings yet
Lecture4-Semantic Analysis
19 pages
Lec6 - SemanticAnalysis 3
PDF
No ratings yet
Lec6 - SemanticAnalysis 3
38 pages
Unit 4
PDF
No ratings yet
Unit 4
16 pages
Compiler Construction Final
PDF
No ratings yet
Compiler Construction Final
6 pages
7.CD Lab Manual
PDF
No ratings yet
7.CD Lab Manual
35 pages
Semantic Analysis: Checking What Parsers Cannot
PDF
No ratings yet
Semantic Analysis: Checking What Parsers Cannot
21 pages
Chapter 4 Semantic Analysis PDF
PDF
No ratings yet
Chapter 4 Semantic Analysis PDF
16 pages
CSE2002 - Module6 - PARTA - Notes
PDF
No ratings yet
CSE2002 - Module6 - PARTA - Notes
39 pages
Semantic Report
PDF
No ratings yet
Semantic Report
24 pages
Summary: Semantic Analysis: When SA Is Performed: Semantic Analysis May Be Performed
PDF
No ratings yet
Summary: Semantic Analysis: When SA Is Performed: Semantic Analysis May Be Performed
7 pages
Syntax Analysis
PDF
No ratings yet
Syntax Analysis
20 pages
The Structure of A Compiler (1) The Structure of A Compiler
PDF
No ratings yet
The Structure of A Compiler (1) The Structure of A Compiler
22 pages
Group Members: Sohail Memon (429) Abdul Qayoom (350) Rehmatullah (408) Muhammad Bilal (392) Noor-ul-Ain
PDF
No ratings yet
Group Members: Sohail Memon (429) Abdul Qayoom (350) Rehmatullah (408) Muhammad Bilal (392) Noor-ul-Ain
15 pages
Semantic Analysis
PDF
No ratings yet
Semantic Analysis
41 pages
Phases of Compiler
PDF
No ratings yet
Phases of Compiler
9 pages