chunk.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. ******************************************************************************
  3. * @file : chunk.h
  4. * @author : simon
  5. * @brief : Chunks contain almost all of the information
  6. * that the runtime needs from the user’s source code
  7. * @attention : None
  8. * @date : 2023/8/16
  9. ******************************************************************************
  10. */
  11. #ifndef CLOX__CHUNK_H_
  12. #define CLOX__CHUNK_H_
  13. #include "common.h"
  14. #include "value.h"
  15. typedef enum {
  16. OP_CONSTANT,///<OP_CONSTANT (index)+>
  17. OP_NEGATE, /// \brief prefix -
  18. OP_ADD, /// \brief +
  19. OP_SUBTRACT, /// \brief -
  20. OP_MULTIPLY, /// \brief *
  21. OP_DIVIDE, /// \brief /
  22. OP_RETURN, ///<OP_RETURN>
  23. } OpCode;
  24. //============================================================================
  25. // Dynamic array of instructions 扩容步骤
  26. //1. Allocate a new array with more capacity.
  27. //2. Copy the existing elements from the old array to the new one.
  28. //3. Store the new capacity.
  29. //4. Delete the old array.
  30. //5. Update code to point to the new array.
  31. //6. Store the element in the new array now that there is room.
  32. //7. Update the count.
  33. //============================================================================
  34. typedef struct {
  35. int count; // 使用量
  36. int capacity; // 容量
  37. uint8_t *code; // unsigned char*
  38. int *lines; // 源代码行数
  39. ValueArray constants;// 常量池
  40. } Chunk;
  41. /// 初始化 chunk
  42. /// \param chunk 对象
  43. void initChunk(Chunk *chunk);
  44. /// 释放 chunk
  45. /// \param chunk 对象
  46. void freeChunk(Chunk *chunk);
  47. /// 写入 chunk
  48. /// \param chunk 对象
  49. /// \param byte 命令或数据
  50. /// \param line 源代码行数
  51. void writeChunk(Chunk *chunk, uint8_t byte, int line);
  52. /// 添加常量
  53. /// \param chunk 指令数组
  54. /// \param value 值
  55. /// \return index of constant 常量位置
  56. int addConstant(Chunk *chunk, Value value);
  57. #endif//CLOX__CHUNK_H_