vm.c 11 KB

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