chunk.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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_NIL,
  18. OP_TRUE,
  19. OP_FALSE,
  20. OP_NOT, /// \brief print !true; // "false"
  21. OP_NEGATE,/// \brief prefix -
  22. OP_EQUAL,
  23. OP_GREATER,
  24. OP_LESS,
  25. OP_ADD, /// \brief +
  26. OP_SUBTRACT,/// \brief -
  27. OP_MULTIPLY,/// \brief *
  28. OP_DIVIDE, /// \brief /
  29. OP_RETURN, ///<OP_RETURN>
  30. } OpCode;
  31. //============================================================================
  32. // Dynamic array of instructions 扩容步骤
  33. //1. Allocate a new array with more capacity.
  34. //2. Copy the existing elements from the old array to the new one.
  35. //3. Store the new capacity.
  36. //4. Delete the old array.
  37. //5. Update code to point to the new array.
  38. //6. Store the element in the new array now that there is room.
  39. //7. Update the count.
  40. //============================================================================
  41. typedef struct {
  42. int count; // 使用量
  43. int capacity; // 容量
  44. uint8_t *code; // unsigned char*
  45. int *lines; // 源代码行数
  46. ValueArray constants;// 常量池
  47. } Chunk;
  48. /// 初始化 chunk
  49. /// \param chunk 对象
  50. void initChunk(Chunk *chunk);
  51. /// 释放 chunk
  52. /// \param chunk 对象
  53. void freeChunk(Chunk *chunk);
  54. /// 写入 chunk
  55. /// \param chunk 对象
  56. /// \param byte 命令或数据
  57. /// \param line 源代码行数
  58. void writeChunk(Chunk *chunk, uint8_t byte, int line);
  59. /// 添加常量
  60. /// \param chunk 指令数组
  61. /// \param value 值
  62. /// \return index of constant 常量位置
  63. int addConstant(Chunk *chunk, Value value);
  64. #endif//CLOX__CHUNK_H_