aboutsummaryrefslogtreecommitdiffstats
path: root/src/bytecode/compiler.h
blob: d7d7920181dce6e4a4ae17c3b7a510f603e62dc5 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#ifndef BDL_COMPILER_H
#define BDL_COMPILER_H

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

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

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

Chunk * compile(Token *tokens);

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

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

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

void
emit_constant(Chunk *chunk, Token tok, Object obj) {
    size_t prev_size = array_size(chunk->constants);
    size_t num_idx = add_constant(chunk, obj);
    add_code(chunk, OP_CONSTANT, tok.line, tok.column);
    add_code(chunk, num_idx, tok.line, tok.column);

    // If the non value constant was already present we need to properly free
    // the memory from the object given to this function.
    if (prev_size == array_size(chunk->constants)) {
        object_free(obj);
    }
}

size_t
emit_jump(Chunk *chunk, Token tok, Ops op, ssize_t offset) {
    add_code(chunk, op, tok.line, tok.column);
    add_code(chunk, ((u16)offset >> 8) & 0xFF, tok.line, tok.column);
    add_code(chunk, ((u16)offset) & 0xFF, tok.line, tok.column);
    return array_size(chunk->code) - 2;
}

void
patch_jump(Chunk *chunk, ssize_t offset) {
  ssize_t jump = array_size(chunk->code) - offset - 2;
  assert((u16)jump <= UINT16_MAX && "error: jump is too long");
  chunk->code[offset] = ((u16)jump >> 8) & 0xFF;
  chunk->code[offset + 1] = ((u16)jump) & 0xFF;
}

void
parse_fixnum(Chunk *chunk, Token tok) {
    ssize_t num = 0;
    int sign = 1;
    for (size_t i = 0; i < tok.value.n; i++) {
        char c = tok.value.start[i];
        if (c == '-') {
            sign = -1;
            continue;
        }
        num = num * 10 + (c - '0');
    }
    emit_constant(chunk, tok, FIXNUM_VAL(num * sign));
}

void parse_tree(Chunk *chunk, Compiler *compiler);

void
compile_list_binary_op(Chunk *chunk, Compiler *compiler, Token start, Ops op) {
    size_t n = 0;
    while (has_next_token(compiler)) {
        Token tok = peek_token(compiler);
        if (tok.type == TOKEN_EOF) {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_UNBALANCED_PAREN,
                .line = start.line,
                .col = start.column,
            });
            return;
        }
        if (tok.type == TOKEN_RPAREN) {
            next_token(compiler);
            if (n <= 1) {
                error_push((Error){
                    .type = ERR_TYPE_COMPILER,
                    .value = ERR_NOT_ENOUGH_ARGS,
                    .line = start.line,
                    .col = start.column,
                });
                return;
            }
            break;
        }
        parse_tree(chunk, compiler);
        if (tok.type == TOKEN_SYMBOL) {
            add_code(chunk, OP_GET, tok.line, tok.column);
        }
        n++;
    }
    emit_constant(chunk, start, FIXNUM_VAL(n));
    add_code(chunk, op, start.line, start.column);
}

void
compile_list_unary_op(Chunk *chunk, Compiler *compiler, Token start, Ops op) {
    size_t n = 0;
    while (has_next_token(compiler)) {
        Token tok = peek_token(compiler);
        if (tok.type == TOKEN_EOF) {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_UNBALANCED_PAREN,
                .line = start.line,
                .col = start.column,
            });
            return;
        }
        if (tok.type == TOKEN_RPAREN) {
            next_token(compiler);
            if (n == 0) {
                error_push((Error){
                    .type = ERR_TYPE_COMPILER,
                    .value = ERR_NOT_ENOUGH_ARGS,
                    .line = start.line,
                    .col = start.column,
                });
            }
            return;
        }
        parse_tree(chunk, compiler);
        if (tok.type == TOKEN_SYMBOL) {
            add_code(chunk, OP_GET, tok.line, tok.column);
        }
        add_code(chunk, op, start.line, start.column);
        n++;
        if (n > 1) {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_TOO_MANY_ARGS,
                .line = start.line,
                .col = start.column,
            });
        }
    }
    error_push((Error){
        .type = ERR_TYPE_COMPILER,
        .value = ERR_UNBALANCED_PAREN,
        .line = start.line,
        .col = start.column,
    });
}

