









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










I. Introduction.
These notes are intended to supplement class lectures on attribute grammars. We will begin with functional graphs, and describe methods of evaluating them. Then we will introduce attribute grammars, show an example of their use, and proceed to give an attribute grammar for Tiny.
II. Functional graphs.
Definition : A functional graph is a directed graph in which
i) Nodes represent functions, a. Incoming edges are parameters. b. Outgoing edges represent functional values. ii) Edges represent transmission of data among functions.
Example :
Here we have three functions:
i- Constant function 2. ii- Constant function 3. iii- Binary function + (addition).
After some delay, the value of the addition function is five.
Question : What effect does a cycle in a functional graph have?
Answer : A cycle can make sense only if the graph can achieve a steady state, in which no more changes in the values occur.
Example :
No steady state is achieved, because the value of? keeps incrementing.
Example :
true and?
A steady state is achieved, because regardless of the initial value of the feedback loop, it does not change after the first AND operation, and remains with that value. However, if the "AND" were changed to a "NAND", there would be no steady state.
In general, it is impossible to detect whether a steady state will ever occur (the problem is undecid- able, i.e. as difficult as deciding whether a Turing machine will halt).
If we assume that each node in the graph is a single processor, then the graph can be thought of as a network of parallel processors. We will also assume that all functional graphs are acyclic.
Evaluation of Functional Graphs:
Functional graphs are evaluated by first inserting registers, and then propagating values along the edges.
Register insertion:
Given edges E 1... En from a node A to nodes B 1... Bn , we insert a register so that there is one edge from A to the register, and n edges from the register to B 1... Bn respectively.
Example :
Bn
Bn
All registers must be initialized to some "undefined" value, which must be outside of the domains of all functions.
For an outgoing edge from a "top-most" node, a register is simply added to the graph, so that the edge goes from the node to the register. Note that this is the same as the first case, with n=0.
Functional value propagation:
There are two ways to propagate values along the functional graph. The first, called "data flow analy- sis", makes several passes on the graph, evaluating functions whose inputs (registers) are defined. The other, called "lazy evaluation", uses a stack to perform a depth-first search, backwards (i.e. the opposite direction of the edges), for the "bottom-most" nodes of the graph. The functions are then evaluated in the order specified by the contents of the stack.
Definition : An attribute grammar consists of
A context-free grammar describing the structure of the parse tree.
A set of attributes ATT. Each attribute "decorates" some node in the AST, and later in fact becomes a register in the functional graph.
A set of axioms that express relationships among attributes.
Example : Binary Numbers.
String-to-tree transduction grammar: S → N =>. → N. N =>. N → N D => cat → D D → 0 => 0 D → 1 => 1
Abstract Syntax Tree Grammar:
S → <. N N > → <. N > N → < cat N D > → D D → 0 → 1
The first grammar specifies the transduction from strings to AST’s. The second one (which we will use for the attribute grammar) generates trees in prefix form. There are two types of attributes:
For binary numbers, we have ATT = { value, length, exp }, where
value: the decimal value of the binary number denoted by the subtree. length: the number of binary digits occurring to the left of the right-most binary digit in the sub- tree. This will be used to generate negative exponents, for the fractional part (if any) of the binary number. exp: the exponent (of 2) that is to be multiplied by the right-most binary digit in the subtree.
The synthesized and inherited attributes are specified by two subsets of ATT:
SATT = { value, length } IATT = { exp }
Note: In this particular case, SATT and IATT are disjoint. This is not always the case, as we shall see later.
Attributes are associated with nodes in the AST via two functions:
S: Σ → PowerSet (SATT) I: Σ → PowerSet (IATT)
Σ is the vocabulary in the grammar. In our case, Σ = { 0, 1, cat,. }. Note that meta-symbols ’<’ and ’>’ are left out of Σ. Functions S and I map each symbol to a subset of the synthesized and inherited attributes, respectively. In our case,
S(0) = { value, length } S(1) = { value, length } S(cat) = { value, length } S(.) = { value } I(0) = { exp } I(1) = { exp } I(cat) = { exp } I(.) = { }
Recall that attributes are "attached" to tree nodes, and that they become registers in the functional graph.
Example : Suppose the input binary number is ’10.1’. Here’s the AST, with the corresponding attributes attached:
cat 1
v
e v l e v l
e v l e v l
The inherited attributes are depicted on the left of each node, and the synthesized attributes are depicted on the right. This is simply a convention. However, it aids in understanding the flow of information: top-down on the left, and bottom-up on the right.
For a given tree node, a certain attribute may occur both at that node and at some of its siblings. In the above example, attribute "value" occurs "locally" at the root node and at both its first and second kid. To prevent confusion, we will use a tree addressing scheme, as follows:
Definition : Given a tree node T, with kids T 1,... Tn ,
i- a( ε ) refers to attribute "a" at node T, and ii- a(i) refers to attribute "a" at the i’th kid of T (i.e. node Ti ).
In the above example, given that we are referring to the root node, v( ε ) refers to the "value" attribute at the root node, while v(1) and v(2) refer to the "value" attribute at the first and second kids of the root, respec- tively.
The axioms are:
value( ε ) = value(1) + value(2) exp(1) = 0 exp(2) = - length(2)
The segment of functional graph is shown below. The lines connecting trees nodes have been omitted.
v
e v l e v l
0 neg
Note that the length attribute from the first kid is ignored, while the length from the second kid is negated and sent down the exponent of the second kid. The length attribute is used only for the second kid of the root (if any), so that negative exponents may be computed. At the bottom of T 2 (the right-hand side tree), length will originate with value 1. It will be incremented by one on the way up, negated at the top, and sent down via the inherited exponent attribute (and incremented along the way), to be used as the correct (neg- ative) power of 2, for the binary digits. The two synthesized "value" attributes (the integral and the frac- tional part of the binary number) are added together to form the decimal result.
Here’s the entire set of axioms: S → <. N N > value( ε ) = value(1) + value(2) exp(1) = 0 exp(2) = - length(2) # explained above S → <. N > value( ε ) = value(1) # no fraction; copy value up. exp(1) = 0 N → < cat N D > value( ε ) = value(1) + value (2) # add two values. length( ε ) = length(1) + 1 # increment length up left. exp(1) = exp ( ε ) + 1 # increment exp down left exp(2) = exp ( ε ) # copy exp down right N → D
D → 0 value( ε ) = 0 # zero no matter what. length( ε ) = 1 # initial length. D → 1 value( ε ) = 2 ** exp( ε ) # compute value. length( ε ) = 1 # initial length.
Here’s a complete example, for input "10.1".
cat 1
v
e v l e v l
e v l e v l
0 neg
Once the functional graph is evaluated:
cat 1
v
e v l e v l
e v l e v l
0 neg
So far we’ve seen how a human would build a functional graph from an attribute grammar. Here we describe how functional graphs can be generated automatically from the attribute grammar. The starting point is an AST, produced by a string-to-tree transducer. To guarantee that the tree will be recognized, we must first transform the tree to fully-parenthesized postfix notation, and use an LR parser to recognize it. Fortunately, an LR(0) parser (that’s right, no look-ahead) can always do the job. In the case of binary num- bers:
Scanner Specification
Scanner Generator
Scan Table Scanner
Source Input
Screener Specification
Screener Generator
Screen Table Screener
Parser Specification
Parser Generator
Parse Table Parser
prefix→postfix Tree Transducer
AST (postfix)
LR Tree Parser & Graph Generator
GRAPH
Graph Evaluator
Target Output
Tables (& Axioms)
LR(0) Tree Parser Generator
AG (postfix)
prefix→postfix Grammar Transducer
Attribute Grammar
Tokens
Tokens
The larger dashed box is the translator genration system; the smaller is the translator being generated. The phases of the translation (scanning, screening, parsing, and back-end processing) are shown. In the case of binary numbers, the user of the system provides the three front-end specifications and the attribute grammar. The system generates a parser from the front-end specifications, and a graph generator from the attribute grammar. The user then provides a sample source input, which is transduced to the AST, trans- formed into postfix notation, and recognized by the LR(0) tree parser, which in turn builds the functional graph, and passes it to the graph evaluator to produce the translated output. In our case the source language is that of binary numbers, and the target language is that of decimal numbers. The correctness of the trans- lation, of course, depends on ALL four specifications.
Now, finally, the real world. In the case of binary numbers, all attributes were integers. However, attributes can be whatever we want them to be, as long as we have well-defined semantic functions to manipulate them. In the next section, we use attribute grammars to specify (completely) the semantics of a (very) small language, called Tiny for lack of a better name. In this attribute grammar, the most important
attribute will be a "file" attribute -- the code file in which instructions of the target machine will be placed. This code file attribute will propagate around the entire abstract syntax tree, collecting instructions as the evaluation of the graph (and the translation) proceeds.
The result of the evaluation of the functional graph will be this code file, i.e. the sequence of machine instructions to which the source program has been translated. To execute the translated program, of course, the code file must be loaded into the target machine and executed.
An Attribute Grammar for Tiny
Tiny is a very small Pascal-like language, with the following characteristics:
Every program is given a name.
There are user-defined variables, of type integer.
Legal expressions are composed of variables, integers, the intrinsic function "read", boolean operator "not", equality operator "=", binary operators "+" and "-" and unary "-". "not" and unary "-’ are the most binding operators, "+" and "-" are next, and "=" is the least binding. "+" and "-" are left asso- ciative; parentheses override both precedence and associativity.
There are assignment statements, and variables must be assigned a value before they are used in expressions. There are no declarations.
There is an if-then-else construct, a while-loop, statement sequencing, and an intrinsic procedure "output".
Here’s Tiny’s syntax:
Tiny → ’program’ Name ’:’ Statement ’end’ Name ’.’ => ’program’; Statement → ’assign’ Name ’:=’ Expression => ’assign’ → ’output’ Expression => ’output’ → ’if ’ Expression ’then’ Statement ’else’ Statement ’fi’ => ’if’ → ’while’ Expression ’do’ Statement ’od’ => ’while’ → Statement list ’;’ => ’;’ ; Expression → Term ’=’ Term => ’=’ → Term; Term → Term ’+’ Factor => ’+’ → Term ’-’ Factor => ’-’ → Factor; Factor → ’-’ Factor => ’-’ → ’not’ Factor => ’not’ → Name → ’read’ => ’read’ → ’’ → ’(’ Expression ’)’; Name → ’’;
Here’s a sample Tiny program, that copies 10 integers from the input to the output:
program copy: assign i := 1; while not (i=11) do output read; assign i := i + 1 od end copy.
1: lit 1 # i := 1 2: load 1 # i = 11 3: lit 11 4: equal 5: not 6: iffalse 14 # while 7: read 8: print 9: load 1 # i := i + 1 10: lit 1 11: add 12: save 1 13: goto 2 # od 14: stop # end
Our compiler is not ambitious. It recognizes the following semantic errors:
Data structures required:
We will need two data structures: the declaration table and files.
a) function enter(name,l). Associates the given "name" with stack location "l". Returns location "l". b) function lookup(name). Returns the location previously "entered" for "name". Returns 0 if "name" is not found.
a) function gen(file, arg 1 ,... argn ). Writes a new line on the given "file". The line contains arg 1 ,... argn. The function returns the new, modified file. b) function Open. Creates a new file. c) function Close. Closes a file.
Note that we assume that files are generated sequentially.
The Attributes :
code: File of code generated. next: Label of the next instruction to be written on the code file. error: File of semantic errors. top: Current size of run-time stack. type: Type of subtree. Used for type-checking.
ALL attributes are both synthesized and inherited. Hence, to prevent confusion, we will use the following convention:
a↑ is the synthesized attribute a. a↓ is the inherited attribute a.
Synthesized and Inherited Attributes :
S(program) = { code↑, error↑ } I(program) = { } S(assign) = { code↑, next↑, error↑, top↑, type↑ } I(assign) = { code↓, next↓, error↓, top↓ }
All other nodes have the same synthesized and inherited attributes as the "assign" node.
Tree Walking Assumptions :
In general, the tree walk will be as discussed before, i.e. top-down on the left, and bottom-up on the right. On the left of each tree node we will have four inherited attributes (all except type↓). On the right of each tree node we will have all five synthesized attributes. The only exception is the "program" node, which inherits no attributes and only synthesizes the final results of the translation: the code and error files. It should be clear that there are a lot of axioms to write, many of which will be repetitive. Hence the fol- lowing convention:
Whenever an axiom is omitted, we will assume the following:
If the tree node has no kids, then a↑( ε ) = a↓( ε ) If the tree node has "n" kids, then
a↓(1) = a↓( ε ) a↓(i) = a↑(i-1), for 1 < i ≤ n a↑( ε ) = a↑(n)
In short, when axioms are omitted, we assume a "pipeline" that simply passes the attributes along, begin- ning with the inherited attribute at the the root of the subtree, down to the first kid, up from the first kid, down to the second kid, etc., and finally up from the last kid and up from the root. This effectively means that we are making extensive (and implicit) use of the identity function.
TINY’s ATTRIBUTE GRAMMAR :
Here’s the attribute grammar, in all its gory detail.
E → ’:n’ code↑( ε ) = gen ( code↓( ε ), "lit", "n" ) next↑( ε ) = next↓( ε ) + 1 top↑( ε ) = top↓( ε ) + 1 type↑( ε ) = "integer"
E → ’:x’ code↑( ε ) = gen ( code↓( ε ), "load", lookup("x") ) next↑( ε ) = next↓( ε ) + 1 top↑( ε ) = top↓( ε ) + 1 type↑( ε ) = "integer" error↑( ε ) = if lookup("x") = 0 then gen ( error↓( ε ), "identifier un-initialized" ) else error↓( ε )
E → < assign ’:x’ E > code↑( ε ) = if lookup("x") = 0 then enter("x",top↑(2)); code↑(2) else gen ( code↑(2), "save", lookup("x") ) next↑( ε ) = if lookup("x") = 0 then next↑(2) else next↑(2) + 1 top↑( ε ) = if lookup ("x") = 0 then top↑(2) else top↑(2) - 1 error↑( ε ) = if type↑(2) = "integer" then error↑(2) else gen ( error↑(2), "Assignment type clash" ) type↑( ε ) = "statement"
E → < output E >
code↑( ε ) = gen ( code↑(1), "print" ) next↑( ε ) = next↑(1) + 1 top↑( ε ) = top↑(1) - 1 type↑( ε ) = "statement" error↑( ε ) = if type↑(1) = "integer" then error↑(1) else gen ( error↑(1), "Illegal type for output" )
E → < ; E* >
Use Defaults!
E → < if E E E >
code↓(2) = gen ( code↑(1), "iffalse", next↑(2) + 1 ) next↓(2) = next↑(1) + 1 top↓(2) = top↑(1) - 1 code↓(3) = gen ( code↑(2), "goto", next↑(3) ) next↓(3) = next↑(2) + 1 error↓(2) = if type↑(1) = "boolean" then error↑(1) else gen ( error↑(1), "Illegal expression for if" ) error↓(3) = if type↑(2) = "statement" then error↑(2) else gen ( error↑(2), "Statement required for if" ) error↑( ε ) = if type↑(3) = "statement" then error↑(3) else gen ( error↑(3), "Statement required for if" )
E → < while E E > code↓(2) = gen ( code↑(1), "iffalse", next↑(2) + 1 ) next↓(2) = next↑(1) + 1 top↓(2) = top↑(1) - 1
code↑( ε ) = gen ( code↑(2), "goto", next↓( ε ) ) next↑( ε ) = next↑(2) + 1 type↑( ε ) = "statement" error↓(2) = if type↑(1) = "boolean" then error↑(1) else gen ( error↑(1), "Illegal expression in while" ) error↑( ε ) = if type↑(2) = "statement" then error↑(2) else gen ( error↑(2), "Statement required in while" )
Tiny → < program ’:x’ E ’:y’ > code↓(2) = Open error↓(2) = Open next↓(2) = 1 top↓(2) = 0 code↑( ε ) = close ( gen ( code↑(2), "stop" ) ) error↑( ε ) = close ( if x = y then error↑(2) else gen ( error↑(2), "program names don’t match" ) )
It would be useful to draw pictures of the functional graph segments, and maybe even the entire AST and functional graph for the sample Tiny program shown above.