debug.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 STARTING ==\n", name);
  11. for (int offset = 0; offset < chunk->count;) {
  12. offset = disassembleInstruction(chunk, offset);
  13. }
  14. printf("== %s END ==\n", name);
  15. }
  16. int disassembleInstruction(Chunk *chunk, int offset) {
  17. printf("%04d ", offset);
  18. if (offset > 0 && chunk->lines[offset] == chunk->lines[offset - 1]) {
  19. printf(" | ");
  20. } else {
  21. printf("%4d ", chunk->lines[offset]);
  22. }
  23. uint8_t instruction = chunk->code[offset];
  24. switch (instruction) {
  25. case OP_CONSTANT: return constantInstruction("OP_CONSTANT", chunk, offset);
  26. case OP_ADD: return simpleInstruction("OP_ADD", offset);
  27. case OP_SUBTRACT: return simpleInstruction("OP_SUBTRACT", offset);
  28. case OP_MULTIPLY: return simpleInstruction("OP_MULTIPLY", offset);
  29. case OP_DIVIDE: return simpleInstruction("OP_DIVIDE", offset);
  30. case OP_NEGATE: return simpleInstruction("OP_NEGATE", offset);
  31. case OP_RETURN: return simpleInstruction("OP_RETURN", offset);
  32. default:printf("Unknown opcode %d\n", instruction);
  33. return offset + 1;
  34. }
  35. }
  36. /**
  37. * @brief 打印常量指令
  38. * @param name
  39. * @param chunk
  40. * @param offset
  41. * @return
  42. */
  43. static int constantInstruction(const char *name, Chunk *chunk, int offset) {
  44. uint8_t constant = chunk->code[offset + 1];
  45. printf("%-16s %4d '", name, constant);
  46. printValue(chunk->constants.values[constant]);
  47. printf("'\n");
  48. return offset + 2;
  49. }
  50. /**
  51. * @brief 打印指令
  52. * @param name 名称
  53. * @param offset 偏移
  54. * @return
  55. */
  56. static int simpleInstruction(const char *name, int offset) {
  57. printf("%s\n", name);
  58. return offset + 1;
  59. }