Parser
In compiling parsing is one of the most important steps where the input is parsed according to the grammar. In parsing we use stack and table of terminals and non-terminals.
//Submitted by Ayushi Garg(ProbDESK(http://www.ProbCOMP.com/forum/) Member:-Ayushi)//
#include<stdio.h>
#include<iostream>
#include<process.h>
using namespace std;
class stack
{
int s[100];
int top;
public:
stack()
{
top = -1;
}
void push(char ele)
{
top++;
s[top]=ele;
cout<<"\n push :"<<ele;
}
char pop()
{
char ele = s[top];
top--;
cout<<"\n pop :"<<ele;
return ele;
}
char rtop()
{
return s[top];
}
};
int main()
{
char non_terminal[]={'E','P','T','Q','F'};
char terminal[]={'+','*','(',')','i','$'};
char prod[][10]={"ETP","P+TP","P@","TFQ","Q*FQ","Q@","F(E)","Fi"};
int table[5][6]={{8,8,0,8,0,8},{1,8,8,2,8,2},{8,8,3,8,3,8},{5,4,8,5,8,5},{8,8,6,8,7,8}};
char input[100];
cin>>input;
stack st;
st.push('$');
st.push('E');
for(int i=0;input[i] != '\0';)
{
char top = st.rtop();
int term=-1,non_term=-1;
for(int j=0;j<6;j++)
{
if(top == terminal[j])
{
term=j;
break;
}
}
if(term != -1)
{
if(top != input[i])
{
cout<<"\nerror1";
exit(0);
}
else
{
st.pop();
i++;
}
}
else
{
for(int j=0;j<5;j++)
{
if(top==non_terminal[j])
{
non_term = j;
break;
}
}
int inp=-1;
for(int j=0;j<6;j++)
{
if(input[i] == terminal[j])
{
inp = j;
break;
}
}
int t = table[non_term][inp];
if(t==8)
{
cout<<"\nerror2";
exit(0);
}
else
{
cout<<endl<<prod[t];
int len=0;
st.pop();
for(int k=0;prod[t][k]!='\0';k++)
len++;
for(int k=len-1;k>=1;k--)
{
if(prod[t][k] != '@')
st.push(prod[t][k]);
}
}
}
}
return 0;
}
Download Program


