debug.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // Created by 李晓明 on 2023/8/16.
  3. //
  4. #include "debug.h"
  5. #include <stdio.h>
  6. #include "value.h"
  7. static int constantInstruction(const char *, Chunk *, int);
  8. static int simpleInstruction(const char *name, int offset);
  9. void disassembleChunk(Chunk *chunk, const char *name) {
  10. printf("== %s ==\n", name);
  11. for (int offset = 0; offset < chunk->count;) {
  12. offset = disassembleInstruction(chunk, offset);
  13. }
  14. }
  15. int disassembleInstruction(Chunk *chunk, int offset) {
  16. printf("%04d ", offset);
  17. uint8_t instruction = chunk->code[offset];
  18. switch (instruction) {
  19. case OP_CONSTANT:return constantInstruction("OP_CONSTANT", chunk, offset);
  20. case OP_RETURN:return simpleInstruction("OP_RETURN", offset);
  21. default:printf("Unknown opcode %d\n", instruction);
  22. return offset + 1;
  23. }
  24. }
  25. /**
  26. * @brief 打印常量指令
  27. * @param name
  28. * @param chunk
  29. * @param offset
  30. * @return
  31. */
  32. static int constantInstruction(const char *name, Chunk *chunk, int offset) {
  33. uint8_t constant = chunk->code[offset + 1];
  34. printf("%-16s %4d '", name, constant);
  35. printValue(chunk->constants.values[constant]);
  36. printf("'\n");
  37. return offset + 2;
  38. }
  39. /**
  40. * @brief 打印指令
  41. * @param name 名称
  42. * @param offset 偏移
  43. * @return
  44. */
  45. static int simpleInstruction(const char *name, int offset) {
  46. printf("%s\n", name);
  47. return offset + 1;
  48. }