chunk.h 2.2 KB

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