You are on page 1of 3

#include<map>

#include<iostream>
#include<stack>
#include<string>
using namespace std;

//initialising stl stack


stack<string> s;
map<string,map<string,string> > m;
std::string::iterator it;

string input;

void push_to_stack(string st){

it = st.end()-1;
while(*it != '>'){

if(*it == 'd'){
it--;
s.push("id");
}
else if( *it == '\'' ){
it--;
if(*it == 'E'){
s.push("E'");
}
else if(*it == 'T'){
s.push("T'");
}
}
else
{
s.push( string() + *it );
}

--it;
if(s.top() == " "){
s.pop();
}
}
}

void display_stack(){
stack<string> st = s;
while(!st.empty()){
cout<<st.top()<<endl;
st.pop();
}
cout<<endl;
}

int main(){

ios_base::sync_with_stdio(false);
cin.tie(NULL);

//building LL(1) parsing table.


m["E"]["id"] = "E->TE'";
m["E"]["("] = "E->TE'";
m["E'"]["+"] = "E'->+TE'";
m["E'"][")"] = "E'->e";
m["E'"]["$"] = "E->e";
m["T"]["id"] = "T->FT'";
m["T"]["("] = "T->FT'";
m["T'"]["+"] = "T'->e";
m["T'"]["*"] = "T'->*FT'";
m["T'"][")"] = "T'->e";
m["T'"]["$"] = "T'->e";
m["F"]["id"] = "F->id";
m["F"]["("] = "F->(E)";

//appending $ to input string


input = "id+(idid)";
cout<<"Input String is: "+input<<endl;
input += '$';

//pushing $ and first expression into stack i.e.., $, E->TE'


s.push("$");
push_to_stack("E->TE'");
bool flag = true;
string temp;
for( int i=0;i<input.size();){

if(flag)
{

if(input[i]=='i'){
i++;
temp = "id";
}
else{
temp = string()+input[i];
}

//algorithm

//when top of stack matches with input symbol


if(s.top() == temp){
cout<<"match"+s.top()<<endl;
s.pop();
i++;
flag = true;
}
//if doesnt match expand the symbol by looking at the first in the
parsing table
else {
if (m.find(s.top()) != m.end() && m[s.top()].find(temp) !=
m[s.top()].end()) {
string temp1 = m[s.top()][temp];
s.pop();
cout<<temp1<<endl;
if(temp1[temp1.size()-1]=='e'){
//do nothing
}
else
{
push_to_stack(temp1);
}
flag = false;
}
else
{
break;
}
}

if(s.empty()){
cout<<"accepted"<<endl;
}
else{
cout<<"not accepted"<<endl;
}

return 0;
}

You might also like