Implementation of Calculator using lex and yacc
file name Cal.l
%{
#include<stdio.h>
#include "y.tab.h"
//extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext); return NUMBER; }
[\n] return 0;
. return yytext[0];
%%
int yywrap()
{
return 1;
}
file name cal.y
%{
#include<stdio.h>
int flag=0;
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
%%
ArithmeticExpression: E{
printf("\nResult=%d\n",$$);
return 0;
};
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|E'%'E {$$=$1%$3;}
|'('E')' {$$=$2;}
| NUMBER {$$=$1;}
;
%%
int main()
{
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
return 0;
}
int yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
return 0;
}
output :
rach@rach-virtual-machine:~/Compilers/Calc$
lex Calc.l
rach@rach-virtual-machine:~/Compilers/Calc$ yacc -d Calci.y
rach@rach-virtual-machine:~/Compilers/Calc$ cc lex.yy.c y.tab.c
rach@rach-virtual-machine:~/Compilers/Calc$ ./a.out
4+5
Result=9
Entered arithmetic expression is Valid
rach@rach-virtual-machine:~/Compilers/Calc$ ./a.out
4+
Entered arithmetic expression is Invalid
rach@rach-virtual-machine:~/Compilers/Calc$ ./a.out
+6
Entered arithmetic expression is Invalid
rach@rach-virtual-machine:~/Compilers/Calc$ yacc -d Calci.y
rach@rach-virtual-machine:~/Compilers/Calc$ cc lex.yy.c y.tab.c
rach@rach-virtual-machine:~/Compilers/Calc$ ./a.out
4+5
Result=9
Entered arithmetic expression is Valid
rach@rach-virtual-machine:~/Compilers/Calc$ ./a.out
4+
Entered arithmetic expression is Invalid
rach@rach-virtual-machine:~/Compilers/Calc$ ./a.out
+6
Entered arithmetic expression is Invalid