This repository was archived by the owner on Jul 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_generator.c
More file actions
898 lines (720 loc) · 21.2 KB
/
code_generator.c
File metadata and controls
898 lines (720 loc) · 21.2 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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
#include "token.h"
#include "data.h"
#include "symbol.h"
#include <string.h>
#include <stdlib.h>
/**
* This pointer is set when by codeGenerator() func and used by printEmittedCode() func.
*
* You are not required to use it anywhere. The implemented part of the skeleton
* handles the printing. Instead, you are required to fill the vmCode properly by making
* use of emit() func.
* */
FILE* _out;
/**
* Token list iterator used by the code generator. It will be set once entered to
* codeGenerator() and reset before exiting codeGenerator().
*
* It is better to use the given helper functions to make use of token list iterator.
* */
TokenListIterator _token_list_it;
/**
* Current level. Use this to keep track of the current level for the symbol table entries.
* */
unsigned int currentLevel;
/**
* Current scope. Use this to keep track of the current scope for the symbol table entries.
* NULL means global scope.
* */
Symbol* currentScope;
/**
* Symbol table.
* */
SymbolTable symbolTable;
/**
* The array of instructions that the generated(emitted) code will be held.
* */
Instruction vmCode[MAX_CODE_LENGTH];
/**
* The next index in the array of instructions (vmCode) to be filled.
* */
int nextCodeIndex;
/**
* The id of the register currently being used.
* */
int currentReg;
/**
* Emits the instruction whose fields are given as parameters.
* Internally, writes the instruction to vmCode[nextCodeIndex] and returns the
* nextCodeIndex by post-incrementing it.
* If MAX_CODE_LENGTH is reached, prints an error message on stderr and exits.
* */
int emit(int OP, int R, int L, int M);
/**
* Prints the emitted code array (vmCode) to output file.
*
* This func is called in the given codeGenerator() function. You are not required
* to have another call to this function in your code.
* */
void printEmittedCodes();
/**
* Returns the current token using the token list iterator.
* If it is the end of tokens, returns token with id nulsym.
* */
Token getCurrentToken();
/**
* Returns the type of the current token. Returns nulsym if it is the end of tokens.
* */
int getCurrentTokenType();
/**
* Advances the position of TokenListIterator by incrementing the current token
* index by one.
* */
void nextToken();
/**
* Functions used for non-terminals of the grammar
*
* rel-op func is removed on purpose. For code generation, it is easier to parse
* rel-op as a part of condition.
* */
int program();
int block();
int const_declaration();
int var_declaration();
int proc_declaration();
int statement(int reg);
int condition(int reg);
int expression(int reg);
int term(int reg);
int factor(int reg);
/******************************************************************************/
/* Definitions of helper functions starts *************************************/
/******************************************************************************/
Token getCurrentToken()
{
return getCurrentTokenFromIterator(_token_list_it);
}
int getCurrentTokenType()
{
return getCurrentToken().id;
}
void nextToken()
{
_token_list_it.currentTokenInd++;
}
/**
* Given the code generator error code, prints error message on file by applying
* required formatting.
* */
void printCGErr(int errCode, FILE* fp)
{
if(!fp || !errCode) return;
fprintf(fp, "CODE GENERATOR ERROR[%d]: %s.\n", errCode, codeGeneratorErrMsg[errCode]);
}
int emit(int OP, int R, int L, int M)
{
if(nextCodeIndex == MAX_CODE_LENGTH)
{
fprintf(stderr, "MAX_CODE_LENGTH(%d) reached. Emit is unsuccessful: terminating code generator..\n", MAX_CODE_LENGTH);
exit(0);
}
vmCode[nextCodeIndex] = (Instruction){ .op = OP, .r = R, .l = L, .m = M};
return nextCodeIndex++;
}
void printEmittedCodes()
{
for(int i = 0; i < nextCodeIndex; i++)
{
Instruction c = vmCode[i];
fprintf(_out, "%d %d %d %d\n", c.op, c.r, c.l, c.m);
}
}
/******************************************************************************/
/* Definitions of helper functions ends ***************************************/
/******************************************************************************/
/**
* Advertised codeGenerator function. Given token list, which is possibly the
* output of the lexer, parses a program out of tokens and generates code.
* If encountered, returns the error code.
*
* Returning 0 signals successful code generation.
* Otherwise, returns a non-zero code generator error code.
* */
int codeGenerator(TokenList tokenList, FILE* out)
{
// Set output file pointer
_out = out;
/**
* Create a token list iterator, which helps to keep track of the current
* token being parsed.
* */
_token_list_it = getTokenListIterator(&tokenList);
// Initialize current level to 0, which is the global level
currentLevel = -1;
// Initialize current scope to NULL, which is the global scope
currentScope = NULL;
// The index on the vmCode array that the next emitted code will be written
nextCodeIndex = 0;
// The id of the register currently being used
currentReg = 0;
// Initialize symbol table
initSymbolTable(&symbolTable);
// Start parsing by parsing program as the grammar suggests.
int err = program();
// Print symbol table - if no error occured
if(!err)
{
// Print the emitted codes to the file
printEmittedCodes();
}
// Reset output file pointer
_out = NULL;
// Reset the global TokenListIterator
_token_list_it.currentTokenInd = 0;
_token_list_it.tokenList = NULL;
// Delete symbol table
deleteSymbolTable(&symbolTable);
// Return err code - which is 0 if parsing was successful
return err;
}
// Already implemented.
int program()
{
// Generate code for block
int err = block();
if(err) return err;
// After parsing block, periodsym should show up
if( getCurrentTokenType() == periodsym )
{
// Consume token
nextToken();
// End of program, emit halt code
emit(SIO_HALT, 0, 0, 3);
return 0;
}
else
{
// Periodsym was expected. Return error code 6.
return 6;
}
}
int block()
{
currentLevel++;
emit(INC, 0, 0, 4);
int err = const_declaration();
if (err)
return err;
err = var_declaration();
if (err)
return err;
int instr = nextCodeIndex;
emit(JMP, 0, 0, 0);
err = proc_declaration();
if (err)
return err;
//modify that jmp instr M to be this nextCodeIndex
vmCode[instr].m = nextCodeIndex;
err = statement(0);
if (err)
return err;
//only return if current scope is not null, i.e. not global. u cant return from global scope. the program() will do halt instead.
//if (currentScope)
emit(RTN, 0, 0, 0);
currentLevel--;
return 0;
}
int const_declaration()
{
if(getCurrentTokenType() == constsym)
{
// Loop until token !- commasym
do
{
Symbol sym;
sym.type = CONST;
// Consume token and move on
nextToken();
// Check if the current token is not an identsym
if(getCurrentTokenType() != identsym)
{
// Error: must have identifier after
return 3;
}
// Copy the name into symbol table and consume the token
strcpy(sym.name, getCurrentToken().lexeme);
nextToken();
// Check if token is equal symbol
if(getCurrentTokenType() != eqsym)
{
return 2;
}
// Consume token and move on
nextToken();
if(getCurrentTokenType() != numbersym)
{
// Error: must have a number after
return 1;
}
// Update symbol table value, level, and scope (which is currentScope)
sym.value = atoi(getCurrentToken().lexeme);
sym.level = currentLevel;
sym.scope = currentScope;
addSymbol(&symbolTable, sym);
// Consume token and move onto next one
nextToken();
}
while(getCurrentTokenType() == commasym);
// Current token is not equal to semicolon
if(getCurrentTokenType() != semicolonsym)
{
// Missing semicolon return error code 4
return 4;
}
//printCurrentToken();
nextToken();
}
// Successful parsing.
return 0;
}
int var_declaration()
{
if(getCurrentTokenType() == varsym)
{
// Count variable to account for activation record's contents (indexed at 0)
int count = 0;
// Loop until token !- commasym
do
{
count++;
// Symbol operations: type is set to VAR
// address is updated to get a value of 4 since activation record has 4
// scope is set to current scope
Symbol sym;
sym.type = VAR;
sym.address = count + 3;
sym.scope = currentScope;
// Consume the token and move on
nextToken();
if(getCurrentTokenType() != identsym)
{
return 3;
}
strcpy(sym.name, getCurrentToken().lexeme);
sym.level = currentLevel;
addSymbol(&symbolTable, sym);
//printCurrentToken();
nextToken();
}
while(getCurrentTokenType() == commasym);
if(getCurrentTokenType() != semicolonsym)
{
// Missing semicolon return error code 4
return 4;
}
// Emit an increment with the offset being count (which was incremented in the loop to account for activation record)
emit(INC, 0, 0, count);
// Consume the token and move onto next
nextToken();
}
// Successful parsing.
return 0;
}
int proc_declaration()
{
while (getCurrentTokenType() == procsym)
{
Symbol sym;
sym.type = PROC;
nextToken();
if (getCurrentTokenType() != identsym)
{
return 3;
}
strcpy(sym.name, getCurrentToken().lexeme);
sym.level = currentLevel;
sym.scope = currentScope;
sym.address = nextCodeIndex;
Symbol *tmpScope = currentScope;
currentScope = addSymbol(&symbolTable, sym);
nextToken();
if (getCurrentTokenType() != semicolonsym)
{
return 5;
}
nextToken();
int err = block();
if (err)
return err;
if (getCurrentTokenType() != semicolonsym)
{
return 5;
}
nextToken();
}
return 0;
}
int statement(int reg)
{
if(getCurrentTokenType() == identsym)
{
// Check for valid variable
Symbol *sym = findSymbol(&symbolTable, currentScope, getCurrentToken().lexeme);
// If error found then return undeclared identifier error
if(!sym)
return 15;
// Check if symboltype != variable
if(sym->type != VAR)
{
// Error: Assignment to constant/procedure is not allowed
return 16;
}
// Move onto next token
nextToken();
if(getCurrentTokenType() != becomessym)
{
// Return an error if its not becomessym
return 7;
}
// Consume token
nextToken();
// Call EXPRESSION
int err = expression(reg);
if(err)
return err;
// Store the variable into a register
emit(STO, reg, currentLevel - sym->level, sym->address);
// Successful parsing
return 0;
}
if(getCurrentTokenType() == callsym)
{
// Consume token
nextToken();
if(getCurrentTokenType() != identsym)
{
// Throw an error if its not an identsym after a callsym
return 8;
}
Symbol *sym = findSymbol(&symbolTable, currentScope, getCurrentToken().lexeme);
// If error found then return undeclared identifier error
if(!sym)
return 15;
// Check if symboltype != proc
if(sym->type != PROC)
{
// Error: Assignment to constant/procedure is not allowed
return 17;
}
emit(CAL, 0, currentLevel - sym->level, sym->address); //TODO: Do we need to do currentLevel - sym->level for this one?
// Get token
nextToken();
return 0;
}
if(getCurrentTokenType() == beginsym)
{
nextToken();
int err = statement(reg);
if(err)
return err;
while(getCurrentTokenType() == semicolonsym)
{
nextToken();
err = statement(reg);
if(err)
return err;
}
if(getCurrentTokenType() != endsym)
{
return 10;
}
nextToken();
return 0;
}
if(getCurrentTokenType() == ifsym)
{
// Consume the token and move forward
nextToken();
// Error check for condition
int err = condition(reg);
if(err)
return err;
// Check for then symbol
if(getCurrentTokenType() != thensym)
{
// Then expected but not found so return error
return 9;
}
// Hold onto the next index used in the VMCode array
int instr = nextCodeIndex;
// Jump conditionally when you skip to end of the "then" part of an if-then statement
emit(JPC, reg, 0, 0);
// Consume the token and move forward
nextToken();
// Error check for statement
err = statement(reg);
if(err)
return err;
// Update vmCode array
vmCode[instr].m = nextCodeIndex;
if(getCurrentTokenType() == elsesym)
{
nextToken();
vmCode[instr].m = nextCodeIndex + 1;
instr = nextCodeIndex;
emit(JMP, 0, 0, 0);
err = statement(reg);
if(err)
return err;
vmCode[instr].m = nextCodeIndex;
}
return 0;
}
if(getCurrentTokenType() == whilesym)
{
int instr1 = nextCodeIndex;
nextToken();
int err = condition(reg);
if(err)
return err;
int instr2 = nextCodeIndex;
emit(JPC, reg, 0, 0);
if(getCurrentTokenType() != dosym)
{
// Do expected but not found return error
return 11;
}
nextToken();
err = statement(reg);
if(err)
return err;
emit(JMP, 0, 0, instr1);
vmCode[instr2].m = nextCodeIndex;
return 0;
}
if(getCurrentTokenType() == readsym)
{
// Grab the token
nextToken();
if(getCurrentTokenType() != identsym)
{
// Throw an error if identsym not found after readsym
return 3;
}
// Grab the symbol you are on right now
Symbol *sym = findSymbol(&symbolTable, currentScope, getCurrentToken().lexeme);
if(sym->type != VAR)
{
// Cannot do assignment to constant or procedure
return 16;
}
// Read the variable and then Store the variable
emit(SIO_READ, reg, 0, 2);
emit(STO, reg, currentLevel - sym->level, sym->address);
// Get token
nextToken();
return 0;
}
if(getCurrentTokenType() == writesym)
{
// Move onto next token
nextToken();
if(getCurrentTokenType() != identsym)
{
// No ident after write throw an error
return 3;
}
Symbol *sym = findSymbol(&symbolTable, currentScope, getCurrentToken().lexeme);
// Check the symbol type to see if its a VAR. If so emit a LOD operation
if(sym->type == VAR)
{
emit(LOD, reg, currentLevel - sym->level, sym->address);
}
// Check if symbol type is CONST. If so emit a LIT operation
else if(sym->type == CONST)
{
emit(LIT, reg, 0, sym->value);
}
else{
// Error: Can't write a procedure
return 18;
}
// Actual emit for writing
emit(SIO_WRITE, reg, 0, 1);
// Consume the token and move on
nextToken();
// Succesful parsing
return 0;
}
// Successful parsing
return 0;
}
int condition(int reg)
{
if(getCurrentTokenType() == oddsym)
{
// If oddsym consume this token and move onto next one
nextToken();
// Call the expression and check if an error occured in parsing
int err = expression(reg);
// Throw out the error if it occurs
if(err)
return err;
emit(ODD, reg, 0, 0);
}
else
{
// Call expression again
int err = expression(reg);
if (err)
return err;
int op = 0;
//EQL = 19, NEQ = 20, LSS = 21, LEQ = 22, GTR = 23, GEQ = 24
if (getCurrentTokenType() == eqsym)
{
op = EQL;
}
else if (getCurrentTokenType() == neqsym)
{
op = NEQ;
}
else if (getCurrentTokenType() == lessym)
{
op = LSS;
}
else if (getCurrentTokenType() == leqsym)
{
op = LEQ;
}
else if (getCurrentTokenType() == gtrsym)
{
op = GTR;
}
else if (getCurrentTokenType() == geqsym)
{
op = GEQ;
}
else
{
return 12; //relational operator expected
}
nextToken();
err = expression(reg + 1);
if (err)
return err;
emit(op, reg, reg, reg + 1);
}
// Successful parse
return 0;
}
int expression(int reg)
{
int op = 0;
if(getCurrentTokenType() == plussym || getCurrentTokenType() == minussym)
{
op = getCurrentTokenType();
// Consume the token if its plussym or minussym
nextToken();
}
int err = term(reg);
if (op == minussym)
emit(NEG, reg, reg, 0);
if(err)
return err;
while(getCurrentTokenType() == plussym || getCurrentTokenType() == minussym)
{
op = getCurrentTokenType();
nextToken();
err = term(reg + 1);
if(err)
return err;
emit(op == plussym ? ADD : SUB, reg, reg, reg + 1);
}
return 0;
}
int term(int reg)
{
int err = factor(reg);
if (err)
return err;
while(getCurrentTokenType() == multsym || getCurrentTokenType() == slashsym)
{
int tok = getCurrentTokenType();
// Consume the token and move it forward
nextToken();
if(getCurrentToken().id == nulsym)
return 6; // Error: Period expected
// Call the factor function
int fact = factor(reg + 1);
// Check if the factor function passes it
if(fact)
return fact;
// Emit either mult op or div op (reg = reg + (reg + 1))
emit(tok == multsym ? MUL : DIV, reg, reg, reg + 1);
}
// Successful parsing
return 0;
}
int factor(int reg)
{
/**
* There are three possibilities for factor:
* 1) ident
* 2) number
* 3) '(' expression ')'
* */
// Is the current token a identsym?
if(getCurrentTokenType() == identsym)
{
Symbol* sym = findSymbol(&symbolTable, currentScope, getCurrentToken().lexeme);
if (!sym)
return 15; // Error: identifier out of scope
if (sym->type == VAR)
emit(LOD, reg, currentLevel - sym->level, sym->address);
else if (sym->type == CONST)
emit(LIT, reg, 0, sym->value);
else
return 16;
// Consume identsym
nextToken(); // Go to the next token..
// Success
return 0;
}
// Is that a numbersym?
else if(getCurrentTokenType() == numbersym)
{
int num = atoi(getCurrentToken().lexeme);
emit(LIT, reg, 0, num);
// Consume numbersym and move token forward
nextToken();
// Success
return 0;
}
// Is that a lparentsym?
else if(getCurrentTokenType() == lparentsym)
{
// Consume lparentsym and move to the next token
nextToken();
// Continue by parsing expression.
int err = expression(reg);
if(err)
return err;
// After expression, right-parenthesis should come
if(getCurrentTokenType() != rparentsym)
{
/**
* Error code 13: Right parenthesis missing.
* Stop parsing and return error code 13.
* */
return 13;
}
// It was a rparentsym. Consume rparentsym and move to next token.
nextToken();
}
else
{
// Error code 14: The preceding factor cannot begin with this symbol.
return 14;
}
return 0;
}