diff --git a/clox/src/memory.c b/clox/src/memory.c index d1e0c5a..677feed 100644 --- a/clox/src/memory.c +++ b/clox/src/memory.c @@ -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); diff --git a/clox/src/object.c b/clox/src/object.c index 376742f..935a258 100644 --- a/clox/src/object.c +++ b/clox/src/object.c @@ -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; diff --git a/clox/src/object.h b/clox/src/object.h index 36ec034..44de6ed 100644 --- a/clox/src/object.h +++ b/clox/src/object.h @@ -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);