aboutsummaryrefslogtreecommitdiffstats
path: root/src/compiler.h
blob: 64e6df9cb216676f0f1fb18496c6983590376dd3 (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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#ifndef BDL_COMPILER_H
#define BDL_COMPILER_H

#define PRELUDE_FILE "src/x86_64/prelude.asm"
#define POSTLUDE_FILE "src/x86_64/postlude.asm"

#define HEAP_SIZE   MB(32)

typedef struct Constant {
    Object *obj;
    char *label;
} Constant;

static Constant *constants = NULL;
static char **labels = NULL;
static char **procedures = NULL;

static char* current_context = NULL;
#define context_printf(fmt, ...) \
do { \
    char buf[KB(4)]; \
    int n_chars = sprintf(buf, fmt, ##__VA_ARGS__); \
    array_insert(current_context, buf, n_chars); \
} while(false);


// TODO: Separate c/h files
// TODO: Create a "driver.c" file with the (display) function for external
// linkage or assembly inlining.

// Immediate constants.
#define NIL_VAL      47LU
#define BOOL_MASK    127LU
#define BOOL_TAG     31LU
#define BOOL_SHIFT   7LU
#define TRUE_VAL     ((1 << BOOL_SHIFT) | BOOL_TAG)
#define FALSE_VAL    ((0 << BOOL_SHIFT) | BOOL_TAG)
#define FIXNUM_MASK  3LU
#define FIXNUM_TAG   0LU
#define FIXNUM_SHIFT 2LU

// Heap allocated objects.
#define STRING_INV_MASK  ~7LU
#define STRING_MASK  7LU
#define STRING_TAG   3LU
#define PAIR_MASK    7LU
#define PAIR_TAG     1LU

void compile_object(Object *obj);
void compile_fixnum(Object *obj);
void compile_proc_call(Object *obj);
void compile(Root *roots);

char *
generate_label(char *prefix) {
    static size_t label_counter = 0;
    char buf[32];
    sprintf(buf, "%s%zu", prefix, label_counter++);
    size_t len = strlen(buf);
    char * ret = malloc(len + 1);
    memcpy(ret, buf, len);
    ret[len] = 0;
    array_push(labels, ret);
    return ret;
}

void
emit_file(char *file_name) {
    FILE *file = fopen(file_name, "r");
    if (!file) {
        fprintf(stderr, "error: couldn't open input file: %s\n", file_name);
        exit(EXIT_FAILURE);
    }
    char buf[1024];
    size_t n = 0;
    while ((n = fread(&buf, 1, 1024, file)) > 0) {
        fwrite(buf, 1, n, stdout);
    }
}

void
compile_fixnum(Object *obj) {
    context_printf("    ;; --> compile_fixnum\n");
    context_printf("    mov     rax, %zu\n", (obj->fixnum << FIXNUM_SHIFT) | FIXNUM_TAG);
    context_printf("    push    rax\n");
    context_printf("    ;; <-- compile_fixnum\n");
}

void
compile_boolean(Object *obj) {
    context_printf("    ;; --> compile_boolean\n");
    int is_true = obj->type == OBJ_TYPE_TRUE;
    context_printf("    mov     rax, %zu\n", (is_true << BOOL_SHIFT) | BOOL_TAG);
    context_printf("    push    rax\n");
    context_printf("    ;; <-- compile_boolean\n");
}

void
compile_nil(void) {
    context_printf("    ;; --> compile_nil\n");
    context_printf("    mov     rax, NIL_VAL\n");
    context_printf("    push    rax\n");
    context_printf("    ;; <-- compile_nil\n");
}

typedef enum OpType {
    // Arithmetic.
    OP_ADD,
    OP_SUB,
    OP_MUL,
    OP_DIV,
    OP_MOD,
    // Type predicates.
    OP_IS_NIL,
    OP_IS_ZERO,
    OP_IS_BOOL,
    OP_IS_FIXNUM,
    // Logic operations.
    OP_EQUAL,
    OP_GREATER,
    OP_LESS,
    OP_GREATER_EQ,
    OP_LESS_EQ,
} OpType;

void
compile_type_predicate(OpType op, Object* args) {
    context_printf("    ;; --> compile_type_predicate\n");
    compile_object(args->head);
    context_printf("    pop     rax\n");
    switch (op) {
        case OP_IS_NIL: {
            context_printf("    cmp     rax, NIL_VAL\n");
        } break;
        case OP_IS_ZERO: {
            context_printf("    cmp     rax, 0\n");
        } break;
        case OP_IS_BOOL: {
            context_printf("    and     rax, BOOL_MASK\n");
            context_printf("    cmp     rax, BOOL_TAG\n");
        } break;
        case OP_IS_FIXNUM: {
            context_printf("    and     rax, FIXNUM_MASK\n");
            context_printf("    cmp     rax, FIXNUM_TAG\n");
        } break;
        default: break;
    }
    context_printf("    mov     rax, 0\n");
    context_printf("    sete    al\n");
    context_printf("    shl     rax, BOOL_SHIFT\n");
    context_printf("    or      rax, BOOL_TAG\n");
    context_printf("    push    rax\n");
    context_printf("    ;; <-- compile_type_predicate\n");
}

void
compile_not(Object* args) {
    context_printf("    ;; --> compile_not\n");
    compile_object(args->head);
    context_printf("    pop     rax\n");
    context_printf("    cmp     rax, FALSE_VAL\n");
    context_printf("    mov     rax, 0\n");
    context_printf("    sete    al\n");
    context_printf("    shl     rax, BOOL_SHIFT\n");
    context_printf("    or      rax, BOOL_TAG\n");
    context_printf("    push    rax\n");
    context_printf("    ;; <-- compile_not\n");
}

void
compile_and(Object *args) {
    context_printf("    ;; --> compile_and\n");
    char *lab_false = generate_label("BDLL");
    char *lab_exit = generate_label("BDLL");
    while (args != NULL) {
        compile_object(args->head);
        args = args->tail;
        context_printf("    pop     rax\n");
        context_printf("    cmp     rax, FALSE_VAL\n");
        context_printf("    je      %s\n", lab_false);
    }
    context_printf("    mov     rax, TRUE_VAL\n");
    context_printf("    push    rax\n");
    context_printf("    jmp     %s\n", lab_exit);
    context_printf("%s:\n", lab_false);
    context_printf("    mov     rax, FALSE_VAL\n");
    context_printf("    push    rax\n");
    context_printf("%s:\n", lab_exit);
    context_printf("    ;; <-- compile_and\n");
}

void
compile_or(Object *args) {
    context_printf("    ;; --> compile_or\n");
    char *lab_true = generate_label("BDLL");
    char *lab_exit = generate_label("BDLL");
    while (args != NULL) {
        compile_object(args->head);
        args = args->tail;
        context_printf("    pop     rax\n");
        context_printf("    cmp     rax, FALSE_VAL\n");
        context_printf("    jne     %s\n", lab_true);
    }
    context_printf("    mov     rax, FALSE_VAL\n");
    context_printf("    push    rax\n");
    context_printf("    jmp     %s\n", lab_exit);
    context_printf("%s:\n", lab_true);
    context_printf("    mov     rax, TRUE_VAL\n");
    context_printf("    push    rax\n");
    context_printf("%s:\n", lab_exit);
    context_printf("    ;; <-- compile_or\n");
}

void
compile_cmp_list(OpType op, Object* args) {
    context_printf("    ;; --> compile_cmp_list\n");
    compile_object(args->head);
    char *lab_false = generate_label("BDLL");
    char *lab_exit = generate_label("BDLL");
    args = args->tail;
    while (args != NULL) {
        compile_object(args->head);
        args = args->tail;

        // Current value.
        context_printf("    pop     rcx\n");

        // Previous value.
        context_printf("    pop     rax\n");

        // Comparison.
        context_printf("    cmp     rax, rcx\n");
        switch (op) {
            case OP_EQUAL:      { context_printf("    jne     %s\n", lab_false); } break;
            case OP_GREATER:    { context_printf("    jle     %s\n", lab_false); } break;
            case OP_LESS:       { context_printf("    jge     %s\n", lab_false); } break;
            case OP_GREATER_EQ: { context_printf("    jl      %s\n", lab_false); } break;
            case OP_LESS_EQ:    { context_printf("    jg      %s\n", lab_false); } break;
            default: break;
        }
        context_printf("    push    rcx\n");
    }
    context_printf("    pop     rcx\n");
    context_printf("    mov     rax, TRUE_VAL\n");
    context_printf("    push    rax\n");
    context_printf("    jmp     %s\n", lab_exit);
    context_printf("%s:\n", lab_false);
    context_printf("    mov     rax, FALSE_VAL\n");
    context_printf("    push    rax\n");
    context_printf("%s:\n", lab_exit);
    context_printf("    ;; <-- compile_cmp_list\n");
}

void
compile_arithmetic_list(OpType op, Object* args) {
    context_printf("    ;; --> compile_arithmetic\n");
    compile_object(args->head);
    args = args->tail;
    while (args != NULL) {
        compile_object(args->head);
        args = args->tail;
        context_printf("    pop     rcx\n");
        context_printf("    pop     rax\n");
        switch (op) {
            case OP_ADD: { context_printf("    add     rax, rcx\n"); } break;
            case OP_SUB: { context_printf("    sub     rax, rcx\n"); } break;
            case OP_MUL: {
                context_printf("    sar     rax, FIXNUM_SHIFT\n");
                context_printf("    sar     rcx, FIXNUM_SHIFT\n");
                context_printf("    mul     rcx\n");
                context_printf("    shl     rax, FIXNUM_SHIFT\n");
            } break;
            case OP_DIV: {
                context_printf("    sar     rax, FIXNUM_SHIFT\n");
                context_printf("    sar     rcx, FIXNUM_SHIFT\n");
                context_printf("    mov     rdx, 0\n");
                context_printf("    div     rcx\n");
                context_printf("    shl     rax, FIXNUM_SHIFT\n");
            } break;
            case OP_MOD: {
                context_printf("    sar     rax, FIXNUM_SHIFT\n");
                context_printf("    sar     rcx, FIXNUM_SHIFT\n");
                context_printf("    mov     rdx, 0\n");
                context_printf("    div     rcx\n");
                context_printf("    mov     rax, rdx\n");
                context_printf("    shl     rax, FIXNUM_SHIFT\n");
            } break;
            default: break;
        }
        context_printf("    push    rax\n");
    }
    context_printf("    ;; <-- compile_arithmetic\n");
}

void
compile_cons(Object *obj) {
    context_printf("    ;; --> compile_cons\n");
    // Store objects into the car and cdr.
    compile_object(obj->head);
    compile_object(obj->tail->head);
    context_printf("    pop     rdx\n");
    context_printf("    pop     rax\n");
    context_printf("    mov     [r15], rax\n");
    context_printf("    mov     [r15 + 8], rdx\n");

    // Push memory address of cons cell.
    context_printf("    mov     rax, r15\n");
    context_printf("    or      rax, %zu\n", PAIR_TAG);
    context_printf("    push    rax\n");

    // Bump allocation register.
    context_printf("    add     r15, 16\n");
    context_printf("    ;; <-- compile_cons\n");
}

void
compile_car(Object *obj) {
    context_printf("    ;; --> compile_car\n");
    compile_object(obj->head);
    context_printf("    pop     rax\n");
    context_printf("    and     rax, %zu\n", ~PAIR_MASK);
    context_printf("    mov     rdx, [rax]\n");
    context_printf("    push    rdx\n");
    context_printf("    ;; <-- compile_car\n");
}

void
compile_cdr(Object *obj) {
    context_printf("    ;; --> compile_cdr\n");
    compile_object(obj->head);
    context_printf("    pop     rax\n");
    context_printf("    and     rax, %zu\n", ~PAIR_MASK);
    context_printf("    mov     rdx, [rax + 8]\n");
    context_printf("    push    rdx\n");
    context_printf("    ;; <-- compile_cdr\n");
}

void
compile_proc_call(Object *obj) {
    // TODO: Probably we want to use a hash table for these lookups that is
    // initialized at the start of the compilation procedure.
    if (sv_equal(&obj->head->text, &STRING("+"))) {
        compile_arithmetic_list(OP_ADD, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("-"))) {
        compile_arithmetic_list(OP_SUB, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("*"))) {
        compile_arithmetic_list(OP_MUL, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("/"))) {
        compile_arithmetic_list(OP_DIV, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("%"))) {
        compile_arithmetic_list(OP_MOD, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("nil?"))) {
        compile_type_predicate(OP_IS_NIL, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("zero?"))) {
        compile_type_predicate(OP_IS_ZERO, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("fixnum?"))) {
        compile_type_predicate(OP_IS_FIXNUM, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("bool?"))) {
        compile_type_predicate(OP_IS_BOOL, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("display"))) {
        compile_object(obj->tail->head);
        context_printf("    pop     rdi\n");
        context_printf("    call    display\n");
    } else if (sv_equal(&obj->head->text, &STRING("not"))) {
        compile_not(obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("and"))) {
        compile_and(obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("or"))) {
        compile_or(obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("="))) {
        compile_cmp_list(OP_EQUAL, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING(">"))) {
        compile_cmp_list(OP_GREATER, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("<"))) {
        compile_cmp_list(OP_LESS, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING(">="))) {
        compile_cmp_list(OP_GREATER_EQ, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("<="))) {
        compile_cmp_list(OP_LESS_EQ, obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("cons"))) {
        compile_cons(obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("car"))) {
        compile_car(obj->tail);
    } else if (sv_equal(&obj->head->text, &STRING("cdr"))) {
        compile_cdr(obj->tail);
    } else {
        fprintf(stderr, "error: not implemented\n");
        exit(EXIT_FAILURE);
    }
}

void
compile_if(Object *obj) {
    char *lab_false = generate_label("BDLL");
    compile_object(obj->condition);
    context_printf("    pop     rax\n");
    context_printf("    cmp     rax, FALSE_VAL\n");
    context_printf("    je      %s\n", lab_false);
    compile_object(obj->expr_true);
    if (obj->expr_false != NULL) {
        char *lab_exit = generate_label("BDLL");
        context_printf("    jmp     %s\n", lab_exit);
        context_printf("%s:\n", lab_false);
        compile_object(obj->expr_false);
        context_printf("%s:\n", lab_exit);
    } else {
        context_printf("%s:\n", lab_false);
    }
}

void
compile_string(Object *obj) {
    context_printf("    ;; --> compile_string\n");
    Constant c;

    // Check if the string is already stored as a constant.
    ssize_t idx = -1;
    for (size_t i = 0; i < array_size(constants); i++) {
        c = constants[i];
        if (object_equal(c.obj, obj)) {
            idx = i;
            break;
        }
    }
    if (idx < 0) {
        idx = array_size(constants);
        c = (Constant){
            .obj = obj,
            .label = generate_label("BDLC"),
        };
        array_push(constants, c);
    }

    // Create a tagged pointer to the label.
    context_printf("    mov     rax, %s\n", c.label);
    context_printf("    or      rax, STRING_TAG\n");
    context_printf("    push    rax\n");
    context_printf("    ;; <-- compile_string\n");
}

void
compile_lambda(Object *obj) {
    // Create a new compilation context.
    char *prev_context = current_context;
    current_context = NULL;
    array_init(current_context, 0);

    char *name = generate_label("BDLP");
    context_printf("%s:\n", name);
    for (size_t i = 0; i < array_size(obj->body); i++) {
        compile_object(obj->body[i]);
    }
    context_printf("    ret\n");
    context_printf("\n");

    // Restore previous compilation context.
    array_push(procedures, current_context);
    current_context = prev_context;

    // TODO: Create tagged pointer with this lambda procedure.
    // TODO: Push compiled object to the stack.
}

void
compile_object(Object *obj) {
    switch (obj->type) {
        case OBJ_TYPE_NIL: { compile_nil(); } break;
        case OBJ_TYPE_TRUE:
        case OBJ_TYPE_FALSE: { compile_boolean(obj); } break;
        case OBJ_TYPE_FIXNUM: { compile_fixnum(obj); } break;
        case OBJ_TYPE_PAIR: { compile_proc_call(obj); } break;
        case OBJ_TYPE_STRING: { compile_string(obj); } break;
        case OBJ_TYPE_IF: { compile_if(obj); } break;
        case OBJ_TYPE_LAMBDA: { compile_lambda(obj); } break;
        default: break;
    }
}

void
emit_bss_section(void) {
    printf("section .bss\n");
    printf("bdl_heap:\n");
    printf("    resb    HEAP_SIZE\n");
    printf("\n");
}

void
emit_data_section(void) {
    printf("section .data\n");
    printf("true_str: db \"true\", 10, 0, 0, 0\n");
    printf("false_str: db \"false\", 10, 0, 0\n");
    for (size_t i = 0; i < array_size(constants); i++) {
        // NOTE: Only supporting string constants for now.
        Constant c = constants[i];
        int n = c.obj->text.n;
        // TODO: escape characters maybe?
        // TODO: quote all strings maybe?
        printf("%s:\n", c.label);
        printf("    dq %d\n", n + 1);
        printf("    db \"%.*s\", 10\n", n, c.obj->text.start);
        // Ensure alignment to 8 bytes.
        int remainder = (n + 1) % 8;
        if (remainder != 0) {
            printf("    times %d db 0\n", 8 - (n + 1) % 8);
        }
    }
    printf("\n");
}

void
compile(Root *roots) {
    // Prepare compilation variables.
    array_init(constants, 0);
    array_init(labels, 0);
    array_init(procedures, 0);
    array_init(current_context, 0);

    // Compile program.
    for (size_t i = 0; i < array_size(roots); i++) {
        Object *root = roots[i];
        compile_object(root);
    }

    // Base defines.
    printf("%%define NIL_VAL      %zu\n", NIL_VAL);
    printf("%%define TRUE_VAL     %zu\n", TRUE_VAL);
    printf("%%define FALSE_VAL    %zu\n", FALSE_VAL);
    printf("%%define BOOL_MASK    %zu\n", BOOL_MASK);
    printf("%%define BOOL_TAG     %zu\n", BOOL_TAG);
    printf("%%define BOOL_SHIFT   %zu\n", BOOL_SHIFT);
    printf("%%define FIXNUM_MASK  %zu\n", FIXNUM_MASK);
    printf("%%define FIXNUM_TAG   %zu\n", FIXNUM_TAG);
    printf("%%define FIXNUM_SHIFT %zu\n", FIXNUM_SHIFT);
    printf("%%define PAIR_MASK    %zu\n", PAIR_MASK);
    printf("%%define PAIR_TAG     %zu\n", PAIR_TAG);
    printf("%%define STRING_INV_MASK  %zu\n", STRING_INV_MASK);
    printf("%%define STRING_MASK  %zu\n", STRING_MASK);
    printf("%%define STRING_TAG   %zu\n", STRING_TAG);
    printf("%%define HEAP_SIZE    %zu\n", HEAP_SIZE);
    printf("\n");

    // Prelude.
    emit_file(PRELUDE_FILE);
    printf("\n");

    // Function definitions.
    for (size_t i = 0; i < array_size(procedures); i++) {
        char *ctx = procedures[i];
        for (size_t i = 0; i < array_size(ctx); i++) {
            putchar(ctx[i]);
        }
    }

    // Main context.
    printf("global _start\n");
    printf("_start:\n");
    printf("    mov     r15, bdl_heap\n");
    printf("    push    NIL_VAL\n");
    for (size_t i = 0; i < array_size(current_context); i++) {
        putchar(current_context[i]);
    }

    // Postlude.
    emit_file(POSTLUDE_FILE);
    emit_data_section();
    emit_bss_section();

    // Clean resources.
    array_free(constants);
    for (size_t i = 0; i < array_size(labels); i++) {
        free(labels[i]);
    }
    array_free(labels);
    for (size_t i = 0; i < array_size(procedures); i++) {
        array_free(procedures[i]);
    }
    array_free(procedures);
}

#endif // BDL_COMPILER_H