-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleftRecursion.c
More file actions
87 lines (74 loc) · 3.13 KB
/
leftRecursion.c
File metadata and controls
87 lines (74 loc) · 3.13 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
#include "leftRecursion.h"
#include "utils.h"
/**
* Removes left recursion from the global grammar.
*
* This function iterates over each rule in the grammar, identifying and eliminating
* left recursion. For a grammar rule with left recursion, it separates the productions
* into two groups: those that begin with the non-terminal (alpha) and those that do not
* (beta). It then constructs new rules to eliminate the left recursion by introducing
* a new non-terminal.
*
* The function modifies the global `grammar` array and updates `numRules` to reflect
* the new rules added during the left recursion removal process.
*/
void removeLeftRecursion() {
printf("\nPerforming Left Recursion Removal...\n");
int usedLetters[26] = {0};
for (int i = 0; i < numRules; i++) {
usedLetters[grammar[i].nonTerminal - 'A'] = 1;
}
for (int i = 0; i < numRules; i++) {
char alpha[MAX_PRODUCTIONS][MAX_LENGTH], beta[MAX_PRODUCTIONS][MAX_LENGTH];
int alphaCount = 0, betaCount = 0;
char nonTerminal = grammar[i].nonTerminal;
for (int j = 0; j < grammar[i].count; j++) {
char *production = grammar[i].productions[j];
if (production[0] == nonTerminal) {
strcpy(alpha[alphaCount++], production + 1);
} else {
strcpy(beta[betaCount++], production);
}
}
if (alphaCount > 0) {
char newNonTerminal = 'A' + numRules;
usedLetters[newNonTerminal - 'A'] = 1;
grammar[i].count = 0;
int uniqueIndex = 0;
char uniqueProductions[MAX_PRODUCTIONS][MAX_LENGTH] = {0};
for (int j = 0; j < betaCount; j++) {
int isDuplicate = 0;
for (int p = 0; p < uniqueIndex; p++) {
if (strcmp(uniqueProductions[p], beta[j]) == 0) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
strcpy(uniqueProductions[uniqueIndex++], beta[j]);
sprintf(grammar[i].productions[grammar[i].count++], "%s %c", beta[j], newNonTerminal);
}
}
grammar[numRules].nonTerminal = newNonTerminal;
grammar[numRules].count = 0;
uniqueIndex = 0;
memset(uniqueProductions, 0, sizeof(uniqueProductions));
for (int j = 0; j < alphaCount; j++) {
int isDuplicate = 0;
for (int p = 0; p < uniqueIndex; p++) {
if (strcmp(uniqueProductions[p], alpha[j]) == 0) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
strcpy(uniqueProductions[uniqueIndex++], alpha[j]);
sprintf(grammar[numRules].productions[grammar[numRules].count++], "%s %c", alpha[j], newNonTerminal);
}
}
strcpy(grammar[numRules].productions[grammar[numRules].count++], "#");
numRules++;
}
}
printf("\nLeft Recursion Removal Completed.\n");
}