-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleftFactoring.c
More file actions
79 lines (65 loc) · 2.69 KB
/
leftFactoring.c
File metadata and controls
79 lines (65 loc) · 2.69 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
#include "leftFactoring.h"
#include "utils.h"
/**
* Performs left factoring on the global grammar.
*
* This function iterates over each rule in the grammar and identifies common prefixes
* among the productions of a non-terminal. If a common prefix is found, it replaces
* the common part with a new non-terminal and adds the remaining production as a rule
* for the new non-terminal. This process helps in transforming the grammar into a form
* suitable for LL(1) parsing by removing left recursion.
*
* The function modifies the global `grammar` array and updates `numRules` to reflect
* the new rules added during the left factoring process.
*/
void leftFactorGrammar() {
printf("\nPerforming Left Factoring...\n");
for (int i = 0; i < numRules; i++) {
bool prev[MAX_PRODUCTIONS] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
char c[128] = {0}, ch;
int j = 0, maxCount;
while (true) {
maxCount = 0;
for (int k = 0; k < grammar[i].count; k++) {
if (prev[k] && strlen(grammar[i].productions[k]) > j)
c[grammar[i].productions[k][j]]++;
}
for (int k = 0; k < 128; k++) {
if (c[k] > maxCount) {
maxCount = c[k];
ch = k;
}
c[k] = 0;
}
if (maxCount < 2) break;
for (int k = 0; k < grammar[i].count; k++)
prev[k] = j < strlen(grammar[i].productions[k]) && grammar[i].productions[k][j] == ch;
j++;
}
if (j == 0) continue;
char newNonTerminal = 'A' + numRules;
grammar[numRules].nonTerminal = newNonTerminal;
grammar[numRules].count = 0;
int uniqueIndex = 0;
char uniqueProductions[MAX_PRODUCTIONS][MAX_LENGTH] = {0};
for (int k = 0; k < grammar[i].count; k++) {
if (prev[k] && grammar[i].productions[k][0] != '\0') {
int isDuplicate = 0;
for (int p = 0; p < uniqueIndex; p++) {
if (strcmp(uniqueProductions[p], grammar[i].productions[k] + j) == 0) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
strcpy(uniqueProductions[uniqueIndex++], grammar[i].productions[k] + j);
strcpy(grammar[numRules].productions[grammar[numRules].count++], grammar[i].productions[k] + j);
}
grammar[i].productions[k][j] = newNonTerminal;
grammar[i].productions[k][j + 1] = '\0';
}
}
numRules++;
}
printf("\nLeft Factoring Completed.\n");
}