aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: e36d91298b84da78e1dcd8b3df1ea3d148a61516 (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
#include "../include/parser.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

static char* file_get_content(const char *filepath, size_t *filesize) {
    struct stat file_stat;
    int fd = open(filepath, O_RDONLY);
    char *result = NULL;
    *filesize = 0;
    if(fd == -1) {
        perror(filepath);
        return NULL;
    }

    if(fstat(fd, &file_stat) == -1) {
        perror(filepath);
        goto cleanup;
    }

    if(!S_ISREG(file_stat.st_mode)) {
        fprintf(stderr, "Error: %s is not a file\n", filepath);
        goto cleanup;
    }

    *filesize = file_stat.st_size;
    result = malloc(*filesize + 1);
    if(!result) {
        *filesize = 0;
        fprintf(stderr, "Error: Failed to malloc %lu bytes from file %s\n", *filesize, filepath);
        goto cleanup;
    }

    result[*filesize] = '\0';
    if((size_t)read(fd, result, *filesize) != *filesize) {
        free(result);
        *filesize = 0;
        fprintf(stderr, "Error: Failed to read all data from file %s\n", filepath);
        goto cleanup;
    }

    cleanup:
    close(fd);
    return result;
}

static void usage() {
    puts("usage: tsl [file]");
}

int main(int argc, char **argv) {
    char *file_content;
    size_t filesize;
    TslProgram program;
    int result = 0;

    if(argc != 2) {
        usage();
        return 1;
    }

    file_content = file_get_content(argv[1], &filesize);
    if(!file_content)
        return 2;

    tsl_program_init(&program);

    if(!tsl_parse(file_content, filesize, &program)) {
        result = 3;
        goto cleanup;
    }

    if(!tsl_program_run(&program)) {
        result = 4;
        goto cleanup;
    }

    cleanup:
    free(file_content);
    tsl_program_deinit(&program);
    return result;
}