object.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. ******************************************************************************
  3. * @file : object.h
  4. * @author : simon
  5. * @brief : None
  6. * @attention : None
  7. * @date : 2023/8/23
  8. ******************************************************************************
  9. */
  10. #ifndef CLOX_OBJECT_H
  11. #define CLOX_OBJECT_H
  12. #include "chunk.h"
  13. #include "common.h"
  14. #include "value.h"
  15. #define OBJ_TYPE(value) (AS_OBJ(value)->type)
  16. #define IS_CLOSURE(value) isObjType(value, OBJ_CLOSURE)
  17. #define IS_FUNCTION(value) isObjType(value, OBJ_FUNCTION)
  18. #define IS_NATIVE(value) isObjType(value, OBJ_NATIVE)
  19. #define IS_STRING(value) isObjType(value, OBJ_STRING)
  20. #define AS_CLOSURE(value) ((ObjClosure *) AS_OBJ(value))
  21. #define AS_FUNCTION(value) ((ObjFunction *) AS_OBJ(value))
  22. #define AS_NATIVE(value) (((ObjNative *) AS_OBJ(value))->function)
  23. #define AS_STRING(value) ((ObjString *) AS_OBJ(value))
  24. #define AS_CSTRING(value) (((ObjString *) AS_OBJ(value))->chars)
  25. typedef enum {
  26. OBJ_STRING,
  27. OBJ_FUNCTION,
  28. OBJ_NATIVE,
  29. OBJ_CLOSURE,
  30. OBJ_UPVALUE,
  31. } ObjType;
  32. struct Obj {
  33. ObjType type;
  34. bool isMarked;
  35. struct Obj *next;
  36. };
  37. typedef struct {
  38. struct Obj obj;
  39. int arity;// stores the number of parameters the function expects
  40. int upvalueCount;
  41. Chunk chunk;
  42. ObjString *name;
  43. } ObjFunction;
  44. typedef Value (*NativeFn)(int argCount, Value *args);
  45. typedef struct {
  46. struct Obj obj;
  47. NativeFn function;
  48. } ObjNative;
  49. struct ObjString {
  50. struct Obj obj;
  51. int length;
  52. char *chars;
  53. uint32_t hash;// 缓存 hash 值
  54. };
  55. typedef struct ObjUpvalue {
  56. struct Obj obj;
  57. Value *location;
  58. Value closed;
  59. struct ObjUpvalue *next;
  60. } ObjUpvalue;
  61. typedef struct {
  62. struct Obj obj;
  63. ObjFunction *function;
  64. ObjUpvalue **upvalues;
  65. int upvalueCount;
  66. } ObjClosure;
  67. ObjClosure *newClosure(ObjFunction *function);
  68. ObjFunction *newFunction();
  69. ObjNative *newNative(NativeFn function);
  70. ObjString *takeString(char *chars, int length);
  71. ObjString *copyString(const char *chars, int length);
  72. ObjUpvalue *newUpvalue(Value *slot);
  73. void printObject(Value value);
  74. static inline bool isObjType(Value value, ObjType type) {
  75. return IS_OBJ(value) && AS_OBJ(value)->type == type;
  76. }
  77. #endif//CLOX_OBJECT_H