vm.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. ******************************************************************************
  3. * @file : vm.c
  4. * @author : simon
  5. * @brief : Interpret the bytecode from chunk
  6. * @attention : None
  7. * @date : 2023/8/17
  8. ******************************************************************************
  9. */
  10. #include "common.h"
  11. #include "vm.h"
  12. #include "debug.h"
  13. #include "compiler.h"
  14. VM vm;
  15. /// \brief 重置栈
  16. static void resetStack() {
  17. vm.stackTop = vm.stack; // 指针指向栈顶
  18. }
  19. void initVM() {
  20. resetStack();
  21. }
  22. static InterpretResult run() {
  23. //! <macro> reads the byte currently pointed at by ip
  24. //! and then advances the instruction pointer
  25. #define READ_BYTE() (*vm.ip++)
  26. //! reads the next byte from the bytecode
  27. //! treats the resulting number as an index
  28. #define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])
  29. #define BINARY_OP(op) \
  30. do { \
  31. double b = pop(); \
  32. double a = pop(); \
  33. push(a op b); \
  34. } while(false)
  35. for (;;) {
  36. #ifdef DEBUG_TRACE_EXECUTION
  37. //! <Stack tracing> start
  38. printf("------------------------\n|");
  39. for (Value *slot = vm.stack; slot < vm.stackTop; slot++) {
  40. printf("[ ");
  41. printValue(*slot);
  42. printf(" ]");
  43. }
  44. printf("\n------------------------");
  45. printf("\n");
  46. //! <Stack tracing> end
  47. disassembleInstruction(vm.chunk, (int) (vm.ip - vm.chunk->code));
  48. #endif
  49. uint8_t instruction;
  50. switch (instruction = READ_BYTE()) {
  51. case OP_CONSTANT: {
  52. Value constant = READ_CONSTANT();
  53. push(constant);
  54. break;
  55. }
  56. case OP_ADD: BINARY_OP(+);
  57. break;
  58. case OP_SUBTRACT: BINARY_OP(-);
  59. break;
  60. case OP_MULTIPLY: BINARY_OP(*);
  61. break;
  62. case OP_DIVIDE: BINARY_OP(/);
  63. break;
  64. case OP_NEGATE: push(-pop());
  65. break;
  66. case OP_RETURN: {
  67. printValue(pop());
  68. printf("\n");
  69. return INTERPRET_OK;
  70. }
  71. }
  72. }
  73. #undef READ_BYTE
  74. #undef READ_CONSTANT
  75. #undef BINARY_OP
  76. }
  77. void freeVM() {
  78. }
  79. InterpretResult interpret(const char *source) {
  80. compile(source);
  81. return INTERPRET_OK;
  82. }
  83. void push(Value value) {
  84. *vm.stackTop = value;
  85. vm.stackTop++;
  86. }
  87. Value pop() {
  88. vm.stackTop--;
  89. //! NOTE: 出栈后,里面的值没有清除
  90. return *vm.stackTop;
  91. }