-
Notifications
You must be signed in to change notification settings - Fork 65
/
main.c
111 lines (99 loc) · 2.33 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "mzcc.h"
static char *outfile = NULL, *infile = NULL;
extern FILE *outfp;
static bool dump_ast;
static void usage()
{
fprintf(stdout,
"mzcc [options] filename\n"
"OPTIONS\n"
" -o filename Write output to the specified file.\n"
" --dump-ast Dump abstract syntax tree(AST)\n");
}
static void print_usage_and_exit()
{
usage();
exit(1);
}
static void parse_args(int argc, char **argv)
{
if (argc < 2) {
print_usage_and_exit();
}
while (true) {
argc--;
argv++;
if (!argc) {
break;
}
if ((*argv)[0] == '-') {
switch ((*argv)[1]) {
case '\0':
infile = "/dev/stdin";
break;
case 'o':
argc--;
argv++;
outfile = *argv;
break;
case '-':
if (!strcmp(*argv, "--dump-ast")) {
dump_ast = true;
break;
}
default:
print_usage_and_exit();
}
} else {
if (infile) {
// The second non-option argument is not what we expect.
print_usage_and_exit();
}
infile = argv[0];
}
}
}
static void open_output_file()
{
if (outfile) {
if (!(outfp = fopen(outfile, "w"))) {
printf("Can not open file %s\n", outfile);
exit(1);
}
} else {
outfp = stdout;
}
}
static void open_input_file()
{
if (!infile) {
printf("Input file is not specified\n\n");
print_usage_and_exit();
}
if (!freopen(infile, "r", stdin)) {
printf("Can not open file %s\n", infile);
exit(1);
}
}
int main(int argc, char **argv)
{
parse_args(argc, argv);
open_input_file();
open_output_file();
List *toplevels = read_toplevels();
if (!dump_ast)
emit_data_section();
for (Iter i = list_iter(toplevels); !iter_end(i);) {
Ast *v = iter_next(&i);
if (dump_ast)
printf("%s", ast_to_string(v));
else
emit_toplevel(v);
}
list_free(cstrings);
list_free(ctypes);
return 0;
}