90 likes | 292 Views
Lecture # 16. Chapter # 5: Syntax Directed Translation. Syntax-Directed Translation. Uses a CFG to specify the syntactic structure of the language It associates a set of attributes with the terminals and nonterminals of the grammar
E N D
Lecture # 16 Chapter # 5: Syntax Directed Translation
Syntax-Directed Translation • Uses a CFG to specify the syntactic structure of the language • It associates a set of attributes with the terminals and nonterminals of the grammar • It associates with each production a set of semantic rules to compute values of attributes • A parse tree is traversed and semantic rules applied: after the computations are completed the attributes contain the translated form of the input
Synthesized and Inherited Attributes • An attribute is said to be … • synthesized if its value at a parse-tree node is determined from the attribute values at the children of the node • inherited if its value at a parse-tree node is determined by the parent (by enforcing the parent’s semantic rules)
Syntax-Directed Definitions • A syntax-directed definition (or attribute grammar) binds a set of semantic rules to productions • Terminals and nonterminals have attributes holding values set by the semantic rules • A depth-first traversal algorithm traverses the parse tree thereby executing semantic rules to assign attribute values • After the traversal is complete the attributes contain the translated form of the input
Example Attribute Grammar Production Semantic Rule L EnE E1+TE TT T1*FT FF (E) F digit print(E.val)E.val:= E1.val + T.valE.val:= T.valT.val:= T1.val * F.valT.val:= F.valF.val:= E.valF.val:=digit.lexval Note: all attributes inthis example are ofthe synthesized type
Depth-First Traversals (Example) L print(16) E.val= 16 E.val= 14 T.val = 2 F.val = 5 E.val= 9 T.val= 5 T.val = 9 F.val = 5 F.val = 9 Note: all attributes inthis example are ofthe synthesized type 9 + 5 + 2 n
Example Attribute Grammar String concat operator Production Semantic Rule expr expr1+termexpr expr1-termexpr termterm 0term 1…term 9 expr.t := expr1.t // term.t // “+”expr.t := expr1.t // term.t // “-”expr.t := term.tterm.t := “0”term.t := “1”… term.t := “9”
Example Annotated Parse Tree expr.t = “95-2+” expr.t = “95-” term.t = “2” expr.t = “9” term.t = “5” term.t = “9” 9 - 5 + 2
Depth-First Traversals procedure visit(n : node);begin for each child m of n, from left to right dovisit(m); evaluate semantic rules at node nend