-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpp.c
74 lines (61 loc) · 1.96 KB
/
cpp.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
#include "cc.h"
Map *macros;
void directives(Vector *process_token, Vector *token_vector) {
bool newline = true;
for (int i = 0; i < token_vector->length; i++) {
Token *token = token_vector->array[i];
if (token->type == tNEWLINE) {
newline = true;
continue;
}
if (newline && token->type == tHASH) {
i++;
Token *directive = token_vector->array[i];
if (directive->type == tIDENTIFIER && strcmp(directive->identifier, "include") == 0) {
i++;
Token *header = token_vector->array[i];
if (header->type == tSTRING_LITERAL) {
char *file = header->string_value->buffer;
char *src = read_source(file);
Vector *tokens = lexical_analyze(src);
directives(process_token, tokens);
vector_pop(process_token);
continue;
} else {
while (1) {
Token *next = token_vector->array[i++];
if (next->type == tNEWLINE) break;
}
continue;
}
} else if (directive->type == tIDENTIFIER && strcmp(directive->identifier, "define") == 0) {
i++;
Token *id = token_vector->array[i++];
Vector *sequence = vector_new();
while (1) {
Token *next = token_vector->array[i];
if (next->type == tNEWLINE) break;
i++;
vector_push(sequence, next);
}
map_put(macros, id->identifier, sequence);
continue;
}
}
if (token->type == tIDENTIFIER && map_lookup(macros, token->identifier)) {
Vector *sequence = map_lookup(macros, token->identifier);
for (int j = 0; j < sequence->length; j++) {
vector_push(process_token, sequence->array[j]);
}
} else {
vector_push(process_token, token);
}
newline = false;
}
}
Vector *preprocess(Vector *token_vector) {
macros = map_new();
Vector *process_tokens = vector_new();
directives(process_tokens, token_vector);
return process_tokens;
}