vm.c 12 KB

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