Thursday, November 24, 2011

Infix to Prefix

Share Orkut

LEX Program



%{
#include <stdio.h>
#include <string.h>
#include "y.tab.h"
%}
DIGIT [0-9]+
ID [a-zA-Z][a-zA-Z0-9]*
op "+"|"-"|"*"|"/"
%%
{ID} { strcpy(yylval.str,yytext); return id; }
{DIGIT} { strcpy(yylval.str,yytext); return no; }
{op} { return (int) yytext[0]; }
\n { return(0); }
. { return err; }
%%


YACC Program



%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char result[50];
int f=0;
%}
%union{
  char str[50];
};
%token <str> id
%token <str> no
%token <str> err
%type <str> exp
%left '-' '+'
%left '*' '/'
%%
input: /* empty string */
   | input exp {strcpy(result,$2);}
   | error {f=1;}
   ;
exp: exp '+' exp { sprintf($$,"+%s %s",$1,$3); }
   | exp '-' exp {sprintf($$,"-%s %s",$1,$3); }
   | exp '*' exp { sprintf($$,"*%s %s",$1,$3); }
   | exp '/' exp {sprintf($$,"/%s %s",$1,$3);}
   | id {strcpy($$,$1);}
   | no {strcpy($$,$1);}
   ;
%%
int main()
{
   printf("\nEnter an arithmetic expression:\n\n");
   yyparse();
   printf("\n");
   if(f==1)
     printf("Invalid Expression\n");
   else
     puts(result);
   return 0;
}
int yywrap()
{
   return 1;
}
int yyerror(char *mes) {
   return 0;
}

OUTPUT



Order of execution--(multicharacter identifier and numbers)

Share Orkut

LEX Program



%{
#include <stdio.h>
#include <string.h>
#include "y.tab.h"
%}
DIGIT [0-9]+
ID [a-zA-Z][a-zA-Z0-9]*
op "+"|"-"|"*"|"/"
%%
{ID} { strcpy(yylval.str,yytext); return id; }
{DIGIT} { strcpy(yylval.str,yytext); return no; }
{op} { return (int) yytext[0]; }
\n { return(0); }
. { return err; }
%%


YACC Program



%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char result[50];
int f=0;
%}
%union{
  char str[50];
};
%token <str> id
%token <str> no
%token <str> err
%type <str> exp
%left '-' '+'
%left '*' '/'
%%
input: /* empty string */
   | input exp {strcpy(result,$2);}
   | error {f=1;}
   ;
exp: exp '+' exp { sprintf($$,"(%s + %s)",$1,$3); }
   | exp '-' exp {sprintf($$,"(%s - %s)",$1,$3); }
   | exp '*' exp { sprintf($$,"(%s * %s)",$1,$3); }
   | exp '/' exp {sprintf($$,"(%s / %s)",$1,$3);}
   | id {strcpy($$,$1);}
   | no {strcpy($$,$1);}
   ;
%%
int main()
{
   printf("\nEnter an arithmetic expression:\n\n");
   yyparse();
   printf("\n");
   if(f==1)
     printf("Invalid Expression\n");
   else
     puts(result);
   return 0;
}
int yywrap()
{
   return 1;
}
int yyerror(char *mes) {
   return 0;
}


OUTPUT

Wednesday, November 23, 2011

Order of execution

Share Orkut

LEX Program



%{
#include <stdio.h>
#include "y.tab.h"
%}
op "+"|"-"|"*"|"/"
%%
[a-z] { yylval=*yytext; return id; }
{op} { return (int) yytext[0]; }
\n { return(0); }
. { return err; }
%%

LEX Program



%{
#include <stdio.h>
#include <ctype.h>
#define YYSTYPE char
void push(char);
void attach(char);
int f=0;
struct node{
      char str[30];
};
struct node stack[20];
int stkPtr=-1;
%}
%token id err
%left '-' '+'
%left '*' '/'
%%
input: /* empty string */
      | input exp {}
      | error {f=1;}
   ;
exp: exp '+' exp { attach('+'); }
      | exp '-' exp { attach('-'); }
      | exp '*' exp { attach('*');}
      | exp '/' exp {attach('/');}
      | id { push($1); }
   ;
