-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
69 lines (53 loc) · 1.37 KB
/
main.c
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
#include "cimple.h"
static char *opt_o;
static char *input_path;
static void usage(int status) {
fprintf(stderr, "cimple [ -o <path> ] <file>\n");
exit(status);
}
static void parse_args(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--help"))
usage(0);
if (!strcmp(argv[i], "-o")) {
if (!argv[++i])
usage(1);
opt_o = argv[i];
continue;
}
if (!strncmp(argv[i], "-o", 2)) {
opt_o = argv[i] + 2;
continue;
}
if (argv[i][0] == '-' && argv[i][1] != '\0')
error("unknown argument: %s", argv[i]);
input_path = argv[i];
}
if (!input_path)
error("no input files");
}
static FILE *open_file(char *path) {
if (!path || strcmp(path, "-") == 0)
return stdout;
FILE *out = fopen(path, "w");
if (!out)
error("cannot open output file: %s: %s", path, strerror(errno));
return out;
}
static void close_file(FILE *file) {
if (file != stdout)
fclose(file);
}
int main(int argc, char **argv) {
parse_args(argc, argv);
// Tokenize and parse.
Token *tok = tokenize_file(input_path);
Obj *prog = parse(tok);
// Traverse the AST to emit assembly.
FILE *out = open_file(opt_o);
fprintf(out, ".file 1 \"%s\"\n", input_path);
codegen(prog, out);
close_file(out);
// free_tokens(tok); // the process will exit anyway (after this point)
return 0;
}