void
compile_list_simple_op(Chunk *chunk, Compiler *compiler, Token start, Ops op) {
    if (has_next_token(compiler)) {
        Token tok = peek_token(compiler);
        if (tok.type == TOKEN_EOF) {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_UNBALANCED_PAREN,
                .line = start.line,
                .col = start.column,
            });
            return;
        }
        if (tok.type != TOKEN_RPAREN) {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_TOO_MANY_ARGS,
                .line = start.line,
                .col = start.column,
            });
            return;
        }
        next_token(compiler);
        add_code(chunk, op, start.line, start.column);
        return;
    }
    error_push((Error){
        .type = ERR_TYPE_COMPILER,
        .value = ERR_UNBALANCED_PAREN,
        .line = start.line,
        .col = start.column,
    });
}

void
compile_declare_op(Chunk *chunk, Compiler *compiler, Token start, Ops op) {
    Token name = peek_token(compiler);
    if (name.type != TOKEN_SYMBOL) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_WRONG_ARG_TYPE,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    parse_tree(chunk, compiler);
    Token expr = peek_token(compiler);
    if (name.type == TOKEN_EOF || expr.type == TOKEN_EOF) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_UNBALANCED_PAREN,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    if (name.type == TOKEN_RPAREN || expr.type == TOKEN_RPAREN) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_NOT_ENOUGH_ARGS,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    parse_tree(chunk, compiler);
    if (expr.type == TOKEN_SYMBOL) {
        add_code(chunk, OP_GET, expr.line, expr.column);
    }
    if (peek_token(compiler).type != TOKEN_RPAREN) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_TOO_MANY_ARGS,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    next_token(compiler);
    add_code(chunk, op, start.line, start.column);
}

void
compile_if_op(Chunk *chunk, Compiler *compiler, Token start) {
    Token tok = peek_token(compiler);
    if (tok.type == TOKEN_EOF) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_UNBALANCED_PAREN,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    if (tok.type == TOKEN_RPAREN) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_NOT_ENOUGH_ARGS,
            .line = start.line,
            .col = start.column,
        });
        return;
    }

    // Condition.
    parse_tree(chunk, compiler);
    size_t jmp_false = emit_jump(chunk, start, OP_JUMP_IF_FALSE, 0xFFFF);

    // True expression.
    parse_tree(chunk, compiler);

    // No second expression.
    if (peek_token(compiler).type == TOKEN_RPAREN) {
        patch_jump(chunk, jmp_false);
        next_token(compiler);
        return;
    }

    // False expression.
    size_t jmp_end = emit_jump(chunk, start, OP_JUMP, 0xFFFF);
    patch_jump(chunk, jmp_false);
    parse_tree(chunk, compiler);
    patch_jump(chunk, jmp_end);

    if (peek_token(compiler).type != TOKEN_RPAREN) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_TOO_MANY_ARGS,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    next_token(compiler);
}

