object.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. ******************************************************************************
  3. * @file : object.cpp
  4. * @author : simon
  5. * @brief : None
  6. * @attention : None
  7. * @date : 2023/8/23
  8. ******************************************************************************
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include "memory.h"
  13. #include "object.h"
  14. #include "vm.h"
  15. static Obj *allocateObject(size_t size, ObjType type);
  16. #define ALLOCATE_OBJ(type, objectType) \
  17. (type *) allocateObject(sizeof(type), objectType)
  18. static ObjString *allocateString(char *chars, int length) {
  19. ObjString *string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
  20. string->length = length;
  21. string->chars = chars;
  22. return string;
  23. }
  24. ObjString *copyString(const char *chars, int length) {
  25. char *heapChars = ALLOCATE(char, length + 1);
  26. memcpy(heapChars, chars, length);
  27. heapChars[length] = '\0';
  28. return allocateString(heapChars, length);
  29. }
  30. void printObject(Value value) {
  31. switch (OBJ_TYPE(value)) {
  32. case OBJ_STRING:
  33. printf("%s", AS_CSTRING(value));
  34. break;
  35. }
  36. }
  37. ObjString *takeString(char *chars, int length) {
  38. return allocateString(chars, length);
  39. }
  40. static Obj *allocateObject(size_t size, ObjType type) {
  41. Obj *object = (Obj *) reallocate(NULL, 0, size);
  42. object->type = type;
  43. object->next = vm.objects;
  44. vm.objects = object;
  45. return object;
  46. }