vm.c 11 KB

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