chunk.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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_GET_UPVALUE,
  27. OP_SET_UPVALUE,
  28. OP_NOT, /// \brief print !true; // "false"
  29. OP_NEGATE,/// \brief prefix -
  30. OP_EQUAL,
  31. OP_GREATER,
  32. OP_LESS,
  33. OP_ADD, /// \brief +
  34. OP_SUBTRACT,/// \brief -
  35. OP_MULTIPLY,/// \brief *
  36. OP_DIVIDE, /// \brief /
  37. OP_PRINT,
  38. OP_JUMP_IF_FALSE,/// <OP_JUMP_IF_FALSE + +>
  39. OP_JUMP, /// <OP_JUMP + +> 往后跳
  40. OP_LOOP, /// <OP_LOOP ++> 往前跳
  41. OP_CALL, /// <OP_CALL argCount>
  42. OP_RETURN, ///<OP_RETURN>
  43. OP_CLOSURE,
  44. OP_CLOSE_UPVALUE,
  45. OP_SET_PROPERTY,
  46. OP_GET_PROPERTY,
  47. OP_INVOKE,
  48. OP_SUPER_INVOKE,
  49. OP_INHERIT,
  50. OP_CLASS,
  51. OP_METHOD,
  52. OP_GET_SUPER,
  53. } OpCode;
  54. //============================================================================
  55. // Dynamic array of instructions 扩容步骤
  56. //1. Allocate a new array with more capacity.
  57. //2. Copy the existing elements from the old array to the new one.
  58. //3. Store the new capacity.
  59. //4. Delete the old array.
  60. //5. Update code to point to the new array.
  61. //6. Store the element in the new array now that there is room.
  62. //7. Update the count.
  63. //============================================================================
  64. typedef struct {
  65. int count; // 使用量
  66. int capacity; // 容量
  67. uint8_t *code; // unsigned char*
  68. int *lines; // 源代码行数
  69. ValueArray constants;// 常量池
  70. } Chunk;
  71. /// 初始化 chunk
  72. /// \param chunk 对象
  73. void initChunk(Chunk *chunk);
  74. /// 释放 chunk
  75. /// \param chunk 对象
  76. void freeChunk(Chunk *chunk);
  77. /// 写入 chunk
  78. /// \param chunk 对象
  79. /// \param byte 命令或数据
  80. /// \param line 源代码行数
  81. void writeChunk(Chunk *chunk, uint8_t byte, int line);
  82. /// 添加常量
  83. /// \param chunk 指令数组
  84. /// \param value 值
  85. /// \return index of constant 常量位置
  86. int addConstant(Chunk *chunk, Value value);
  87. #endif//CLOX__CHUNK_H_