aboutsummaryrefslogtreecommitdiffstats
path: root/src/bytecode/debug.h
blob: 25ac693b9daeed9b9eadf99032be0e4a51217150 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#ifndef BDL_DEBUG_H
#define BDL_DEBUG_H

#include "chunk.h"

void disassemble_chunk(Chunk *chunk, const char *name);
size_t disassemble_instruction(Chunk *chunk, size_t offset);

void
disassemble_chunk(Chunk *chunk, const char *name) {
    printf("== %s ==\n", name);
    printf("code:\n");
    size_t offset = 0;
    while (offset < array_size(chunk->code)) {
        offset = disassemble_instruction(chunk, offset);
    }
    printf("\nconstants:\n");
    offset = 0;
    while (offset < array_size(chunk->constants)) {
        printf("\t%04ld -> ", offset);
        display(chunk->constants[offset]);
        printf("\n");
        offset++;
    }
}

size_t
disassemble_instruction(Chunk *chunk, size_t offset) {
    printf("\t%04ld ", offset);
    if (offset > 0
            && chunk->lines[offset].line == chunk->lines[offset - 1].line
            && chunk->lines[offset].col == chunk->lines[offset - 1].col) {
        printf("%4s|%-4s ", " ", " ");
    } else {
        printf("%4ld:%-4ld ", chunk->lines[offset].line, chunk->lines[offset].col);
    }
    u8 instruction = chunk->code[offset];
    switch (instruction) {
        case OP_CONSTANT: {
            u8 constant = chunk->code[offset + 1];
            printf("%-16s %4d -> ", "OP_CONSTANT", constant);
            display(chunk->constants[constant]);
            printf("\n");
            return offset + 2;
        } break;
        case OP_SUM: { printf("OP_SUM\n"); return offset + 1; } break;
        case OP_SUB: { printf("OP_SUB\n"); return offset + 1; } break;
        case OP_MUL: { printf("OP_MUL\n"); return offset + 1; } break;
        case OP_DIV: { printf("OP_DIV\n"); return offset + 1; } break;
        case OP_MOD: { printf("OP_MOD\n"); return offset + 1; } break;
        case OP_RETURN: { printf("OP_RETURN\n"); return offset + 1; } break;
        default: {
            printf("Unknown OP: %d\n", instruction);
            return offset + 1;
        } break;
    }
}

#endif // BDL_DEBUG_H