/** ****************************************************************************** * @file : object.cpp * @author : simon * @brief : None * @attention : None * @date : 2023/8/23 ****************************************************************************** */ #include #include #include "memory.h" #include "object.h" #include "table.h" #include "vm.h" static Obj *allocateObject(size_t size, ObjType type); static uint32_t hashString(const char *key, int length); #define ALLOCATE_OBJ(type, objectType) \ (type *) allocateObject(sizeof(type), objectType) static ObjString *allocateString(char *chars, int length, uint32_t hash) { ObjString *string = ALLOCATE_OBJ(ObjString, OBJ_STRING); string->length = length; string->chars = chars; string->hash = hash; push(OBJ_VAL(string)); tableSet(&vm.strings, string, NIL_VAL); pop(); return string; } ObjString *copyString(const char *chars, int length) { uint32_t hash = hashString(chars, length); ObjString *interned = tableFindString(&vm.strings, chars, length, hash); if (interned != NULL) return interned; char *heapChars = ALLOCATE(char, length + 1); memcpy(heapChars, chars, length); heapChars[length] = '\0'; return allocateString(heapChars, length, hash); } static void printFunction(ObjFunction *function) { if (function->name == NULL) { printf("