%%
void push(char c){
struct node newNode;
      newNode.str[0]=c;
      newNode.str[1]='\0';
      stack[++stkPtr]=newNode;
}
void attach(char op){
      struct node newNode;
      struct node temp1=stack[stkPtr--];
      struct node temp2=stack[stkPtr--];
      sprintf(newNode.str,"(%s %c %s)",temp2.str,op,temp1.str);
     stack[++stkPtr]=newNode;
}
int main()
{
     printf("\nEnter an arithmetic expression:\n\n");
      yyparse();
      printf("\n");
      if(f==0)
           printf("%s\n",stack[stkPtr].str);
      else
           printf("Invalid Expression\n");
      return 0;
}
int yywrap()
{
      return 1;
}
int yyerror(char *mes) {
      return 0;
}

Infix to Postfix using lex and yacc

Share Orkut

LEX Program



%{
#include <stdio.h>
#include "y.tab.h"
%}
op "+"|"-"|"*"|"/"
%%
[a-z] { yylval=*yytext; return id; }
{op} { return (int) yytext[0]; }
\n { return(0); }
. { return err; }
%%

YACC Program



%{
#include <stdio.h>
#include <ctype.h>
#define YYSTYPE char
int f=0;
%}
%token id err
%left '-' '+'
%left '*' '/'
%%
input: /* empty string */
     | input exp {}
     | error {f=1;}
   ;
exp: exp '+' exp { printf("+"); }
     | exp '-' exp { printf("-"); }
     | exp '*' exp { printf("*"); }
     | exp '/' exp { printf("/");}
     | id { printf("%c",yylval); }
   ;
%%
int main()
{
   printf("\nEnter an arithmetic expression:\n\n");
   yyparse();
   printf("\n");
   if(f==1)
     printf("Invalid Expression\n");
   return 0;
}
int yywrap()
{
   return 1;
}
int yyerror(char *mes) {
   return 0;
}

Sunday, October 9, 2011

Eliminate Left Recursion -- simple

Share Orkut
#include<stdio.h>
#include<string.h>
char inp[50][50];
char out[50][50];
void im_rec(int);
int out_ptr=0,len;
int main(){
   int i=0,j,f=0;
   char key[2];
   printf("Enter the grammer. Enter 's' to stop\n");
   while(1){
     scanf("%s",inp[i]);
     if(strcmp(inp[i],"s")==0)
       break;
     i++;
   }
   len=i;
   for(i=0;i<len;i++){
     f=0;
     for(j=0;inp[i][j]!='\0';j++){
       if((inp[i][j]=='>' || inp[i][j]=='|') && inp[i][j+1]==inp[i][0]){
         im_rec(i);
         f=1;
         break;
       }
     }
     if(f==0)
       strcpy(out[out_ptr++],inp[i]);
   }
   printf("Grammer without Left Recursion\n");
   for(i=0;i<out_ptr;i++)
     printf("%s\n",out[i]);
   return 0;
}
void im_rec(int i){
   int j=0,outj=2,outj1=3;
   char ep[11]="|epsilon";
   ep[8]='\0';
   out[out_ptr][j]=inp[i][j];
   out[out_ptr+1][j]=inp[i][j];
   out[out_ptr][++j]='-';
   out[out_ptr+1][j]='\'';
   out[out_ptr][++j]='>';
   out[out_ptr+1][j]='-';
   out[out_ptr+1][++j]='>';
   do{
     if((inp[i][j-1]=='>' || inp[i][j-1]=='|') && inp[i][j]==inp[i][0]){
       j++;
       if(out[out_ptr+1][outj1]!='>')
         out[out_ptr+1][++outj1]='|';
       while(inp[i][j]!='\0' && inp[i][j]!='|')
         out[out_ptr+1][++outj1]=inp[i][j++];
       out[out_ptr+1][++outj1]=inp[i][0];
       out[out_ptr+1][++outj1]='\'';
      }
     else{
       if(out[out_ptr][outj]!='>')
         out[out_ptr][++outj]='|';
       while(inp[i][j]!='\0' && inp[i][j]!='|')
          out[out_ptr][++outj]=inp[i][j++];
       out[out_ptr][++outj]=inp[i][0];
       out[out_ptr][++outj]='\'';
      }
   }while(inp[i][j++]!='\0');
   out[out_ptr][++outj]='\0';
   out[out_ptr+1][++outj1]='\0';
   strcat(out[out_ptr+1],ep);
   out_ptr+=2;
}

