chunk.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // Created by 李晓明 on 2023/6/14.
  3. //
  4. #include "chunk.h"
  5. #include "memory.h"
  6. #include "vm.h"
  7. void initChunk(Chunk *chunk) {
  8. chunk->count = 0;
  9. chunk->capacity = 0;
  10. chunk->code = NULL;
  11. chunk->lines = NULL;
  12. initValueArray(&chunk->constants);
  13. }
  14. void freeChunk(Chunk *chunk) {
  15. FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
  16. FREE_ARRAY(int, chunk->lines, chunk->capacity);
  17. freeValueArray(&chunk->constants);
  18. initChunk(chunk);
  19. }
  20. void writeChunk(Chunk *chunk, uint8_t byte, int line) {
  21. // 容量不够
  22. if (chunk->capacity < chunk->count + 1) {
  23. int oldCapacity = chunk->capacity;
  24. chunk->capacity = GROW_CAPACITY(oldCapacity);
  25. chunk->code = GROW_ARRAY(uint8_t, chunk->code, oldCapacity, chunk->capacity);
  26. chunk->lines = GROW_ARRAY(int, chunk->lines, oldCapacity, chunk->capacity);
  27. }
  28. // 赋值
  29. chunk->code[chunk->count] = byte;
  30. chunk->lines[chunk->count] = line;
  31. chunk->count++;
  32. }
  33. int addConstant(Chunk *chunk, Value value) {
  34. push(value);
  35. writeValueArray(&chunk->constants, value);
  36. pop();
  37. return chunk->constants.count - 1;
  38. }