Download Objects and Classes - Compiler Construction - Assignment 8 | ECEN 4553 and more Assignments Electrical and Electronics Engineering in PDF only on Docsity!
Assignment 8: objects and classes
ECEN 4553 & 5013, CSCI 4555 & 5525
Prof. Jeremy G. Siek
November 3, 2008
The main ideas for this week are:
- objects and classes
- attributes and methods
- inheritance
1 Syntax of P 5
The concrete syntax of P 5 is shown in Figure 1 and the abstract syntax (the
Python AST classes) is shown in Figure 2.
expression ::= expression "." identifier expression_list ::= expression ( "," expression )* [","] statement ::= "class" name ["(" expression_list ")"] ":" statement target ::= expression "." identifier
Figure 1: Concrete syntax for the P 5 subset of Python. (In addition to that
of P 4 .)
2 Semantics of P 5
This week we add one new statement for creating classes. For example, the
following statement creates a class named C.
>>> class C: ... x = 42
Assignments in the body of a class create class attributes. The above code
creates a class C with an attribute x. Class attributes may be accessed using
the dot operator. For example:
class AssAttr(Node): def init(self, expr, attrname, flags): self.expr = expr self.attrname = attrname self.flags = flags # ignore this
class Class(Node): def init(self, name, bases, doc, code): self.name = name self.bases = bases self.doc = doc # ignore this self.code = code
class Getattr(Node): def init(self, expr, attrname): self.expr = expr self.attrname = attrname
Figure 2: The Python classes for P 5 ASTs.
>>> print C.x 42
The body of a class may include arbitrary statements, including statements
that perform I/O. These statements are executed as the class is created.
>>> class C: ... print 4 * 10 + 2 42
If a class attribute is a function, then accessing the attribute produces an
unbound method.
>>> class C: f = lambda o, dx: o.x + dx >>> C.f >
An unbound method is like a function except that the first argument must
be an instance of the class from which the method came. We’ll talk more
about instances and methods later.
Classes are first-class objects, and may be assigned to variables, re-
turned from functions, etc. The following if expression evaluates to the
class C, so the attribute reference evaluates to 42.
>>> class C: ... x = 42 >>> class D:
An instance may have associated data attributes, which are created by
assigning to the attribute. Data attributes are accessed with the dot opera-
tor.
>>> o.x = 7 >>> print o.x 7
Different objects may have different values for the same attribute.
>>> p = C(42) 42 >>> p.x = 10 >>> print o.x, p.x 7, 10
Objects live on the heap and may be aliased (like lists and dictionaries).
>>> print o is p False >>> q = o >>> print q is o True >>> q.x = 1 >>> print o.x 1
A data attribute may be a function (because functions are first class). Such
a data attribute is not a method (the object is not passed as the first param-
eter).
>>> o.f = lambda n: n * n >>> o.f(3) 9
When the dot operator is applied to an object but the specified attribute is
not present, the class of the object is searched followed by the base classes
in depth-first, left-to-right order.
>>> class C: ... y = 3 >>> o = C() >>> print o.y 3
If an attribute reference resolves to a function in the class or base class
of an object, then the result is a bound method.
>>> class C: ... def move(o,dx): ... o.x = o.x + dx
>>> o = C() >>> o.move >
A bound method ties together the receiver object (o in the above example)
with the function from the class (move). A bound method can be called like
a function, where the receiver object is implicitly the first argument and the
arguments provided at the call are the rest of the arguments.
>>> o.x = 40 >>> o.move(2) >>> print o.x 42
Just like everything else in Python, bound methods are first class and may
be stored in lists, passed as arguments to functions, etc.
>>> mlist = [o.move,o.move,o.move] >>> i = 0 >>> while i != 3 ... mlisti ... i = i + 1 >>> print o.x 47
You might wonder how does the Python implementation know whether to
make a normal function call or whether to perform a method call (which
requires passing the receiver object as the first argument). The answer is
that the implementation checks the type tag in the operator to see whether
it is a function or bound method and then treats the two differently.
Exercise 2.1. Read:
1. Section 9 of the Python Tutorial
2. Python Language Reference, Section 3.
3 Compilation to C
Figure 3 shows the structure of the compiler with the addition of objects.
We insert a new pass at the beginning of the compiler that lowers classes
and objects to more primitive operations and then we update the C code
generation to handle these new primitives. The other passes will also need
to be updated to pass along but otherwise ignore the new primitives.
In addition to the new passes and primitives, the entities introduced
this week are all first-class, so the pyobj union needs to be extended.
The class definition should be compiled into an assignment to a variable
named C. The right-hand-side of the assignment should be an expression
that allocates a class object with an empty hashtable for attributes and an
empty list of base classes. So, in general, the transformation should be
class C: pass =⇒ C = make_class()
where make class is a new PrimitiveOp that is ignored by subsequent
passes until we get to C code generation, where we output a call to a C
helper function or macro.
While a class with no attributes is useless in C++, in Python you can
add attributes to the class after the fact. For example, we can proceed to
write
>>> C.x = 3 >>> print C.x 3
An assignment such as C.x = 3 (the AssAttr node) should be passed along
through the compiler passes until you get to C code generation. At that
point it should be translated into a hashtable search in the class object’s
hashtable followed by an assignment to the value, if one was found, or else
a hashtable insert if none was found. This translation can be handled as
you are generating C code.
The attribute access C.x (the Getattr node) in the print statement should
be translated into a hashtable search in the class object’s hashtable. If the
value of the attribute is a function (test whether the value of the attribute
has the tag CLOSURE), then one extra step is needed before returning the
value: the function must be wrapped into unbound method.
3.2 Compiling class definitions
A class body may contain an arbitrary sequence of statements, and some of
those statements (assignments and function definitions) add attributes to
the class object. Consider the following example.
class C: x = 3 if True: def foo(self, y): w = 3 return y + w
z = x + 9 else: def foo(self, y): return self.x + y print ’hello world!\n’
This class definition creates a class object with three attributes: x, foo, and
z, and prints out hello world!.
The main trick to compiling the body of a class is to replace assignments
and function definitions so that they refer to attributes in the class. The re-
placement needs to go inside compound statements such as If and While,
but not inside function bodies, as those assignments correspond to local
variables of the function. One can imagine transforming the above code to
something like the following:
class C: pass C.x = 3 if True: def __foo(self, y): w = 3 return y + w C.foo = __foo C.z = C.x + 9 else: def __foo(self, y): return self.x + y C.foo = __foo print ’hello world!\n’
Once the code is transformed as above, the rest of the compilation passes
can be applied to it as usual.
In general, the translation for class definitions is as follows.
class C: body =⇒ C = make_class() newbody
The body is translated to newbody by recursively applying the following
transformations. You will need to know which variables are assigned to
(which variables are class attributes), so before transforming the body, first
find all the variables assigned-to in the body (but not assigned to inside
functions in the body).
The translation for assignments is:
x = e
The Python IfExp is normally written as e 1 if e 0 else e 2 where e 0 is
the condition, e 1 is evaluated if e 0 is true, and e 2 is evaluated if e 0 is false.
I’ll instead use the following textual representation:
if e 0 then e 1 else e 2
In general, function calls can now be compiled like this:
e 0 (e 1 ,.. .,en) =⇒ let f = e 0 in if is_class(f ) then let o = make_obj(f ) in if has_attr(f , ’init’) then let ini = get_attr(f , ’init’) in let _ = ini(o, e 1 ,.. .,en) in o else if n = 0 then o else Exit(-1) else f (e 1 ,.. .,en) # normal function call
In the above, is class, make obj, and has attr are all primitive opera-
tions that you need to define.
The next step is to add support for creating and accessing attributes of
an object. Consider the following example.
o = C() o.w = 42
print o.w print o.x # attribute from the class C
The object contain a hashtable for their attributes. An assignment to
an attribute associates the value of the right-hand-side with the attribute’s
name in the hashtable for the object. So the assignment o.w = 42 inserts
the item ’w’:42 to o’s hashtable (or overwrite the value if there is already
an item with a key equal to ’w’). The translation of a AssAttr node into the
hashtable lookup can be done during the generation of C code, and can be
facilitated by a helper C function. To avoid changing the passes in between,
translate the AssAttr node into a primitive operation.
The same applies to compiling access to an attribute of an object (the
Getattr node). To access an attribute, first do a hashtable search in the
object’s dictionary. If you find an item, return the value. Otherwise, go
to the object’s class (this should be stored inside the representation of the
object) and do a search. (You already implemented search for classes in Sec-
tion 3.1.) If the result is an unbound method, then create a bound method
that contains the receiver object and the method. Otherwise return the re-
sult.
3.4 Compiling bound and unbound method calls
Calls to bound and unbound methods show up as a function call node
(CallFunc) in the AST, so we now have four things that can happen at
a function call (we already had object construction and normal function
calls). To handle bound and unbound methods, we just need to add more
conditions to check whether the operator is a bound or unbound method.
In the case of an unbound method, you should check that the object is an
instance of the class associated with the unbound method (when we add
inheritance, objects of subclasses are OK too), and then call the underlying
function. In the case of a bound method, you call the underlying function,
passing the receiver object (obtained from inside the bound method) as the
first argument followed by the normal arguments. A suggested translation
for function calls is given below. This translation uses several more primi-
tive operations: is unbound method, get class, is bound method, get function,
and get object.
e 0 (e 1 ,.. .,en) =⇒ let f = e 0 in if is_class(f ) then let o = make_obj(f ) in if has_attr(f , ’init’) then let ini = get_attr(f , ’init’) in let _ = ini(o, e 1 ,.. .,en) in o else if n = 0 then o else Exit(-1) else if is_unbound_method(f ) then let o = e 1 in if get_class(f ) == get_class(o) then get_function(f )(o, e 2 ,.. .,en) else Exit(-1) else if is_bound_method(f ) then get_function(f )(get_object(f ), e 1 ,.. .,en) else f (e 1 ,.. .,en) # normal function call