-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.c
409 lines (385 loc) · 11.1 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
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
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/*
For the language grammar, please refer to Grammar section on the github page:
https://github.com/lightbulb12294/CSI2P-II-Mini1#grammar
*/
#define MAX_LENGTH 200
typedef enum {
ASSIGN, ADD, SUB, MUL, DIV, REM, PREINC, PREDEC, POSTINC, POSTDEC, IDENTIFIER, CONSTANT, LPAR, RPAR, PLUS, MINUS, END
} Kind;
typedef enum {
STMT, EXPR, ASSIGN_EXPR, ADD_EXPR, MUL_EXPR, UNARY_EXPR, POSTFIX_EXPR, PRI_EXPR
} GrammarState;
typedef struct TokenUnit {
Kind kind;
int val; // record the integer value or variable name
struct TokenUnit *next;
} Token;
typedef struct ASTUnit {
Kind kind;
int val; // record the integer value or variable name
struct ASTUnit *lhs, *mid, *rhs;
} AST;
/// utility interfaces
// err marco should be used when a expression error occurs.
#define err(x) {\
puts("Compile Error!");\
if(DEBUG) {\
fprintf(stderr, "Error at line: %d\n", __LINE__);\
fprintf(stderr, "Error message: %s\n", x);\
}\
exit(0);\
}
// You may set DEBUG=1 to debug. Remember setting back to 0 before submit.
#define DEBUG 0
// Split the input char array into token linked list.
Token *lexer(const char *in);
// Create a new token.
Token *new_token(Kind kind, int val);
// Translate a token linked list into array, return its length.
size_t token_list_to_arr(Token **head);
// Parse the token array. Return the constructed AST.
AST *parser(Token *arr, size_t len);
// Parse the token array. Return the constructed AST.
AST *parse(Token *arr, int l, int r, GrammarState S);
// Create a new AST node.
AST *new_AST(Kind kind, int val);
// Find the location of next token that fits the condition(cond). Return -1 if not found. Search direction from start to end.
int findNextSection(Token *arr, int start, int end, int (*cond)(Kind));
// Return 1 if kind is ASSIGN.
int condASSIGN(Kind kind);
// Return 1 if kind is ADD or SUB.
int condADD(Kind kind);
// Return 1 if kind is MUL, DIV, or REM.
int condMUL(Kind kind);
// Return 1 if kind is RPAR.
int condRPAR(Kind kind);
// Check if the AST is semantically right. This function will call err() automatically if check failed.
void semantic_check(AST *now);
// Generate ASM code.
void codegen(AST *root);
// Free the whole AST.
void freeAST(AST *now);
/// debug interfaces
// Print token array.
void token_print(Token *in, size_t len);
// Print AST tree.
void AST_print(AST *head);
char input[MAX_LENGTH];
int main() {
while (fgets(input, MAX_LENGTH, stdin) != NULL) {
Token *content = lexer(input);
size_t len = token_list_to_arr(&content);
if (len == 0) continue;
AST *ast_root = parser(content, len);
semantic_check(ast_root);
codegen(ast_root);
free(content);
freeAST(ast_root);
}
return 0;
}
Token *lexer(const char *in) {
Token *head = NULL;
Token **now = &head;
for (int i = 0; in[i]; i++) {
if (isspace(in[i])) // ignore space characters
continue;
else if (isdigit(in[i])) {
(*now) = new_token(CONSTANT, atoi(in + i));
while (in[i+1] && isdigit(in[i+1])) i++;
}
else if ('x' <= in[i] && in[i] <= 'z') // variable
(*now) = new_token(IDENTIFIER, in[i]);
else switch (in[i]) {
case '=':
(*now) = new_token(ASSIGN, 0);
break;
case '+':
if (in[i+1] && in[i+1] == '+') {
i++;
// In lexer scope, all "++" will be labeled as PREINC.
(*now) = new_token(PREINC, 0);
}
// In lexer scope, all single "+" will be labeled as PLUS.
else (*now) = new_token(PLUS, 0);
break;
case '-':
if (in[i+1] && in[i+1] == '-') {
i++;
// In lexer scope, all "--" will be labeled as PREDEC.
(*now) = new_token(PREDEC, 0);
}
// In lexer scope, all single "-" will be labeled as MINUS.
else (*now) = new_token(MINUS, 0);
break;
case '*':
(*now) = new_token(MUL, 0);
break;
case '/':
(*now) = new_token(DIV, 0);
break;
case '%':
(*now) = new_token(REM, 0);
break;
case '(':
(*now) = new_token(LPAR, 0);
break;
case ')':
(*now) = new_token(RPAR, 0);
break;
case ';':
(*now) = new_token(END, 0);
break;
default:
err("Unexpected character.");
}
now = &((*now)->next);
}
return head;
}
Token *new_token(Kind kind, int val) {
Token *res = (Token*)malloc(sizeof(Token));
res->kind = kind;
res->val = val;
res->next = NULL;
return res;
}
size_t token_list_to_arr(Token **head) {
size_t res;
Token *now = (*head), *del;
for (res = 0; now != NULL; res++) now = now->next;
now = (*head);
if (res != 0) (*head) = (Token*)malloc(sizeof(Token) * res);
for (int i = 0; i < res; i++) {
(*head)[i] = (*now);
del = now;
now = now->next;
free(del);
}
return res;
}
AST *parser(Token *arr, size_t len) {
for (int i = 1; i < len; i++) {
// correctly identify "ADD" and "SUB"
if (arr[i].kind == PLUS || arr[i].kind == MINUS) {
switch (arr[i - 1].kind) {
case PREINC:
case PREDEC:
case IDENTIFIER:
case CONSTANT:
case RPAR:
arr[i].kind = arr[i].kind - PLUS + ADD;
default: break;
}
}
}
return parse(arr, 0, len - 1, STMT);
}
AST *parse(Token *arr, int l, int r, GrammarState S) {
AST *now = NULL;
if (l > r)
err("Unexpected parsing range.");
int nxt;
switch (S) {
case STMT:
if (l == r && arr[l].kind == END)
return NULL;
else if (arr[r].kind == END)
return parse(arr, l, r - 1, EXPR);
else err("Expected \';\' at the end of line.");
case EXPR:
return parse(arr, l, r, ASSIGN_EXPR);
case ASSIGN_EXPR:
if ((nxt = findNextSection(arr, l, r, condASSIGN)) != -1) {
now = new_AST(arr[nxt].kind, 0);
now->lhs = parse(arr, l, nxt - 1, UNARY_EXPR);
now->rhs = parse(arr, nxt + 1, r, ASSIGN_EXPR);
return now;
}
return parse(arr, l, r, ADD_EXPR);
case ADD_EXPR:
if((nxt = findNextSection(arr, r, l, condADD)) != -1) {
now = new_AST(arr[nxt].kind, 0);
now->lhs = parse(arr, l, nxt - 1, ADD_EXPR);
now->rhs = parse(arr, nxt + 1, r, MUL_EXPR);
return now;
}
return parse(arr, l, r, MUL_EXPR);
case MUL_EXPR:
// TODO: Implement MUL_EXPR.
// hint: Take ADD_EXPR as reference.
case UNARY_EXPR:
// TODO: Implement UNARY_EXPR.
// hint: Take POSTFIX_EXPR as reference.
case POSTFIX_EXPR:
if (arr[r].kind == PREINC || arr[r].kind == PREDEC) {
// translate "PREINC", "PREDEC" into "POSTINC", "POSTDEC"
now = new_AST(arr[r].kind - PREINC + POSTINC, 0);
now->mid = parse(arr, l, r - 1, POSTFIX_EXPR);
return now;
}
return parse(arr, l, r, PRI_EXPR);
case PRI_EXPR:
if (findNextSection(arr, l, r, condRPAR) == r) {
now = new_AST(LPAR, 0);
now->mid = parse(arr, l + 1, r - 1, EXPR);
return now;
}
if (l == r) {
if (arr[l].kind == IDENTIFIER || arr[l].kind == CONSTANT)
return new_AST(arr[l].kind, arr[l].val);
err("Unexpected token during parsing.");
}
err("No token left for parsing.");
default:
err("Unexpected grammar state.");
}
}
AST *new_AST(Kind kind, int val) {
AST *res = (AST*)malloc(sizeof(AST));
res->kind = kind;
res->val = val;
res->lhs = res->mid = res->rhs = NULL;
return res;
}
int findNextSection(Token *arr, int start, int end, int (*cond)(Kind)) {
int par = 0;
int d = (start < end) ? 1 : -1;
for (int i = start; (start < end) ? (i <= end) : (i >= end); i += d) {
if (arr[i].kind == LPAR) par++;
if (arr[i].kind == RPAR) par--;
if (par == 0 && cond(arr[i].kind) == 1) return i;
}
return -1;
}
int condASSIGN(Kind kind) {
return kind == ASSIGN;
}
int condADD(Kind kind) {
return kind == ADD || kind == SUB;
}
int condMUL(Kind kind) {
return kind == MUL || kind == DIV || kind == REM;
}
int condRPAR(Kind kind) {
return kind == RPAR;
}
void semantic_check(AST *now) {
if (now == NULL) return;
// Left operand of '=' must be an identifier or identifier with one or more parentheses.
if (now->kind == ASSIGN) {
AST *tmp = now->lhs;
while (tmp->kind == LPAR) tmp = tmp->mid;
if (tmp->kind != IDENTIFIER)
err("Lvalue is required as left operand of assignment.");
}
// Operand of INC/DEC must be an identifier or identifier with one or more parentheses.
// TODO: Implement the remaining semantic_check code.
// hint: Follow the instruction above and ASSIGN-part code to implement.
// hint: Semantic of each node needs to be checked recursively (from the current node to lhs/mid/rhs node).
}
void codegen(AST *root) {
// TODO: Implement your codegen in your own way.
// You may modify the function parameter or the return type, even the whole structure as you wish.
}
void freeAST(AST *now) {
if (now == NULL) return;
freeAST(now->lhs);
freeAST(now->mid);
freeAST(now->rhs);
free(now);
}
void token_print(Token *in, size_t len) {
const static char KindName[][20] = {
"Assign", "Add", "Sub", "Mul", "Div", "Rem", "Inc", "Dec", "Inc", "Dec", "Identifier", "Constant", "LPar", "RPar", "Plus", "Minus", "End"
};
const static char KindSymbol[][20] = {
"'='", "'+'", "'-'", "'*'", "'/'", "'%'", "\"++\"", "\"--\"", "\"++\"", "\"--\"", "", "", "'('", "')'", "'+'", "'-'"
};
const static char format_str[] = "<Index = %3d>: %-10s, %-6s = %s\n";
const static char format_int[] = "<Index = %3d>: %-10s, %-6s = %d\n";
for(int i = 0; i < len; i++) {
switch(in[i].kind) {
case LPAR:
case RPAR:
case PREINC:
case PREDEC:
case ADD:
case SUB:
case MUL:
case DIV:
case REM:
case ASSIGN:
case PLUS:
case MINUS:
fprintf(stderr, format_str, i, KindName[in[i].kind], "symbol", KindSymbol[in[i].kind]);
break;
case CONSTANT:
fprintf(stderr, format_int, i, KindName[in[i].kind], "value", in[i].val);
break;
case IDENTIFIER:
fprintf(stderr, format_str, i, KindName[in[i].kind], "name", (char*)(&(in[i].val)));
break;
case END:
fprintf(stderr, "<Index = %3d>: %-10s\n", i, KindName[in[i].kind]);
break;
default:
fputs("=== unknown token ===", stderr);
}
}
}
void AST_print(AST *head) {
static char indent_str[MAX_LENGTH] = " ";
static int indent = 2;
const static char KindName[][20] = {
"Assign", "Add", "Sub", "Mul", "Div", "Rem", "PreInc", "PreDec", "PostInc", "PostDec", "Identifier", "Constant", "Parentheses", "Parentheses", "Plus", "Minus"
};
const static char format[] = "%s\n";
const static char format_str[] = "%s, <%s = %s>\n";
const static char format_val[] = "%s, <%s = %d>\n";
if (head == NULL) return;
char *indent_now = indent_str + indent;
indent_str[indent - 1] = '-';
fprintf(stderr, "%s", indent_str);
indent_str[indent - 1] = ' ';
if (indent_str[indent - 2] == '`')
indent_str[indent - 2] = ' ';
switch (head->kind) {
case ASSIGN:
case ADD:
case SUB:
case MUL:
case DIV:
case REM:
case PREINC:
case PREDEC:
case POSTINC:
case POSTDEC:
case LPAR:
case RPAR:
case PLUS:
case MINUS:
fprintf(stderr, format, KindName[head->kind]);
break;
case IDENTIFIER:
fprintf(stderr, format_str, KindName[head->kind], "name", (char*)&(head->val));
break;
case CONSTANT:
fprintf(stderr, format_val, KindName[head->kind], "value", head->val);
break;
default:
fputs("=== unknown AST type ===", stderr);
}
indent += 2;
strcpy(indent_now, "| ");
AST_print(head->lhs);
strcpy(indent_now, "` ");
AST_print(head->mid);
AST_print(head->rhs);
indent -= 2;
(*indent_now) = '\0';
}