|
6.2.3 A Word about Example 1It is common in computer science to use examples which explain the idea clearly, but which are not necessarily the best application of the idea. Thus, recursion is often introduced using factorial, a nice clear example, but not necessarily the best way to compute a factorial ( iteratively is faster and takes up less space). So it is with our first example of an attribute grammar. This example computes the value of the expression represented in a parse tree. Most compilers would not do this since their ultimate gola is to put out code (which then gets executed). EXAMPLE 1 Using attributes to evaluate expressions Consider the following attribute grammar: Syntax Semantics E0E1+T E0.Value:=E1.Value+T.Value ET E.Value:=T.Value T0T1*F T0.Value:=T1.Value*F.Value TF T.Value:=F.Value F(E) F.Value:=E.Value FConstant F.Value:=Constant.Value There is one attribute, Value, and it is a synthesized attribute. The value of this attribute can be calcuted by one pass up the parse tree. Consider the string 4+2*3 and its parse tree:
Using the semantic functions, and starting at the bottom of the tree, the various values of Value are computed. The lexical analyzer finds the value of Constant.Value. This is the value shown in the above parse tree. Send questions and comments to: Karen Lemone |