Operator precedence parser -- simple

Share Orkut

E -> E + E | E * E | id

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
char table[4][4]={'0','>','>','>',
       '<','>','<','>',
       '<','>','>','>',
       '<','<','<','0'};
char tab_ordr[4]={'i','+','*','$'};
char stack[100];
int stkPtr=-1;
void push(char);
char pop();
char peek();
void error();
int preced(char,char);
int main(){
   char str[20],temp,t[10];
   int len,inp_ptr=0,prec,countOfI=0;
   printf("Enter the expression:- ");
   scanf("%s",str);
   push('$');
   len=strlen(str);
   str[len]='$';
   str[len+1]='\0';
   while(str[inp_ptr]!='$' || peek()!='$')
   {
     if(str[inp_ptr]>='0'&&str[inp_ptr]<='9'){
       while(str[inp_ptr]>='0' && str[inp_ptr]<='9')
         inp_ptr++;
       str[--inp_ptr]='i';
   }
   prec=preced(peek(),str[inp_ptr]);
   if(prec==0){
     if(str[inp_ptr]=='i')
       countOfI++;
     else
       countOfI--;
     push(str[inp_ptr++]);
   }
   else if(prec==1){
     do{
       temp=pop();
     }while(preced(peek(),temp)!=0);
   }
   else
     error();
   }
   if(countOfI!=1)
     error();
   printf("Success\n",countOfI);
   return 0;
}
void push(char a){
   stack[++stkPtr]=a;
}
char pop(){
   return stack[stkPtr--];
}
char peek(){
   return stack[stkPtr];
}
void error(){
   printf("Error\n");
   exit(1);
}
int preced(char a,char b)
{
   int i,j;
   for(i=0;i<4;i++){
     if(tab_ordr[i]==a)
       break;
   }
   for(j=0;j<4;j++){
     if(tab_ordr[j]==b)
       break;
   }
   if(i==4 || j==4)
     error();
   else{
     if(table[i][j]=='<')
       return 0;
     else if(table[i][j]=='>')
       return 1;
     else
       return 2;
   }
}

Shift reduce parser-- simple

Share Orkut

E -> E + E | E * E | id

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str[100],stack[100];
int stkPtr=-1;
void push(char);
char pop();
char peek();
void error();
int main(){
   int i,len,k;
   printf("Enter the expression:- ");
   gets(str);
   push('$');
   len=strlen(str);
   str[len]='$';
   str[len+1]='\0';
   for(i=0;i<len;i++){
     if(str[i]>='0' && str[i]<='9'){
       while(str[i+1]>='0'&&str[i+1]<='9')
         i++;
       push('E');
     }
     else if(str[i]=='+' || str[i]=='-' || str[i]=='/' || str[i]=='*')
       push(str[i]);
     else
       error();
   }
   while(stkPtr>=3){
     if(stack[stkPtr]=='E' && (stack[stkPtr-1]=='+' || stack[stkPtr-1]=='-' || stack[stkPtr-1]=='*' || stack[stkPtr-1]=='/') && stack[stkPtr-2]=='E'){
     pop();
     pop();
   }
   else
     error();
   }
   if(stack[stkPtr]=='E' && stack[stkPtr-1]=='$')
     printf("SUCCESS\n");
   else
     error();
   return 0;
}
void push(char a){
   stack[++stkPtr]=a;
}
char pop(){
   return stack[stkPtr--];
}
char peek(){
   return stack[stkPtr];
}
void error(){
   printf("ERROR\n");
   exit(1);
}

Thursday, September 22, 2011

Eliminate Left Recursion

