aboutsummaryrefslogtreecommitdiff
path: root/src/core.c
blob: 0ed711d31088183c784695c6a103421358561484 (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
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
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>

#include <posthaste/execute.h>
#include <posthaste/parser.h>
#include <posthaste/debug.h>
#include <posthaste/scope.h>
#include <posthaste/check.h>
#include <posthaste/lower.h>
#include <posthaste/core.h>
#include <posthaste/ast.h>

static char *read_file(const char *fname, FILE *f)
{
	fseek(f, 0, SEEK_END);
	long s = ftell(f);
	if (s == LONG_MAX) {
		/** @todo should probably do this via fstat or something */
		fprintf(stderr, "%s might be a directory", fname);
		return NULL;
	}

	fseek(f, 0, SEEK_SET);

	char *buf = malloc(s + 1);
	if (!buf)
		return NULL;

	fread(buf, s + 1, 1, f);
	/* remember terminating null */
	buf[s] = 0;
	return buf;
}

int run(const char *fname)
{
	int ret = 0;
	const char *buf = NULL;
	struct scope *scope = NULL;
	struct parser *p = NULL;

	FILE *f = fopen(fname, "rb");
	if (!f) {
		fprintf(stderr, "failed opening %s: %s\n", fname,
		        strerror(errno));
		return -1;
	}

	buf = read_file(fname, f);
	fclose(f);

	if (!buf) {
		ret = -1;
		goto out;
	}

	p = create_parser();
	if (!p) {
		ret = -1;
		goto out;
	}

	parse(p, fname, buf);
	if (p->failed) {
		ret = -1;
		goto out;
	}

	scope = create_scope();
	if (!scope) {
		ret = -1;
		goto out;
	}

	scope_set_file(scope, fname, buf);

	struct ast *ast = p->tree;
	if (check(scope, ast)) {
		ret = -1;
		goto out;
	}

	lower_ast(ast);
	execute();
out:
	free((void *)buf);
	destroy_lowering();
	destroy_scopes();
	destroy_ast_nodes();
	destroy_parser(p);
	return ret;
}