Objects Overview
Okay, so objects are very important to the language, especially to understanding how anything more complicated than a simple number is represented inside of Oli-Nat. Objects are the representation of every more complicated value type. So, looking back at the Value struct, which is how every item exists on the stack during the language’s runtime:
typedef struct
{
ValueType type;
union
{
bool boolean;
double double_val;
float float_val;
int int_val;
Obj* object_val;
}as;
} Value;Found in /include/value.h
Now, as you can see we have a union, and by definition a union in C is just one shared memory space that is the size of the largest member it can hold. This lets a single Value hold any one of the items you see in the union.
We have the most basic items of course, but then what is this object_val? Well, like I just said, a union is only as big as its largest member. This is perfectly fine when we know the standard size of our items, but what about a string? A string can be any size, and not only that, it can be huge! If we always reserved some large amount of memory for a possible string, we would waste a ton of memory every time we just wanted to store an int.
This is where the Obj* comes in. A pointer is always the same size (8 bytes on a 64 bit machine), so it doesn’t make the Value any bigger, but we can use it to point to an object somewhere else in memory, like a struct that holds the pointer to an array of characters. Here is the basic Obj struct, followed by the string struct:
//set up object class to be stored inside of value struct
typedef struct Obj
{
ObjType type;
bool isMarked;
struct Obj* next; //for storing in vm
} Obj;
//string representation for Oli-Nat
typedef struct ObjString
{
Obj obj;
int length;
char* chars;
uint32_t hash;
} ObjString;Found in /include/object.h
As you can see, the Obj struct is very important. Originally, before I added the garbage collector, all it held was the type of the object, more on that further down. Now it also stores a bit of mandatory state for every object: the isMarked boolean, and a pointer to the next object, so that every object can be stored in one linked list. See how this applies in the Garbage Collector documentation.
This sets the standard for every object, but how do we actually store any other data? Well, we do a sort of inheritance. C of course does not support classes, but it does support structs, and the fields of a struct are laid out in memory one after another, in order. This is why you may notice that the ObjString struct has Obj obj as its very first field, which is then followed by all of the data that represents a string, like the char* to the start of the characters, and the length.
What is really important is the order. Because the obj field comes first, followed by whatever data the “sub class” needs, every object starts with an Obj. We can treat an ObjString* as just a regular Obj*, by only looking at those first few bytes of memory. And going the other way, we can turn an Obj* back into an ObjString*, because the Obj stores its own type, so we can safely check the type first, and then know how to read the memory that comes after the original object struct.
It is a bit of a low level concept, but it is absolutely genius, and it is the true foundation for how objects work and why they are so convenient in this language. It all works through these types:
typedef enum
{
OBJ_STRING,
OBJ_FUNCTION,
OBJ_STATIC_ARRAY,
OBJ_NATIVE,
OBJ_CLOSURE,
OBJ_UPVALUE,
OBJ_CLASS,
OBJ_INSTANCE
} ObjType;Found in /include/object.h
We can treat any object as an Obj, and then check its actual type and cast it to whatever struct it really is, to get at the data it stores. That is why all of this ties back into the Obj* in the Value struct.
Creating Objects
So, we have a basic understanding of how a string is represented, but how is it actually created? Of course, creating any one object varies a lot, and depends on the context of both the object itself and the code around it.
We save most of that for the AST Compiler documentation though. Here, I mainly want to talk about a function and a small little macro:
#define ALLOCATE_OBJ(type, objectType, vm) \
(type*)allocateObject(sizeof(type), objectType, vm);
static Obj* allocateObject(size_t size, ObjType type, struct Vm* vm)
{
Obj* object = (Obj*)reallocate(NULL, 0, size, vm);
object->type = type;
object->isMarked = false;
object->next = vm->objects;
vm->objects = object;
#ifdef DEBUG_LOG_GC
printf("%p allocate %zu for %d\n", (void*)object, size, type);
#endif
return object;
}Found in /src/object.c
The allocation of ALL objects goes through this function. It allocates enough memory for the whole object, the size that gets passed in, so for a string that is the size of an entire ObjString. But it only treats that memory as a plain Obj*, since every object starts with one, and fills in the parts that every object shares: the type it is supposed to be, isMarked, and then it adds the object to the front of the VM’s linked list of objects (see the garbage collector docs for the reason why).
The beauty in this is that the function only has to work with a plain Obj*. Then the ALLOCATE_OBJ macro passes in sizeof the real struct, and casts the result back to that struct on return. So we get back an ObjString*, or whatever object we asked for, with its shared Obj part already filled in, and the rest of the memory ready for us to fill. Very simple in practice, but super convenient for the code we have to go over next.
Different Types of Objects
There are a lot of different types of objects, and they all do very different things. All of them are in the enum above, and each one generally has a struct, as well as some sort of constructor function. The following are all of the objects and their constructors (at least as best as I can):
Strings
Strings are a bit different from the others, because we intern them in the VM’s strings hashmap, and they are a bit more dynamic. They are a good example of how objects work, but they are a bit more fleshed out, just because they are such an integral part of the language:
typedef struct ObjString
{
Obj obj;
int length;
char* chars;
uint32_t hash;
} ObjString;
static ObjString* allocateString(char* chars, int length, uint32_t hash, struct Vm* vm)
{
ObjString* string = ALLOCATE_OBJ(ObjString, OBJ_STRING, vm);
string->length = length;
string->chars = chars;
string->hash = hash;
push(vm, CREATE_OBJECT_VAL((Obj*)string));
MapSet(&vm->strings, string, CREATE_EMPTY_VAL(), vm);
pop(vm);
return string;
}Found in /src/object.c & /include/object.h
This is really the bulk of what creates a string. We go through the regular allocation described in the section before this one, and now we have a full object struct that we just need to fill with data.
This is simple, because all of the data is passed into this function, whether the string came from your source code at compile time, or was made by something like joining two strings together at runtime. We fill in all of the fields, and then return the pointer to the string object.
Technically, before interning that was all we did, but now there are a few things that make it more complicated, that weird push and pop being one of them, though that is more because of the garbage collector (MapSet() can allocate memory, so the string has to be protected while it is added to the table). Anyways, to intern strings, we hash them:
static uint32_t hashString(const char* key, int length) //basic hashing function
{
uint32_t hash = 2166136261u;
for (int i = 0; i < length; i++)
{
hash ^= (uint8_t)key[i]; //runs XOR (it mixes the character) with the ascii value of the character at that index in the string
hash *= 16777619; //the FNV prime, (another prime number with neat math properties), it spreads out the bits
}
return hash;
}Found in /src/object.c
The hash function is basically a really fancy math algorithm, called FNV-1a. For every character, it XORs the character into the hash, and then multiplies the hash by a very specific prime number. Together, these spread our characters out as much as possible, so we get the best spread we can when indexing into the hashmap.
Of course, it would be pretty computationally expensive to do this every single time we need the hash, so every string object stores its own hash, worked out once when it is created:
ObjString* copyString(const char* chars, int length, struct Vm* vm)
{
uint32_t hash = hashString(chars, length);
//TODO: intern the string (DONE)
ObjString* interned = hashmapFindString(&vm->strings, chars, length, hash);
if (interned != NULL) return interned;
char* heapChars = ALLOCATE(char, length+1, vm);
memcpy(heapChars, chars, length);
heapChars[length] = '\0';
return allocateString(heapChars, length, hash, vm); //TODO: add hashing
}Found in /src/object.c
This way, whenever we want to make a string from some piece of text, like a bit of the source code, we use the copyString() function, which interns it into the hashmap. If the string is already interned, we don’t waste our time making it again, we just return the one we already have. Otherwise, we copy the characters into a brand new array of our own on the heap (with the \0 on the end that every C string needs), and make a new string object out of it. This is very specific to strings, and doesn’t really apply to the other objects. As I said, strings are a bit special.
Cool Note: Because of this, there is only ever one copy of any string in memory. That is why comparing two strings in Oli-Nat is just comparing two pointers, which is instant, no matter how long the strings are.
Functions
//functions
typedef struct ObjFunction
{
Obj obj;
int arity;
ParamInfo params[MAX_PARAMS];
ValueType returnType;
Chunk chunk;
const char* name;
int nameLength;
int upValueCount;
bool isConstructor;
} ObjFunction;Found in /include/object.h
Functions are where we really get into a groove for how objects are defined and allocated. The struct for a function holds a lot of information. Of course we have the standard Obj, like every other object, but a lot follows it.
We have the arity, which is the number of parameters the function takes. We then have params, an array of ParamInfo, which is a helper struct that holds information about each of the parameters in the function declaration, similar to how a regular variable works:
typedef struct ParamInfo
{
ValueType type;
const char* name;
int length;
bool isOptional;
} ParamInfo;Found in /include/object.h
Either way, we have a fixed size array of them (up to MAX_PARAMS), and this works well for natives later on as well, since the type checker uses that same array to check their arguments. After that, we have the return type of the function, which is used by the AST Compiler and type checker a lot, to check that calls and returns line up.
Most importantly, every function has its own chunk. This is the actual bytecode of the function, its very own array of instructions and constants, which is what the VM runs when the function is called.
After that, we get to more of the metadata, like the name of the function and the length of its name. The name is used for things like the stack trace when there is a runtime error. Note that this is not what the globals hashmap uses though. The globals hashmap uses the function’s name as an interned string for the key, and the value at that key is the function, wrapped up in a closure (more on those below).
As for actually creating a function:
ObjFunction* newFunction(const char* name, int nameLength, ValueType returnType, struct Vm* vm)
{
ObjFunction* function = ALLOCATE_OBJ(ObjFunction, OBJ_FUNCTION, vm);
function->arity = 0;
function->name = name;
function->nameLength = nameLength;
function->upValueCount = 0;
initChunk(&function->chunk);
function->returnType = returnType;
function->isConstructor = false;
return function;
}Found in /src/object.c
Really basic. As I have said before, most of this is either zeroed out, so the AST compiler can fill it in a second or two later as it keeps consuming the oh so tasty tokens, or is already known and passed in.
The real benefit is that it is so general, so we can use this same function for things like methods and constructors in classes, without having to create a whole new object type like ObjConstructor or something. A constructor is just a function with isConstructor set to true.
Closures and Upvalues
Closures and upvalues really tend to work hand in hand. A closure is the wrapper around a function that lets it capture variables from the scope around it, so it can use them in its own code. The representation is rather simple:
typedef struct ObjUpValue
{
Obj obj;
Value* location;
struct ObjUpValue* next;
Value closed;
} ObjUpValue;
typedef struct ObjClosure
{
Obj obj;
ObjFunction* function;
ObjUpValue** upValues;
int upValueCount;
} ObjClosure;Found in /include/object.h
An ObjUpValue is one captured variable. Its location points at the variable it captured, which starts out living in a slot on the stack. The issue is that the variable might go out of scope, and get popped off of the stack, before the closure that uses it is done with it. So when that happens, the upvalue is closed: the value gets copied into its own closed field, and location is pointed at that instead. The closure never notices the difference. The next pointer is for the VM’s list of upvalues that are still open, so it can find them when their variables go out of scope.
Closures themselves are sort of like if a function put on a bedsheet and said it was a ghost. A closure holds a pointer to its function, since that is the actual code it runs, and then also has access to all of the upvalues it captured. In Oli-Nat, every function gets wrapped in a closure when it is created at runtime, even ones that don’t capture anything.
Notice that a closure holds a list of pointers to upvalues. This is because a closure does not own its upvalues outright. If it did, we would have an issue whenever more than one closure captured the same variable (which they often do), since each one would have its own separate copy. So instead, they all just hold a reference to the same upvalue, and see each other’s changes.
Natives
Native functions are the functions of the standard library that are written in C. Since the VM has to be able to call them just like any other value, they get their own object too:
typedef Value (*NativeFn)(int argCount, Value* args, struct Vm* vm);
typedef struct ObjNative
{
Obj obj;
NativeFn function;
const char* name;
int nameLength;
} ObjNative;Found in /include/object.h
The NativeFn line is a function pointer type. It says that every native has to be a C function that takes the number of arguments, a pointer to where those arguments are on the stack, and the VM, and gives back a Value. Every single native in the standard library follows that exact shape, which is what lets the VM call all of them in the exact same way. The ObjNative just holds that function pointer, along with its name.
Creating one is about as simple as an object gets:
ObjNative* newNative(NativeFn function, const char* name, int length, struct Vm* vm)
{
ObjNative* native = ALLOCATE_OBJ(ObjNative, OBJ_NATIVE, vm);
native->function = function;
native->name = name;
native->nameLength = length;
return native;
}Found in /src/object.c
And here is what a native function actually looks like on the inside, this one being length() for arrays:
Value lengthNative(int argCount, Value* args, struct Vm* vm)
{
ObjStaticArray* array = (ObjStaticArray*)GET_OBJECT_VAL(args[0]);
return CREATE_INT_VAL(array->length);
}Found in /src/natives.c
The arguments are read straight off of the stack through args, cast to the right object, and the result is turned back into a Value and returned. There is no need to check that args[0] really is an array, because the type checker already made sure of that before the program ran. See the VM docs for how natives get registered and called, and the Standard Library Overview for all of the natives that exist.
Arrays
Arrays in Oli-Nat are static arrays, which means that once one is created, its size never changes:
typedef struct ObjStaticArray
{
Obj obj;
ValueType arrayType;
int length;
Value* values;
} ObjStaticArray;Found in /include/object.h
An array knows what type of values it holds (arrayType), how many it holds (length), and has a pointer to the values themselves. Notice that the values are just a plain array of Values, so an array can hold anything a Value can, including other objects like strings.
ObjStaticArray* newStaticArray(int count, ValueType type, struct Vm* vm)
{
ObjStaticArray* array = ALLOCATE_OBJ(ObjStaticArray, OBJ_STATIC_ARRAY, vm);
array->length = count;
array->arrayType =type;
array->values = ALLOCATE(Value, count, vm);
return array;
}Found in /src/object.c
Creating an array allocates the array object first, and then a separate block of memory big enough for count values. The array object itself is always the same size, only that values block depends on how many items there are. This is the same trick as strings, where the object is a fixed size and points to its data.
The values don’t get filled in here though. That is done by the OP_CREATE_ARRAY instruction in the VM, which pops each element off of the stack and puts it into the array.
Classes
Classes are the biggest objects in the language, and are actually split into two different objects: the class itself, and instances of that class.
//classes
typedef struct
{
ValueType type;
ObjString* name;
int length;
Value defaultValue;
} FieldInfo;
typedef struct ObjClass
{
//basic stuff
Obj obj;
const char* name;
int nameLength;
//inner class fields
FieldInfo fields[MAX_FIELDS];
int fieldCount;
Hashmap methods;
ObjClosure* constructor;
struct ObjClass* superClass;
} ObjClass;Found in /include/object.h
A class holds its name, and then everything that is shared between all of its instances. Its methods live in a Hashmap, keyed by the method’s name, with the closure as the value. The constructor is kept on its own in constructor (or NULL if there isn’t one), and superClass points to the class it inherits from, if it inherits from anything.
The fields are the interesting part. A class doesn’t store the actual values of its fields, it stores information about them, in a fixed size array of FieldInfo: the name of each field, its type, and its default value. The actual values belong to each instance:
typedef struct ObjInstance
{
Obj obj;
ObjClass* class;
Value* fields; //a somewhat static field since instances cannot create new fields
int fieldCount;
} ObjInstance;Found in /include/object.h
An instance is really small. It points to the class it came from, and holds an array with the actual value of every one of its fields. That is all it needs, since everything else, like the methods, can be found through class.
Creating a class is simple, it just starts out empty, and gets filled in by the VM as it runs the class’s instructions:
ObjClass* newClass(const char* name, int nameLength, struct Vm* vm)
{
//different name for porting to another language like c++ or something
ObjClass* klass = ALLOCATE_OBJ(ObjClass, OBJ_CLASS, vm);
klass->name = name;
klass->nameLength = nameLength;
klass->fieldCount = 0;
klass->constructor = NULL;
klass->superClass = NULL;
initMap(&klass->methods);
return klass;
}Found in /src/object.c
Creating an instance takes a bit more work, because of inheritance:
ObjInstance* newInstance(ObjClass* klass, struct Vm* vm)
{
ObjInstance* instance = ALLOCATE_OBJ(ObjInstance, OBJ_INSTANCE, vm);
instance->class = klass;
instance->fields = NULL;
instance->fieldCount = 0;
//push instance onto stack so gc can see it
push(vm, CREATE_OBJECT_VAL((Obj*)instance));
//count total fields across the whole inheritance chain
int totalFields = 0;
ObjClass* current = klass;
while (current != NULL)
{
totalFields += current->fieldCount;
current = current->superClass;
}
//initalize after the gc can safely read it
instance->fields = ALLOCATE(Value, totalFields, vm);
instance->fieldCount = totalFields;
int slot = 0;
ObjClass* chain[256]; // max depth for class inheritance
int depth = 0;
current = klass;
while (current!=NULL)
{
//copy over the chain of class inheritence
chain[depth++] = current;
current = current->superClass;
}
//walk down the list of super classes and set the default values for each one according to if the newsubclasses set actual vals
for (int i = depth - 1; i >= 0; i--)
{
for (int j = 0; j < chain[i]->fieldCount; j++)
{
instance->fields[slot++] = chain[i]->fields[j].defaultValue;
}
}
pop(vm); //remove instance off stack
return instance;
}Found in /src/object.c
An instance needs room for the fields of its whole inheritance chain, not just its own class. So first we walk up the chain of superClasses, adding up how many fields every class has, and allocate one array big enough for all of them. Notice the push and pop here again, since that ALLOCATE could trigger the garbage collector while the new instance isn’t on the stack yet.
Then we fill in that array with every field’s default value, starting from the very top of the chain, so the oldest parent’s fields come first, then its child’s, all the way down to the class we are creating. That order is exactly what OP_GET_FIELD and OP_SET_FIELD rely on in the VM when they work out which slot a field is in.
Cool Note: That comment in the struct, “instances cannot create new fields”, is a big difference from languages like JavaScript or Python, where you can add a new field to an object whenever you want. In Oli-Nat, every field has to be declared in the class, so an instance’s fields can be a plain fixed size array, instead of a whole hashmap. That makes them a lot faster to access, and it is what lets the type checker know every field ahead of time.
Where to Go Next
That is every object in Oli-Nat! Every one of them starts with an Obj, gets created through allocateObject(), and ends up in the VM’s linked list of objects. Which means every one of them eventually has to be cleaned up, and that is exactly what the Garbage Collector page covers.