Share Orkut
#include<stdio.h>
#include<string.h>
char inp[50][50];
char out[50][50];
void im_rec(int);
void indirect(int,int);
int out_ptr=0,len;
int main(){
   int i=0,j,f=0;
   char key[2];
   printf("Enter the grammer. Enter 's' to stop\n");
   while(1){
     scanf("%s",inp[i]);
     if(strcmp(inp[i],"s")==0)
       break;
     i++;
   }
   len=i;
   for(i=0;i<len;i++){
     f=0;
     for(j=0;inp[i][j]!='\0';j++){
       if((inp[i][j]=='>' || inp[i][j]=='|') && inp[i][j+1]==inp[i][0]){
         im_rec(i);
         indirect(i,out_ptr-2);
         f=1;
         break;
       }
     }
     if(f==0){
       strcpy(out[out_ptr++],inp[i]);
       indirect(i,out_ptr-1);
     }
   }
   printf("Grammer without Left Recursion\n");
   for(i=0;i<out_ptr;i++)
     printf("%s\n",out[i]);
   return 0;
}
void im_rec(int i){
   int j=0,outj=2,outj1=3;
   char ep[11]="|epsilon";
ep[8]='\0';
   out[out_ptr][j]=inp[i][j];
   out[out_ptr+1][j]=inp[i][j];
   out[out_ptr][++j]='-';
   out[out_ptr+1][j]='\'';
   out[out_ptr][++j]='>';
   out[out_ptr+1][j]='-';
   out[out_ptr+1][++j]='>';
   do{
     if((inp[i][j-1]=='>' || inp[i][j-1]=='|') && inp[i][j]==inp[i][0]){
     j++;
     if(out[out_ptr+1][outj1]!='>')
       out[out_ptr+1][++outj1]='|';
       while(inp[i][j]!='\0' && inp[i][j]!='|'){
         out[out_ptr+1][++outj1]=inp[i][j++];

       }
       out[out_ptr+1][++outj1]=inp[i][0];
       out[out_ptr+1][++outj1]='\'';
     }
     else{
       if(out[out_ptr][outj]!='>')
         out[out_ptr][++outj]='|';
       while(inp[i][j]!='\0' && inp[i][j]!='|')
         out[out_ptr][++outj]=inp[i][j++];
       out[out_ptr][++outj]=inp[i][0];
       out[out_ptr][++outj]='\'';
     }
   }while(inp[i][j++]!='\0');
   out[out_ptr][++outj]='\0';
   out[out_ptr+1][++outj1]='\0';
   strcat(out[out_ptr+1],ep);
   out_ptr+=2;
}
void indirect(int i,int outPtr){
   int j=3,k,tempPtr,l,tp,m;
   char temp[50];
   m=i;
   while(out[outPtr][j]!='\0'){
     if(out[outPtr][j-1]=='>' || out[outPtr][j-1]=='|'){ //search each production
       for(i=m+1;i<len;i++){ //search each rule
         tempPtr=0;
         if(inp[i][0]==out[outPtr][j]){ // if starting of production is a nonterminal

          for(k=0;inp[i][k]!='\0';k++){ //search the production of nonterminal
           if((out[outPtr][0]==inp[i][k]) && (inp[i][k-1]=='>' || inp[i][k-1]=='|')){ //check for any indirect recursion
            l=3;
//substitute the nonterminal with its production
            do{
             if(out[outPtr][l]=='|' || out[outPtr][l]=='\0'){
              tp=k+1;
              while(inp[i][tp]!='|' && inp[i][tp]!='\0')
               temp[tempPtr++]=inp[i][tp++];
             }
             if(out[outPtr][l]!='\0')
             temp[tempPtr++]=out[outPtr][l];
            }while(out[outPtr][l++]!='\0');
            k=tp-1;
          }
          else
           temp[tempPtr++]=inp[i][k];
          }
          temp[tempPtr]='\0';
          strcpy(inp[i],temp);
        }

      }
    }
    j++;
   }
}

Output


Operator precedence parser

Share Orkut

E -> E + E | E * E | id


#include<stdio.h>
#include<string.h>
#include <stdlib.h>
char table[4][4]={'0','>','>','>',
         '<','>','<','>',
         '<','>','>','>',
         '<','<','<','0'};
