-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1202 lines (982 loc) · 33.6 KB
/
main.cpp
File metadata and controls
1202 lines (982 loc) · 33.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
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
/**
* to view changes made for assignment 3 search "assignment 3"
*/
/*
{ Sample program
in TINY language
compute factorial
}
{all these loops where tested with python to
make sure the results were correct}
for i from 0 to 10 inc 1
startfor
write i
endfor; {output from 0 to 9}
for i from 0 to 10 inc 1
startfor
write i;
if i=5 then break end
endfor; {output from 0 to 5}
for i from 0 to 2 inc 1
startfor
for j from 20 to 10 inc 0-1
startfor
if j=18 then
break
else
write i+j
end
endfor
endfor; {output 20 19 21 20}
sum:=0;
for i from 1 to 20 inc 2
startfor
sum := sum+i;
if i=11 then break end
endfor;
write sum; {output 36}
sum := 0;
for i from 0 to 10 inc 1
startfor
for j from 20 to 10 inc 0-1
startfor
for k from 0 to 10 inc 2
startfor
sum := sum+k+i+j
endfor
endfor
endfor;
write sum; {output 12000}
sum := 0;
for i from 0 to 10 inc 1
startfor
for j from 0 to 10 inc 1
startfor
for k from 0 to 10 inc 1
startfor
sum := sum+k+i+j;
if k=3 then break end
endfor
endfor
endfor;
write sum {output 4200}
sum := 0;
for i from 0 to 10 inc 1
startfor
for j from 0 to 10 inc 1
startfor
for k from 0 to 10 inc 1
startfor
sum := sum+k+i+j;
if k=3 then break end
endfor;
if j=4 then break end
endfor;
if i=5 then break end
endfor;
write sum {output 720}
*/
// sequence of statements separated by ;
// no procedures - no declarations
// all variables are integers
// variables are declared simply by assigning values to them :=
// if-statement: if (boolean) then [else] end
// repeat-statement: repeat until (boolean)
// boolean only in if and repeat conditions < = and two mathematical expressions
// math expressions integers only, + - * / ^
// I/O read write
// Comments {}
////////////////////////////////////////////////////////////////////////////////////
// Strings /////////////////////////////////////////////////////////////////////////
bool Equals(const char* a, const char* b)
{
return strcmp(a, b)==0;
}
bool StartsWith(const char* a, const char* b)
{
int nb=strlen(b);
return strncmp(a, b, nb)==0;
}
void Copy(char* a, const char* b, int n=0)
{
if(n>0) {strncpy(a, b, n); a[n]=0;}
else strcpy(a, b);
}
void AllocateAndCopy(char** a, const char* b)
{
if(b==0) {*a=0; return;}
int n=strlen(b);
*a=new char[n+1];
strcpy(*a, b);
}
////////////////////////////////////////////////////////////////////////////////////
// Input and Output ////////////////////////////////////////////////////////////////
#define MAX_LINE_LENGTH 10000
struct InFile
{
FILE* file;
int cur_line_num;
char line_buf[MAX_LINE_LENGTH];
int cur_ind, cur_line_size;
InFile(const char* str) {file=0; if(str) file=fopen(str, "r"); cur_line_size=0; cur_ind=0; cur_line_num=0;}
~InFile(){if(file) fclose(file);}
void SkipSpaces()
{
while(cur_ind<cur_line_size)
{
char ch=line_buf[cur_ind];
if(ch!=' ' && ch!='\t' && ch!='\r' && ch!='\n') break;
cur_ind++;
}
}
bool SkipUpto(const char* str)
{
while(true)
{
SkipSpaces();
while(cur_ind>=cur_line_size) {if(!GetNewLine()) return false; SkipSpaces();}
if(StartsWith(&line_buf[cur_ind], str))
{
cur_ind+=strlen(str);
return true;
}
cur_ind++;
}
return false;
}
bool GetNewLine()
{
cur_ind=0; line_buf[0]=0;
if(!fgets(line_buf, MAX_LINE_LENGTH, file)) return false;
cur_line_size=strlen(line_buf);
if(cur_line_size==0) return false; // End of file
cur_line_num++;
return true;
}
char* GetNextTokenStr()
{
SkipSpaces();
while(cur_ind>=cur_line_size) {if(!GetNewLine()) return 0; SkipSpaces();}
return &line_buf[cur_ind];
}
void Advance(int num)
{
cur_ind+=num;
}
};
struct OutFile
{
FILE* file;
OutFile(const char* str) {file=0; if(str) file=fopen(str, "w");}
~OutFile(){if(file) fclose(file);}
void Out(const char* s)
{
fprintf(file, "%s\n", s); fflush(file);
}
};
////////////////////////////////////////////////////////////////////////////////////
// Compiler Parameters /////////////////////////////////////////////////////////////
struct CompilerInfo
{
InFile in_file;
OutFile out_file;
OutFile debug_file;
CompilerInfo(const char* in_str, const char* out_str, const char* debug_str)
: in_file(in_str), out_file(out_str), debug_file(debug_str)
{
}
};
////////////////////////////////////////////////////////////////////////////////////
// Scanner /////////////////////////////////////////////////////////////////////////
#define MAX_TOKEN_LEN 40
enum TokenType{
IF, THEN, ELSE, END, REPEAT, UNTIL, READ, WRITE,
ASSIGN, EQUAL, LESS_THAN,
PLUS, MINUS, TIMES, DIVIDE, POWER,
SEMI_COLON,
LEFT_PAREN, RIGHT_PAREN,
LEFT_BRACE, RIGHT_BRACE,
ID, NUM,
ENDFILE, ERROR,
/// assignment 3
/// added new tokens for the for statement and the break statement
FOR, FROM, TO, INC, START_FOR, END_FOR, BREAK
};
// Used for debugging only /////////////////////////////////////////////////////////
const char* TokenTypeStr[]=
{
"If", "Then", "Else", "End", "Repeat", "Until", "Read", "Write",
"Assign", "Equal", "LessThan",
"Plus", "Minus", "Times", "Divide", "Power",
"SemiColon",
"LeftParen", "RightParen",
"LeftBrace", "RightBrace",
"ID", "Num",
"EndFile", "Error",
/// assignment 3
/// added new token type strings for the for and break statement
"For", "From", "To", "Inc", "StartFor", "EndFor", "Break"
};
struct Token
{
TokenType type;
char str[MAX_TOKEN_LEN+1];
Token(){str[0]=0; type=ERROR;}
Token(TokenType _type, const char* _str) {type=_type; Copy(str, _str);}
};
const Token reserved_words[]=
{
Token(IF, "if"),
Token(THEN, "then"),
Token(ELSE, "else"),
Token(END, "end"),
Token(REPEAT, "repeat"),
Token(UNTIL, "until"),
Token(READ, "read"),
Token(WRITE, "write"),
/// assignment 3
/// added reserved words for the added tokens above
Token(FOR, "for"),
Token(FROM, "from"),
Token(TO, "to"),
Token(INC, "inc"),
Token(START_FOR, "startfor"),
Token(END_FOR, "endfor"),
Token(BREAK, "break")
};
const int num_reserved_words=sizeof(reserved_words)/sizeof(reserved_words[0]);
// if there is tokens like < <=, sort them such that sub-tokens come last: <= <
// the closing comment should come immediately after opening comment
const Token symbolic_tokens[]=
{
Token(ASSIGN, ":="),
Token(EQUAL, "="),
Token(LESS_THAN, "<"),
Token(PLUS, "+"),
Token(MINUS, "-"),
Token(TIMES, "*"),
Token(DIVIDE, "/"),
Token(POWER, "^"),
Token(SEMI_COLON, ";"),
Token(LEFT_PAREN, "("),
Token(RIGHT_PAREN, ")"),
Token(LEFT_BRACE, "{"),
Token(RIGHT_BRACE, "}")
};
const int num_symbolic_tokens=sizeof(symbolic_tokens)/sizeof(symbolic_tokens[0]);
inline bool IsDigit(char ch){return (ch>='0' && ch<='9');}
inline bool IsLetter(char ch){return ((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'));}
inline bool IsLetterOrUnderscore(char ch){return (IsLetter(ch) || ch=='_');}
void GetNextToken(CompilerInfo* pci, Token* ptoken)
{
ptoken->type=ERROR;
ptoken->str[0]=0;
int i;
char* s=pci->in_file.GetNextTokenStr();
if(!s)
{
ptoken->type=ENDFILE;
ptoken->str[0]=0;
return;
}
for(i=0;i<num_symbolic_tokens;i++)
{
if(StartsWith(s, symbolic_tokens[i].str))
break;
}
if(i<num_symbolic_tokens)
{
if(symbolic_tokens[i].type==LEFT_BRACE)
{
pci->in_file.Advance(strlen(symbolic_tokens[i].str));
if(!pci->in_file.SkipUpto(symbolic_tokens[i+1].str)) return;
return GetNextToken(pci, ptoken);
}
ptoken->type=symbolic_tokens[i].type;
Copy(ptoken->str, symbolic_tokens[i].str);
}
else if(IsDigit(s[0]))
{
int j=1;
while(IsDigit(s[j])) j++;
ptoken->type=NUM;
Copy(ptoken->str, s, j);
}
else if(IsLetterOrUnderscore(s[0]))
{
int j=1;
while(IsLetterOrUnderscore(s[j])) j++;
ptoken->type=ID;
Copy(ptoken->str, s, j);
for(i=0;i<num_reserved_words;i++)
{
if(Equals(ptoken->str, reserved_words[i].str))
{
ptoken->type=reserved_words[i].type;
break;
}
}
}
int len=strlen(ptoken->str);
if(len>0) pci->in_file.Advance(len);
}
////////////////////////////////////////////////////////////////////////////////////
// Parser //////////////////////////////////////////////////////////////////////////
/// assignment 3
// program -> stmtseq
// stmtseq -> stmt { ; stmt }
/// added forstmt and breakstmt
// stmt -> ifstmt | repeatstmt | assignstmt | readstmt | writestmt | forstmt | breakstmt
// ifstmt -> if exp then stmtseq [ else stmtseq ] end
// repeatstmt -> repeat stmtseq until expr
// assignstmt -> identifier := expr
// readstmt -> read identifier
// writestmt -> write expr
// forstmt -> for identifier from mathexpr to mathexpr inc mathexpr
// breakstmt -> break
// expr -> mathexpr [ (<|=) mathexpr ]
// mathexpr -> term { (+|-) term } left associative
// term -> factor { (*|/) factor } left associative
// factor -> newexpr { ^ newexpr } right associative
// newexpr -> ( mathexpr ) | number | identifier
enum NodeKind{
IF_NODE, REPEAT_NODE, ASSIGN_NODE, READ_NODE, WRITE_NODE,
OPER_NODE, NUM_NODE, ID_NODE,
/// assignment 3
/// added two nodes for the for and break statements
FOR_NODE, BREAK_NODE
};
// Used for debugging only /////////////////////////////////////////////////////////
const char* NodeKindStr[]=
{
"If", "Repeat", "Assign", "Read", "Write",
"Oper", "Num", "ID",
/// assignment 3
/// added two more for the added nodes above
"For", "Break"
};
enum ExprDataType {VOID, INTEGER, BOOLEAN};
// Used for debugging only /////////////////////////////////////////////////////////
const char* ExprDataTypeStr[]=
{
"Void", "Integer", "Boolean"
};
/// assignment 3
/// changed it from 3 to 4 since the for statements will have 4 children
#define MAX_CHILDREN 4
struct TreeNode
{
TreeNode* child[MAX_CHILDREN];
TreeNode* sibling; // used for sibling statements only
NodeKind node_kind;
union{TokenType oper; int num; char* id;}; // defined for expression/int/identifier only
ExprDataType expr_data_type; // defined for expression/int/identifier only
int line_num;
TreeNode() {int i; for(i=0;i<MAX_CHILDREN;i++) child[i]=0; sibling=0; expr_data_type=VOID;}
};
struct ParseInfo
{
Token next_token;
};
void Match(CompilerInfo* pci, ParseInfo* ppi, TokenType expected_token_type)
{
pci->debug_file.Out("Start Match");
if(ppi->next_token.type!=expected_token_type) throw "Matching failed";
GetNextToken(pci, &ppi->next_token);
fprintf(pci->debug_file.file, "[%d] %s (%s)\n", pci->in_file.cur_line_num, ppi->next_token.str, TokenTypeStr[ppi->next_token.type]); fflush(pci->debug_file.file);
}
TreeNode* Expr(CompilerInfo*, ParseInfo*);
// newexpr -> ( mathexpr ) | number | identifier
TreeNode* NewExpr(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start NewExpr");
// Compare the next token with the First() of possible statements
if(ppi->next_token.type==NUM)
{
TreeNode* tree=new TreeNode;
tree->node_kind=NUM_NODE;
char* num_str=ppi->next_token.str;
tree->num=0; while(*num_str) tree->num=tree->num*10+((*num_str++)-'0');
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, ppi->next_token.type);
pci->debug_file.Out("End NewExpr");
return tree;
}
if(ppi->next_token.type==ID)
{
TreeNode* tree=new TreeNode;
tree->node_kind=ID_NODE;
AllocateAndCopy(&tree->id, ppi->next_token.str);
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, ppi->next_token.type);
pci->debug_file.Out("End NewExpr");
return tree;
}
if(ppi->next_token.type==LEFT_PAREN)
{
Match(pci, ppi, LEFT_PAREN);
TreeNode* tree=Expr(pci, ppi);
Match(pci, ppi, RIGHT_PAREN);
pci->debug_file.Out("End NewExpr");
return tree;
}
throw "newexpr couldn't recognize next token";
return 0;
}
// factor -> newexpr { ^ newexpr } right associative
TreeNode* Factor(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start Factor");
TreeNode* tree=NewExpr(pci, ppi);
if(ppi->next_token.type==POWER)
{
TreeNode* new_tree=new TreeNode;
new_tree->node_kind=OPER_NODE;
new_tree->oper=ppi->next_token.type;
new_tree->line_num=pci->in_file.cur_line_num;
new_tree->child[0]=tree;
Match(pci, ppi, ppi->next_token.type);
new_tree->child[1]=Factor(pci, ppi);
pci->debug_file.Out("End Factor");
return new_tree;
}
pci->debug_file.Out("End Factor");
return tree;
}
// term -> factor { (*|/) factor } left associative
TreeNode* Term(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start Term");
TreeNode* tree=Factor(pci, ppi);
while(ppi->next_token.type==TIMES || ppi->next_token.type==DIVIDE)
{
TreeNode* new_tree=new TreeNode;
new_tree->node_kind=OPER_NODE;
new_tree->oper=ppi->next_token.type;
new_tree->line_num=pci->in_file.cur_line_num;
new_tree->child[0]=tree;
Match(pci, ppi, ppi->next_token.type);
new_tree->child[1]=Factor(pci, ppi);
tree=new_tree;
}
pci->debug_file.Out("End Term");
return tree;
}
// mathexpr -> term { (+|-) term } left associative
TreeNode* MathExpr(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start MathExpr");
TreeNode* tree=Term(pci, ppi);
while(ppi->next_token.type==PLUS || ppi->next_token.type==MINUS)
{
TreeNode* new_tree=new TreeNode;
new_tree->node_kind=OPER_NODE;
new_tree->oper=ppi->next_token.type;
new_tree->line_num=pci->in_file.cur_line_num;
new_tree->child[0]=tree;
Match(pci, ppi, ppi->next_token.type);
new_tree->child[1]=Term(pci, ppi);
tree=new_tree;
}
pci->debug_file.Out("End MathExpr");
return tree;
}
// expr -> mathexpr [ (<|=) mathexpr ]
TreeNode* Expr(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start Expr");
TreeNode* tree=MathExpr(pci, ppi);
if(ppi->next_token.type==EQUAL || ppi->next_token.type==LESS_THAN)
{
TreeNode* new_tree=new TreeNode;
new_tree->node_kind=OPER_NODE;
new_tree->oper=ppi->next_token.type;
new_tree->line_num=pci->in_file.cur_line_num;
new_tree->child[0]=tree;
Match(pci, ppi, ppi->next_token.type);
new_tree->child[1]=MathExpr(pci, ppi);
pci->debug_file.Out("End Expr");
return new_tree;
}
pci->debug_file.Out("End Expr");
return tree;
}
// writestmt -> write expr
TreeNode* WriteStmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start WriteStmt");
TreeNode* tree=new TreeNode;
tree->node_kind=WRITE_NODE;
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, WRITE);
tree->child[0]=Expr(pci, ppi);
pci->debug_file.Out("End WriteStmt");
return tree;
}
// readstmt -> read identifier
TreeNode* ReadStmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start ReadStmt");
TreeNode* tree=new TreeNode;
tree->node_kind=READ_NODE;
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, READ);
if(ppi->next_token.type==ID) AllocateAndCopy(&tree->id, ppi->next_token.str);
Match(pci, ppi, ID);
pci->debug_file.Out("End ReadStmt");
return tree;
}
// assignstmt -> identifier := expr
TreeNode* AssignStmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start AssignStmt");
TreeNode* tree=new TreeNode;
tree->node_kind=ASSIGN_NODE;
tree->line_num=pci->in_file.cur_line_num;
if(ppi->next_token.type==ID) AllocateAndCopy(&tree->id, ppi->next_token.str);
Match(pci, ppi, ID);
Match(pci, ppi, ASSIGN); tree->child[0]=Expr(pci, ppi);
pci->debug_file.Out("End AssignStmt");
return tree;
}
TreeNode* StmtSeq(CompilerInfo*, ParseInfo*);
// repeatstmt -> repeat stmtseq until expr
TreeNode* RepeatStmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start RepeatStmt");
TreeNode* tree=new TreeNode;
tree->node_kind=REPEAT_NODE;
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, REPEAT); tree->child[0]=StmtSeq(pci, ppi);
Match(pci, ppi, UNTIL); tree->child[1]=Expr(pci, ppi);
pci->debug_file.Out("End RepeatStmt");
return tree;
}
/// assignment 3
/// added a function for the for statement explained below
// forstm> -> for <identifier> from <mathexpr> to <mathexpr> inc <mathexpr> startfor <stmtseq> endfor
TreeNode* ForStmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start ForStmt");
TreeNode* tree=new TreeNode;
tree->node_kind=FOR_NODE; // set the node to FOR_BODE
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, FOR);
if(ppi->next_token.type==ID) AllocateAndCopy(&tree->id, ppi->next_token.str); // if the next token is id then alocate and copy
Match(pci, ppi, ID);
// set every mathexpr to a child to compute later
Match(pci, ppi, FROM);
tree->child[0] = MathExpr(pci, ppi);
Match(pci, ppi, TO);
tree->child[1] = MathExpr(pci, ppi);
Match(pci, ppi, INC);
tree->child[2] = MathExpr(pci, ppi);
// set the stmtseq after the 'startfor' to a child to loop over it
Match(pci, ppi, START_FOR);
tree->child[3] = StmtSeq(pci, ppi);
Match(pci, ppi, END_FOR);
pci->debug_file.Out("End ForStmt");
return tree;
}
/// assignment 3
/// added a function for the break statement
// breakstmt -> break
TreeNode* BreakStmt(CompilerInfo* pci, ParseInfo* ppi)
{
TreeNode* tree=new TreeNode;
tree->node_kind=BREAK_NODE; // we just set the node here
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, BREAK);
pci->debug_file.Out("Break");
return tree;
}
// ifstmt -> if exp then stmtseq [ else stmtseq ] end
TreeNode* IfStmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start IfStmt");
TreeNode* tree=new TreeNode;
tree->node_kind=IF_NODE;
tree->line_num=pci->in_file.cur_line_num;
Match(pci, ppi, IF); tree->child[0]=Expr(pci, ppi);
Match(pci, ppi, THEN); tree->child[1]=StmtSeq(pci, ppi);
if(ppi->next_token.type==ELSE) {Match(pci, ppi, ELSE); tree->child[2]=StmtSeq(pci, ppi);}
Match(pci, ppi, END);
pci->debug_file.Out("End IfStmt");
return tree;
}
// stmt -> ifstmt | repeatstmt | assignstmt | readstmt | writestmt
TreeNode* Stmt(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start Stmt");
// Compare the next token with the First() of possible statements
TreeNode* tree=0;
if(ppi->next_token.type==IF) tree=IfStmt(pci, ppi);
else if(ppi->next_token.type==REPEAT) tree=RepeatStmt(pci, ppi);
else if(ppi->next_token.type==ID) tree=AssignStmt(pci, ppi);
else if(ppi->next_token.type==READ) tree=ReadStmt(pci, ppi);
else if(ppi->next_token.type==WRITE) tree=WriteStmt(pci, ppi);
/// assignment 3
/// added two else if conditions for the for and break tokens to call their functions
else if(ppi->next_token.type==FOR) tree=ForStmt(pci, ppi);
else if(ppi->next_token.type==BREAK) tree=BreakStmt(pci, ppi);
else throw "stmt couldn't recognize the next stmt";
pci->debug_file.Out("End Stmt");
return tree;
}
// stmtseq -> stmt { ; stmt }
TreeNode* StmtSeq(CompilerInfo* pci, ParseInfo* ppi)
{
pci->debug_file.Out("Start StmtSeq");
TreeNode* first_tree=Stmt(pci, ppi);
TreeNode* last_tree=first_tree;
/// assignment 3
/// added two more ands for the END_FOR and the BREAK
// If we did not reach one of the Follow() of StmtSeq(), we are not done yet
while(ppi->next_token.type!=ENDFILE && ppi->next_token.type!=END &&
ppi->next_token.type!=ELSE && ppi->next_token.type!=UNTIL &&
ppi->next_token.type!=END_FOR && ppi->next_token.type!=BREAK)
{
Match(pci, ppi, SEMI_COLON);
TreeNode* next_tree=Stmt(pci, ppi);
last_tree->sibling=next_tree;
last_tree=next_tree;
}
pci->debug_file.Out("End StmtSeq");
return first_tree;
}
// program -> stmtseq
TreeNode* Parse(CompilerInfo* pci)
{
ParseInfo parse_info;
GetNextToken(pci, &parse_info.next_token);
TreeNode* syntax_tree=StmtSeq(pci, &parse_info);
if(parse_info.next_token.type!=ENDFILE)
pci->debug_file.Out("Error code ends before file ends");
return syntax_tree;
}
void PrintTree(TreeNode* node, int sh=0)
{
int i, NSH=3;
for(i=0;i<sh;i++) printf(" ");
printf("[%s]", NodeKindStr[node->node_kind]);
if(node->node_kind==OPER_NODE) printf("[%s]", TokenTypeStr[node->oper]);
else if(node->node_kind==NUM_NODE) printf("[%d]", node->num);
/// assignment 3
/// added an or for the FOR_NODE
else if(node->node_kind==ID_NODE || node->node_kind==READ_NODE || node->node_kind==ASSIGN_NODE || node->node_kind==FOR_NODE) printf("[%s]", node->id);
if(node->expr_data_type!=VOID) printf("[%s]", ExprDataTypeStr[node->expr_data_type]);
printf("\n");
for(i=0;i<MAX_CHILDREN;i++) if(node->child[i]) PrintTree(node->child[i], sh+NSH);
if(node->sibling) PrintTree(node->sibling, sh);
}
void DestroyTree(TreeNode* node)
{
int i;
/// assignment 3
/// added an or for the FOR_NODE
if(node->node_kind==ID_NODE || node->node_kind==READ_NODE || node->node_kind==ASSIGN_NODE || node->node_kind==FOR_NODE)
if(node->id) delete[] node->id;
for(i=0;i<MAX_CHILDREN;i++) if(node->child[i]) DestroyTree(node->child[i]);
if(node->sibling) DestroyTree(node->sibling);
delete node;
}
////////////////////////////////////////////////////////////////////////////////////
// Analyzer ////////////////////////////////////////////////////////////////////////
const int SYMBOL_HASH_SIZE=10007;
struct LineLocation
{
int line_num;
LineLocation* next;
};
struct VariableInfo
{
char* name;
int memloc;
LineLocation* head_line; // the head of linked list of source line locations
LineLocation* tail_line; // the tail of linked list of source line locations
VariableInfo* next_var; // the next variable in the linked list in the same hash bucket of the symbol table
};
struct SymbolTable
{
int num_vars;
VariableInfo* var_info[SYMBOL_HASH_SIZE];
SymbolTable() {num_vars=0; int i; for(i=0;i<SYMBOL_HASH_SIZE;i++) var_info[i]=0;}
int Hash(const char* name)
{
int i, len=strlen(name);
int hash_val=11;
for(i=0;i<len;i++) hash_val=(hash_val*17+(int)name[i])%SYMBOL_HASH_SIZE;
return hash_val;
}
VariableInfo* Find(const char* name)
{
int h=Hash(name);
VariableInfo* cur=var_info[h];
while(cur)
{
if(Equals(name, cur->name)) return cur;
cur=cur->next_var;
}
return 0;
}
void Insert(const char* name, int line_num)
{
LineLocation* lineloc=new LineLocation;
lineloc->line_num=line_num;
lineloc->next=0;
int h=Hash(name);
VariableInfo* prev=0;
VariableInfo* cur=var_info[h];
while(cur)
{
if(Equals(name, cur->name))
{
// just add this line location to the list of line locations of the existing var
cur->tail_line->next=lineloc;
cur->tail_line=lineloc;
return;
}
prev=cur;
cur=cur->next_var;
}
VariableInfo* vi=new VariableInfo;
vi->head_line=vi->tail_line=lineloc;
vi->next_var=0;
vi->memloc=num_vars++;
AllocateAndCopy(&vi->name, name);
if(!prev) var_info[h]=vi;
else prev->next_var=vi;
}
void Print()
{
int i;
for(i=0;i<SYMBOL_HASH_SIZE;i++)
{
VariableInfo* curv=var_info[i];
while(curv)
{
printf("[Var=%s][Mem=%d]", curv->name, curv->memloc);
LineLocation* curl=curv->head_line;
while(curl)
{
printf("[Line=%d]", curl->line_num);
curl=curl->next;
}
printf("\n");
curv=curv->next_var;
}
}
}
void Destroy()
{
int i;
for(i=0;i<SYMBOL_HASH_SIZE;i++)
{
VariableInfo* curv=var_info[i];
while(curv)
{
LineLocation* curl=curv->head_line;
while(curl)
{
LineLocation* pl=curl;
curl=curl->next;
delete pl;
}
VariableInfo* p=curv;
curv=curv->next_var;
delete p;
}
var_info[i]=0;
}
}
};
void Analyze(TreeNode* node, SymbolTable* symbol_table)
{
int i;
/// assignment 3
/// since we can save an identefier from the for loop, i added it to this if condition's ors
if(node->node_kind==ID_NODE || node->node_kind==READ_NODE || node->node_kind==ASSIGN_NODE || node->node_kind==FOR_NODE)
symbol_table->Insert(node->id, node->line_num);
for(i=0;i<MAX_CHILDREN;i++) if(node->child[i]) Analyze(node->child[i], symbol_table);
if(node->node_kind==OPER_NODE)
{
if(node->oper==EQUAL || node->oper==LESS_THAN) node->expr_data_type=BOOLEAN;
else node->expr_data_type=INTEGER;
}
else if(node->node_kind==ID_NODE || node->node_kind==NUM_NODE) node->expr_data_type=INTEGER;
if(node->node_kind==OPER_NODE)
{
if(node->child[0]->expr_data_type!=INTEGER || node->child[1]->expr_data_type!=INTEGER)
printf("ERROR Operator applied to non-integers\n");