DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

SLR Parser In C++

04.14.2010
| 5428 views |
  • submit to reddit
        // description of your code here

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<stdio.h>

char in[30];
char T[]={"i+*()$E"};
char prod[4][5]={"EE+E","EE*E","E(E)","Ei"};

char M[10][8]={"sbbsbbg","bssbbab","sbbsbbg",              //matrix to store shift,
	       "brrbrrb","sbbsbbg","sbbsbbg",              //reduce,error and accept states
	       "bssbsbb","brsbrrb","brrbrrb",
	       "brrbrrb"};
int S[10][7]={{3,0,0,2,0,0,1},{0,4,5,0,0,0,0},{3,0,0,2,0,0,6}, //matrix to store goto and action states
	      {0,4,4,0,4,4,0},{3,0,0,2,0,0,7},{3,0,0,2,0,0,8},
	      {0,4,5,0,9,0,0},{0,1,5,0,1,1,0},{0,2,2,0,2,2,0},
	      {0,3,3,0,3,3,0}};



class stack
{
char a[20]; //stores the terminals and states
int b[20];  //stores the states
int top;
int topb;
public:
stack()
{
top=topb=0;
}

void push(char n)
{
a[top]=n;
top++;
}
void pushb(int n)
{
b[topb]=n;
topb++;
}
char pop()
{
if(top>0)
return a[--top];
else return -1;
}
int popb()
{
if(topb>0)
return b[--topb];
else return -1;
}

int tos()
{
return b[topb-1];
}
};

int search(char c)
{
 for(int i=0;i<strlen(T);i++)
 {
 if(c==T[i])
 return i;
 }
 return -1;
}

void print(int ser)
{
cout<<prod[ser][0]<<"->";
for(int i=1;i<strlen(prod[ser]);i++)
cout<<prod[ser][i];
cout<<endl;
}

void main()
{
clrscr();
stack s;
int i=0,x,ser;
char c;

gets(in);
s.pushb(0);
int k=0;
while(k<20)
{k++;
 x=search(in[i]);
 if(x==-1)
 break;
 c=M[s.tos()][x];
 if(c=='b')
 break;
 if(c=='a')
 {
 printf("\naccepted!!!");
 getch();
 exit(0);
 }
 if(c=='s')
 {
 s.push(in[i]);
 i++;
 s.pushb(S[s.tos()][x]);
 continue;
 }
 ser=S[s.tos()][x];
 ser--;
 for(int j=0;j<strlen(prod[ser])-1;j++)
 {
 s.pop();
 s.popb();
 }
 s.push(prod[ser][0]);
 s.pushb(S[s.tos()][search(prod[ser][0])]);
 print(ser);
 }
 printf("Error!!!");
 getch();
}