char tab_ordr[4]={'i','+','*','$'};
int stk_res[100];
char stack[100];
int stkPtr=-1,strePtr=-1;
void push(char);
char pop();
void pushres(int);
int popres();
char peek();
void error();
int preced(char,char);
int main(){
   char str[20],temp,t[10];
   int len,inp_ptr=0,prec,no,f;
   printf("Enter the expression:- ");
   scanf("%s",str);
   push('$');
   len=strlen(str);
   str[len]='$';
   str[len+1]='\0';
   while(str[inp_ptr]!='$' || peek()!='$')
   {
     f=0;
     if(str[inp_ptr]>='0'&&str[inp_ptr]<='9'){
       no=atoi(&str[inp_ptr++]);
       while(str[inp_ptr]>='0' && str[inp_ptr]<='9')
         inp_ptr++;
       str[--inp_ptr]='i';
       f=1;
     }
     prec=preced(peek(),str[inp_ptr]);
     if(prec==0){
       if(f==1)
         pushres(no);
       push(str[inp_ptr++]);
     }
     else if(prec==1){

       do{
         temp=pop();
         switch(temp){
         case '+':if(strePtr<1)
             error();
           pushres(popres()+popres());
           break;
         case '*':if(strePtr<1)
             error();
           pushres(popres()*popres());
           break;
         }
       }
       while(preced(peek(),temp)!=0);
     }
     else
       error();
     }
     printf("Result= %d\n",popres());
     return 0;
}
void push(char a){
   stack[++stkPtr]=a;
}
char pop(){
   return stack[stkPtr--];
}
void pushres(int a){
   stk_res[++strePtr]=a;
}
int popres(){
   return stk_res[strePtr--];
}
char peek(){
  return stack[stkPtr];
}
void error(){
   printf("Error\n");
   exit(1);
}
int preced(char a,char b)
{
  int i,j;
  for(i=0;i<4;i++){
     if(tab_ordr[i]==a)
       break;
  }
  for(j=0;j<4;j++){
     if(tab_ordr[j]==b)
       break;
  }
  if(i==4 || j==4)
     error();
  else{
     if(table[i][j]=='<')
       return 0;
       else if(table[i][j]=='>')
         return 1;
       else
         return 2;
  }
}

Output




Shift reduce parser

Share Orkut

E -> E + E | E * E | id

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str[100],stack[100];
int stkPtr=-1;
void push(char);
char pop();
char peek();
void error(int);
void display(char[],int);
int main(){
  int i,len,tp,k;
   char tmp[3],ch,dis[30];
  printf("Enter the expression:- ");
  gets(str);
  push('$');
  len=strlen(str);
  str[len]='$';
  str[len+1]='\0';
  printf("--------------------------------------------------------------------------------------------------\n");
  printf("|\t\tStack\t\t|\t\tInput\t\t|\t\tAction\t\t |\n");
  printf("--------------------------------------------------------------------------------------------------");
  for(i=0;i<len;i++){
    if(str[i]>='0' && str[i]<='9'){
      tp=i;
      while(str[i+1]>='0'&&str[i+1]<='9')
         i++;
      display("shift",tp);
      push('I');
      if(str[i+1]!='\0'){
        display("reduce:- E->I",i+1);
        ch=pop();
        push('E');
      }
    }
    else if(str[i]=='+' || str[i]=='-' || str[i]=='/' || str[i]=='*'){
       display("shift",i);
      push(str[i]);
    }
    else
      error(i);
  }
  while(stkPtr>=3){
    for(i=stkPtr,k=0;k<3;i--,k++)
      tmp[k]=stack[i];
      if(tmp[0]=='E' && (tmp[1]=='+' || tmp[1]=='-' || tmp[1]=='*' || tmp[1]=='/') && tmp[2]=='E'){
         sprintf(dis,"reduce:- E->%c%c%c",tmp[0],tmp[1],tmp[2]);
        display(dis,strlen(str)-1);
        pop();
        pop();
      }
    else
      error(strlen(str)-1);
  }
  k=stkPtr;
  for(i=stkPtr;i>=0;i--)
    tmp[i]=stack[i];
  tmp[k+1]='\0';
  if(strcmp(tmp,"$E")==0)
    display("SUCCESS",strlen(str)-1);
  else
    error(strlen(str)-1);
  printf("\n--------------------------------------------------------------------------------------------------\n");
  return 0;
}
void push(char a){
  stack[++stkPtr]=a;
}
char pop(){
   return stack[stkPtr--];
}
char peek(){
  return stack[stkPtr];
}
void error(int a){
  display("ERROR",a);
  printf("\n--------------------------------------------------------------------------------------------------\n");
  exit(1);
}
void display(char a[100],int m){
  int j;
  char *ptr,stk[100];
  ptr=&str[m];
  printf("\n| ");
  for(j=0;j<=stkPtr;j++)
    stk[j]=stack[j];
  stk[j]='\0';
  printf("%-30s",stk);
  printf("|%25s\t",ptr);
  printf("|\t%-25s|",a);
}

