aboutsummaryrefslogtreecommitdiffstats
path: root/src/bytecode/compiler.h
blob: 6991a86aa64e4f62af40a0966132484ce9b24ebb (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
#ifndef BDL_COMPILER_H
#define BDL_COMPILER_H

#include "chunk.h"
#include "lexer.h"

typedef struct Visitor {
    Token *tokens;
    size_t current;
} Visitor;

// Mimics the functionality in the Scanner functions, but for entire tokens.
Token next_token(Visitor *visitor);
Token peek_token(const Visitor *visitor);
bool has_next_token(const Visitor *visitor);

Chunk * compile(Token *tokens);

Token
peek_token(const Visitor *visitor) {
    return visitor->tokens[visitor->current];
}

Token
next_token(Visitor *visitor) {
    return visitor->tokens[visitor->current++];
}

bool
has_next_token(const Visitor *visitor) {
    return visitor->current < array_size(visitor->tokens);
}

Chunk *
compile(Token *tokens) {
    Chunk *chunk = NULL;
    chunk = chunk_init();
    // error_push((Error){
    //     .type = ERR_TYPE_COMPILER,
    //     .value = ERR_UNKNOWN,
    // });
    size_t const_a = add_constant(chunk, 7);
    add_code(chunk, OP_CONSTANT, 1, 1);
    add_code(chunk, const_a, 1, 1);
    size_t const_b = add_constant(chunk, 2);
    add_code(chunk, OP_CONSTANT, 1, 2);
    add_code(chunk, const_b, 1, 2);
    add_code(chunk, OP_MOD, 1, 3);
    add_code(chunk, OP_RETURN, 1, 1);
    return chunk;
}

#endif // BDL_COMPILER_H