vm.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 "vm.h"
  11. #include "common.h"
  12. #include "compiler.h"
  13. #include "debug.h"
  14. #include "memory.h"
  15. #include <stdarg.h>
  16. #include <time.h>
  17. VM vm;
  18. /// \brief 重置栈
  19. static void resetStack() {
  20. vm.stackTop = vm.stack;// 指针指向栈底
  21. vm.frameCount = 0;
  22. }
  23. static void runtimeError(const char *format, ...) {
  24. va_list args;
  25. va_start(args, format);
  26. vfprintf(stderr, format, args);
  27. va_end(args);
  28. fputs("\n", stderr);
  29. for (int i = vm.frameCount - 1; i >= 0; i--) {
  30. CallFrame *frame = &vm.frames[i];
  31. ObjFunction *function = frame->function;
  32. size_t instruction = frame->ip - frame->function->chunk.code - 1;
  33. int line = function->chunk.lines[instruction];
  34. fprintf(stderr, "[line %d] in ", line);
  35. if (function->name == NULL) {
  36. fprintf(stderr, "script\n");
  37. } else {
  38. fprintf(stderr, "%s()\n", function->name->chars);
  39. }
  40. }
  41. resetStack();
  42. }
  43. static void defineNative(const char *name, NativeFn function) {
  44. push(OBJ_VAL(copyString(name, (int) strlen(name))));
  45. push(OBJ_VAL(newNative(function)));
  46. tableSet(&vm.globals, AS_STRING(vm.stack[0]), vm.stack[1]);
  47. pop();
  48. pop();
  49. }
  50. static Value clockNative(int argCount, Value *args) {
  51. return NUMBER_VAL((double) clock() / CLOCKS_PER_SEC);
  52. }
  53. void initVM() {
  54. resetStack();
  55. vm.objects = NULL;
  56. initTable(&vm.globals);
  57. initTable(&vm.strings);
  58. /// Native Function define.
  59. defineNative("clock", clockNative);
  60. }
  61. static Value peek(int distance) {
  62. return vm.stackTop[-1 - distance];
  63. }
  64. static bool call(ObjFunction *function, int argCount) {
  65. if (argCount != function->arity) {
  66. runtimeError("Expected %d arguments but got %d", function->arity, argCount);
  67. return false;
  68. }
  69. if (vm.frameCount == FRAMES_MAX) {
  70. runtimeError("Stack overflow.");
  71. return false;
  72. }
  73. CallFrame *frame = &vm.frames[vm.frameCount++];
  74. frame->function = function;
  75. frame->ip = function->chunk.code;
  76. frame->slots = vm.stackTop - argCount - 1;
  77. return true;
  78. }
  79. static bool callValue(Value callee, int argCount) {
  80. if (IS_OBJ(callee)) {
  81. switch (OBJ_TYPE(callee)) {
  82. case OBJ_FUNCTION:
  83. return call(AS_FUNCTION(callee), argCount);
  84. case OBJ_NATIVE: {
  85. NativeFn fn = AS_NATIVE(callee);
  86. Value result = fn(argCount, vm.stackTop - argCount);
  87. vm.stackTop -= argCount + 1;
  88. push(result);
  89. return true;
  90. }
  91. default:
  92. break;// Non-callable object type.
  93. }
  94. }
  95. runtimeError("Can only call functions and classes.");
  96. return false;
  97. }
  98. static bool isFalse(Value value) {
  99. // the nil and false will return true
  100. return IS_NIL(value) || (IS_BOOL(value) && !AS_BOOL(value));
  101. }
  102. static void concatenate() {
  103. ObjString *b = AS_STRING(pop());
  104. ObjString *a = AS_STRING(pop());
  105. int length = a->length + b->length;
  106. char *chars = ALLOCATE(char, length + 1);
  107. memcpy(chars, a->chars, a->length);
  108. memcpy(chars + a->length, b->chars, b->length);
  109. chars[length] = '\0';
  110. ObjString *result = takeString(chars, length);
  111. push(OBJ_VAL(result));
  112. }
  113. static InterpretResult run() {
  114. CallFrame *frame = &vm.frames[vm.frameCount - 1];
  115. //! <macro> reads the byte currently pointed at by ip
  116. //! and then advances the instruction pointer
  117. #define READ_BYTE() (*frame->ip++)
  118. //! reads the next byte from the bytecode
  119. //! treats the resulting number as an index
  120. #define READ_CONSTANT() (frame->function->chunk.constants.values[READ_BYTE()])
  121. #define READ_SHORT() \
  122. (frame->ip += 2, (uint16_t) ((frame->ip[-2] << 8) | frame->ip[-1]))
  123. #define READ_STRING() AS_STRING(READ_CONSTANT())
  124. #define BINARY_OP(valueType, op) \
  125. do { \
  126. if (!IS_NUMBER(peek(0)) || !IS_NUMBER(peek(1))) { \
  127. runtimeError("Operands must be numbers."); \
  128. return INTERPRET_RUNTIME_ERROR; \
  129. } \
  130. double b = AS_NUMBER(pop()); \
  131. double a = AS_NUMBER(pop()); \
  132. push(valueType(a op b)); \
  133. } while (false)
  134. for (;;) {
  135. #ifdef DEBUG_TRACE_EXECUTION
  136. //! <Stack tracing> start
  137. printf("\n!!! <Stack tracing now>:\n");
  138. printf("------------------------\n|");
  139. for (Value *slot = vm.stack; slot < vm.stackTop; slot++) {
  140. printf("[ ");
  141. printValue(*slot);
  142. printf(" ]");
  143. }
  144. printf("\n------------------------");
  145. printf("\n");
  146. printf("\n");
  147. //! <Stack tracing> end
  148. printf("The Instruction: \n");
  149. disassembleInstruction(&frame->function->chunk, (int) (frame->ip - frame->function->chunk.code));
  150. #endif
  151. uint8_t opCode = READ_BYTE();
  152. switch (opCode) {
  153. case OP_CONSTANT: {
  154. Value constant = READ_CONSTANT();
  155. push(constant);
  156. break;
  157. }
  158. case OP_NIL:
  159. push(NIL_VAL);
  160. break;
  161. case OP_TRUE:
  162. push(BOOL_VAL(true));
  163. break;
  164. case OP_FALSE:
  165. push(BOOL_VAL(false));
  166. break;
  167. case OP_POP:
  168. pop();
  169. break;
  170. case OP_DEFINE_GLOBAL: {
  171. ObjString *name = READ_STRING();
  172. tableSet(&vm.globals, name, peek(0));
  173. pop();
  174. break;
  175. }
  176. case OP_GET_GLOBAL: {
  177. ObjString *name = READ_STRING();
  178. Value value;
  179. if (!tableGet(&vm.globals, name, &value)) {
  180. runtimeError("Undefined variable '%s'.", name->chars);
  181. return INTERPRET_RUNTIME_ERROR;
  182. }
  183. push(value);
  184. break;
  185. }
  186. case OP_SET_GLOBAL: {
  187. ObjString *name = READ_STRING();
  188. if (tableSet(&vm.globals, name, peek(0))) {
  189. tableDelete(&vm.globals, name);
  190. runtimeError("Undefined variable '%s'.", name->chars);
  191. return INTERPRET_RUNTIME_ERROR;
  192. }
  193. break;
  194. }
  195. case OP_GET_LOCAL: {
  196. uint8_t slot = READ_BYTE();
  197. push(frame->slots[slot]);
  198. break;
  199. }
  200. case OP_SET_LOCAL: {
  201. uint8_t slot = READ_BYTE();
  202. frame->slots[slot] = peek(0);
  203. break;
  204. }
  205. case OP_ADD: {
  206. if (IS_STRING(peek(0)) && IS_STRING(peek(1))) {
  207. // 字串拼接
  208. concatenate();
  209. } else if (IS_NUMBER(peek(0)) && IS_NUMBER(peek(1))) {
  210. double b = AS_NUMBER(pop());
  211. double a = AS_NUMBER(pop());
  212. push(NUMBER_VAL(a + b));
  213. } else {
  214. runtimeError("Operands must be two numbers or two strings.");
  215. return INTERPRET_RUNTIME_ERROR;
  216. }
  217. break;
  218. }
  219. case OP_SUBTRACT:
  220. BINARY_OP(NUMBER_VAL, -);
  221. break;
  222. case OP_MULTIPLY:
  223. BINARY_OP(NUMBER_VAL, *);
  224. break;
  225. case OP_DIVIDE:
  226. BINARY_OP(NUMBER_VAL, /);
  227. break;
  228. case OP_NOT:
  229. push(BOOL_VAL(isFalse(pop())));
  230. break;
  231. case OP_NEGATE:
  232. if (!IS_NUMBER(peek(0))) {
  233. runtimeError("Operand must be a number.");
  234. return INTERPRET_RUNTIME_ERROR;
  235. }
  236. push(NUMBER_VAL(-AS_NUMBER(pop())));
  237. break;
  238. case OP_EQUAL: {
  239. Value b = pop();
  240. Value a = pop();
  241. push(BOOL_VAL(valuesEqual(a, b)));
  242. break;
  243. }
  244. case OP_GREATER:
  245. BINARY_OP(BOOL_VAL, >);
  246. break;
  247. case OP_LESS:
  248. BINARY_OP(BOOL_VAL, <);
  249. break;
  250. case OP_PRINT: {
  251. printValue(pop());
  252. printf("\n");
  253. break;
  254. }
  255. case OP_JUMP_IF_FALSE: {
  256. uint16_t offset = READ_SHORT();
  257. if (isFalse(peek(0))) frame->ip += offset;
  258. break;
  259. }
  260. case OP_JUMP: {
  261. uint16_t offset = READ_SHORT();
  262. frame->ip += offset;
  263. break;
  264. }
  265. case OP_LOOP: {
  266. uint16_t offset = READ_SHORT();
  267. frame->ip -= offset;
  268. break;
  269. }
  270. case OP_CALL: {
  271. int argCount = READ_BYTE();
  272. if (!callValue(peek(argCount), argCount)) {
  273. return INTERPRET_RUNTIME_ERROR;
  274. }
  275. frame = &vm.frames[vm.frameCount - 1];
  276. break;
  277. }
  278. case OP_RETURN: {
  279. Value result = pop();
  280. vm.frameCount--;
  281. if (vm.frameCount == 0) {
  282. pop();
  283. return INTERPRET_OK;
  284. }
  285. vm.stackTop = frame->slots;
  286. push(result);
  287. frame = &vm.frames[vm.frameCount - 1];
  288. break;
  289. }
  290. default:
  291. break;
  292. }
  293. }
  294. #undef READ_BYTE
  295. #undef READ_CONSTANT
  296. #undef READ_SHORT
  297. #undef READ_STRING
  298. #undef BINARY_OP
  299. }
  300. void freeVM() {
  301. freeTable(&vm.globals);
  302. freeTable(&vm.strings);
  303. freeObjects();
  304. }
  305. InterpretResult interpret(const char *source) {
  306. ObjFunction *function = compile(source);
  307. if (function == NULL) return INTERPRET_COMPILE_ERROR;
  308. push(OBJ_VAL(function));
  309. // CallFrame *frame = &vm.frames[vm.frameCount++];
  310. // frame->function = function;
  311. // frame->ip = function->chunk.code;
  312. // frame->slots = vm.stack;
  313. call(function, 0);
  314. return run();
  315. }
  316. void push(Value value) {
  317. *vm.stackTop = value;
  318. vm.stackTop++;
  319. }
  320. Value pop() {
  321. vm.stackTop--;
  322. //! NOTE: 出栈后,里面的值没有清除
  323. return *vm.stackTop;
  324. }