Output




Recursive descent parser

Share Orkut

E -> E + T | T
T -> T * F | F
F -> (E) | id

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void T();
void EPRIME();
void F();
void TPRIME();
void ERROR();
void E();
int i=0;
char str[100];
int main(){
  printf("Enter the expression:- ");
  gets(str);
   E();
  if(strlen(str)==i)
    printf("Valid Expression\n");
  else
    printf("Invalid Expression\n");
  return 0;
}
void E(){
  T();
  EPRIME();
}
void EPRIME(){
  if(str[i]=='+'){
    i++;
    T();
    EPRIME();
  }
}
void T(){
  F();
  TPRIME();
}
void TPRIME(){
   if(str[i]=='*'){
    i++;
    F();
    TPRIME();
  }
}
void F(){
   if(str[i]>='0'&&str[i]<='9'){
    i++;
    while(str[i]>='0'&&str[i]<='9')
      i++;
  }
  else{
    if(str[i]=='('){
      i++;
      E();
      if(str[i]==')')
        i++;
      else
        ERROR();
    }
    else
      ERROR();
  }
}
void ERROR(){
  printf("Invalid Expression\n");
   exit(1);
}

Output


Friday, July 29, 2011

Recognize if-else, while and do-while

Share Orkut


Lex Program


%{
#include "y.tab.h"
%}
DIGIT   [0-9]+
ID     [a-zA-Z][a-zA-Z0-9]*
OP    "+"|"-"|"*"|"/"|"%"|"=="|">"|"<"|">="|"="|"<="|"--"|"++"|"!="
OTHR     ";"|"+"|"("|")"|"{"|"}"
ERR     [0-9][a-zA-Z0-9]*
%%
"if"     { return IF; }
"while" { return WHILE; }
"do"    { return DO; }
"else"    { return ELSE; }
{DIGIT} { return DIGIT; }
{ID}    { return ID; }
{ERR}    { return ERR; }
{OP}    { return OPERATOR; }
{OTHR}  { return (int) yytext[0]; }
\n
.
%%
int main()
{
         char inp[20];
         printf("Enter the input file name:-  ");
         scanf("%s",inp);
         yyin=fopen(inp,"r");
         callParser();
         fclose(yyin);
         return 0;
}

Yacc Program


%{
#include <stdio.h>
void callParser();
int if_count=0;
int while_count=0;
int do_count=0;
%}
%token DIGIT ID IF ELSE WHILE DO OPERATOR ERR
%left IF ELSE WHILE DO
%%
COMMANDS: /* empty */
           |COMMANDS WHILE_STMT { while_count++; }
           |COMMANDS IF_STMT { if_count++; }
           |COMMANDS DO_STMT { do_count++; }
       |error
;
WHILE_STMT: WHILE COND ';'
       | WHILE COND '{' STMTS '}'
       | WHILE COND COMMANDS
;
IF_STMT: IF COND ';'
       | IF COND COND ';'
       | IF COND '{' STMTS '}' 
       | IF COND COND ';' ELSE COND ';'
       | IF COND COND ';' ELSE '{' STMTS '}'
       | IF COND '{' STMTS '}' ELSE COND ';'
       | IF COND '{' STMTS '}' ELSE '{' STMTS '}'
       | IF COND COMMANDS ELSE COND ';'
       | IF COND COMMANDS ELSE '{' STMTS '}'
       | IF COND COND ';' ELSE COMMANDS
       | IF COND '{' STMTS '}' ELSE COMMANDS
;
DO_STMT: DO COND ';' WHILE COND ';'
       | DO '{' STMTS '}' WHILE COND ';'
       | DO COMMANDS WHILE COND ';'
;
STMTS: STMTS COND ';'
       | COND ';'
       | STMTS COMMANDS
       |
;
COND: COND OPERATOR COND
       | OPERATOR COND
       | COND OPERATOR
       | ID
       | DIGIT
       | '(' COND ')'
;
%%
void callParser(){
         yyparse();
         printf("No of while statments %d\n",while_count);
         printf("No of if statments %d\n",if_count);
         printf("No of do while statments %d\n",do_count);
}
int yywrap()
{
         return 1;
}
int yyerror(char *mes) {
        return 0;
}

