/** ****************************************************************************** * @file : object.h * @author : simon * @brief : None * @attention : None * @date : 2023/8/23 ****************************************************************************** */ #ifndef CLOX_OBJECT_H #define CLOX_OBJECT_H #include "chunk.h" #include "common.h" #include "value.h" #define OBJ_TYPE(value) (AS_OBJ(value)->type) #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_CLOSURE(value) ((ObjClosure *) AS_OBJ(value)) #define AS_FUNCTION(value) ((ObjFunction *) AS_OBJ(value)) #define AS_NATIVE(value) (((ObjNative *) AS_OBJ(value))->function) #define AS_STRING(value) ((ObjString *) AS_OBJ(value)) #define AS_CSTRING(value) (((ObjString *) AS_OBJ(value))->chars) typedef enum { OBJ_STRING, OBJ_FUNCTION, OBJ_NATIVE, OBJ_CLOSURE, OBJ_UPVALUE, } ObjType; struct Obj { ObjType type; struct Obj *next; }; typedef struct { struct Obj obj; int arity;// stores the number of parameters the function expects int upvalueCount; Chunk chunk; ObjString *name; } ObjFunction; typedef Value (*NativeFn)(int argCount, Value *args); typedef struct { struct Obj obj; NativeFn function; } ObjNative; struct ObjString { struct Obj obj; int length; char *chars; uint32_t hash;// 缓存 hash 值 }; typedef struct ObjUpvalue { struct Obj obj; Value *location; Value closed; struct ObjUpvalue *next; } ObjUpvalue; typedef struct { struct Obj obj; ObjFunction *function; ObjUpvalue **upvalues; int upvalueCount; } ObjClosure; ObjClosure *newClosure(ObjFunction *function); ObjFunction *newFunction(); ObjNative *newNative(NativeFn function); ObjString *takeString(char *chars, int length); ObjString *copyString(const char *chars, int length); ObjUpvalue *newUpvalue(Value *slot); void printObject(Value value); static inline bool isObjType(Value value, ObjType type) { return IS_OBJ(value) && AS_OBJ(value)->type == type; } #endif//CLOX_OBJECT_H