Write a program to eliminate left recursion from a production of a grammar using JavaScript in Compiler Design
In this article, we present a JavaScript program that removes left recursion from a production of a grammar. We'll provide an overview of the theory behind left recursion and its elimination, delve into the code implementation, and showcase input/output examples.
A production of grammar is said to have left recursion if the leftmost variable of its RHS is same as variable of LHS.
If we have the left-recursive pair of productions:
A → Aα / β
where β does not begin with an A.
Then, we can eliminate left recursion by replacing the pair of productions with:
A → βA’
A’ → αA’ / ∈.
Eliminate left recursion from a production of a grammar in JavaScript:
Let's explore the JavaScript code that eliminates left recursion from a grammar production:
const RemoveLeftRecursion = (nonTerminal, productionRule) => {
let output1 = '';
let output2 = '';
let productions = productionRule.split('|').filter(e => e !== '#');
for (let production of productions) {
if (!production.startsWith(nonTerminal)) {
output1 += `${production}${nonTerminal}'|`;
console.log(`Production ${productions.indexOf(production) + 1} does not have left recursion`);
} else {
output2 += production.replace(nonTerminal, '').concat(`${nonTerminal}'|`);
console.log(`Production ${productions.indexOf(production) + 1} has left recursion`);
}
}
console.log(`The output is:`);
output1 = output1.slice(0, output1.length - 1);
console.log(`${nonTerminal} --> ${output1}`);
console.log(`${nonTerminal}' --> ${output2}#`);
}
let nonTerminal = 'E';
let productions = 'Ea|Eb|z';
console.log(`The given grammar is: ${nonTerminal} --> ${productions}`);
RemoveLeftRecursion(nonTerminal, productions);
0 Response to Write a program to eliminate left recursion from a production of a grammar using JavaScript in Compiler Design
Post a Comment