Tag Archives: literals

Primitives, Pragmas, Literals and their relation to CompiledMethods

What is a primitive?

Do you want to know the answer?¬† Just do what we always do in Smalltalk: browse code ūüôā¬†¬† Open your image and browse the method #whatIsAPrimitive. You can read the following information there:

“Some messages in the system are responded to primitively. A primitive response is performed directly by the interpreter rather than by evaluating expressions in a method. The methods for these messages indicate the presence of a primitive response by including <primitive: xx> before the first expression in the method.¬†¬†

Primitives exist for several reasons. Certain basic or ‘primitive’ operations cannot be performed in any other way. Smalltalk without primitives can move values from one variable to another, but cannot add two SmallIntegers together. Many methods for arithmetic and comparison between numbers are primitives. Some primitives allow Smalltalk to communicate with I/O devices such as the disk, the display, and the keyboard.¬† Some primitives exist only to make the system run faster; each does the same thing as a certain Smalltalk method, and its implementation as a primitive is optional. ¬†

When the Smalltalk interpreter begins to execute a method which specifies a primitive response, it tries to perform the primitive action and to return a result. If the routine in the interpreter for this primitive is successful, it will return a value and the expressions in the method will not be evaluated. If the primitive routine is not successful, the primitive ‘fails’, and the Smalltalk expressions in the method are executed instead. These expressions are evaluated as though the primitive routine had not been called.¬†

The Smalltalk code that is evaluated when a primitive fails usually anticipates why that primitive might fail. If the primitive is optional, the expressions in the method do exactly what the primitive would have done (See Number @). If the primitive only works on certain classes of arguments, the Smalltalk code tries to coerce the argument or appeals to a superclass to find a more general way of doing the operation (see SmallInteger +). If the primitive is never supposed to fail, the expressions signal an error (see SmallInteger asFloat). 

Each method that specifies a primitive has a comment in it. If the primitive is optional, the comment will say ‘Optional’. An optional primitive that is not implemented always fails, and the Smalltalk expressions do the work instead.¬† If a primitive is not optional, the comment will say, ‘Essential’. Some methods will have the comment, ‘No Lookup’. See Object >> #howToModifyPrimitives for an explanation of special selectors which are not looked up.¬†

For the primitives for +, -, *, and bitShift: in SmallInteger, and truncated in Float, the primitive constructs and returns a 16-bit LargePositiveInteger when the result warrants it. Returning 16-bit LargePositiveIntegers from these primitives instead of failing is optional in the same sense that the LargePositiveInteger arithmetic primitives are optional. The comments in the SmallInteger primitives say, ‘Fails if result is not a SmallInteger’, even though the implementor has the option to construct a LargePositiveInteger. For further information on primitives, see the ‘Primitive Methods’ part of the chapter on the formal specification of the interpreter in the Smalltalk book.”

Primitives examples

As we will see later in another post, in the object header of every object (except compact classes) there is a pointer to its class (another object). Hence, accessing to that pointer of the object header has to be done by a primitive:

Object >> class
"Primitive. Answer the object which is the receiver's class. Essential. See
Object documentation whatIsAPrimitive."

<primitive: 111>
self primitiveFailed

We read in the comment of the method #whatIsAPrimitive that what it is after <primitive: XXX> is ONLY called when the primitive fails. In this case, when that happens, the code “self primitiveFailed” will be executed: there is nothing we can do from image side if this primitive fails. Notice that the declaration of <primitive: XXX> has to be first in the method. The only possible thing before that is comments and declare temp variables: it is not possible to write code before that. So, this is not possible:

Object >> class
"Primitive. Answer the object which is the receiver's class. Essential. See
Object documentation whatIsAPrimitive."
Transcript show: '#class was called!!'.
<primitive: 111>
self primitiveFailed

Another example of a primitive:

SmallInteger >> bitOr: arg
"Primitive. Answer an Integer whose bits are the logical OR of the
receiver's bits and those of the argument, arg.
Numbers are interpreted as having 2's-complement representation.
Essential.  See Object documentation whatIsAPrimitive."

<primitive: 15>
self >= 0 ifTrue: [^ arg bitOr: self].
^ arg < 0
ifTrue: [(self bitInvert bitAnd: arg bitInvert) bitInvert]
ifFalse: [(self bitInvert bitClear: arg) bitInvert]

