-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCFG.cpp
368 lines (334 loc) · 12.7 KB
/
CFG.cpp
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
//
// Created by Cédric Leclercq on 08/10/2021.
//
#include "CFG.h"
#include <iostream>
using namespace std;
bool comparePairWords(const pair<string,vector<string>>& a, const pair<string,vector<string>>& b) {
if (a.first == b.first) {
string one;
for (const auto& elem: a.second)
one += elem;
string two;
for (const auto& elem: b.second)
two += elem;
return one < two;
}
return a.first < b.first;
}
bool compareWords(const string& a, const string& b) {
return a < b;
}
void CFG::createExampleCFG() {
// Used by the constructor to create the CFG for the first assignment
this->variables = {"BINDIGIT", "S"};
this->terminals = {"0", "1", "a", "b"};
vector<string> prod1 = {""};
vector<string> prod2 = {"a","S","b","BINDIGIT"};
vector<string> prod3 = {"0"};
vector<string> prod4 = {"1"};
this->productions.emplace_back("BINDIGIT", prod3);
this->productions.emplace_back("BINDIGIT", prod4);
this->productions.emplace_back("S", prod1);
this->productions.emplace_back("S",prod2);
this->start = "S";
}
void CFG::print() {
// Printing variables
cout << "V = {";
for (const auto& element: this->variables) {
cout << element; // Print element
if (element != this->variables.back()) cout << ", "; // Add the comma except at the end
else cout << "}" << endl; // Add the end of the vector to the end
}
// Printing terminals
cout << "T = {";
for (const auto& element: this->terminals) {
cout << element; // Print element
if (element != this->terminals.back()) cout << ", "; // Add the comma except at the end
else cout << "}" << endl; // Add the end of the vector to the end
}
// Printing productions
cout << "P = {" << endl;
for (const auto& element: this->productions) {
// Printing all replacements
cout << " " << element.first << " -> `";
/*
for (const auto& replacement: element.second) {
cout << replacement;
if (replacement != element.second.back()) {
cout << " ";
} // Add the comma except at the end
else {
cout << "`" << endl; // Add the end of the vector to the end
}
}
*/
bool other = false;
for (auto it = element.second.begin(); it != element.second.end(); it++) {
cout << (*it);
if (next(it) != element.second.end()) {
cout << " ";
} else cout << "`" << endl;
}
} cout << "}" << endl;
// Printing start
cout << "S = " << this->start << endl; // TODO maybe remove endl
}
void CFG::parser(const json& j) {
vector<string> variablesIn = j["Variables"];
vector<string> terminalsIn = j["Terminals"];
this->variables = variablesIn;
this->terminals = terminalsIn;
for (auto prod: j["Productions"]) {
if (prod["body"].empty()) {
vector<string> emptyVector = {""};
this->productions.emplace_back(prod["head"],emptyVector);
} else {
this->productions.emplace_back(prod["head"], prod["body"]);
}
}
sort(this->productions.begin(), this->productions.end(), comparePairWords);
sort(this->terminals.begin(),this->terminals.end(), compareWords);
sort(this->variables.begin(),this->variables.end(), compareWords);
string startChar = j["Start"];
this->start = startChar;
}
void CFG::createTable(const string& str) {
this->table.clear(); // Clearing past entries
this->table.reserve((int)str.size());
for (int i = 0; i < (int)str.size(); i++) {
vector<vector<string>> cur; // Current vector to be pushed
cur.reserve((int)str.size()); // Reserving size
for (int j = 0; j < (int)str.size(); j++) {
vector<string> cur2;
cur.emplace_back(cur2);
}
table.push_back(cur);
}
}
bool CFG::accepts(const string& str) {
// First creating CYK table
this->createTable(str);
// Now setting up the algorithm
vector<pair<string,vector<string>>> allResults;
for (int i = 1; i <= (int)str.size(); i++) {
vector<string> test = CFG::splitInPieces(str,i);
for (int j = 0; j < (int)test.size(); j++) {
string toTest = test[j]; // what we should use for calculating
// base case, we are on the first row
if (i == 1) {
this->table[i-1][j] = this->findCharInProd(toTest);
allResults.emplace_back(toTest,this->table[i-1][j]);
}
// Normal case (where we are NOT at the first row)
else if (toTest.size() == 2){
// First calculating cartesian product of what we need
vector<vector<string>> allComb;
for (auto ch: toTest) {
allComb.push_back(this->findCharInProd(string(1,ch)));
}
// TODO fix not so clean code
vector<vector<string>> cartProd = cartesianProduct(allComb);
vector<string> matches;
for (const auto& item: cartProd) {
string str1;
for (const auto& item1: item)
str1 += item1;
for (const auto& prod: this->productions) {
string str2;
for (const auto& item2: prod.second) {
str2 += item2;
}
if (str1 == str2) {
matches.emplace_back(prod.first);
}
}
}
// We found all the matches, we can store it into the table
this->table[i-1][j] = matches;
allResults.emplace_back(toTest,this->table[i-1][j]);
//this->printTable();
} else {
// First splitting input, we just need to move the comma
for (int it = 1; it < toTest.size(); it++) {
string sub1 = toTest.substr(0,it);
string sub2 = toTest.substr(it,string::npos);
// The input is now split, we can search for its substrings in our allResults vector
pair<vector<string>,vector<string>> found;
for (const auto& result: allResults) {
if (result.first == sub1) {
found.first = result.second;
}
if (result.first == sub2) {
found.second = result.second;
}
}
// We have the two vectors that we need to calculate the cartesian product of
vector<vector<string>> cartProd = cartesianProduct({found.first,found.second});
vector<string> matches;
for (const auto& item: cartProd) {
string str1;
for (const auto& item1: item)
str1 += item1;
for (const auto& prod: this->productions) {
string str2;
for (const auto& item2: prod.second) {
str2 += item2;
}
if (str1 == str2) {
matches.emplace_back(prod.first);
}
}
}
// We found all the matches, we can store it into the table
for (const auto& id: matches) {
if (find(this->table[i-1][j].begin(), this->table[i-1][j].end(), id) == this->table[i-1][j].end()) {
this->table[i - 1][j].push_back(id);
}
}
//this->printTable();
}
allResults.emplace_back(toTest,this->table[i-1][j]);
sort(this->table[i-1][j].begin(),this->table[i-1][j].end(), compareWords);
}
}
}
this->printTable();
cout << boolalpha << this->evaluateAcceptanceTable() << endl; // So that ING is happy
return this->evaluateAcceptanceTable();
}
vector<string> CFG::splitInPieces(const string& str, int amount) {
vector<string> ret;
ret.reserve((int)str.size());
for (int i = 0; i < (int)str.size(); i++) {
if (amount <= (int)str.size()) {
string result = str.substr(i, amount);
if (result.size() < amount)
continue;
else ret.push_back(result);
}
}
return ret;
}
void CFG::printTable() {
// Preprocessing to find the longest element in every row for printing the spaces before the |
vector<int> sizes;
sizes.reserve(this->table.size());
for (int i = 0; i < this->table.size(); i++) {
sizes.push_back(0);
}
for (auto & i : this->table) {
for (int j = 0; j < i.size(); j++) {
if (i[j].size() > sizes[j])
sizes[j] = (int)i[j].size();
}
}
// Per element in de vector dat een vector minder heeft moet het twee spaties extra toevoegen
int elem1 = 0;
for (int i = (int)this->table.size() - 1; i >= 0; i--) {
elem1++;
int currentElem = 0;
cout << "|";
int k = 0;
int max = 3;
int iterator = 0;
bool empty = true;
for (auto item: this->table[i]) {
if (!item.empty())
empty = false;
}
if (empty) {
string spaces;
for (int j = 0; j < sizes[iterator]; j++) {
spaces += " ";
}
cout << " " << "{}" << spaces << "|";
currentElem++;
}
for (auto it2 = this->table[i].begin(); it2 != this->table[i].end(); it2++) {
k++;
string s = " {";
for (auto it = (*it2).begin(); it != (*it2).end(); it++) {
s+= (*it);
if (next(it) != (*it2).end()) {
s += ", ";
} else {
string spaces;
for (int j = 0; j < sizes[iterator] - (*it2).size(); j++) {
spaces += " ";
} if (!(*it2).empty() and sizes[iterator] != (*it2).size()) {
spaces += " ";
}
if (sizes[iterator] == (*it2).size())
spaces += " ";
cout << s + "}" << spaces << "|";
currentElem++;
}
}
if (currentElem < elem1 and (*it2).empty()) {
string spaces;
for (int j = 0; j < sizes[iterator] - (*it2).size(); j++) {
spaces += " ";
} if (!(*it2).empty() and sizes[iterator] != (*it2).size()) {
spaces += " ";
}
if (sizes[iterator] == (*it2).size())
spaces += " ";
cout << s << "}" << spaces << "|";
currentElem++;
}
iterator++;
}
cout << endl;
/*
for (auto & j : this->table[i]) { // Or j == size() see for later
string s = " {";
for (auto it = j.begin(); it != j.end(); it++) {
s += (*it);
if (next(it) != j.end()) {
s += ", ";
} else cout << s + "} |";
}
if (j.empty())
cout << s << "} |";
} cout << endl;
*/
}
}
std::vector<std::string> CFG::findCharInProd(const std::string& ch) {
vector<string> result;
for (const auto& prod: this->productions) {
for (const auto& rep: prod.second) {
if (rep == ch) {
result.push_back(prod.first);
}
}
}
return result;
}
std::vector<std::vector<std::string>> CFG::cartesianProduct(std::vector<std::vector<std::string>> v) {
vector<vector<string>> fullResult;
for (const auto& item: v[0]) {
for (const auto& item2: v[1]) {
vector<string> result = {item,item2};
fullResult.push_back(result);
}
}
return fullResult;
}
bool CFG::evaluateAcceptanceTable() {
if (table.empty())
return false;
for (auto it = this->table.begin(); it != this->table.end(); it++) {
if (next(it) == this->table.end()) {
for (const auto& elem: (*it)) {
for (const auto& ch: elem) {
if (ch == "S")
return true;
}
}
}
}
return false;
}