-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.c
More file actions
612 lines (577 loc) · 16.6 KB
/
calculator.c
File metadata and controls
612 lines (577 loc) · 16.6 KB
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#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
} 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);
//void inc_dec(int inc,int dec);
/// 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 flag = 1;
int sp = -1;
int main()
{
while (fgets(input, MAX_LENGTH, stdin) != NULL)
{
Token *content = lexer(input);
size_t len = token_list_to_arr(&content);
AST *ast_root = parser(content, len);
semantic_check(ast_root);
flag = 1;
sp = -1;
//AST_print(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 (in[i] == ' ' || in[i] == '\n') // ignore space and newline
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;
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 = (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)
{
if (S == STMT)
return now;
else
err("Unexpected parsing range.");
}
int nxt;
switch (S)
{
case STMT:
if (l > r)
return now;
else
return parse(arr, l, r, EXPR);
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.
if ((nxt = findNextSection(arr, r, l, condMUL)) != -1)
{
now = new_AST(arr[nxt].kind, 0);
now->lhs = parse(arr, l, nxt - 1, MUL_EXPR);
now->rhs = parse(arr, nxt + 1, r, UNARY_EXPR);
return now;
}
return parse(arr, l, r, UNARY_EXPR);
case UNARY_EXPR:
// TODO: Implement UNARY_EXPR.
// hint: Take POSTFIX_EXPR as reference.
if (arr[l].kind == PLUS || arr[l].kind == MINUS || arr[l].kind == PREINC || arr[l].kind == PREDEC)
{
now = new_AST(arr[l].kind, 0);
now->mid = parse(arr, l + 1, r, UNARY_EXPR);
return now;
}
return parse(arr, l, r, POSTFIX_EXPR);
case POSTFIX_EXPR:
if (arr[r].kind == PREINC || arr[r].kind == PREDEC)
{
// translate "PREINC", "PREDEC" into "POSTINC", "POSTDEC"
now = new_AST((Kind)(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).
if (now->kind == PREINC || now->kind == PREDEC || now->kind == POSTDEC || now->kind == POSTINC)
{
AST *tmp = now->mid;
while (tmp->kind == LPAR)
tmp = tmp->mid;
if (tmp->kind != IDENTIFIER)
err("INC/DEC semantic error");
}
semantic_check(now->lhs);
semantic_check(now->mid);
semantic_check(now->rhs);
}
void codegen(AST *root){
static int assign_mem = -1;
if(root == NULL)
return;
switch(root->kind){
case ASSIGN:
codegen(root->rhs);
codegen(root->lhs);
printf("store [%d] r%d\n", assign_mem, sp-1);
sp--;
break;
case ADD:
codegen(root->lhs);
codegen(root->rhs);
printf("add r%d r%d r%d\n", sp-1, sp, sp-1);
sp--;
break;
case SUB:
codegen(root->lhs);
codegen(root->rhs);
printf("sub r%d r%d r%d\n", sp-1, sp-1, sp);
sp--;
break;
case MUL:
codegen(root->lhs);
codegen(root->rhs);
printf("mul r%d r%d r%d\n", sp-1, sp, sp-1);
sp--;
break;
case DIV:
codegen(root->lhs);
codegen(root->rhs);
printf("div r%d r%d r%d\n", sp-1, sp-1, sp);
sp--;
break;
case REM:
codegen(root->lhs);
codegen(root->rhs);
printf("rem r%d r%d r%d\n", sp-1, sp-1, sp);
sp--;
break;
case PREINC:
codegen(root->mid);
printf("add r%d r%d 1\n", sp, sp);
printf("store [%d] r%d\n", assign_mem, sp);
break;
case PREDEC:
codegen(root->mid);
printf("sub r%d r%d 1\n", sp, sp);
printf("store [%d] r%d\n", assign_mem, sp);
break;
case POSTINC:
codegen(root->mid);
printf("add r%d r%d 1\n", sp, sp);
printf("store [%d] r%d\n", assign_mem, sp);
printf("sub r%d r%d 1\n", sp, sp);
break;
case POSTDEC:
codegen(root->mid);
printf("sub r%d r%d 1\n", sp, sp);
printf("store [%d] r%d\n", assign_mem, sp);
printf("add r%d r%d 1\n", sp, sp);
break;
case IDENTIFIER: {
int mem = (root->val - 120) * 4;
sp++;
assign_mem = mem;
printf("load r%d [%d]\n", sp, mem);
break;
}
case CONSTANT:
sp++;
printf("add r%d 0 %d\n", sp, root->val);
break;
case LPAR:
codegen(root->mid);
break;
case RPAR:
break;
case PLUS:
codegen(root->mid);
break;
case MINUS:
codegen(root->mid);
printf("sub r%d 0 r%d\n", sp, sp);
break;
}
return;
}
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"};
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:
printf(format_str, i, KindName[in[i].kind], "symbol", KindSymbol[in[i].kind]);
break;
case CONSTANT:
printf(format_int, i, KindName[in[i].kind], "value", in[i].val);
break;
case IDENTIFIER:
printf(format_str, i, KindName[in[i].kind], "name", (char *)(&(in[i].val)));
break;
default:
puts("=== unknown token ===");
}
}
}
void AST_print(AST *head)
{
static char indent_str[MAX_LENGTH] = "";
static int indent = 0;
char *indent_now = indent_str + indent;
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;
indent_str[indent - 1] = '-';
printf("%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:
printf(format, KindName[head->kind]);
break;
case IDENTIFIER:
printf(format_str, KindName[head->kind], "name", (char *)&(head->val));
break;
case CONSTANT:
printf(format_val, KindName[head->kind], "value", head->val);
break;
default:
puts("=== unknown AST type ===");
}
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';
}