Wednesday, 29 April 2015

Filled Under:

How to Make a Desk Calculator using Flex/Lex and Yacc/Bison

Post By - Tanmay | 4/29/2015 05:38:00 am
In this tutorial you'll come to know about making a desk calculator using Lex and Yacc.

1:  statement:NAME'='expression {printf("x=%d",$2);};   
2:  |expression {printf("=%d",$1);};  
3:  expression:expression'-'NUMBER {$$=$1-$3;};  
4:  |expression'+'NUMBER {$$=$1+$3;};  
5:  |expression'*'NUMBER {$$=$1*$3;};  
6:  |expression'/'NUMBER {if($3==0) printf("0 Encountered"); else $$=$1/$3;};  
7:  |'('expression')' {$$=$2;}  
8:  |NUMBER {$$=$1;};  

Above grammar rule will be used in program. If you haven't installed the Flex and Bison in Windows, read the tutorial here.

Now, Lex File : calc.l

1:  %{  
2:  #include"y.tab.h"  
3:  extern int yylval;  
4:  %}  
5:  %%  
6:  [0-9]+ {yylval= atoi (yytext);printf("Number is Enc : %d",yylval); return NUMBER;}  
7:  [a-z] {printf("Character : %c",yytext[0]); return NAME;}  
8:  . {printf(""); return yytext[0];}  
9:  %%  

Yacc File : calc.y
1:  %{  
2:  #include"stdio.h"  
3:  int yyerror(char *str){  
4:        return fprintf(stderr,str);  
5:  }  
6:  int yywrap(){  
7:       return 1;  
8:  }  
9:  int main(){  
10:       yyparse();  
11:       return 1;  
12:  }  
13:  %}  
14:  %token NAME NUMBER  
15:  %%  
16:  statement:NAME'='expression {printf("x=%d",$2);};   
17:  |expression {printf("=%d",$1);};  
18:  expression:expression'-'NUMBER {$$=$1-$3;};  
19:  |expression'+'NUMBER {$$=$1+$3;};  
20:  |expression'*'NUMBER {$$=$1*$3;};  
21:  |expression'/'NUMBER {if($3==0) printf("0 Encountered"); else $$=$1/$3;};  
22:  |'('expression')' {$$=$2;}  
23:  |NUMBER {$$=$1;};  
24:  %%  

Compile & Link them using "gcc" to achieve the goal.

Output :