Chapter 27.1

This commit is contained in:
Tom Willemse 2022-08-12 20:13:25 -07:00
parent ad6a98f6ad
commit 63527558a7
3 changed files with 27 additions and 0 deletions

View file

@ -76,6 +76,11 @@ static void blackenObject(Obj *object) {
printf("\n");
#endif
switch (object->type) {
case OBJ_CLASS: {
ObjClass *klass = (ObjClass *)object;
markObject((Obj *)klass->name);
break;
}
case OBJ_CLOSURE: {
ObjClosure *closure = (ObjClosure *)object;
markObject((Obj *)closure->function);
@ -105,6 +110,10 @@ static void freeObject(Obj *object) {
#endif // DEBUG_LOG_GC
switch (object->type) {
case OBJ_CLASS: {
FREE(ObjClass, object);
break;
}
case OBJ_CLOSURE: {
ObjClosure *closure = (ObjClosure *)object;
FREE_ARRAY(ObjUpvalue *, closure->upvalues, closure->upvalueCount);

View file

@ -25,6 +25,12 @@ static Obj *allocateObject(size_t size, ObjType type) {
return object;
}
ObjClass *newClass(ObjString *name) {
ObjClass *klass = ALLOCATE_OBJ(ObjClass, OBJ_CLASS);
klass->name = name;
return klass;
}
ObjClosure *newClosure(ObjFunction *function) {
ObjUpvalue **upvalues = ALLOCATE(ObjUpvalue *, function->upvalueCount);
for (int i = 0; i < function->upvalueCount; i++) {
@ -116,6 +122,9 @@ static void printFunction(ObjFunction *function) {
void printObject(Value value) {
switch (OBJ_TYPE(value)) {
case OBJ_CLASS:
printf("%s", AS_CLASS(value)->name->chars);
break;
case OBJ_CLOSURE:
printFunction(AS_CLOSURE(value)->function);
break;

View file

@ -7,11 +7,13 @@
#define OBJ_TYPE(value) (AS_OBJ(value)->type)
#define IS_CLASS(value) isObjType(value, OBJ_CLASS)
#define IS_CLOSURE(value) isObjType(value, OBJ_CLOSURE)
#define IS_FUNCTION(value) isObjType(value, OBJ_FUNCTION)
#define IS_NATIVE(value) isObjType(value, OBJ_NATIVE)
#define IS_STRING(value) isObjType(value, OBJ_STRING)
#define AS_CLASS(value) ((ObjClass *)AS_OBJ(value))
#define AS_CLOSURE(value) ((ObjClosure *)AS_OBJ(value))
#define AS_FUNCTION(value) ((ObjFunction *)AS_OBJ(value))
#define AS_NATIVE(value) (((ObjNative *)AS_OBJ(value))->function)
@ -19,6 +21,7 @@
#define AS_CSTRING(value) (((ObjString *)AS_OBJ(value))->chars)
typedef enum {
OBJ_CLASS,
OBJ_CLOSURE,
OBJ_FUNCTION,
OBJ_NATIVE,
@ -68,6 +71,12 @@ typedef struct {
int upvalueCount;
} ObjClosure;
typedef struct {
Obj obj;
ObjString *name;
} ObjClass;
ObjClass *newClass(ObjString *name);
ObjClosure *newClosure(ObjFunction *function);
ObjFunction *newFunction();
ObjNative *newNative(NativeFn function);