5 Primitives for a reflective class-based kernel

Now that all the infrastructure has been explained you are ready to start. The first tasks are to define how we will manipulate objObjects. We will define Pharo methods that will act as primitive functionalities to build later the language kernel. Such primitives could be written in C, assembly or any other languages. They are the low-level functionalities on top of which we will build the object model of ObjVLisp: mainly the class ObjObject and ObjClass.

5.1 Structure and primitives

The first issue is how to represent objects. We have to agree on an initial representation. In this implementation, we chose to represent the objInstances as arrays (instances of Obj a subclass of Array). In the following, we use the term 'array' for talking about instances of the class Obj.

Your job.

Check that the class Obj exists and inherits from Array.

5.2 Structure of a class

The first object that we will have to create is the class ObjClass. Therefore we focus now on the minimal structure of the classes in our language.

An objInstance representing a class has the following structure: an identifier to its class, a name, an identifier to its superclass (we limit the model to single inheritance), a list of instance variables, a list of initialization keywords, and a method dictionary.

For example, the class ObjPoint has the following structure:

#(#ObjClass #ObjPoint #ObjObject #(class x y) #(:x :y) nil)

It means that the objClass ObjPoint is an instance of ObjClass, is named #ObjPoint, inherits from a class named ObjObject, has three instance variables, two initialization keywords, and an uninitialized method dictionary. To access this structure we define some primitives as shown in Figure 5.1.

Class structure representation.
Figure 5.1 Class structure representation.

To avoid manipulating numbers we defined some Pharo methods returning the corresponding constants of the object and class structure. These methods start with the offset term. We have offsetForClassIdId, offsetForName, offsetOfSuperclassId, and more. Figure 5.2 shows how offsets are used to access the information of an objClass.

Here is the definition of offsetForName: It just defines that given an objobject representing an objclass the name of the class is located at the second position.

Obj >> offsetForName
	^ 2

Using the method offsetForName we can simply define a Pharo primitive named objName that returns the name of a class as follows:

Obj >> objName
	^ self at: self offsetForName

The corresponding setter objName: is then defined as follows:

Obj >> objName: aString 
	^ self at: self offsetForName put: aString

Using offset to access information.
Figure 5.2 Using offset to access information.

Your job.

The test methods of the class RawObjTest that are in the categories 'step01-tests-structure of objects' and 'step02-tests-structure of classes' give some examples of structure accesses. Here are two examples of such test methods:

RawObjTest >> testPrimitiveStructureObjClassId
   self assert: pointClass objClassId equals: #ObjClass

RawObjTest >> testPrimitiveStructureObjIVs
   self assert: pointClass objIVs equals: #(#class #x #y)

Access of ClassId for any objects.

Using the method offsetForClassIdId, implement in protocol 'object structure primitives' the primitives objClassId and objClassId: aSymbol. The receiver is an objObject. This means that this primitive can be applied on any objInstances (be it a class or an instance such as a point objObject) to get its class identifier. Execute the test method testPrimitiveStructureObjClassId.

Class structure access.

Now we can focus on the other primitives that give access to class information.

Implement in protocol 'class structure primitives' the primitives that manage:

5.3 Finding the class of an object

Every object keeps the identifier of its class (its name). For example, an instance of ObjPoint has then the following structure: #(#ObjPoint 10 15) where #ObjPoint is a symbol identifying the class ObjPoint.

Your job.

Using the primitive giveClassNamed: aSymbol defined at the class level of Obj (See Section 4.5), define the primitive objClass in the protocol 'object-structure primitive' that returns the objInstance that represents its class (classes are objects too in ObjVLisp).

Make sure that you execute the test method: testClassAccess

RawObjTest >> testClassAccess
   self assert: aPoint objClass equals: pointClass

Now we will be ready to manipulate objInstances via proper API. We will now use the class ObjTest for more elaborate tests.

5.4 Accessing object instance variable values

Instance variable offset asked to the class.
Figure 5.3 Instance variable offset asked to the class.

A first simple method.

Now you will implement a primitive that when sent to an objClass returns the offset of the instance variable represented by the symbol. It returns 0 if the variable is not defined. The following test illustrates the behavior of this primitive ivClassOffset: (It could have been named classOffsetForIV:)

