I have implemented descent recursive parser in C++ that is based on EBNF grammar and its pseudo-code. Here is the code:
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
char s[100];
int pos=-1,len;
void asignstmt();
void variable();
void expression();
void term();
void primary();
void subscriptlist();
void identifier();
void letter();
void digit();
void error();
void main()
{
clrscr();
cout<<"Enter the String ";
cin>>s;
len=strlen(s);
s[len]='$';
asignstmt();
if (len==pos)
cout<<"string Accepted";
else
cout<<"Strig not Accepted";
getch();
}
void asignstmt()
{
pos++;
cout<<pos<<" "<<s[pos]<<endl;
if(pos<len)
{
variable();
if(s[pos]== '=')
{
pos++;cout<<pos<<" "<<s[pos]<<endl;
expression();
}
else
error();
}
}
void variable()
{
identifier();
if(s[pos]=='[')
{
pos++;cout<<pos<<" "<<s[pos]<<endl;
subscriptlist();
if(s[pos]==']')
pos++;
}
}
void expression()
{
term();
while (s[pos]=='+' || s[pos]=='-')
{
pos++; cout<<pos<<" "<<s[pos]<<endl;
term();
}
}
void term()
{
primary();
while (s[pos]=='*' || s[pos]=='/')
{
pos++; cout<<pos<<" "<<s[pos]<<endl;
primary();
}
}
void primary()
{
if ((s[pos]>='A'|| s[pos]>='a') &&(s[pos]<='Z'|| s[pos]<='z'))
variable();
else if ( s[pos]>='0' && s[pos]<='9')
digit();
else if ( s[pos]=='(')
{ pos++; cout<<pos<<" "<<s[pos]<<endl;
expression();
if(s[pos]==')')
pos++; cout<<pos<<" "<<s[pos]<<endl;
}
else
error();
}
void subscriptlist()
{
expression();
if(s[pos]==',')
pos++; cout<<pos<<" "<<s[pos]<<endl;
expression();
}
void identifier()
{
int fl=pos;
letter();
if(pos==fl)
error();
while ( (s[pos]>='A'&& s[pos]<='Z') ||(s[pos]>='a'&& s[pos]<='z')||(s[pos]>='0'&& s[pos]<='9'))
{ letter();
digit();
}
}
void letter()
{
if((s[pos]>='A'&& s[pos]<='Z') ||(s[pos]>='a'&& s[pos]<='z'))
pos++;
cout<<pos<<" "<<s[pos]<<endl;
}
void digit()
{
if(s[pos]>='0' && s[pos]<='9')
pos++;
cout<<pos<<" "<<s[pos]<<endl;
}
void error()
{
cout<<"Error Due to grammar Mismatch"<<endl;
getch();
exit(0);
}
This program simply takes an input(input will be a valid assignment statement without spaces) from user. Checks it whether the assignment statement is correctly suntax-ed or not. Then, prints a message of acceptance or rejection of input string.
My purpose of this implementation is to yield a parser. I have this code, that is working / recognizing correct assignment statement. But I am unable to implement this as a parser in which: It will take a .cpp file as an argument, check it character by character and see if it has correct assignment statement or not.
For example, if the name of my parser is userParser.cpp and the user code file that contains assignment statement is sample.cpp, then the command Like: userParser sample.cpp should parser and check the file for correct syntax of assignment statement. Please guide me to implement the c++ implementation as a parser. Thank you.