-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparser.c
1121 lines (986 loc) · 32.8 KB
/
parser.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
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
/*
Group Number : 2
1 Dhruv Rawat 2019B3A70537P thedhruvrawat
2 Chirag Gupta 2019B3A70555P Chirag5128
3 Swastik Mantry 2019B1A71019P Swastik-Mantry
4 Shreyas Sheeranali 2019B3A70387P ShreyasSR
5 Vaibhav Prabhu 2019B3A70593P prabhuvaibhav
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parser.h"
#include "Set.h"
#include "colorCodes.h"
#include "lexer.h"
#include "stackADT.h"
Trie* grammarTrie;
#define TOTAL_RULES 200 // total number of rules in grammar
#define NULL_RULES 50 // expected number of nullable rules
// Flag to check if there is a parse error
bool PARSER_ERROR = false;
ProductionTable* pdtable; // stores all rules
int parseTable[TOTAL_RULES][TOTAL_RULES];
Set** firstSets = NULL;
Set** firstSetsRules = NULL;
Set** followSets = NULL;
char** elements;
bool* computed;
listElement** LHSLoc;
listElement** RHSLoc;
int base;
int EPSILON;
int DOLLAR;
static bool synCorrPrint = true;
/**
* @brief Allocate memory for the production table from the heap
*
* @param pdtable
* @param maxRules
* @return ProductionTable*
*/
ProductionTable* initializeProductionTable(ProductionTable* pdtable, int maxRules)
{
pdtable = malloc(sizeof(ProductionTable));
pdtable->maxRules = maxRules;
pdtable->ruleCount = 0;
pdtable->grammarrules = malloc(maxRules * (sizeof(ProductionRule*)));
return pdtable;
}
/**
* @brief Insert the production rule into the production table
*
* @param pdtable
* @param p
*/
void insertRuleInProductionTable(ProductionTable* pdtable, ProductionRule* p)
{
if (pdtable->ruleCount == pdtable->maxRules - 1) {
printf(RED BOLD "Sorry, table is full\n" RESET);
return;
}
pdtable->grammarrules[pdtable->ruleCount] = p;
pdtable->ruleCount++;
}
/**
* @brief Print the parse error based on the error number and print necessary information
*
* @param p_errno
* @param top
* @param tok
*/
void printParseError(int p_errno, stackNode* top, TOKEN* tok)
{
PARSER_ERROR = true;
synCorrPrint = false;
switch (p_errno) {
case 1: {
printf(RED BOLD "[Parser] Line: %d Error in the input as expected token is %s \n" RESET, tok->linenum, top->GE->lexeme);
break;
}
case 2: {
printf(RED BOLD "[Parser] Line: %d Error in the input as expected token is %s \n" RESET, tok->linenum, top->GE->lexeme);
break;
}
case 3: {
printf(RED BOLD "[Parser] Stream has ended but the stack is non-empty\n" RESET);
break;
}
}
}
/**
* @brief Print the production table
*
* @param pdtable
*/
void printProductionTable(ProductionTable* pdtable)
{
printf("Printing Production Table\n");
int sz = pdtable->ruleCount;
for (int i = 1; i <= sz; i++) {
printf("[%d]\t(%d)%s -> ", pdtable->grammarrules[i - 1]->productionID, pdtable->grammarrules[i - 1]->LHS->tokenID, pdtable->grammarrules[i - 1]->LHS->lexeme);
grammarElement* ptr = pdtable->grammarrules[i - 1]->RHSHead;
while (ptr != NULL) {
printf("(%d)%s", ptr->tokenID, ptr->lexeme);
// if(ptr->isTerminal)
// printf("*"); // Print a star, if the element is a terminal
printf(" ");
ptr = ptr->next;
}
printf("\n");
printf(CYAN BOLD "FIRST SET = ");
for (int j = 0; j < base; ++j) {
if (pdtable->grammarrules[i - 1]->firstSet->contains[j]) {
printf("%s, ", elements[j]);
}
}
printf("\n" RESET);
if (pdtable->grammarrules[i - 1]->firstSet->contains[EPSILON]) {
printf(YELLOW BOLD "FOLLOW SET = ");
for (int j = 0; j < base; ++j) {
if (pdtable->grammarrules[i - 1]->followSet->contains[j]) {
printf("%s, ", elements[j]);
}
}
printf("\n" RESET);
}
}
return;
}
/**
* @brief Recursive function invoked by computeFirstSet() to find the first set for a particular non-terminal
*
* @param tokenID
* @return true
* @return false
*/
bool findFirst(int tokenID)
{
// If the token is a terminal, just return
if (tokenID < 0) {
return false;
}
// If already computed return
if (firstSets[tokenID] != NULL) {
return (firstSets[tokenID]->contains[EPSILON]);
}
// Traversing LHSLoc
firstSets[tokenID] = initSet(base);
listElement* head = LHSLoc[tokenID];
while (head != NULL) {
grammarElement* RHS = pdtable->grammarrules[head->productionID]->RHSHead;
if (!computed[head->productionID]) {
if (firstSetsRules[head->productionID] == NULL) {
firstSetsRules[head->productionID] = initSet(base);
}
// loop if epsilon
bool isEpsilon = false;
while ((isEpsilon = findFirst(RHS->tokenID - base))) {
unionSet(firstSetsRules[head->productionID], firstSets[RHS->tokenID - base]);
RHS = RHS->next;
if (RHS == NULL) {
break;
}
firstSetsRules[head->productionID]->contains[EPSILON] = false;
}
// In case the token is a terminal
if (RHS != NULL && RHS->tokenID - base < 0) {
firstSetsRules[head->productionID]->contains[RHS->tokenID] = true;
} else if (RHS != NULL) { // Union in the case no epsilon in FIRST(RHS)
unionSet(firstSetsRules[head->productionID], firstSets[RHS->tokenID - base]);
}
computed[head->productionID] = true;
bool flag = unionSet(firstSets[tokenID], firstSetsRules[head->productionID]);
if (flag) {
printf(RED BOLD "LL(1) violated\n" RESET);
printf(RED BOLD "Rule Number %d with token %s\n" RESET, head->productionID, elements[tokenID + base]);
exit(1);
}
} else {
bool flag = unionSet(firstSets[tokenID], firstSetsRules[head->productionID]);
if (flag) {
printf(RED BOLD "LL(1) violated\n" RESET);
printf(RED BOLD "Rule Number %d with token %s\n" RESET, head->productionID, elements[tokenID + base]);
exit(1);
}
}
head = head->next;
}
return (firstSets[tokenID]->contains[EPSILON]);
}
/**
* @brief Computes the First Sets for all non-terminals
*
* @param nonTerminalLen
* @param terminalLen
*/
void computeFirstSet(int nonTerminalLen, int terminalLen)
{
int ruleCount = pdtable->ruleCount;
base = terminalLen + 2;
EPSILON = terminalLen;
DOLLAR = terminalLen + 1;
elements = getElements(grammarTrie);
// Array of linked lists to store the id of production rules of that non-terminal
LHSLoc = malloc(nonTerminalLen * sizeof(listElement*));
memset(LHSLoc, 0, nonTerminalLen * sizeof(listElement*));
for (int i = 0; i < ruleCount; ++i) {
int nt = pdtable->grammarrules[i]->LHS->tokenID;
nt -= (base); // epsilon and $ after terminals
listElement* newNode = malloc(sizeof(listElement));
newNode->productionID = i;
newNode->next = LHSLoc[nt];
LHSLoc[nt] = newNode;
}
/* // Printing to check
for (int i = 0; i < nonTerminalLen; ++i) {
listElement* head = LHSLoc[i];
printf("%s: ", elements[i + base]);
while (head != NULL) {
printf("%d ", head->productionID);
head = head->next;
}
printf("\n");
}
exit(0); */
// To track whether FIRST of that rule has already been calculated or not
computed = malloc(ruleCount * sizeof(bool));
memset(computed, 0, ruleCount * sizeof(bool));
firstSetsRules = malloc(ruleCount * sizeof(Set*));
memset(firstSetsRules, 0, ruleCount * sizeof(Set*));
firstSets = malloc(nonTerminalLen * sizeof(Set*));
memset(firstSets, 0, nonTerminalLen * sizeof(Set*));
bool isEpsilon = false;
for (int i = 0; i < nonTerminalLen; ++i) {
findFirst(i);
}
for (int i = 0; i < ruleCount; ++i) {
pdtable->grammarrules[i]->firstSet = firstSetsRules[i]; // attaching first set
}
return;
}
/**
* @brief Recursive function invoked by computeFollowSet() to find the follow set for a particular non-terminal
*
* @param tokenID
* @return true
* @return false
*/
bool findFollow(int tokenID)
{
// If the token is a terminal, return false
if (tokenID < 0) {
return false;
}
// Checking if the Follow Set for the given tokenID has already been computed or not
if (followSets[tokenID] != NULL) {
return followSets[tokenID]->contains[EPSILON];
}
followSets[tokenID] = initSet(base);
listElement* head = RHSLoc[tokenID];
while (head != NULL) {
ProductionRule* rule = pdtable->grammarrules[head->productionID];
grammarElement* RHS = rule->RHSHead;
bool computing = false;
while (RHS != NULL) {
while (RHS != NULL && RHS->tokenID != (tokenID + base)) {
RHS = RHS->next;
}
if (RHS == NULL) {
break;
}
computing = true;
RHS = RHS->next;
while (RHS != NULL) {
if (RHS->isTerminal) {
followSets[tokenID]->contains[RHS->tokenID] = true;
break;
} else {
unionSet(followSets[tokenID], firstSets[RHS->tokenID - base]);
if (followSets[tokenID]->contains[EPSILON]) {
RHS = RHS->next;
followSets[tokenID]->contains[EPSILON] = false;
} else {
break;
}
}
}
if (RHS != NULL) {
computing = false;
}
}
if (computing) {
int LHStokenID = rule->LHS->tokenID - base;
if (LHStokenID == tokenID) {
head = head->next;
continue;
}
findFollow(LHStokenID);
unionSet(followSets[tokenID], followSets[LHStokenID]);
}
head = head->next;
}
return false;
}
/**
* @brief Computes the Follow Sets for all non-terminals deriving EPSILON
*
* @param nonTerminalLen
* @param terminalLen
*/
void computeFollowSet(int nonTerminalLen, int terminalLen)
{
int ruleCount = pdtable->ruleCount;
// Allocating space for Follow Sets and setting to NULL
followSets = malloc(nonTerminalLen * sizeof(Set*));
memset(followSets, 0, nonTerminalLen * sizeof(Set*));
// Creating an array to store the location of the nonterminals in the RHS
RHSLoc = malloc(nonTerminalLen * sizeof(listElement*));
memset(RHSLoc, 0, nonTerminalLen * sizeof(listElement*));
// Adding $ to <program>
followSets[0] = initSet(base);
followSets[0]->contains[terminalLen + 1] = true;
for (int i = 0; i < ruleCount; ++i) {
grammarElement* RHS = pdtable->grammarrules[i]->RHSHead;
while (RHS != NULL) {
if (RHS->tokenID - base >= 0) {
listElement* newNode = malloc(sizeof(listElement));
newNode->productionID = i;
newNode->next = RHSLoc[RHS->tokenID - base];
RHSLoc[RHS->tokenID - base] = newNode;
}
RHS = RHS->next;
}
}
/* // Printing to check
for (int i = 0; i < nonTerminalLen; ++i) {
listElement* head = RHSLoc[i];
printf("%s: ", elements[i + base]);
while (head != NULL) {
printf("%d ", head->productionID);
head = head->next;
}
printf("\n");
}
exit(0); */
// Iterating over First Sets and compute Follow for the ones that are nullable
// base is terminalLen + 2, which is the length of firstSets
// epsilon at terminalLen
for (int i = 0; i < nonTerminalLen; ++i) {
if (firstSets[i]->contains[EPSILON]) {
findFollow(i);
}
}
return;
}
/**
* @brief Used to link First and Follow Sets with corresponding production rules.
*
*/
void attachFollowToRule()
{
for (int i = 0; i < pdtable->ruleCount; ++i) {
if (pdtable->grammarrules[i]->firstSet->contains[EPSILON]) {
int currNT = pdtable->grammarrules[i]->LHS->tokenID;
pdtable->grammarrules[i]->followSet = followSets[currNT - base];
}
}
}
/**
* @brief Computes the Parse Table
*
*/
void computeParseTable()
{
// Initializing to -1
memset(parseTable, -1, sizeof(parseTable));
// Iterate through the production table
for (int i = 0; i < pdtable->ruleCount; ++i) {
int LHS = pdtable->grammarrules[i]->LHS->tokenID - base;
// For each terminal 'a' in FIRST(RHS), add A -> RHS to parseTable[A][a]
for (int j = 0; j < EPSILON; ++j) {
if (pdtable->grammarrules[i]->firstSet->contains[j]) {
// if (parseTable[LHS][j] != -1) { printf("ERROR1\n"); exit(1); }
parseTable[LHS][j] = i;
}
}
if (pdtable->grammarrules[i]->firstSet->contains[EPSILON]) {
// If EPSILON is in FIRST(RHS), add A -> RHS to parseTable[A][a]
for (int j = 0; j < EPSILON; ++j) {
if (pdtable->grammarrules[i]->followSet->contains[j]) {
// if (parseTable[LHS][j] != -1) { printf("ERROR2\n"); exit(1); }
parseTable[LHS][j] = i;
}
}
// If EPSILON is in FIRST(RHS), and $ is in FOLLOW(A), add A -> RHS to parseTable[A][$]
if (pdtable->grammarrules[i]->followSet->contains[DOLLAR]) {
// if (parseTable[LHS][DOLLAR] != -1) { printf("ERROR3\n"); exit(1); }
parseTable[LHS][DOLLAR] = i;
}
}
}
/* // Printing parse table to check
for (int i = 0; i < grammarTrie->count - base; ++i) {
for (int j = 0; j < base; ++j) {
if (parseTable[i][j] == -1) {
printf("%s,", "e");
} else {
printf("%d,", parseTable[i][j]);
}
}
printf("\n");
} */
return;
}
ParseTree* parseTree;
const int ROOT = 618; // Average of all our IDs
#define MAX(a, b) (((a) >= (b)) ? (a) : (b))
/**
* @brief Adds the root note to the Parse Tree
*
*/
void initRootNode()
{
parseTree->sz++;
parseTree->treeDepth++;
ParseTreeNode* root = malloc(sizeof(ParseTreeNode));
root->depth = 1;
root->tokenID = pdtable->grammarrules[0]->LHS->tokenID;
root->nonLeaf.productionID = -1;
root->tokenDerivedFrom = -1;
root->isLeaf = false;
root->next = NULL;
root->child = NULL;
parseTree->root = root;
return;
}
/**
* @brief Initializes the Parse Tree
*
*/
void initParseTree()
{
parseTree = malloc(sizeof(ParseTree));
parseTree->sz = 0;
parseTree->treeDepth = 0;
initRootNode();
return;
}
/**
* @brief Inserts given rule into the Parse Tree
*
* @param parent
* @param productionID
* @param tok
* @param st
*/
void insertRuleInParseTree(ParseTreeNode* parent, int productionID, TOKEN* tok, stack* st)
{
ParseTreeNode* head = NULL;
ParseTreeNode* currNode;
grammarElement* g = pdtable->grammarrules[productionID]->RHSTail;
while (g != NULL) {
currNode = malloc(sizeof(ParseTreeNode));
parseTree->sz++;
currNode->depth = parent->depth + 1;
currNode->tokenID = g->tokenID;
currNode->tokenDerivedFrom = parent->tokenID;
currNode->isLeaf = g->isTerminal;
if (currNode->isLeaf) {
currNode->leaf.tok = NULL;
}
currNode->next = head;
currNode->child = NULL;
head = currNode;
pushStackGE(st, g, currNode);
g = g->prev;
}
parseTree->treeDepth = MAX(parseTree->treeDepth, parent->depth + 1);
parent->child = head;
return;
}
/**
* @brief Recursive function invoked by printParseTree() to print the parse tree
*
* @param node
* @param fp
* @param firstChild
*/
void printParseTreeRec(ParseTreeNode* node, bool firstChild)
{
if (node == NULL) {
return;
}
printParseTreeRec(node->child, true);
if (node->isLeaf && node->leaf.tok != NULL) {
printf("%-25s%-10d%-15s", node->leaf.tok->lexeme, node->leaf.tok->linenum, elements[node->tokenID]);
} else if (node->isLeaf) {
printf("%-25s%-10s%-15s", "(null)", "(null)", "(null)");
} else {
printf("%-25s%-10s%-15s", "--------------------", "---", "----------");
}
if (node->isLeaf && node->leaf.tok == NULL) {
printf("%-20s", "(null)");
} else if (node->isLeaf && node->leaf.tok->tok == NUM) {
printf("%-20d", node->leaf.tok->num);
} else if (node->isLeaf && node->leaf.tok->tok == RNUM) {
printf("%-20lf", node->leaf.tok->rnum);
} else {
printf("%-20s", "---------------");
}
if (node->tokenDerivedFrom >= 0) {
printf("%-40s", elements[node->tokenDerivedFrom]);
} else {
printf("%-40s", "ROOT");
}
printf("%-5s", (node->isLeaf ? "Yes" : "No"));
if (!node->isLeaf) {
printf("%-20s", elements[node->tokenID]);
}
printf("\n");
if (node->child != NULL) {
printParseTreeRec(node->child->next, false);
}
if (!firstChild) {
printParseTreeRec(node->next, false);
}
return;
}
/**
* @brief Prints the Parse Tree to console in an inorder traversal.
*
* @param parseTree
* @param outFile
*/
void printParseTree(ParseTree* parseTree)
{
printParseTreeRec(parseTree->root, false);
return;
}
/**
* @brief Initializes the Parsing Stack; Pushes DOLLAR and Start State (<program>)
*
* @param st
*/
void initParseStack(stack* st)
{
grammarElement* dollar = (grammarElement*)malloc(sizeof(grammarElement));
dollar->isTerminal = true;
dollar->tokenID = DOLLAR;
strcpy(dollar->lexeme, "EOF");
dollar->next = NULL;
dollar->prev = NULL;
pushStackGE(st, dollar, NULL);
// push <program> into stack
grammarElement* S = pdtable->grammarrules[0]->LHS;
pushStackGE(st, S, parseTree->root);
}
/**
* @brief Creates a copy of the given token as the lexer uses common memory for all the tokens
*
* @param curTok
* @return TOKEN*
*/
TOKEN* createTokenCopy(TOKEN* curTok)
{
TOKEN* temp = malloc(sizeof(TOKEN));
if (curTok == NULL) {
free(temp);
printf(GREEN BOLD "End of Stream of Tokens\n" RESET);
return curTok;
}
memcpy(temp, curTok, sizeof(TOKEN));
curTok = temp;
return curTok;
}
/**
* @brief Computes the Synchronizing Set for a given non-terminal
*
* @param g
* @return Set*
*/
Set* initSynchronizingSet(grammarElement* g)
{
Set* res = initSet(base);
unionSet(res, firstSets[g->tokenID - base]);
if (followSets[g->tokenID - base] != NULL) {
unionSet(res, followSets[g->tokenID - base]);
}
res->contains[START] = true;
res->contains[END] = true;
res->contains[SEMICOL] = true;
res->contains[DECLARE] = true;
res->contains[DRIVERDEF] = true;
res->contains[DRIVERENDDEF] = true;
res->contains[DEF] = true;
res->contains[ENDDEF] = true;
res->contains[FOR] = true;
res->contains[SWITCH] = true;
res->contains[WHILE] = true;
return res;
}
/**
* @brief Parses the user code through non-recursive predictive parsing while constructing a parse tree
*
*/
void parse()
{
printf(UNDERLINE BOLD "Into Parser\n" RESET);
stack* st = initStack();
initParseStack(st);
// Checking the Current Token and Top of the Stack
TOKEN* curTok = getNextToken();
curTok = createTokenCopy(curTok);
if (curTok->tok == EOF_SYMBOL) {
printParseError(3, st->top, curTok);
free(curTok);
destroyStack(st);
return;
}
stackNode* topStack = peekStack(st);
while (!(isEmpty(st))) {
if (topStack->GE->tokenID == EPSILON) {
popStack(st);
topStack = peekStack(st);
continue;
}
// top of the stack is terminal
if (topStack->GE->isTerminal) {
if (topStack->GE->tokenID == curTok->tok) { // Match
// printf("terminal\t");
// printf(GREEN BOLD "Top Stack: %-30s" RESET, topStack->GE->lexeme);
// printf(GREEN BOLD "Current Token: %-20s\t" RESET, curTok->lexeme);
// printf(GREEN BOLD "MATCHED\n" RESET);
if (curTok->tok == DOLLAR) {
break;
}
topStack->nodeAddr->leaf.tok = curTok;
popStack(st);
topStack = peekStack(st);
// Move Ahead i.e. Fetch another Token
curTok = getNextToken();
curTok = createTokenCopy(curTok);
// if (curTok->tok == DOLLAR && st->size > 1) {
// printParseError(3,st->top,curTok);
// destroyStack(st);
// return;
// }
} else {
printParseError(2, st->top, curTok);
if (topStack->GE->tokenID == COLON || topStack->GE->tokenID == CASE || topStack->GE->tokenID == DEFAULT) {
popStack(st);
topStack = peekStack(st);
free(curTok);
curTok = getNextToken();
curTok = createTokenCopy(curTok);
continue;
}
while (curTok->tok != SEMICOL && curTok->tok != START && curTok->tok != END) {
free(curTok);
curTok = getNextToken();
curTok = createTokenCopy(curTok);
if (curTok->tok == DOLLAR) {
break;
}
}
while ((topStack = peekStack(st))) {
if (topStack->GE->isTerminal && topStack->GE->tokenID == curTok->tok) {
break;
} else if (!topStack->GE->isTerminal && parseTable[topStack->GE->tokenID - base][curTok->tok] != -1) {
break;
}
popStack(st);
}
}
} else {
// printf("nonTerminal\t");
// printf("Top Stack: %-30s", topStack->GE->lexeme);
// printf("Current Token: %-20s\n", curTok->lexeme);
// Use curToken, parseTable to pop current Element and Push Rule
int nonTerminalID = topStack->GE->tokenID;
int terminalID = curTok->tok;
int ruleID = parseTable[nonTerminalID - base][terminalID];
// printf("(%d)%s, (%d)%s, %d\n", nonTerminalID - base, elements[nonTerminalID], terminalID, elements[terminalID], ruleID);
if (ruleID == -1) {
synCorrPrint = false;
PARSER_ERROR = true;
printf(RED BOLD "[Parser] Line: %d Error in the input as no entry found in parseTable[%s][%s]\n" RESET, curTok->linenum, topStack->GE->lexeme, elements[curTok->tok]);
Set* synchronizingSet = initSynchronizingSet(topStack->GE);
bool once = true;
while (synchronizingSet->contains[curTok->tok] == false) {
free(curTok);
curTok = getNextToken();
curTok = createTokenCopy(curTok);
if (curTok->tok == DOLLAR && st->size > 1) {
if (once) {
once = false;
continue;
}
printParseError(3, st->top, curTok);
destroyStack(st);
destroySet(synchronizingSet);
if (synCorrPrint) {
synCorrPrint = true;
}
free(curTok);
return;
}
}
destroySet(synchronizingSet);
popStack(st);
topStack = peekStack(st);
free(curTok);
curTok = getNextToken();
curTok = createTokenCopy(curTok);
} else {
// Pop current nonTerminal, push Rule, update topStack
ParseTreeNode* topStackAddr = topStack->nodeAddr;
topStackAddr->productionID = ruleID;
popStack(st);
insertRuleInParseTree(topStackAddr, ruleID, curTok, st);
topStack = peekStack(st);
}
}
}
if (curTok->tok != EOF_SYMBOL) {
printf(RED BOLD "The stack is empty but the stream has not ended.\n" RESET);
}
while (curTok->tok != EOF_SYMBOL) {
free(curTok);
curTok = getNextToken();
curTok = createTokenCopy(curTok);
}
free(curTok);
destroyStack(st);
if (synCorrPrint) {
synCorrPrint = true;
}
return;
}
/**
* @brief Frees the memory allocated for the production table and first set for that particular rule
*
* @param pdtable
*/
void freePDTable(ProductionTable* pdtable)
{
int cnt = pdtable->ruleCount;
for (int i = 0; i < cnt; ++i) {
free(pdtable->grammarrules[i]->LHS);
grammarElement* head = pdtable->grammarrules[i]->RHSHead;
while (head != NULL) {
grammarElement* temp = head->next;
free(head);
head = temp;
}
destroySet(pdtable->grammarrules[i]->firstSet);
free(pdtable->grammarrules[i]);
}
free(pdtable->grammarrules);
free(firstSetsRules);
free(pdtable);
return;
}
/**
* @brief Frees the memory allocated for the first sets and follow sets of non-terminals
*
* @param nonTerminalLen
*/
void freeFirstAndFollowSets(int nonTerminalLen)
{
for (int i = 0; i < nonTerminalLen; ++i) {
destroySet(firstSets[i]);
if (followSets[i] != NULL) {
destroySet(followSets[i]);
}
}
free(firstSets);
free(followSets);
}
/**
* @brief Frees the memory allocated for elements array
*
* @param elements
* @param count
*/
void freeElements(char** elements, int count)
{
for (int i = 0; i < count; ++i) {
free(elements[i]);
}
free(elements);
return;
}
/**
* @brief Frees the memory allocated for the data structure storing the locations of rules
*
* @param nonTerminalLen
*/
void freeRuleLocs(int nonTerminalLen)
{
for (int i = 0; i < nonTerminalLen; ++i) {
listElement* LHSHead = LHSLoc[i];
while (LHSHead != NULL) {
listElement* temp = LHSHead->next;
free(LHSHead);
LHSHead = temp;
}
listElement* RHSHead = RHSLoc[i];
while (RHSHead != NULL) {
listElement* temp = RHSHead->next;
free(RHSHead);
RHSHead = temp;
}
}
free(LHSLoc);
free(RHSLoc);
}
/**
* @brief Recursive functions invoked by freeParseTree() to free the memory allocated for the parse tree
*
* @param node
*/
void freeParseTreeRec(ParseTreeNode* node)
{
if (node == NULL) {
return;
}
freeParseTreeRec(node->child);
if (node->isLeaf && node->leaf.tok != NULL) {
free(node->leaf.tok);
}
freeParseTreeRec(node->next);
free(node);
return;
}
/**
* @brief Frees the memory allocated for the parse tree
*
* @param parseTree
*/
void freeParseTree(ParseTree* parseTree)
{
freeParseTreeRec(parseTree->root);
free(parseTree);
return;
}
/**
* @brief Frees all the memory allocated for the parser and resets the variables for the next run
*
*/
void cleanParser()
{
synCorrPrint = true;
int nonTerminalLen = grammarTrie->count - base;
int trSize = grammarTrie->count;
freePDTable(pdtable);
pdtable = NULL;
firstSetsRules = NULL;
freeTrie(grammarTrie);
grammarTrie = NULL;
freeFirstAndFollowSets(nonTerminalLen);
firstSets = NULL;
followSets = NULL;
freeElements(elements, trSize);
elements = NULL;
free(computed);
computed = NULL;
freeRuleLocs(nonTerminalLen);
LHSLoc = NULL;
RHSLoc = NULL;
freeParseTree(parseTree);
base = 0;
return;
}
/**
* @brief Driver function of the parser; invoked by the parser to parse the user code
*