WAP in C to generate recursive descend parser


#include<stdio.h>
#include<conio.h>
#include<ctype.h>

int lptr=0;//look ahead pointer
char buff[100];//buffer to store input string
int success=1;//to reflect success or failure

void E();
void EDASH();
void T();
void TDASH();
void V();

void start()
{
 E();
}

int isvalid(char ch)
{
 if(isalpha(ch))
 return 1;
 else if(toascii(ch)>=47&&toascii(ch)<=57)
 return 1;
 else
 return 0;
}

void advance()
{
 lptr++;
}

void E()
{
 T();
 EDASH();
}

void EDASH()
{
 if(buff[lptr]=='+')
 {
  advance();
  T();
  EDASH();
 }
}

void T()
{
 V();
 TDASH();
}

void TDASH()
{
 if(buff[lptr]=='*')
 {
  advance();
  V();
  TDASH();
 }
}

void V()
{
 if(isvalid(buff[lptr]))
 {
  advance();
 }
 else if(buff[lptr]=='(')
 {
  advance();
  E();
  if(buff[lptr]==')')
  {
   advance();
  }
  else
  {
   printf("\n* Right parantheses missing ");
   success=0;
  }
 }
 else
 {
  printf("\n* Symbol(s) unidentified");
  success=0;
  getch();
  exit(0);
 }
}


void main()
{
 int n;
 clrscr();
 printf("\n\t----------------");
 printf("\n\t    GRAMMAR");
 printf("\n\t----------------\n");
 printf("\n\t E ::= TE'");
 printf("\n\t E'::= +TE'|$");
 printf("\n\t T ::= VT'");
 printf("\n\t T'::= *VT'|$");
 printf("\n\t V ::= <id>");
 printf("\n\t----------------\n\n");
 printf("\n Enter an expression: ");
 gets(buff);
 n=strlen(buff);
 start();

 if(success==1&&lptr>=n)
 {
  printf("\n* Correct syntax of expression");
 }
 else
 {
  printf("\n* Incorrect syntax of expression");
 }

 getch();
}

Post a Comment

0 Comments