summaryrefslogtreecommitdiff
path: root/main.c
blob: 4cb0ba761b5b3f4182a87f4a87b2e3a50ff9f71f (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
#include "lexer.h"
#include "parser.h"
#include "codegen.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void test_lexer(int argc, char** argv) {
    struct token token;
    for (int i = 1; i < argc; i++) {
        lexer_load(argv[i]);
        while (lexer_pop(&token)) {
            printf("[%s]: ", argv[i]);
            switch (token.type) {
                case TK_IDENT:
                    printf("got identifier: %s\n", token.data.ident);
                    free(token.data.ident);
                    break;
                case TK_STR_LIT:
                    printf("got string: %s\n", token.data.str_lit);
                    free(token.data.str_lit);
                    break;
                case TK_INT_LIT:
                    printf("got int: %lld\n", token.data.int_lit);
                    break;
                case TK_FLOAT_LIT:
                    printf("got float: %lf\n", token.data.float_lit);
                    break;
                case TK_CHAR_LIT:
                    printf("got char: %c\n", token.data.char_lit);
                    break;
                default:
                    printf("got simple token: %d\n", token.type);
            }
        }
        lexer_close();
    }
}

void test_parser(int argc, char** argv) {
    for (int i = 1; i < argc; i++) {
        struct root_node* root = parse(argv[i]);
        unsigned int fn_sz = strlen(argv[i]);
        char asm_file[fn_sz + 1];
        strcpy(asm_file, argv[i]);
        asm_file[fn_sz - 1] = 's';
        asm_file[fn_sz] = 0;

        emit_code(root, asm_file);
        ast_destroy(root);

        char obj_file[fn_sz + 1];
        strcpy(obj_file, argv[i]);
        obj_file[fn_sz - 1] = 'o';
        obj_file[fn_sz] = 0;

        char cmd_buffer[2*fn_sz + 20];
        snprintf(
            cmd_buffer,
            sizeof(cmd_buffer),
            "nasm -f elf64 %s -o %s",
            asm_file,
            obj_file);
        int status = system(cmd_buffer);
        if (status != 0) exit(status);
    }
}

int main(int argc, char** argv) {
    if (argc < 2) {
        fprintf(stderr, "ccc: no input files\n");
        return 1;
    }

    test_parser(argc, argv);
}