ObjTest >> testIVOffset
   self 
   	assert: (pointClass ivClassOffset: #x) 
   	equals: 2.
   self 
   	assert: (pointClass ivClassOffset: #lulu) 
   	equals: 0

Your job.

In the protocol 'iv management' define a method called ivClassOffset: aSymbol Look at the tests #testIVOffset of the class ObjTest. Make sure that you execute the test method: testIVOffset.

Hints: Use the Pharo method indexOf:. Pay attention that such a primitive is applied to an objClass as shown in the test.

Instance variable offset asked to the instance itself.
Figure 5.4 Instance variable offset asked to the instance itself.

Two simple methods.

Now that we know from the class the offset for a given instance variable, we can define a primitive that performs a similar behavior but that is sent to an instance and not a class. Using it we can easily get access to the value of an instance variable of an instance.

The following test illustrates the expected behavior:

ObjTest >> testIVOffsetAndValue

   self 
   	assert: (aPoint ivOffset: #x) 
	equals: 2.
   self 
   	assert: (aPoint valueOfInstanceVariable: #x) 
	equals: 10

Your job.

Using the previous method, define in the protocol 'iv management':

  1. When sent to an objObject, the primitive ivOffset: aSymbol that returns the offset of the instance variable. Note that this time the method is applied to an objInstance presenting an instance and not a class (as shown in Figure 5.4). (It could have been named objectOffsetForIV:).
  2. the method valueOfInstanceVariable: aSymbol that returns the value of this instance variable in the given object as shown in the test below.

Note that for the method ivOffset: you can check that the instance variable exists in the class of the object and else raise an error using the Pharo method error:.

Make sure that you execute the test method: testIVOffsetAndValue and it passes.

5.5 Object allocation and initialization

The creation of an object is the composition of two elementary operations: its allocation and its initialization. We now define the primitives that allow us to allocate and initialize an object. Remember that:

Instance allocation

As shown in the class ObjTest, if the class ObjPoint has two instance variables: ObjPoint allocateAnInstance returns #(#ObjPoint nil nil).

ObjTest >> testAllocate

   | newInstance |
   newInstance := pointClass allocateAnInstance.
   self assert: (newInstance at: 1) equals: #ObjPoint.
   self assert: (newInstance size) equals: 3.
   self assert: (newInstance at: 2) isNil.
   self assert: (newInstance at: 3) isNil.
   self assert: newInstance objClass equals: pointClass

Your job.

In the protocol 'instance allocation' implement the primitive called allocateAnInstance that when sent to an objClass returns a new instance whose instance variable values are nil and whose objClassId represents the objClass.

Hints: in Pharo we use the message new: to specify the size of Arrays. For example, Array new: 5 will create an array of 5 elements.

Make sure that you execute the test method: testAllocate

5.6 Keywords primitives

The original implementation of ObjVLisp uses the facility offered by the Lisp keywords to ease the specification of the instance variable values during instance creation. It also provides a uniform and unique way to create objects. We have to implement some functionality to support keywords. However, as this is not really interesting that you lose time we give you all the necessary primitives.

Your job.

All the functionality for managing the keywords are defined in the protocol 'keyword management'. Read the code and the associated test called testKeywords in the class ObjTest.

ObjTest >> testKeywords

   | dummyObject |
   dummyObject := Obj new.
   self 
        assert: (dummyObject generateKeywords: #(#titi #toto #lulu))
        equals: #(#titi: #toto: #lulu:).
   self 
        assert:
             (dummyObject 
                  keywordValue: #x
                  getFrom: #(#toto 33 #x 23)
                  ifAbsent: 2)
        equals: 23.
   self 
         assert:
              (dummyObject 
                   keywordValue: #x
                   getFrom: #(#toto 23)
                   ifAbsent: 2)
         equals: 2.
   self 
         assert:
              (dummyObject 
                  returnValuesFrom: #(#x 22 #y 35)
                  followingSchema: #(#y #yy #x #y))
         equals: #(35 nil 22 35)

Make sure that you execute the test method: testKeywords and that it passes.

5.7 Object initialization

Once an object is allocated, it may be initialized by the programmer by specifying a list of initialization values. We can represent such a list by an array containing alternatively a keyword and a value like #(#toto 33 #x 23) where 33 is associated with #toto and 23 with #x.

Your job.

Read in the protocol 'instance initialization' the primitive initializeUsing: anArray that, when sent to an object along with an initialization list, returns the initialized object.

ObjTest >> testInitialize

   | newInstance  |
   newInstance := pointClass allocateAnInstance.
   newInstance initializeUsing: #(#y: 2 #z: 3 #t: 55 #x: 1).
   self assert: (newInstance at: 1) equals: #ObjPoint.
   self assert: (newInstance at: 2) equals: 1.
   self assert: (newInstance at: 3) equals: 2.

5.8 Static inheritance of instance variables

Instance variables are statically inherited at class creation time. The simplest form of instance variable inheritance is to define the complete set of instance variables as the ordered fusion between the inherited instance variables and the locally defined instance variables. For simplicity and similarity with most languages, we chose to forbid duplicated instance variables in the inheritance chain.

Your job.

In the protocol 'iv inheritance', read and understand the primitive computeNewIVFrom: superIVOrdCol with: localIVOrdCol.

The primitive takes two ordered collections of symbols and returns an ordered collection containing the union of the two ordered collections but with the extra constraint that the order of elements of the first ordered collection is kept. Look at the test method testInstanceVariableInheritance below for examples.

Make sure that you execute the test method: testInstanceVariableInheritance and that it passes.

ObjTest >> testInstanceVariableInheritance
   "a better choice would be to throw an exception if there are duplicates"
   self 
        assert:
    	  (Obj new 
		computeNewIVFrom: #(#a #b #c #d)
		with: #(#a #z #b #t))
        equals: #(#a #b #c #d #z #t).
   self 
         assert: (Obj new 
			computeNewIVFrom: #()
			with: #(#a #z #b #t))
         equals: #(#a #z #b #t)

Side remark

You could think that keeping the same order of the instance variables between a superclass and its subclass is not an issue. This is partly true in this simple implementation because the instance variable accessors compute each time the corresponding offset to access an instance variable using the primitive ivClassOffset:. However, the structure (instance variable order) of a class is hardcoded by the primitives. That's why your implementation of the primitive computeNewIVFrom:with: should take care of that aspect. In real language, compilers will try to ensure that a method defined in a superclass can be applied to instances of the subclasses.

5.9 Method management

A class defines the instance behavior expressed by methods stored in a method dictionary. As such they are shared by all the instances of a class. In our implementation, we represent methods by associating a symbol to a Pharo block (a lexical closure). The block is then stored in the method dictionary of an objClass.

In this implementation, we do not offer the ability to directly access instance variables of the class in which the method is defined. This could be done by sharing a common environment among all the methods. The programmer has to use accessors or the setIV and getIV objMethods defined on ObjObject to access the instance variables. You can find the definition of those methods in the bootstrap protocol on the class side of Obj.

In our ObjVLisp implementation, we do not have a specific (non Pharo) syntax for message passing. Instead, we call the primitives using the Pharo syntax for message passing using the message send:withArguments:. The objVLisp expression objself getIV: #x is expressed as follows: objself send: #getIV withArguments: #(#x).

Method definition.

We need a way to define a method, e.g., add a block to the method dictionary. We use the method addUnaryMethod: aName withBody: aString.

The following code describes the definition of the accessor method x defined on the objClass ObjPoint that invokes a field access using the message getIV.

ObjPoint
   addUnaryMethod: #x
   withBody: 'objself send: #getIV withArguments: #(#x)'.

As a first approximation, this code will create the following block that will get stored in the class method dictionary: [ :objself | objself send: #getIV withArguments: #(#x) ]. As you may notice, in our implementation, the receiver is always an explicit argument of the method. Here we named it objself.

We propose two variations for the method definition: The primitives addUnaryMethod:withBody: and addMethod:args:withBody:. The first one is a version that avoids having an empty list of arguments.

ObjPoint
   addMethod: #x
   args: ''
   withBody: 'objself send: #getIV withArguments: #(#x)'.

Note that the arguments of args: are expressed in a string where arguments are separated by a space.

Defining a method and sending a message

As we want to keep this implementation as simple as possible, we define only one primitive for sending a message: it is send:withArguments:. To see the mapping between Pharo and ObjVlisp ways of expressing message sent, look at the comparison below:

Pharo Unary: self odd
ObjVLisp: objself send: #odd withArguments: #()

Pharo Binary: a + 4
ObjVLisp: a send: #+ withArguments: #(4)

Pharo Keyword: a max: 4
ObjVLisp: a send: #max: withArguments: #(4)

While in Pharo you would write the following method definition:

bar: x 
   self foo: x

In our implementation of ObjVlisp you write:

anObjClass
   addMethod: #bar:
   args: 'x'
   withBody: 'objself send: #foo: withArguments: #(x)'.

Your job.

We provide all the primitives that handle method definition.

Make sure that you execute the test method: testMethodManagement

ObjTest >> testMethodManagement

   self assert: (pointClass doesUnderstand: #x).
   self assert: (pointClass doesUnderstand: #xx) not.

   pointClass
      addUnaryMethod: #xx
      withBody: 'objself valueOfInstanceVariable: #x '.
   self assert: ((pointClass bodyOfMethod: #xx) value: aPoint) equals: 10.
   self assert: (pointClass doesUnderstand: #xx).
   pointClass removeMethod: #xx.
   self assert: (pointClass doesUnderstand: #xx) not.
   self assert: ((pointClass bodyOfMethod: #x) value: aPoint) equals: 10

5.10 Message passing and dynamic lookup

Sending a message is the result of the composition of method lookup and execution.

The following basicSend:withArguments:from: primitive just implements it. First, it looks up the method into the class or superclass of the receiver then if a method has been found it executes it, else lookup: returns nil and we raise a Pharo error.

Obj >> basicSend: selector withArguments: arguments from: aClass
   "Execute the method found starting from aClass and whose name is selector.
   The core of message sending reused for both a normal send or a super one."

   | methodOrNil |
   methodOrNil := aClass lookup: selector.
   ^ methodOrNil
      ifNotNil: [ methodOrNil valueWithArguments: (Array with: self) , arguments ]
      ifNil: [ Error signal: 'Obj message' , selector asString, ' not understood' ]

Based on this primitive we can express send:withArguments: as follows:

Obj >> send: selector withArguments: arguments
   "send the message whose selector is <selector> to the receiver. The arguments of the messages are an array <arguments>. The method is looked up in the class of the receiver. self is an objObject or a objClass."

   ^ self basicSend: selector withArguments: arguments from:  self objClass

Note that the definition above of basicSend:withArguments:from: does not let us ObjVLisp developers redefine the error handing. We will propose a solution in subsequent sections.

5.11 Method lookup

The primitive lookup: selector applied to an objClass should return the method associated to the selector if it found it, else nil to indicate that it failed.

Your job.

Implement the primitive lookup: selector that when sent to an objClass with a method selector, a symbol, and the initial receiver of the message, returns the method-body of the method associated with the selector in the objClass or its superclasses. Moreover, if the method is not found, nil is returned.

Make sure that you execute the test methods: testNilWhenErrorInLookup and testRaisesErrorSendWhenErrorInLookup whose code is given below:

ObjTest >> testNilWhenErrorInLookup

   self assert: (pointClass lookup: #zork) isNil.
   "The method zork is NOT implemented on pointClass"
ObjTest >> testRaisesErrorSendWhenErrorInLookup

   self should: [ pointClass send: #zork withArguments: { aPoint } ] raise: Error.

5.12 Managing super

To invoke a superclass hidden method, in Java and Pharo you use super, which means that the lookup up will start above the class defining the method containing the super expression. In fact, we can consider that in Java or Pharo, super is a syntactic sugar to refer to the receiver but changes where the method lookup starts. This is what we see in our implementation where we do not have syntactic support.

Let us see how we will express the following situation.

bar: x
   super foo: x

In our implementation of ObjVlisp we do not have a syntactic construct to express super, you have to use the super:withArguments:from: Pharo message as follows.

anObjClass
   addMethod: #bar:
   args: 'x'
   withBody: 'objself super: #foo: withArguments: #(#x) from: superclassOfClassDefiningTheMethod'.

Note that superclassOfClassDefiningTheMethod is a variable that is bound to the superclass of anObjClass i.e., the class defining the method bar (see later).

Pharo Unary: super odd
ObjVLisp: objself super: #odd withArguments: #() from: superclassOfClassDefiningTheMethod

Pharo Binary: super + 4
ObjVLisp: objself super: #+ withArguments: #(4) from: superclassOfClassDefiningTheMethod

Pharo Keyword: super max: 4
ObjVlisp: objself super: #max: withArguments: #(4) from: superclassOfClassDefiningTheMethod

5.13 Representing super

We would like to explain to you where the superclassOfClassDefiningTheMethod variable comes from. When we compare the primitive send:withArguments: to its variation using super, for super sends we added a third parameter to the primitive and we called it super:withArguments:from:.

This extra parameter corresponds to the superclass of the class in which the method is defined. This argument should always have the same name, i.e., superclassOfClassDefiningTheMethod. This variable will be set when the method is added to the method dictionary of an objClass.

If you want to understand how we bind the variable, here is the explanation: In fact, a method is not only a block but it needs to know the class that defines it or its superclass. We added such information using a currification. A currification is the transformation of a function with n arguments into function with less arguments but an environment capture: f(x,y)= (+ x y) is transformed into a function f(x)=f(y)(+ x y) that returns a function of a single argument y and where x is bound to a value and obtain a function generator. For example, f(2,y) returns a function f(y)=(+ 2 y) that adds its parameter to 2. A currification acts as a generator of functions where one of the arguments of the original function is fixed.

In Pharo, we wrap the block representing the method around another block with a single parameter and we bind this parameter with the superclass of the class defining the method. When the method is added to the method dictionary, we evaluate the first block with the superclass as a parameter as illustrated as follows:

method := [ :superclassOfClassDefiningTheMethod |
     [ :objself :otherArgs  |
           ... method code ...
           ]]
method value: (Obj giveClassNamed: self objSuperclassId)

So now you know where the superclassOfClassDefiningTheMethod variable comes from. Make sure that you execute the test method: testMethodLookup and that i passes.

Your job.

Now you should implement super: selector withArguments: arguments from: aSuperclass using the primitive basicSend:withArguments:from:.

5.14 Handling not understood messages

Now we can revisit error handling. Instead of raising a Pharo error, we want to send an ObjVlisp message to the receiver of the message to give him a chance to trap the error.

Compare the two following versions of basicSend: selector withArguments: arguments from: aClass and propose an implementation of sendError: selector withArgs: arguments.

Obj >> basicSend: selector withArguments: arguments from: aClass

   | methodOrNil |
   methodOrNil := (aClass lookup: selector).
   ^ methodOrNil
      ifNotNil: [ methodOrNil valueWithArguments: (Array with: self) , arguments ]
      ifNil: [ Error signal: 'Obj message' , selector asString, ' not understood' ]
Obj >> basicSend: selector withArguments: arguments from: aClass

   | methodOrNil |
   methodOrNil := (aClass lookup: selector).
   ^ methodOrNil
      ifNotNil: [ methodOrNil valueWithArguments: (Array with: self) , arguments ]
      ifNil: [ self sendError: selector withArgs: arguments ]

It should be noted that the obj method is defined as follows in the ObjObject class (see the bootstrap method on the class side of the class Obj). The obj error method expects a single parameter: an array of arguments whose first element is the selector of the not understood message.

objObject
   addMethod: #error
   args: 'arrayOfArguments'
   withBody: 'Transcript show: ''error '', arrayOfArguments first.  ''error '', arrayOfArguments first'.
Obj >> sendError: selector withArgs: arguments
   "send error wrapping arguments into an array with the selector as first argument. Instead of an array we should create a message object."

   ^ self send: #error withArguments:  {(arguments copyWithFirst: selector)}

Make sure that you read and execute the test method: testSendErrorRaisesErrorSendWhenErrorInLookup. Have a look at the implementation of the #error method defined in ObjObject and in the assembleObjectClass of the ObjTest class.