summaryrefslogtreecommitdiff
path: root/main.c
blob: 319f94371b82ec21090a81d10265b5bcfc2988d3 (plain) (blame)
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
#include "cgen.h"
#include "lex.h"
#include "parse.h"
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    struct lex l = {0};
    struct ast p = {0};
    struct cgen c = {0};
    FILE *f = stdin;
    int opened = 0, ret = EXIT_FAILURE;

    if (argc != 2)
    {
        fprintf(stderr, "%s: error: missing input file\n", *argv);
        goto end;
    }
    else if (strcmp(argv[1], "-"))
    {
        if (!(f = fopen(argv[1], "rb")))
        {
            fprintf(stderr, "failed to open %s: %s\n", argv[1],
                strerror(errno));
            goto end;
        }

        opened = 1;
        l.loc.f = argv[1];
    }
    else
        l.loc.f = "stdin";

    if (lex(&l, f) || parse(&l, &p) || cgen(&p, &c))
        goto end;

    ret = EXIT_SUCCESS;

end:
    if (opened && fclose(f))
    {
        perror("fclose(3)");
        ret = EXIT_FAILURE;
    }

    lex_free(&l);
    ast_free(&p);
    cgen_free(&c);
    return ret;
}