object.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. struct Obj *next;
  35. };
  36. typedef struct {
  37. struct Obj obj;
  38. int arity;// stores the number of parameters the function expects
  39. int upvalueCount;
  40. Chunk chunk;
  41. ObjString *name;
  42. } ObjFunction;
  43. typedef Value (*NativeFn)(int argCount, Value *args);
  44. typedef struct {
  45. struct Obj obj;
  46. NativeFn function;
  47. } ObjNative;
  48. struct ObjString {
  49. struct Obj obj;
  50. int length;
  51. char *chars;
  52. uint32_t hash;// 缓存 hash 值
  53. };
  54. typedef struct ObjUpvalue {
  55. struct Obj obj;
  56. Value *location;
  57. Value closed;
  58. struct ObjUpvalue *next;
  59. } ObjUpvalue;
  60. typedef struct {
  61. struct Obj obj;
  62. ObjFunction *function;
  63. ObjUpvalue **upvalues;
  64. int upvalueCount;
  65. } ObjClosure;
  66. ObjClosure *newClosure(ObjFunction *function);
  67. ObjFunction *newFunction();
  68. ObjNative *newNative(NativeFn function);
  69. ObjString *takeString(char *chars, int length);
  70. ObjString *copyString(const char *chars, int length);
  71. ObjUpvalue *newUpvalue(Value *slot);
  72. void printObject(Value value);
  73. static inline bool isObjType(Value value, ObjType type) {
  74. return IS_OBJ(value) && AS_OBJ(value)->type == type;
  75. }
  76. #endif//CLOX_OBJECT_H