simple calculator yacc program
cal.lex
**************************
%{
/* Definition section */
#include<stdio.h>
#include "cal.tab.h"
extern int yylval;
%}
%option noyywrap
/* Rule Section */
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;
}
[\t] ;
[\n] return 0;
. return yytext[0];
%%
cal.y
*********************************************
%{
/* Definition section */
#include<stdio.h>
int flag=0;
void yyerror();
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
/* Rule Section */
%%
S: 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;}
;
%%
//driver code
void main()
{
printf("\nEnter Any Arithmetic Expression\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
}
void yyerror()
{
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
}
Execution
**************
$ bison -d cal.y
$ lex cal.lex
$ gcc lex.yy.c cal.tab.c
$ ./a.out
Enter Any Arithmetic Expression
(2+3)*2
Result=10
Entered arithmetic expression is Valid
(base) [ftpb07@login01 yacc]$ ./a.out
Enter Any Arithmetic Expression
2-3*2
Result=-4
Entered arithmetic expression is Valid
(base) [ftpb07@login01 yacc]$ ./a.out
Enter Any Arithmetic Expression
5/3-2*2
Result=-3
Entered arithmetic expression is Valid
Enter Any Arithmetic Expression
2-3+
Entered arithmetic expression is Invalid
Comments
Post a Comment