About

Kannur University btech CSE study materials, question papers, syllabus . . .

Saturday, June 8, 2013

S6 CSE COMPILER LAB : PARSER FOR POSTFIX EXPRESSION EVALUATION


            /* PARSER FOR POSTFIX EXPRESSION EVALUATION  */  

YACC Program

%{
#include<stdio.h>
#include<stdlib.h>
int top,i;
char stack[50];
%}
%token sp digit
%left '+''-'
%left '*''/'
%left '^'
%%
S:E {printf("%d",$$);}
 ;
E:E sp E'+'  {$$=$1+$3;}
 |E sp E'-'  {$$=$1-$3;}
 |E sp E'*'  {$$=$1*$3;}
 |E sp E'/'  {$$=$1/$3;}
 |E sp E'^'  {if($3==0)
              $$=1;
              else
               {
                $$=1;
                for(i=0;i<$3;i++)
                {
                  $$=$$*$1;
                }
               }
              }
  |digit  {$$=$1;}
  ;
%%
#include "lex.yy.c"
main()
{
 yyparse();
 yylex();
 return 0;
}
yyerror(char *s)
{
 printf("\nerror\n");
}





LEX Program

%{
#include "y.tab.h"
%}
%%
[0-9]+  {yylval=atoi(yytext);return digit;}
[ ]     {return sp;}
[ \t]   ;
[\n]   {return 0;}
.      {return yytext[0];}
%%

OUTPUT

8 7+
15

6 5*
30

2 3^
8


0 comments:

Post a Comment