-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenizer.c
556 lines (496 loc) · 15.2 KB
/
tokenizer.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#include "mimicc.h"
#include <stdlib.h>
#include <string.h>
int isSpace(char c) { return c == ' ' || c == '\n' || c == '\t'; }
static int isDigit(char c) {
c = c - '0';
return 0 <= c && c <= 9;
}
static int isHexDigit(char c) {
return isDigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F');
}
static int isAlnum(char c) {
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
c == '_')
return 1;
return 0;
}
static int hasPrefix(const char *s1, const char *s2) {
return strncmp(s1, s2, strlen(s2)) == 0;
}
static int isToken(char *p, char *op) {
return hasPrefix(p, op) && !isAlnum(p[strlen(op)]);
}
// Check character after backslash builds an escape character.
// If so, set the escape character to *decoded and returns TRUE.
int checkEscapeChar(char c, char *decoded) {
static const char table[][2] = {
{'\'', '\''},
{'"', '"'},
{'\\', '\\'},
{'?', '\?'},
{'a', '\a'},
{'b', '\b'},
{'f', '\f'},
{'n', '\n'},
{'r', '\r'},
{'t', '\t'},
{'v', '\v'},
{'0', '\0'},
};
for (int i = 0; i < (sizeof(table) / sizeof(table[0])); ++i) {
if (c == table[i][0]) {
*decoded = table[i][1];
return 1;
}
}
*decoded = c;
return 0;
}
// Remove tokens from "token" by range [begin, end].
void popTokenRange(Token *begin, Token *end) {
Token *prev = begin->prev;
Token *next = end->next;
if (!(prev && next))
errorUnreachable();
prev->next = next;
next->prev = prev;
}
// Remove all tokens whose type is TokenNewLine from "token".
void removeAllNewLineToken(Token *token) {
Token *cur = token;
while (cur->type != TokenEOF) {
if (cur->type == TokenNewLine) {
Token *next = cur->next;
popTokenRange(cur, cur);
cur = next;
} else {
cur = cur->next;
}
}
}
void printToken(Token *token) {
if (!token) {
puts("(NULL)");
return;
}
switch (token->type) {
case TokenReserved:
printf("RESERVED: %.*s\n", token->len, token->str);
break;
case TokenTypeName:
printf("TYPENAME: %.*s\n", token->len, token->str);
break;
case TokenIdent:
printf("IDENT : %.*s\n", token->len, token->str);
break;
case TokenNumber:
printf("NUMBER : %d\n", token->val);
break;
case TokenStatic:
puts("static");
break;
case TokenExtern:
puts("extern");
break;
case TokenTypedef:
puts("typedef");
break;
case TokenIf:
puts("if");
break;
case TokenElseif:
puts("else-if");
break;
case TokenElse:
puts("else");
break;
case TokenSwitch:
puts("switch");
break;
case TokenCase:
puts("case");
break;
case TokenDefault:
puts("default");
break;
case TokenFor:
puts("for");
break;
case TokenWhile:
puts("while");
break;
case TokenDo:
puts("do");
break;
case TokenBreak:
puts("break");
break;
case TokenContinue:
puts("continue");
break;
case TokenReturn:
puts("return");
break;
case TokenSizeof:
puts("sizeof");
break;
case TokenLiteralString:
printf("STRING : %s\n", token->literalStr->string);
break;
case TokenStruct:
puts("struct");
break;
case TokenEnum:
puts("enum");
break;
case TokenNewLine:
puts("NEWLINE");
break;
case TokenSOF:
puts("===START OF FILE===");
break;
case TokenEOF:
puts("===END OF FILE===");
break;
}
}
void printTokenList(Token *token) {
for (; token; token = token->next)
printToken(token);
}
#define appendNewToken(tokenType, string, length) \
do { \
current->next = (Token *)safeAlloc(sizeof(Token)); \
current->next->prev = current; \
current = current->next; \
current->type = tokenType; \
current->str = string; \
current->len = length; \
current->line = line; \
current->column = ((string) - lineHead); \
current->file = file; \
} while (0)
#define errorAtChar(pos, msg) \
do { \
appendNewToken(TokenReserved, pos, 0); \
errorAt(current, msg); \
} while (0)
Token *tokenize(char *source, FilePath *file) {
typedef struct List List;
struct List {
List *next;
char *p;
};
char *p = source;
Token head = {};
Token *current = &head;
int line = 1;
char *lineHead = p;
List *erasedNewLine = NULL;
{ // Remove line continuation ('\\' + '\n')
List erasedNewLineHead = {};
char *r, *w;
r = w = source;
erasedNewLine = &erasedNewLineHead;
while (*r != '\0') {
if (r[0] == '\\' && r[1] == '\n') {
r += 2;
erasedNewLine->next = (List *)safeAlloc(sizeof(List));
erasedNewLine = erasedNewLine->next;
erasedNewLine->p = r;
} else {
*w++ = *r++;
}
}
*w = '\0';
erasedNewLine = erasedNewLineHead.next;
}
appendNewToken(TokenSOF, p, 0);
while (*p) {
if (erasedNewLine && p >= erasedNewLine->p) {
List *tofree = erasedNewLine;
line++;
erasedNewLine = erasedNewLine->next;
safeFree(tofree);
}
if (*p == '\n') {
appendNewToken(TokenNewLine, p, 1);
++p;
++line;
lineHead = p;
continue;
}
if (isSpace(*p)) {
++p;
continue;
}
if (hasPrefix(p, "/*")) {
char *q = strstr(p + 2, "*/");
if (q == NULL)
errorAtChar(p, "Unterminated comment");
p = q + 2;
continue;
}
if (hasPrefix(p, "//")) {
p += 2;
while (*p != '\n' && *p != '\0')
++p;
continue;
}
if (isToken(p, "_Noreturn")) {
// Just ignore it now.
p += 9;
continue;
}
if (isToken(p, "void")) {
appendNewToken(TokenTypeName, p, 4);
current->varType = TypeVoid;
p += 4;
continue;
}
if (isToken(p, "int")) {
appendNewToken(TokenTypeName, p, 3);
current->varType = TypeInt;
p += 3;
continue;
}
if (isToken(p, "char")) {
appendNewToken(TokenTypeName, p, 4);
current->varType = TypeChar;
p += 4;
continue;
}
if (isToken(p, "struct")) {
appendNewToken(TokenStruct, p, 6);
p += 6;
continue;
}
if (isToken(p, "enum")) {
appendNewToken(TokenEnum, p, 4);
p += 4;
continue;
}
if (isToken(p, "const")) {
// TODO: Create new token; Take into account when parsing.
p += 5;
continue;
}
if (isToken(p, "static")) {
appendNewToken(TokenStatic, p, 6);
p += 6;
continue;
}
if (isToken(p, "extern")) {
appendNewToken(TokenExtern, p, 6);
p += 6;
continue;
}
if (isToken(p, "typedef")) {
appendNewToken(TokenTypedef, p, 7);
p += 7;
continue;
}
if (isToken(p, "if")) {
appendNewToken(TokenIf, p, 2);
p += 2;
continue;
}
if (isToken(p, "else")) {
char *q = p + 5;
while (*q && isSpace(*q))
++q;
if (isToken(q, "if")) {
q += 2;
appendNewToken(TokenElseif, p, q - p);
p = q;
} else {
appendNewToken(TokenElse, p, 4);
p += 4;
}
continue;
}
if (isToken(p, "switch")) {
appendNewToken(TokenSwitch, p, 6);
p += 6;
continue;
}
if (isToken(p, "case")) {
appendNewToken(TokenCase, p, 4);
p += 4;
continue;
}
if (isToken(p, "default")) {
appendNewToken(TokenDefault, p, 7);
p += 7;
continue;
}
if (isToken(p, "for")) {
appendNewToken(TokenFor, p, 3);
p += 3;
continue;
}
if (isToken(p, "while")) {
appendNewToken(TokenWhile, p, 5);
p += 5;
continue;
}
if (isToken(p, "do")) {
appendNewToken(TokenDo, p, 2);
p += 2;
continue;
}
if (isToken(p, "break")) {
appendNewToken(TokenBreak, p, 5);
p += 5;
continue;
}
if (isToken(p, "continue")) {
appendNewToken(TokenContinue, p, 8);
p += 8;
continue;
}
if (isToken(p, "return")) {
appendNewToken(TokenReturn, p, 6);
p += 6;
continue;
}
if (isToken(p, "sizeof")) {
appendNewToken(TokenSizeof, p, 6);
p += 6;
continue;
}
if (hasPrefix(p, "<<=") || hasPrefix(p, ">>=") || hasPrefix(p, "...")) {
appendNewToken(TokenReserved, p, 3);
p += 3;
continue;
}
if (hasPrefix(p, "==") || hasPrefix(p, "!=") || hasPrefix(p, ">=") ||
hasPrefix(p, "<=") || hasPrefix(p, "+=") || hasPrefix(p, "-=") ||
hasPrefix(p, "*=") || hasPrefix(p, "/=") || hasPrefix(p, "&=") ||
hasPrefix(p, "|=") || hasPrefix(p, "^=") || hasPrefix(p, "++") ||
hasPrefix(p, "--") || hasPrefix(p, "&&") || hasPrefix(p, "||") ||
hasPrefix(p, "<<") || hasPrefix(p, ">>") || hasPrefix(p, "->")) {
appendNewToken(TokenReserved, p, 2);
p += 2;
continue;
}
if (strchr("!+-*/%()=;[]<>{},&^|.?:#", *p)) {
appendNewToken(TokenReserved, p, 1);
p++;
continue;
}
if (isDigit(*p)) {
appendNewToken(TokenNumber, p, 0);
if (*p == '0' && (p[1] == 'x' || p[1] == 'X')) {
// Hex number
char *q = p;
int val = 0;
p += 2;
while (*p && isHexDigit(*p)) {
int d = 0;
if (isDigit(*p))
d = *p - '0';
else if ('a' <= *p && *p <= 'f')
d = *p - 'a' + 10;
else
d = *p - 'A' + 10;
val = (val << 4) | d;
p++;
}
if (p - q <= 2)
errorAtChar(p, "Invalid hex number token.");
current->val = val;
current->len = p - q;
} else if (*p == '0') {
// Octal number or zero
char *q = p++;
int val = 0;
while (*p && '0' <= *p && *p <= '7') {
// Type casting from char to int is necessary because
// mimicc doesn't have usual arithmetic conversion yet.
val = (val << 3) | (int)(*p - '0');
p++;
}
current->val = val;
current->len = p - q;
} else {
// Decimal number
char *q = p;
current->val = strtol(p, &p, 10);
current->len = p - q;
}
continue;
}
if (*p == '\'') {
char *q = p;
char c;
++p;
if (*p == '\0') {
errorAtChar(p, "Character literal is not terminated.");
} else if (*p == '\'') {
errorAtChar(q, "Empty character literal.");
} else if (*p == '\\') {
if (!checkEscapeChar(*(++p), &c)) {
errorAtChar(p - 1, "Invalid escape character.");
}
} else {
c = *p;
}
if (*(++p) != '\'') {
errorAtChar(p, "Character literal is too long.");
}
appendNewToken(TokenNumber, q, p - q + 1);
current->val = c;
p++;
continue;
}
if (*p == '"') {
char *q = p;
int literalLen = 0; // String length on text editor.
int len = 0; // String length in program.
LiteralString *str = NULL;
while (*(++p) != '\0') {
++len;
++literalLen;
if (*p == '"') {
break;
} else if (*p == '\\') {
char c;
++p;
++literalLen;
if (*p == '\0') {
--literalLen;
break;
} else if (!checkEscapeChar(*p, &c)) {
errorAtChar(p - 1, "Invalid escape character.");
}
}
}
if (*p == '\0')
errorAtChar(p - 1, "String is not terminated.");
str = (LiteralString *)safeAlloc(sizeof(LiteralString));
str->id = globals.literalStringCount++;
str->len = len;
str->string = (char *)malloc(literalLen * sizeof(char));
memcpy(str->string, q + 1, literalLen - 1);
str->string[literalLen - 1] = '\0';
str->next = globals.strings;
globals.strings = str;
appendNewToken(TokenLiteralString, q, p - q + 1);
current->literalStr = str;
p++; // Skip closing double quote.
continue;
}
if ('a' <= *p && *p <= 'z' || 'A' <= *p && *p <= 'Z' || *p == '_') {
char *q = p;
while (isAlnum(*p))
++p;
appendNewToken(TokenIdent, q, p - q);
continue;
}
errorAtChar(p, "Cannot tokenize");
}
appendNewToken(TokenEOF, p, 0);
return head.next;
}