Postfix Evaluaion YACC LEX S6

YACC Program:(p1.y)

%{
#include<stdio.h>
#include<assert.h>
 int Pop();
 int Top();
 void Push(int val);
%}

%token T_Int

%%
S : S E    {printf(" %d\n", Top());}
  |
  ;

E : E E '+' {Push(Pop()+Pop());}
  | E E '-' {int op2=Pop();Push(Pop()-op2);}
  | E E '*' {Push(Pop() * Pop());}
  | E E '/' {int op2=Pop();Push(Pop()/op2);}
  | T_Int   {Push(yylval);}
  ;
%%
#include "lex.yy.c"
 int stack[100],count=0;

 int Pop()
 {
  assert(count>0);
  return stack[--count];
 }

 int Top()
 {
  assert(count>0);
  return stack[count-1];
 }

 void Push(int val)
 {
  assert(count<sizeof(stack)/sizeof(int));
  stack[count++]=val;
 }

int main()
 {
  return yyparse();
 }

Lex progam:(p1.l)

DIGIT    [0-9]
%%
{DIGIT}+ {yylval=atoi(yytext);return T_Int;}
[-+*/] {return yytext[0];}
\n    yyterminate();
.    ;

Output:

students@ccflab-desktop:~$ lex p1.l
students@ccflab-desktop:~$ yacc p1.y
conflicts: 1 shift/reduce
students@ccflab-desktop:~$ gcc y.tab.c -ll -ly
students@ccflab-desktop:~$ ./a.out
2 3 +
5
students@ccflab-desktop:~$ ./a.out
2 3 *
6
students@ccflab-desktop:~$ ./a.out
3 2 -
1
students@ccflab-desktop:~$ ./a.out
6 3 /
2
students@ccflab-desktop:~$


1 comment:

Related Posts Plugin for WordPress, Blogger...