Thursday, July 28, 2011

Arithematic calculator using lex and yacc

Share Orkut


Lex Program


%{
#include <stdio.h>
#include "y.tab.h"
%}
number        [0-9]+
flot         [0-9]*"."[0-9]+
op        "+"|"-"|"*"|"/"|"("|")"|"^"|"%"
%%
{number} {    yylval.fvalue=atof(yytext); return number;    }
{flot} {    yylval.fvalue=atof(yytext); return number;    }
{op}    {    return (int) yytext[0];    }
\n      { return(0); }
.    { return err; }
%%

Yacc Program

%{
#include <stdio.h>
#include <math.h>
int f=0;
float result;
%}
%union {
     float fvalue;
     char *string;
};
%token <fvalue> number
%token <string> err
%type <fvalue> exp
%left '-' '+'
%left '*' '/'
%left NEG
%right '^'  
%%
input:    /* empty string */
          | input exp {result=$2;}
         | error {f=1;}
       ;
exp:     exp '+' exp             { $$ = $1 + $3;   }
           | exp '-' exp             { $$ = $1 - $3;    }
           | exp '*' exp             { $$ = $1 * $3;    }
           | exp '/' exp             { $$ = $1 / $3;    }
           | '-' exp  %prec NEG      { $$ = -$2;        }
           | exp '^' exp             { $$ = pow ($1, $3); }
           | '(' exp ')'             { $$ = $2;         }
       | number                  { $$ = $1;         }
     ;
%%
int main()
{
         printf("\nEnter an arithmetic expression:\n\n");
         yyparse();
         if(f==0)
            printf("Result %f\n",result);
         else
            printf("Invalid Expression\n");
         return 0;
}
int yywrap()
{
         return 1;
}
int yyerror(char *mes) {
        return 0;
}

Wednesday, July 27, 2011

Arithematic Calculator

Share Orkut
%{
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define YYSTYPE double
%}
%token number
%left '-' '+'
%left '*' '/'
%right '^'
%right NEG
%%
input: /* empty string */
    | input exp '\n'{printf("Result %lf\n",$2);}
    | error '\n'{printf("Invalid Expression\n",$2);}
;
exp: exp '+' exp { $$ = $1 + $3; }
    | exp '-' exp { $$ = $1 - $3; }
    | exp '*' exp { $$ = $1 * $3; }
    | exp '/' exp { $$ = $1 / $3; }
    | '-' exp %prec NEG { $$ = -$2; }
    | exp '^' exp { $$ = pow ($1, $3); }
    | '(' exp ')' { $$ = $2; }
    | number { $$ = $1; }
;
%%
yylex()
{
    char c;
    while((c=getchar())==' ');
    if(isdigit(c)){
      ungetc(c,stdin);
       scanf("%lf",&yylval);
   return number;
   }
    return c;
}
int main()
{
    printf("\nEnter an arithmetic expression:\n\n");
    yyparse();
    return 0;
}
int yywrap()
{
    return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}

Recognize arithematic expression

Share Orkut


Lex program

%{
#include <stdio.h>
#include "y.tab.h"
%}
number        [0-9]+
flot         [0-9]*"."[0-9]+
identifier    [a-zA-Z][a-zA-Z0-9]*
errr     [0-9][a-zA-Z0-9]*
%%
{number} {    return number;    }
{flot} {    return number;    }
{identifier} {    return identifier;    }
{errr} {    return err; }
[ \t]+
\n  {    return(0); }
.    {    return (int) yytext[0];}
%%


Yacc program

%{
#include <stdio.h>
int f=0;
%}
%token number identifier err
%%
input:    /* empty string */
          | input exp
       |error {f=1;}
       ;
exp:      number
       |identifier
           | exp '+' exp            
           | exp '-' exp           
           | exp '*' exp            
           | exp '/' exp            
           | '-' exp 
           | exp '^' exp  
           | '(' exp ')'
     ;
%%
int main()
{
         printf("\nEnter an arithmetic expression:\n\n");
         yyparse();
         if(f==0)
            printf("Valid Expression \n");
         else
            printf("Invalid Expression\n");
         return 0;
}
int yywrap()
{
           return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}