forked from rui314/chibicc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
49 lines (41 loc) · 1.2 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
#include "chibi.h"
// Returns the contents of a given file.
static char *read_file(char *path) {
// Open and read the file.
FILE *fp = fopen(path, "r");
if (!fp)
error("cannot open %s: %s", path, strerror(errno));
int filemax = 10 * 1024 * 1024;
char *buf = malloc(filemax);
int size = fread(buf, 1, filemax - 2, fp);
if (!feof(fp))
error("%s: file too large");
// Make sure that the string ends with "\n\0".
if (size == 0 || buf[size - 1] != '\n')
buf[size++] = '\n';
buf[size] = '\0';
return buf;
}
int main(int argc, char **argv) {
if (argc != 2)
error("%s: invalid number of arguments", argv[0]);
// Tokenize and parse.
filename = argv[1];
user_input = read_file(argv[1]);
token = tokenize();
Program *prog = program();
// Assign offsets to local variables.
for (Function *fn = prog->fns; fn; fn = fn->next) {
int offset = fn->has_varargs ? 56 : 0;
for (VarList *vl = fn->locals; vl; vl = vl->next) {
Var *var = vl->var;
offset = align_to(offset, var->ty->align);
offset += var->ty->size;
var->offset = offset;
}
fn->stack_size = align_to(offset, 8);
}
// Traverse the AST to emit assembly.
codegen(prog);
return 0;
}