-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
458 lines (395 loc) · 16 KB
/
scripts.js
File metadata and controls
458 lines (395 loc) · 16 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
function procesarGramatica() {
let input = document.getElementById('productions').value;
// Remove extra spaces and blank lines
input = input.replace(/^\s*$(?:\r\n?|\n)/gm, ''); // Remove blank lines
input = input.trim(); // Remove leading and trailing spaces
const producciones = parseProductions(input);
const nuevasProducciones = eliminarRecursionIzquierda(producciones);
mostrarProducciones(nuevasProducciones);
const primeros = calcularPrimero(nuevasProducciones);
mostrarPrimero(primeros);
mostrarPrimeroM(primeros);
document.querySelector('.follow-sets-section').style.display = 'block';
document.getElementById('producciones-follow').value = formatProductionsForFollow(nuevasProducciones);
}
function parseProductions(input) {
const lines = input.split('\n');
const producciones = {};
for (const line of lines) {
const [noTerminal, reglas] = line.split('->').map(s => s.trim());
producciones[noTerminal] = reglas.split('|').map(s => s.trim());
}
return producciones;
}
function eliminarRecursionIzquierda(producciones) {
const nuevasProducciones = {};
for (const noTerminal in producciones) {
const reglas = producciones[noTerminal];
const recursivas = [];
const noRecursivas = [];
for (const regla of reglas) {
if (regla.startsWith(noTerminal)) {
recursivas.push(regla.slice(noTerminal.length));
} else {
noRecursivas.push(regla);
}
}
if (recursivas.length > 0) {
const nuevoNoTerminal = noTerminal + "'";
nuevasProducciones[noTerminal] = noRecursivas.map(nr => nr + nuevoNoTerminal);
nuevasProducciones[nuevoNoTerminal] = recursivas.map(r => '' + r + nuevoNoTerminal).concat(['ε']);
} else {
nuevasProducciones[noTerminal] = reglas;
}
}
return nuevasProducciones;
}
function mostrarProducciones(producciones) {
const output = document.getElementById('output-productions');
const outputM = document.getElementById('output-productions-m');
output.textContent = '';
outputM.textContent = '';
for (const noTerminal in producciones) {
const reglas = producciones[noTerminal].join(' | ');
output.textContent += `${noTerminal} -> ${reglas}\n`;
outputM.textContent += `${noTerminal} -> ${reglas}\n`;
}
}
function calcularPrimero(producciones) {
const primeros = {};
for (const noTerminal in producciones) {
primeros[noTerminal] = new Set();
}
let cambio = true;
while (cambio) {
cambio = false;
for (const noTerminal in producciones) {
const reglas = producciones[noTerminal];
for (const regla of reglas) {
let simbolo;
if (regla.startsWith('id')) {
simbolo = 'id';
} else {
simbolo = regla[0];
}
if (!producciones[simbolo]) {
if (!primeros[noTerminal].has(simbolo)) {
primeros[noTerminal].add(simbolo);
cambio = true;
}
} else {
const oldSize = primeros[noTerminal].size;
for (const elem of primeros[simbolo]) {
primeros[noTerminal].add(elem);
}
if (primeros[noTerminal].size > oldSize) {
cambio = true;
}
}
}
}
}
for (const noTerminal in primeros) {
primeros[noTerminal] = Array.from(primeros[noTerminal]);
}
return primeros;
}
function mostrarPrimero(primeros) {
const output = document.getElementById('output-first');
output.innerHTML = '<tr><th>No Terminal</th><th>Primero</th></tr>';
for (const noTerminal in primeros) {
const row = document.createElement('tr');
const cellNoTerminal = document.createElement('td');
cellNoTerminal.textContent = noTerminal;
const cellPrimero = document.createElement('td');
cellPrimero.textContent = `{${primeros[noTerminal].join(', ')}}`;
row.appendChild(cellNoTerminal);
row.appendChild(cellPrimero);
output.appendChild(row);
}
}
function mostrarPrimeroM(primeros) {
const output = document.getElementById('output-first-m');
output.innerHTML = '';
for (const noTerminal in primeros) {
const resultado = `Prim(${noTerminal}): {${primeros[noTerminal].join(', ')}}`;
output.appendChild(document.createTextNode(resultado));
output.appendChild(document.createElement('br'));
}
}
function formatProductionsForFollow(productions) {
let result = '';
for (const noTerminal in productions) {
const rules = productions[noTerminal].join(' | ').replace(/'/g, '');
result += `${noTerminal} -> ${rules}\n`;
}
return result;
}
function calcularFollowSets() {
const input = document.getElementById('producciones-follow');
input.value = input.value.replace(/'/g, '');
const lines = input.value.trim().split('\n').map(line => line.trim());
const producciones = {};
lines.forEach(line => {
const [nonTerminal, rhs] = line.split('->').map(s => s.trim());
producciones[nonTerminal] = rhs.split('|').map(s => s.trim());
});
const noTerminales = Object.keys(producciones);
const primeros = {};
const siguientes = {};
noTerminales.forEach(v => {
primeros[v] = new Set();
siguientes[v] = new Set();
});
siguientes[noTerminales[0]].add('$');
function calcularPrimeros(cadena) {
const resultado = new Set();
for (let i = 0; i < cadena.length; i++) {
const simbolo = cadena[i];
if (simbolo === 'ε') {
resultado.add('ε');
break;
}
if (!noTerminales.includes(simbolo)) {
resultado.add(simbolo);
break;
}
const firstSimbolo = primeros[simbolo];
firstSimbolo.forEach(x => {
if (x !== 'ε') resultado.add(x);
});
if (!firstSimbolo.has('ε')) break;
if (i === cadena.length - 1) resultado.add('ε');
}
return resultado;
}
let cambios;
do {
cambios = false;
noTerminales.forEach(nonTerminal => { // Ensure consistent naming here
producciones[nonTerminal].forEach(cadena => {
const simbolos = cadena.split('');
const primerosCadena = calcularPrimeros(simbolos);
primerosCadena.forEach(x => {
if (!primeros[nonTerminal].has(x)) { // Use nonTerminal consistently
primeros[nonTerminal].add(x); // Use nonTerminal consistently
cambios = true;
}
});
});
});
} while (cambios);
do {
cambios = false;
noTerminales.forEach(nonTerminal => { // Ensure consistent naming here
producciones[nonTerminal].forEach(cadena => {
const simbolos = cadena.split('');
for (let i = 0; i < simbolos.length; i++) {
const simbolo = simbolos[i];
if (noTerminales.includes(simbolo)) {
const primerosBeta = calcularPrimeros(simbolos.slice(i + 1));
primerosBeta.forEach(x => {
if (x !== 'ε' && !siguientes[simbolo].has(x)) {
siguientes[simbolo].add(x);
cambios = true;
}
});
if (primerosBeta.has('ε') || i === simbolos.length - 1) {
siguientes[nonTerminal].forEach(x => { // Use nonTerminal consistently
if (!siguientes[simbolo].has(x)) {
siguientes[simbolo].add(x);
cambios = true;
}
});
}
}
}
});
});
} while (cambios);
const resultados = document.getElementById('resultados');
resultados.innerHTML = '';
const headerRow = document.createElement('tr');
const headerNoTerminal = document.createElement('th');
headerNoTerminal.textContent = 'No Terminal';
const headerSiguiente = document.createElement('th');
headerSiguiente.textContent = 'Siguiente';
headerRow.appendChild(headerNoTerminal);
headerRow.appendChild(headerSiguiente);
resultados.appendChild(headerRow);
noTerminales.forEach((nonTerminal, index) => { // Ensure consistent naming here
const cantidadApariciones = lines.filter(line => line.startsWith(nonTerminal)).length;
const cantidadMostrar = cantidadApariciones > 1 ? 2 : 1;
for (let i = 0; i < cantidadMostrar; i++) {
const row = document.createElement('tr');
const cellNoTerminal = document.createElement('td');
cellNoTerminal.textContent = i === 0 ? nonTerminal : nonTerminal + "'";
const cellSiguiente = document.createElement('td');
cellSiguiente.textContent = `{${Array.from(siguientes[nonTerminal]).join(', ')}}`; // Use nonTerminal consistently
row.appendChild(cellNoTerminal);
row.appendChild(cellSiguiente);
resultados.appendChild(row);
}
});
const outputFollowM = document.getElementById('output-follow-m');
noTerminales.forEach(nonTerminal => { // Ensure consistent naming here
const cantidadApariciones = lines.filter(line => line.startsWith(nonTerminal)).length;
const cantidadMostrar = cantidadApariciones > 1 ? 2 : 1;
const outputRow = document.createElement('div');
outputRow.classList.add('output-row');
for (let i = 0; i < cantidadMostrar; i++) {
const nonTerminalText = i === 0 ? nonTerminal : nonTerminal + "'";
const siguienteText = `{${Array.from(siguientes[nonTerminal]).join(', ')}}`; // Use nonTerminal consistently
const pElement = document.createElement('p');
pElement.textContent = `Sgte(${nonTerminalText}): ${siguienteText}`;
outputRow.appendChild(pElement);
}
outputFollowM.appendChild(outputRow);
});
}
function generarTabla() {
const produccionesInput = document.getElementById('producciones').value.trim();
if (!produccionesInput) {
console.error("No productions entered");
return;
}
const firstInput = document.getElementById('first').value.trim();
const followInput = document.getElementById('follow').value.trim();
const producciones = analizarProducciones(produccionesInput);
if (Object.keys(producciones).length === 0) {
console.error("Failed to parse productions");
return;
}
const first = analizarConjuntos(firstInput);
const follow = analizarConjuntos(followInput);
const noTerminales = Object.keys(producciones);
const terminales = obtenerTerminales(producciones);
const contenedor = document.getElementById('tablaM-contenedor');
const tabla = document.createElement('table');
tabla.setAttribute('id', 'tablaM');
const cabecera = document.createElement('thead');
const cuerpo = document.createElement('tbody');
const filaEncabezado = document.createElement('tr');
filaEncabezado.appendChild(document.createElement('th'));
terminales.forEach(terminal => {
const th = document.createElement('th');
th.textContent = terminal;
filaEncabezado.appendChild(th);
});
cabecera.appendChild(filaEncabezado);
tabla.appendChild(cabecera);
contenedor.innerHTML = '';
contenedor.appendChild(tabla);
noTerminales.forEach((noTerminal, indiceFila) => {
const fila = document.createElement('tr');
const celda = document.createElement('td');
celda.textContent = noTerminal;
fila.appendChild(celda);
setTimeout(() => {
terminales.forEach((terminal, indiceColumna) => {
setTimeout(() => {
const celda = document.createElement('td');
celda.textContent = obtenerProduccion(noTerminal, terminal, producciones, first, follow);
fila.appendChild(celda);
}, 100 * indiceColumna);
});
cuerpo.appendChild(fila);
}, 200 * indiceFila);
});
tabla.appendChild(cuerpo);
}
function analizarProducciones(entrada) {
if (!entrada || typeof entrada !== 'string') {
console.error("Invalid input for productions");
return {};
}
const lineas = entrada.split('\n');
const resultado = {};
lineas.forEach(linea => {
if (linea.trim() === "") return; // Skip empty lines
const partes = linea.trim().split('->');
if (partes.length < 2) {
console.error("Malformed production rule:", linea);
return;
}
const noTerminal = partes[0].trim();
const producciones = partes[1].trim().split('|').map(p => p.trim());
resultado[noTerminal] = producciones;
});
return resultado;
}
function analizarConjuntos(entrada) {
const lineas = entrada.split('\n');
const resultado = {};
lineas.forEach(linea => {
linea = linea.trim();
if (!linea) return; // Skip empty lines
const partes = linea.split(':');
if (partes.length < 2) {
console.error("Malformed input line:", linea);
return;
}
const noTerminal = partes[0]
.replace('Prim(', '')
.replace('Sgte(', '')
.replace(')', '')
.trim();
if (!partes[1]) {
console.error("Missing symbols for non-terminal:", noTerminal);
return;
}
const simbolos = partes[1]
.replace('{', '')
.replace('}', '')
.split(',')
.map(s => s.trim());
resultado[noTerminal] = simbolos;
});
return resultado;
}
function obtenerTerminales(producciones) {
const conjuntoTerminales = new Set();
Object.values(producciones).flat().forEach(prod => {
const coincidencias = prod.match(/[a-z]+|\S/g);
if (coincidencias) {
coincidencias.forEach(char => {
if (!producciones[char] && char !== '\'' && char !== 'ε') {
conjuntoTerminales.add(char);
}
});
}
});
conjuntoTerminales.delete('$');
const arrayTerminales = Array.from(conjuntoTerminales).sort();
arrayTerminales.push('$');
return arrayTerminales;
}
function obtenerProduccion(noTerminal, terminal, producciones, first, follow) {
const produccionesNoTerminal = producciones[noTerminal];
const conjuntoFirst = first[noTerminal];
const conjuntoFollow = follow[noTerminal];
for (const produccion of produccionesNoTerminal) {
if (produccion.startsWith(terminal)) {
return `${noTerminal} → ${produccion}`;
}
const primerSimboloProduccion = first[produccion[0]];
if (primerSimboloProduccion && primerSimboloProduccion.includes(terminal)) {
return `${noTerminal} → ${produccion}`;
}
if (produccion === 'ε' && conjuntoFollow.includes(terminal)) {
return `${noTerminal} → ε`;
}
if (!noTerminal.includes(terminal) && terminal === produccion) {
return `${noTerminal} → ${produccion}`;
}
}
return '';
}
function alternarExplicacion() {
const popupExplicacion = document.getElementById('popup-explicacion');
popupExplicacion.classList.toggle('mostrar');
}
function cerrarExplicacion() {
const popupExplicacion = document.getElementById('popup-explicacion');
popupExplicacion.classList.remove('mostrar');
}