Saturday, December 4, 2010

SHIFT REDUCE PARSER(in C)

#include
#include
#include
char stack[20];
char input[30];
int curr;
int stacktop=-1;
int len;
void pop()
{
stacktop-=2;
}
void printstack()
{ int i;
printf("\n");
for(i=0;i<=stacktop;i++)
printf("%c",stack[i]);
}
void printinput()
{
int j;
printf("\t\t");
for(j=curr+1;j printf("%c",input[j]);
}
int isnum(char c)
{
switch(c)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':return 1;
break;
default:return 0;

}
}
int isoper(char c)
{
switch(c)
{
case '+':return 2;
break;
case '-':return 3;
break;
case '*':return 4;
break;
case '/':return 5;
break;
default:return 0;

}
}
void shift(char in)
{
stacktop++;
stack[stacktop]=in;
printstack();
printinput();
printf("\t\tShift\n");
}
void reduce(int id)
{
printf("\t\t");
if(id==1)
{
stack[stacktop]='E';
printf("Reduced by E->id");
}
if(id==2)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E+E");
}
if(id==3)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E-E");
}
if(id==4)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E*E");
}
if(id==5)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E/E");
}
printf("\n");
}
int main()
{
int op;
printf("\nEnter the string to be tested:");
scanf("%s",input);
printf("\n%s\n",input);
curr=0;
len=strlen(input);
if(isoper(input[curr]))
{
printf("\n\nERROR REJECTED");
exit(1);
}
printf("\n\nSTACK\t\tINPUT\t\tCOMMENT\n");
do{
if(isnum(input[curr]))
{
shift(input[curr]);
reduce(1);
curr++;
}
op=isoper(input[curr]);
if(op>0)
{
shift(input[curr]);
curr++;
shift(input[curr]);
curr++;
if(isnum(stack[stacktop]))
{
reduce(op);
}
else
{
printf("\n\nERROR!! STIRNG REJECTED\n");
}
}
}while(curr if(stacktop==0&&stack[stacktop]=='E')
printf("\nString ACCEPTED\n");
}

4 comments:

  1. the 3 header files to be included are
    stdio.h
    string.h
    ctype.h

    ReplyDelete
  2. its getting error form this line
    "void printinput()
    {
    int j;
    printf("\t\t");
    for(j=curr+1;j printf("%c",input[j]);
    }"

    ReplyDelete