In this case, if the primitive fails, this method tries to resolve its task in Smalltalk code. Sometimes this works and it means that this primitive is for improving performance, but not mandatory (as it is the case with #class).  In other cases, the code after the primitive (written in Smalltalk) will fail for sure if the primitive has already failed. However, such code is put in Smalltalk with documentation purposes. You can imagine what such primitive does (and why it could fail) in the VM side (Slang/C) by looking its possible code in Smalltalk.

Two important literals

When we talked about CompiledMethod and literals I forgot to mention that there are 2 literals in every CompiledMethod that are really important. CompiledMethod can answer to the messages #methodClass (which answers the class where such CompiledMethod is installed) and #selector (which answers the method’s selector). How can both methods be implemented in CompiledMethod if they don’t hold such information?¬† Ok, they do hold such information as literals. The LAST literal of every CompiledMethod is an Association where the key is the class name and the value the class object. The penultimate literal stores the selector. So if we explore “Date >> #month”:

Literal 3 is the last one and points to the Association and literal 2 is the penultimate and points to the selector.

So you can now understand the methods:

CompiledMethod >> methodClass
"answer the class that I am installed in"
^self numLiterals > 0
ifTrue: [ (self literalAt: self numLiterals) value ]
ifFalse: [ nil ]


CompiledMethod >> selector
"Answer a method's selector.  This is either the penultimate literal,
or, if the method has any properties or pragmas, the selector of
the MethodProperties stored in the penultimate literal."
| penultimateLiteral |
^(penultimateLiteral := self penultimateLiteral) isMethodProperties
ifTrue: [penultimateLiteral selector]
ifFalse: [penultimateLiteral]

Forget for the moment the #isMethodProperties.

Pragmas and CompiledMethods

Now…when we talk about the <primitive: XXX>, what’s that??¬† it is not a regular message send. How can that be compiled by the Compiler? Ok, these are called “Method tags” and their goal is to store metadata of the method. If you are a java developer, method tags can be “similar” to Java annotations. In Pharo Smalltalk, one implementation of method tags is called “Pragmas”. I won’t discuss the advantages or disadvantages of Pragmas against other method tag implementations, or whether to use pragmas o regular subclassification, etc.

For more information about Pragmas, check the class comment of Pragma class and the tests like PragmaTest, MethodPragmaTest, etc. Nowadays, Pragmas are used in Pharo in several places like the new settings framework, the world menu, Metacello, HelpSystem, etc.

Ok…nice. But how are they really stored in a CompiledMethod? Let’s explore “SmallInteger >> #bitOr:”.

So….as we can see in the explorer, at compiling time the Compiler creates an instance of AdditionalMethodState and such object is placed in the penultimate literal. The class comment of AdditionalMethodState says: “I am class holding state for compiled methods. All my instance variables should be actually part of the CompiledMethod itself, but the current implementation of the VM doesn’t allow this.¬† Currently I hold the selector and any pragmas or properties the compiled method has.¬† Pragmas and properties are stored in indexable fields; pragmas as instances of Pragma, properties as instances of Association.”

AdditionalMethodState has two named instance variables: ‘method’ and ‘selector’. No explanation needed here. But since the class format is variable (do you remember them from my old post?) it can also store indexable fields. In this case, pragmas are stored that way. Hence, an instance of Pragma is stored in AdditionalMethodState and that’s what we can see in the explorer. A Pragma instance has 3 instance variables: ¬†‘method keyword arguments’.

But the AdditionalMethodState instance is put in the penultimate literal and that’s where the “selector” should be found. How can “CompiledMethod >> #selector”¬† work with them? If we now take again a look to such method (look above), you will see there is a “isMethodProperties ifTrue: [penultimateLiteral selector]”. Of course, AdditionalMethodState answers true to isMethodProperties and hence the selector is asked to itself (which in fact is an instance variable of it).

Primitives and their impact in CompiledMethod

Since primitives uses Pragma, the first effect is to have an AdditionalMethodState in the penultimate literal instead of a selector. The second effect, is that the primitive number is stored in the CompiledMethod header. You can send the message #primitive and get the value. For example, “(SmallInteger >> #bitOr:) primitive” -> 15. If the method has no primitive then zero is answered. Example, (TestCase >> #assert:) primitive -> 0.

When the VM executes a CompiledMethod it checks whether it is a primitive method or not (checking whether the value in the object header is zero or bigger). If it is, the VM searches in a table and dispatches the  primitive associated to the number.

How primitives are map to the VM side?

Continuing with SmallInteger >> #bitOr:, the primitive number is 15. How can we know the code of such primitive in the VM side? Time to open an image with VMMaker (if you don’t know how to do it read the title “Prepared image for you” in this post). The VM keeps a table that maps primitive numbers with selectors implemented in the interpreter class. The most useful advice here is to check the method that initialices such table: #initializePrimitiveTable. So we can take a look:

For our example of #class the primitive number was 111. In such table 111 maps to #primitiveClass. So we can browse its code. Remember that this code is written in SLANG and it is part of the VMMaker package (check my previous posts for details).

| instance |
instance := self stackTop.
self pop: argumentCount+1 thenPush: (objectMemory fetchClassOf: instance)

(SmallInteger >> #bitOr:)  has primitive number 15, which maps to #primitiveBitOr, which code is:

| integerReceiver integerArgument |
integerArgument := self popPos32BitInteger.
integerReceiver := self popPos32BitInteger.
self successful
ifTrue: [self push: (self positive32BitIntegerFor:
(integerReceiver bitOr: integerArgument))]
ifFalse: [self unPop: 2]

So..you have learnt how to map primitive numbers with methods in VM side ūüôā¬†¬† You already know how to do that for primitives and bytecodes now. Congrats!!!

Future explanations

Browse de method #primDeleteFileNamed: and you will see something like:

primDeleteFileNamed: aFileName
"Delete the file of the given name. Return self if the primitive succeeds, nil otherwise."

^ nil

what’s that primitive? where is the number?¬† Can I create my own primitive? Sure! We will see how to do that in a future post ūüôā


Playing with CompiledMethod

The today’s stop of this Journey through the¬†VM is about CompiledMethods. In the previous post I explained the different class formats and specially, the unique format of CompiledMethod. Today we are going deeper with them and we will see why they are even more special ūüėČ

Summary of the previous post: CompiledMethod instances are internally represented in the VM as bytes. However, CompiledMethod is the only class in the system that mixes pointers (for the literals) with bytes (for the bytecodes). So those bytes encodes both things.

Inspecting a CompiledMethod

What is the normal way to learn something in Smalltalk? Open your image and check senders, references, or someone who does more or less what you need and try to understand it. In the previous post, I showed you how inspecting or exploring a CompiledMethod give us a lot useful information like the header, the literals, the bytecodes and the trailer. Example:

So this means that at least the Inspector and the Explorer can have access to the CompiledMethod and understand its internal. Let’s take the Inspector (we could have taken also the explorer in which case take a look to CompiledMethod >> #explorerContents). When we inspect a CompiledMethod, the inspector class that is used is CompiledMethodInspector. So, first point, there is a special inspector class for CompiledMethod. Otherwise, if we inspect it with a normal inspector, for example if we do “BasicInspector openOn: (MyClass >> #testSomething)” we have something like this:

CompiledMethodInspector has two important methods:

CompiledMethodInspector >> fieldList

| keys |
keys := OrderedCollection new.
keys add: 'self'.
keys add: 'all bytecodes'.
keys add: 'header'.
1 to: object numLiterals do: [ :i |
keys add: 'literal', i printString ].
object initialPC to: object size do: [ :i |
keys add: i printString ].
^ keys asArray
CompiledMethodInspector  >> selection

| bytecodeIndex |
selectionIndex = 0 ifTrue: [^ ''].
selectionIndex = 1 ifTrue: [^ object ].
selectionIndex = 2 ifTrue: [^ object symbolic].
selectionIndex = 3 ifTrue: [^ object headerDescription].
selectionIndex <= (object numLiterals + 3)
ifTrue: [ ^ object objectAt: selectionIndex - 2 ].
bytecodeIndex := selectionIndex - object numLiterals - 3.
^ object at: object initialPC + bytecodeIndex - 1

So…as you can see in the code, “keys add: ‘all bytecodes’.”¬† maps to “selectionIndex = 2 ifTrue: [^ object symbolic].“, and “keys add: ‘header’.” to “selectionIndex = 3 ifTrue: [^ object headerDescription].“.¬† What we should learn from this, is that CompiledMethod >> #symbolic answers a string which nicely shows the bytecodes. So for example, if we have the method:

MyClass >> testSomething
TestCase new.
self name.
Transcript show: 'The answer is:', 42.

Then, “(MyClass >> #testSomething) symbolic” answers the following:

41 <40> pushLit: TestCase
42  send: new
43 <87> pop
44 <70> self
45  send: name
46 <87> pop
47 <43> pushLit: Transcript
48 <25> pushConstant: ''The answer is:''
49 <26> pushConstant: 42
50  send: ,
51  send: show:
52 <87> pop
53 <78> returnSelf

Don’t worry for the moment about the first number in each column (for the interested guys it is the PC -> program counter) and the hexadecimal between <>¬† (it is the bytecode number in hexa). I will explain that in a future post.

This method #symbolic could be the same used by the SystemBrowser when you select “View” -> “Bytecodes”.¬† From the previous example, we can also learn that CompiledMethod implements methods like #numLiterals, #objectAt:, #initialPC, etc.¬† Imagine the CompiledMethod as an array of bytes…how can you determinate which part is literals and which one is bytecodes?¬† How the #numLiterals can be implemented in CompiledMethod if it is just an array of bytes?

CompiledMethod header

It may be already obvious that CompiledMethods have a header. But be careful, CompiledMethod have both, the normal object header every object has, and then a special header which is just the first word (32 bits -> 4 bytes) of the byte array. So this header is just before the literals and the bytecodes. As we can read in the class comment of CompiledMethod:

“The header is a 30-bit integer with the following format:

(index 0)    9 bits:    main part of primitive number   (#primitive)
(index 9)    8 bits:    number of literals (#numLiterals)
(index 17)    1 bit:    whether a large frame size is needed (#frameSize)
(index 18)    6 bits:    number of temporary variables (#numTemps)
(index 24)    4 bits:    number of arguments to the method (#numArgs)
(index 28)    1 bit:    high-bit of primitive number (#primitive)
(index 29)¬†¬† ¬†1 bit:¬†¬† ¬†flag bit, ignored by the VM¬† (#flag)”

Ok, with this comment you may notice the limits imposed in methods. For example, 9 bits for a primitive it means (2^9) -1=511. BTW, I think this class comment is outdated and now there are 11 bits for primitive index, so it is (2^11) – 1 = 2 047. But you get the idea…. anyway, it is not likely that you have ever reached any of these limits.

Who is responsable of generating such header in the CompiledMethod?  In this post, I told you that usually the input for the Compiler was a string representing the source code and the result was a CompiledMethod instance. Hence, the Compiler takes care about creating such CompiledMethod header. Notice that this header is not only used from the image side but also from the VM. Check (in the VMMaker) implementors and senders of #argumentCountOf:, #literal:ofMethod:, #primitiveIndexOf:, #tempCountOf:, etc.

CompiledMethod trailer

Something you should be asking yourself is where the source code is stored?¬† I mean, when you open a browser and see the source code of a method, where does it come from?¬† because in the CompiledMethod we saw that only literals and bytecodes are stored, not source code. So???¬† Ok… the source code is stored in two files: .sources and .changes. The “old” methods’ source code is in the .sources file and the “new” method’s source code in the .changes. You can browse #condenseChanges and #condenseSources for details. So far so good. But…. how a CompiledMethod instance is map to its source code in the file?¬† Excellent question Mariano ūüôā

The same way there is a special header for CompiledMethod, there is a trailer. So far the trailer has been used only for getting the source code of the method. Some time ago, this trailer was one word size (4 bytes) and it encoded a number which was the offset in the .sources/.changes file. That number represent both things: the offset in the file, and a flag to say from which file (if .changes or .sources). Check for example the method #filePositionFromSourcePointer:. In addition, the logic of encoding and decoding the trailer was implemented in the CompiledMethod class.

In today’s Pharo images (and Squeak), this is not true anymore. There are two big differences with the “old” approach:

  1. The trailer was reified with the class CompiledMethodTrailer.
  2. There are different kind of trailers implemented and up to 255 possibilities. The implemented kinds are: normal source pointer, temp names (the decompiler can use such temp names when getting the source so that to generate a source code more similar to the original one), variable length (for example when .changes is bigger than 32MB), etc. For more details, check #trailerKinds. Of course, the most common type is “SourcePointer”.

CompiledMethod is a chunk of bytes (this is why it is a subclass from ByteArray), and its format is “bytes”, so it means it cannot define normal instance variables.¬† So how can it have a CompiledMethodTrailer?¬† Ok, it works this way: when a CompiledMethod is being created (usually by the Compiler), a specific CompiledMethodTrailer instance is also created. That instance of CompiledMethodTrailer has to be created with a specific type (source pointer, temp names, etc). Once the CompiledMethod is almost ready the trailer instance is encoded as bytes in the CompiledMethod instance, and then it is garbage collected. Later on, when someone ask to the CompiledMethod for its source code (using the method #getSource), it delegates to a trailer instance. But there is not trailer instance as this moment. So….every time the source code is needed, the CompiledMethod creates an instance of a trailer. But notice that it is up to the CompiledMethodTrailer to know how many bytes are the trailer, how to decode it and what do the bytes represent (if a source pointer, an array of temp names, etc). Finally, the trailer answers the source code of the method. So, the CompiledMethod just has:

CompiledMethod >> trailer
"Answer the receiver's trailer"
^ CompiledMethodTrailer new method: self

The CompiledMethodTrailer just read the last byte, it checks in an internal table to see which kind of trailer is it, and then perform the correct method to decode the information. The amount of bytes used by the trailer and what they represent, depends on the kind of trailer.

method: aMethod

| flagByte |

data := size := nil.
method := aMethod.
flagByte := method at: (method size).

"trailer kind encoded in 6 high bits of last byte"
kind := self class trailerKinds at: 1+(flagByte>>2).

"decode the trailer bytes"
self perform: ('decode' , kind) asSymbol.

"after decoding the trailer, size must be set"
[size notNil] assert.

Depending on the type of trailer,  CompiledMethodTrailer will finally execute one of the methods encode* when the CompiledMethod is being created, and decode* when asking its source code.

A question to all of you….wouldn’t it make sense to rename CompiledMethodTrailer to MethodSource ? because trailers has been always use only for that….

Decompiling CompiledMethods

Why source code is not stored in CompiledMethod? From my point of view, there are 2 main reasons:

  1. Because as its class name suggests, they reify COMPILED methods, not source methods or whatever name you want to use.
  2. Memory and security reasons. When you deploy an application written in C, do you include source code? no. And in Java? no. So why we would do it in Smalltalk? Remember that the way to “deploy” a Smalltalk application is providing an .image.

The ideal approach would be to have the sources in development and to be able to remove them when deploying. Smalltalk allows us that. Just remove the .sources file and that’s all ūüôā Your image continues to work as if nothing has happened. But sometimes we have a bug in our application and we want to be able to browse the code. Guess what? Smalltalk provides that also ūüėȬ† Let’s try it (don’t try in Pharo1.3 because there is a bug. Use anyone before 1.3). Create a method anywhere, for example:

testSomething: aaa with: bbb and: ccc
| name |
TestCase new.
(4 = 3)
ifTrue: ["I am a nice comment, don't remove meeee pleaeee!"]
ifFalse: ["I like this way of formatting my code"].

name := self name.
Transcript show: 'The answer is:', 42.

Now, close your image. Rename the .changes file (creating a new method will ensure that the source pointer points to the .changes and not to .sources) so that it is not found. Open your image again, and you may have the popup saying that the .changes couldn’t be find. No problem. Accept it.

Now, if you open the system browser, you can browse any method of the image. And only whose source were in the .changes will look similar to this:

testSomething: t1 with: t2 and: t3
| t4 |
TestCase new.
4 = 3.
t4 := self name.
Transcript show: 'The answer is:' , 42

What you are seeing is not the source code of the method but instead the decompiled one. The compiler is able to decompile a CompiledMethod (using the bytecodes and literals) and get the possible “source code”. However, the decompiler source is not exactly the same as the original source. Note that the decompiler the only thing it has for a method is the bytecodes and the literals. Hence, the decompiled code does not have:

  • Temporal variable and parameters¬† names. Since they are not stored in the CompiledMethod they are lost. Both temps and parameters are replaced in the decompiled code with “t1”, “t2”, etc.
  • Comments are lost (they are not stored in the CompiledMethod).
  • Code formatting (tabs and spaces) is lost.

The cool thing is that even with the decompiled code we can get an idea of the code, debug it, and probably find the bug we were looking for.

Notice that the source code of “old” methods are stored not in the .changes but in the .sources. So, even removing .changes there are methods which get the source from the .sources file. Therefore, we can also remove the .sources and that way all methods in the image will be decompiled if you try to browse them.

Depending of what and where you are deploying, getting rid of .sources and .changes could be worth it.

CompiledMethod equality

What do you expect the following expression to answer:

(Boolean>>#&) = (Boolean>>#|)

Ok…you need to see the source code?

& aBoolean
"Evaluating conjunction. Evaluate the argument. Then answer true if
both the receiver and the argument are true."

self subclassResponsibility
| aBoolean
"Evaluating disjunction (OR). Evaluate the argument. Then answer true
if either the receiver or the argument is true."

self subclassResponsibility

So? true or false? TRUEEEE!!! that is true. And why? if they have different comments, they have different selectors! So? who cares about that? we are talking about COMPILED methods. Are the bytecodes the same? yes. Are the literals the same? yes.¬† So they are the same compiled method. Point. So….you would really be careful when putting CompiledMethods in Sets, Dictionaries or things like that. Example:

InstructionClient methods size -> 27
InstructionClient methods asSet size -> 21

Conclusion: use an IdentitySet or a IdentiyDictionary if you want to avoid problems.

Sorry for the long post, but there is too much to talk about CompiledMethods. In the next post we will talk a little more about bytecodes.

Smalltalk reflective model

Hi. I am sure the title of this post is horrible, but I didn’t find anything better. The idea is simple: in this part of the journey, we will talk about bytecodes, primitives, CompiledMethods, FFI, plugins, etc… But before going there, I would like to write some bits about what happens first in the image side. These may be topics everybody know, so in that case, just skip the post and wait for the next one ūüėȬ† My intention is that anyway can follow my posts.

A really quick intro to Smalltalk reflective model

The reflective model of Smalltalk is easy and elegant. As we can read in Pharo by Example, there are two important rules:  1) Everything is an object; 2) Every object is instance of a class. Since classes are objects and every object is an instance of a class, it follows that classes must also be instances of classes. A class whose instances are classes is called a metaclass. Whenever you create a class, the system automatically creates a metaclass. The metaclass defines the structure and behavior of the class that is its instance. The following picture shows a minimized reflective model of Smalltalk. Notice that for clarification purposes this diagram shows only a part of it.

A class contains a name, a format, a method dictionary, its superclass, a list of instance variables, etc. The method dictionary is a map where keys are the methods names (called selectors in Smalltalk) and the values are the compiled methods which are instances of CompiledMethod.

When an object receives a message, the Virtual Machine has to do first what it is commonly called as the Method Lookup. This consist of searching the message through the hierarchy chain of the receiver’s class. For each class in the chain, it checks whether the selector is included or not in the MethodDictionary.¬† If it is not, it continues searching forward in the chain until it finds a method or sends the #doesNotUnderstand: message in case it was not found in the whole hierarchy. When a method is found, it is directly executed.

To understand these topics, I really recommend the two wonderful chapters in Pharo By Example book: Chapter 13 “Classes and Metaclasses” and Chapter 14 “Reflection”. They are both a “must read” if you are more or less new with these topics.

In the internal representation of the Virtual Machine, objects are a chuck of memory. They have an object header which (there will be a whole post about it) can be between one and three words, and following the object header, there are slots (normally of 32 or 64 bytes) that are memory addresses which usually (we will see why I didn’t say always) represent the instance variables. The object header contains bits for the Garbage Collector usage, the hash, the format, a pointer to its class, etc.

Classes and Metaclasses

How do you create a class in Smalltalk? In other languages, you normally create a new text file that after you compile. But in Smalltalk, as we are used to, everything happens by a message send. So, to create a new class you tell to the superclass, “Can you create this subclass with this name, these instance variables and this category please?”. So, when you take a browser and you do a “Ctrl + s” of this code:

Object subclass: #MyClass
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'MyCategory'

The only thing you do, is to send the message #subclass:instanceVariableNames:classVariableNames:poolDictionaries:category: to Object. If fact, you can take that piece of code, evaluate it in a Workspace, and you will get the same results ūüôā

You can see implementors and you will logically find one in Class. Which should be the result of such message sent?  two things: a new class and a new metaclass. Do the following test:

Metaclass instanceCount ->  3710
Class allSubclasses size -> 3710

Now, create a new class, and inspect again:

Metaclass instanceCount ->  3711
Class allSubclasses size -> 3711

The problem with Metaclasses is that they are implicit, so they are very difficult to understand. Imagine that you create a class User, then its class is “User class”. The unique instance of “User class” is “User”. And at the same time, “User class” is an instance of Metaclass. So….complicated, but if you want to understand them, take a look to the chapters I told you.¬† How it is done?¬† it is not really important for the purpose of this post, but it uses the ClassBuilder and also the Compiler (check senders of #compilerClass).

Creating a method

We saw what happens when we create a class. And when you save a method from the browser? what happens ? In a nutshell what happens is that the Smalltalk Compiler does its magic, that is, it receives as an input a string that represents the source code, and as a result you get a CompiledMethod instance. A CompiledMethod contains all the instructions (bytecodes) and information (literals) that the VM needs to interpret and execute such method.

Let’s see it by ourself. Take your image, create a dumy class and then put a breakpoint at the beginning of Behavior >> #compile:classified:notifying:trailer:ifFail:. Now, type the following method and accept it:

Transcript show: 'all this code will be compiled'.

Once you accept such code, the debugger should appear. You can analyze the stacktrace if you want. Notice the arguments that the methods has: compile: code classified: category notifying: requestor trailer: bytes ifFail: failBlock.¬† So, I told you that the basic idea was to send a piece of code as text and get the CompiledMethod instance. The parameter “code” should be the code of the method we type, and yes, it is a ByteString. If you go step by step with the debugger, and inspect the result, that is, “CompiledMethodWithNode generateMethodFromNode: methodNode trailer: bytes.”¬† you will see it answers the CompiledMethodWithNode instance to which you can ask “method” and it is the CompiledMethod instnace.¬† Of course, that method should be the same you get after when doing “MyClass methodDict at: #testCompiler”.

The rest of the parameters are the category in which the method should be, the requestor (someone to notify about this event), the trailer bytes (we will see this later on), and a block to execute if there is an error.


In Smalltalk compiled methods are first-class objects (classes too!), in this case instances of CompiledMethod class. However, the class CompiledMethod is quite special and a little differet from the rest. But we will see this later on….What it is important for the moment, is to know that a CompiledMethod contains a list of bytecodes and a list of¬† literals. Bytecodes are instructions. A method is decomposed in a set of bytecodes, which are grouped in five categories: pushes, stores, sends, returns, and jumps. Literals are all those objects and selectors that are needed by the bytecodes but they are not instance variables of the receiver, hence they need to be stored somewhere.

For example, with our previous example of #testCompiler, we will have a bytecode (among others) for sending the message #show:¬† and we will have the ‘Transcript’ and the selector name ‘show:’ in the literals. As an exersise, inspect the CompiledMethod instance. You can just evaluate: “(MyClass >> #testCompiler) inspect”. But….”exploring” is usually better that “inspect” for compiled methods…I let you see the differences ūüôā¬† Anyway, you will see something like this:

In the next post we will play a bit deeper with CompiledMethods so don’t worry.

The Compiler

My knowledge of the Compiler is quite limited, but is is important to notice that the Compiler does much more things than the one I have said. In a compiler, there are usually several steps like parse the code, validate it, get an intermediate representation, and finally create the CompiledMethod instance. The compiler needs to know how to translate our Smalltalk code to bytecodes understood by the VM.

In Squeak and Pharo, the compiler is mostly implemented in the class Compiler. It seems it is quite difficult to understand and it has some limitations and difficulties to get intermediate representation of the code. Because of that and probably much other reasons, the community started to work in a new compiler called Opal (which at the beginning was called NewCompiler).