forked from keyvank/30cc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
118 lines (106 loc) · 2.69 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
112
113
114
115
116
117
118
#include "libc.h"
#include "lexer.h"
#include "parser/program.h"
#include "linked_list.h"
#include "preprocess/preprocess.h"
#include "preprocess/macro_define.h"
typed_token *process(char *filename, int log_lex, int log_prep)
{
prep_ctx *ctx = (prep_ctx *)malloc(sizeof(prep_ctx));
ctx->curr_path = NULL;
ctx->defs = new_linked_list();
seg_define *_30cc_define = (seg_define *)malloc(sizeof(seg_define));
_30cc_define->arg_names = new_linked_list();
_30cc_define->id = "_30CC";
_30cc_define->replace = new_linked_list();
add_to_list(ctx->defs, _30cc_define);
typed_token *lexed = tokenize_file(filename);
if (log_lex)
{
typed_token *t = lexed;
while (t)
{
t->debug(t);
t = t->next;
}
}
typed_token *prep = preprocess(ctx, filename);
if (log_prep)
{
typed_token *t = prep;
while (t)
{
t->debug(t);
t = t->next;
}
}
return prep;
}
int main(int argc, char **argv)
{
if (argc == 2)
{
if (strcmp(argv[1], "-v") == 0)
{
#ifdef _30CC
char *compiler = "30cc";
#endif
#ifndef _30CC
char *compiler = "gcc";
#endif
printf("30cc compiler version 0.1.0 (Compiled with %s)\n", compiler);
return 0;
}
}
if (argc != 3)
{
fprintf(stderr, "Usage: %s <filename> <mode> (<mode>: --lex, --prep, --asm or --tree)\n", argv[0]);
return 1;
}
if (strcmp(argv[2], "--lex") != 0 && strcmp(argv[2], "--asm") != 0 && strcmp(argv[2], "--tree") != 0 && strcmp(argv[2], "--prep") != 0)
{
fprintf(stderr, "Unknown argument %s", argv[2]);
return 1;
}
int log_lex = !strcmp(argv[2], "--lex");
int log_prep = !strcmp(argv[2], "--prep");
typed_token *tkn = process(argv[1], log_lex, log_prep);
if (tkn == NULL)
{
return 1;
}
parser_node *prog = parse_program(&tkn);
if (prog)
{
if (strcmp(argv[2], "--tree") == 0)
{
prog->debug(0, prog);
return 0;
}
}
else
{
fprintf(stderr, "Parse failed!\n");
return 1;
}
if (strcmp(argv[2], "--asm") == 0)
{
context *ctx = new_context();
prog->apply(prog, ctx);
list_node *curr = ctx->data->first;
printf("section .data\n");
while (curr)
{
printf("%s\n", (char *)curr->value);
curr = curr->next;
}
printf("section .text\n");
curr = ctx->text->first;
while (curr)
{
printf("%s\n", (char *)curr->value);
curr = curr->next;
}
}
return 0;
}