debug.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. if (offset > 0 &&
  18. 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_RETURN:return simpleInstruction("OP_RETURN", offset);
  27. default:printf("Unknown opcode %d\n", instruction);
  28. return offset + 1;
  29. }
  30. }
  31. /**
  32. * @brief 打印常量指令
  33. * @param name
  34. * @param chunk
  35. * @param offset
  36. * @return
  37. */
  38. static int constantInstruction(const char *name, Chunk *chunk, int offset) {
  39. uint8_t constant = chunk->code[offset + 1];
  40. printf("%-16s %4d '", name, constant);
  41. printValue(chunk->constants.values[constant]);
  42. printf("'\n");
  43. return offset + 2;
  44. }
  45. /**
  46. * @brief 打印指令
  47. * @param name 名称
  48. * @param offset 偏移
  49. * @return
  50. */
  51. static int simpleInstruction(const char *name, int offset) {
  52. printf("%s\n", name);
  53. return offset + 1;
  54. }