object.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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_FUNCTION(value) isObjType(value, OBJ_FUNCTION)
  17. #define IS_NATIVE(value) isObjType(value, OBJ_NATIVE)
  18. #define IS_STRING(value) isObjType(value, OBJ_STRING)
  19. #define AS_FUNCTION(value) ((ObjFunction *) AS_OBJ(value))
  20. #define AS_NATIVE(value) (((ObjNative *) AS_OBJ(value))->function)
  21. #define AS_STRING(value) ((ObjString *) AS_OBJ(value))
  22. #define AS_CSTRING(value) (((ObjString *) AS_OBJ(value))->chars)
  23. typedef enum {
  24. OBJ_STRING,
  25. OBJ_FUNCTION,
  26. OBJ_NATIVE,
  27. } ObjType;
  28. struct Obj {
  29. ObjType type;
  30. struct Obj *next;
  31. };
  32. typedef struct {
  33. struct Obj obj;
  34. int arity;// stores the number of parameters the function expects
  35. Chunk chunk;
  36. ObjString *name;
  37. } ObjFunction;
  38. typedef Value (*NativeFn)(int argCount, Value *args);
  39. typedef struct {
  40. struct Obj obj;
  41. NativeFn function;
  42. } ObjNative;
  43. struct ObjString {
  44. struct Obj obj;
  45. int length;
  46. char *chars;
  47. uint32_t hash;// 缓存 hash 值
  48. };
  49. ObjFunction *newFunction();
  50. ObjNative *newNative(NativeFn function);
  51. ObjString *takeString(char *chars, int length);
  52. ObjString *copyString(const char *chars, int length);
  53. void printObject(Value value);
  54. static inline bool isObjType(Value value, ObjType type) {
  55. return IS_OBJ(value) && AS_OBJ(value)->type == type;
  56. }
  57. #endif//CLOX_OBJECT_H