void
parse_list(Chunk *chunk, Compiler *compiler, Token start) {
    if (!has_next_token(compiler)) {
        error_push((Error){
            .type = ERR_TYPE_COMPILER,
            .value = ERR_UNBALANCED_PAREN,
            .line = start.line,
            .col = start.column,
        });
        return;
    }
    Token tok = next_token(compiler);
    switch (tok.type) {
        case TOKEN_ADD: { compile_list_binary_op(chunk, compiler, start, OP_SUM); } break;
        case TOKEN_SUB: { compile_list_binary_op(chunk, compiler, start, OP_SUB); } break;
        case TOKEN_MUL: { compile_list_binary_op(chunk, compiler, start, OP_MUL); } break;
        case TOKEN_DIV: { compile_list_binary_op(chunk, compiler, start, OP_DIV); } break;
        case TOKEN_MOD: { compile_list_binary_op(chunk, compiler, start, OP_MOD); } break;
        case TOKEN_NOT: { compile_list_unary_op(chunk, compiler, start, OP_NOT); } break;
        case TOKEN_AND: { compile_list_binary_op(chunk, compiler, start, OP_AND); } break;
        case TOKEN_OR: { compile_list_binary_op(chunk, compiler, start, OP_OR); } break;
        case TOKEN_EQUAL: { compile_list_binary_op(chunk, compiler, start, OP_EQUAL); } break;
        case TOKEN_LESS: { compile_list_binary_op(chunk, compiler, start, OP_LESS); } break;
        case TOKEN_GREATER: { compile_list_binary_op(chunk, compiler, start, OP_GREATER); } break;
        case TOKEN_LESS_EQUAL: { compile_list_binary_op(chunk, compiler, start, OP_LESS_EQUAL); } break;
        case TOKEN_GREATER_EQUAL: { compile_list_binary_op(chunk, compiler, start, OP_GREATER_EQUAL); } break;
        case TOKEN_PRINT: { compile_list_unary_op(chunk, compiler, start, OP_PRINT); } break;
        case TOKEN_DISPLAY: { compile_list_unary_op(chunk, compiler, start, OP_DISPLAY); } break;
        case TOKEN_NEWLINE: { compile_list_simple_op(chunk, compiler, start, OP_NEWLINE); } break;
        case TOKEN_DEF: { compile_declare_op(chunk, compiler, start, OP_DEF); } break;
        case TOKEN_SET: { compile_declare_op(chunk, compiler, start, OP_SET); } break;
        case TOKEN_IF: { compile_if_op(chunk, compiler, start); } break;
        default: {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_OBJ_NOT_CALLABLE,
                .line = tok.line,
                .col = tok.column,
            });
        } break;
    }
}

void
parse_tree(Chunk *chunk, Compiler *compiler) {
    Token tok = next_token(compiler);
    if (errors_n != 0) {
        return;
    }
    switch (tok.type) {
        case TOKEN_FIXNUM: {
            parse_fixnum(chunk, tok);
            return ;
        } break;
        case TOKEN_TRUE: {
            emit_constant(chunk, tok, TRUE_VAL);
            return;
        } break;
        case TOKEN_FALSE: {
            emit_constant(chunk, tok, FALSE_VAL);
            return;
        } break;
        case TOKEN_RPAREN: {
            error_push((Error){
                .type = ERR_TYPE_COMPILER,
                .value = ERR_UNBALANCED_PAREN,
                .line = tok.line,
                .col = tok.column,
            });
            return;
        } break;
        case TOKEN_QUOTE: {
            // Object *base = make_pair(obj_quote, obj_nil);
            // base->cdr = make_pair(obj_nil, obj_nil);
            // push_root(base);
            // Object *next_obj = parse_tree(compiler);
            // if (next_obj == obj_err) {
            //     return obj_err;
            // }
            // base->cdr->car = next_obj;
            // return base;
            return;
        } break;
        case TOKEN_LPAREN: {
            parse_list(chunk, compiler, tok);
            return;
        } break;
        case TOKEN_STRING: {
            Object obj = make_string(tok.value);
            emit_constant(chunk, tok, obj);
            return;
        } break;
        case TOKEN_SYMBOL: {
            Object obj = make_symbol(tok.value);
            emit_constant(chunk, tok, obj);
            return;
        } break;
        case TOKEN_NIL: {
            emit_constant(chunk, tok, NIL_VAL);
            return;
        } break;
        default: {
            break;
        } break;
    }
    error_push((Error){
        .type = ERR_TYPE_COMPILER,
        .value = ERR_EOF_REACHED,
        .line = tok.line,
        .col = tok.column,
    });
    return;
}

Chunk *
compile(Token *tokens) {
    Chunk *chunk = NULL;
    chunk = chunk_init();
    Compiler compiler = (Compiler){
        .tokens = tokens,
        .current = 0,
    };
    Token start_tok = peek_token(&compiler);
    while (has_next_token(&compiler) && peek_token(&compiler).type != TOKEN_EOF) {
        parse_tree(chunk, &compiler);
    }
    add_code(chunk, OP_RETURN, start_tok.line, start_tok.column);
    return chunk;
}

#endif // BDL_COMPILER_H