aboutsummaryrefslogtreecommitdiffstats
path: root/src/bytecode/debug.h
blob: dc0585bd2cc7fcc4bdf1d89b20caf0396e23122d (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#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);

static const char* ops_str[] = {
    // Load/store ops.
    [OP_CONSTANT] = "OP_CONSTANT",
    [OP_DEF] = "OP_DEF",
    [OP_GET_GLOBAL] = "OP_GET_GLOBAL",
    // Arithmetic ops.
    [OP_SUM] = "OP_SUM",
    [OP_SUB] = "OP_SUB",
    [OP_MUL] = "OP_MUL",
    [OP_DIV] = "OP_DIV",
    [OP_MOD] = "OP_MOD",
    // Logic ops.
    [OP_NOT] = "OP_NOT",
    [OP_AND] = "OP_AND",
    [OP_OR] = "OP_OR",
    // Numerical comparison ops.
    [OP_EQUAL] = "OP_EQUAL",
    [OP_LESS] = "OP_LESS",
    [OP_GREATER] = "OP_GREATER",
    [OP_LESS_EQUAL] = "OP_LESS_EQUAL",
    [OP_GREATER_EQUAL] = "OP_GREATER_EQUAL",
    // Display ops.
    [OP_DISPLAY] = "OP_DISPLAY",
    [OP_PRINT] = "OP_PRINT",
    [OP_NEWLINE] = "OP_NEWLINE",
    // Return.
    [OP_RETURN] = "OP_RETURN",
};

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%03ld -> ", 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;
        default: {
            printf("%s\n", ops_str[instruction]);
            return offset + 1;
        } break;
    }
}

#endif // BDL_DEBUG_H