Write a program to eliminate left factoring from a production of a grammar using JavaScript in Compiler Design
In this article, we will explore left factoring and present a JavaScript program that eliminates left factoring from a production of a grammar. We will explain the theory behind left factoring, delve into the code implementation, and provide input/output examples.
Left factoring is a grammar transformation technique that involves identifying common prefixes among two or more productions and factoring them out into a separate production.
For example, A -> α β | α γ
After left factoring:
A -> α A'
A' -> β | γ
This process helps in avoiding ambiguity and redundancy in the grammar. The goal of left factoring is to simplify the grammar by removing unnecessary repetition.
Remove left factoring from a production of a grammar in JavaScript:
Let's explore the JavaScript code that eliminates left factoring from a grammar production:
let nonTerminal = 'S';
let productions = 'iEtS|iEtSeS|a|iES';
console.log(`The given grammar is: ${nonTerminal} --> ${productions}`);
const LeftFactoring = (productions) => {
let words = productions.split('|').filter(e => e !== '');
if (words.length > 1) {
const counts = words.reduce((acc, w) => {
let prefix = '';
for (let i = 0; i < w.length; i++) {
prefix += w[i];
acc[prefix] = (acc[prefix] || 0) + 1;
}
return acc;
}, {});
try {
const alpha = Object.entries(counts)
.filter(([_, v]) => v > words.length / 2.0)
.sort((a, b) => b[0].length - a[0].length)[0][0];
let nonTerminalPrime = '';
words.filter(word => word.includes(alpha))
.map(word => word.replace(alpha, ''))
.filter(e => e !== '')
.forEach(e => nonTerminalPrime += e + '|');
let gamma = words.filter(word => !word.includes(alpha));
console.log(`${nonTerminal} --> ${alpha}${nonTerminal}'${gamma ? `|${gamma}` : ''}`);
console.log(`${nonTerminal}' --> ${nonTerminalPrime}#`);
nonTerminal = `${nonTerminal}'`;
LeftFactoring(nonTerminalPrime);
} catch {
console.log('...................');
}
}
}
console.log(`After Left Factoring:`);
LeftFactoring(productions);
0 Response to Write a program to eliminate left factoring from a production of a grammar using JavaScript in Compiler Design
Post a Comment