CE442 Design of Language Processor 7CE (July-Dec 2020)
Practical – 7
Aim: Implement a Program that remove left recursion on given grammar.
Theory:
Left Recursion
• A production of grammar is said to have left recursion if the leftmost variable of its RHS is same as
variable of its LHS.
• A grammar containing a production having left recursion is called as Left Recursive Grammar.
• Left recursion is considered to be a problematic situation for Top down parsers.
• Therefore, left recursion has to be eliminated from the grammar.
Removal of Left Recursion
Left recursion is eliminated by converting the grammar into a right recursive grammar.
If we have the left-recursive pair of productions:
A → Aα / β
(Left Recursive Grammar)
where, β does not begin with an A.
Then, we can eliminate left recursion by replacing the pair of productions with:
A → βA’
A’ → αA’ / ∈
(Right Recursive Grammar)
This right recursive grammar functions same as left recursive grammar.
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define REP(i,n) for(i=0;i<n;i++)
#define FOR(i,x,y) for(i=x;i<=y;i++)
char str[100],temp[100],mm[100][100];
void removeLeftRecursion(char str[])
{
int i,j,k,x,in;
k = x = 0;
in = -1;
memset(temp,'\0',sizeof(temp));
REP(i,strlen(str))
{
if(str[i]=='|' || str[i]==' ' || str[i]=='=')
{
if(strlen(temp))
{
strcpy(mm[k++],temp);
memset(temp,'\0',sizeof(temp));
x = 0;
}
ID: 17CE016 Page 31
CE442 Design of Language Processor 7CE (July-Dec 2020)
}
else if(str[i]!='=')
{
temp[x++] = str[i];
}
}
if(strlen(temp))
{
strcpy(mm[k++],temp);
memset(temp,'\0',sizeof(temp));
x = 0;
}
FOR(i,1,k-1)
{
if(mm[i][0]!=mm[0][0])
{
in = i;
break;
}
}
int ff = 0;
FOR(i,1,k-1)
{
if(mm[i][0]==mm[0][0])
ff = 1;
}
if(!ff)
{
printf("\t\tGiven Grammer is not Immediate Left Recursive.");
return ;
}
if(in == -1)
{
printf("\t\t%c -> Z%c'\n",mm[0][0],mm[0][0]);
printf("\t\t%c' -> ");
FOR(i,1,k-1)
{
if(strlen(mm[i])<2)
continue;
if(i>1)
printf(" | ");
FOR(j,1,strlen(mm[i])-1)
printf("%c",mm[i][j]);
printf("%c'",mm[0][0]);
}
printf("| NULL \n");
}
else
{
printf("\t\t%c -> ",mm[0][0]);
int f = 0;
ID: 17CE016 Page 32
CE442 Design of Language Processor 7CE (July-Dec 2020)
REP(i,strlen(mm[in]))
{
if(mm[in][i]==mm[0][0])
{
f = 1;
printf("%c'",mm[0][0]);
}
else
printf("%c",mm[in][i]);
}
if(!f)
printf("%c'",mm[0][0]);
printf("\n");
printf("\t\t%c' -> ",mm[0][0]);
int fl = 0;
FOR(j,1,k-1)
{
if(j==in)
continue;
if(fl)
printf(" | ");
fl = 1;
f = 0;
if(mm[j][0]!=mm[0][0])
printf("%c",mm[j][0]);
FOR(i,1,strlen(mm[j])-1)
{
if(mm[j][i]==mm[0][0])
{
f = 1;
printf("%c'",mm[0][0]);
}
else
printf("%c",mm[j][i]);
}
if(!f)
printf("%c'",mm[0][0]);
}
printf("| NULL \n");
}
}
void main()
{
printf("---- Enter Grammar Rules ----\n");
while(gets(str))
{
removeLeftRecursion(str);
printf("\n\n");
}
}
ID: 17CE016 Page 33
CE442 Design of Language Processor 7CE (July-Dec 2020)
Output:
Conclusion: From this practical, I learnt how to remove left recursion from Grammar rules.
ID: 17CE016 Page 34