Code:
//Lex program starts here
%{
/* LEX FILE*/
/*TO RECOGNIZE INFIX EXPRESSION AND EVALUATE IT.*/
#include"y.tab.h"
#include<stdio.h>
void yyerror(char *);
%}
%%
(([0-9]+)|([0-9]*\.[0-9]+)) {
yylval.dval=atof(yytext);
return NUM;
}
[+-/*\n,~()] {return (*yytext);}
sin return SIN;
cos return COS;
tan return TAN;
sqrt return SQRT;
exit exit(0);
[ \t] /*ignore*/
%%
int yywrap(void)
{
return 1;
}
//End of the program
(([0-9]+)|([0-9]*\.[0-9]+)) {
yylval.dval=atof(yytext);
return NUM;
}
//What happens in abouve block.
// "\." why this slash is given before "."
[+-/*\n,~()] {return (*yytext);}
// what this line is doing?
//Yacc program stars here
%{
/* YACC FILE */
/*LEX AND YACC PROGRAM*/
/*TO RECOGNIZE INFIX EXPRESSION AND EVALUATE IT.*/
#include<stdio.h>
#include<math.h>
void yyerror(char *);
%}
%union
{
double dval;
}
%token <dval> NUM
%token SIN COS TAN SQRT
%right '~'
%left '+' '-'
%left '*' '/'
%type <dval> expression
%%
program: program statement'\n'
|
;
statement:
expression { printf("%lf\n", $1); }
;
expression:
NUM
| expression '+' expression {$$ = $1 + $3;}
| expression '-' expression {$$ = $1 - $3;}
| expression '*' expression {$$ = $1 * $3;}
| expression '/' expression {$$ = $1 / $3;}
| '~' expression {$$ = -(1) * $2;}
| SQRT'('expression')' {$$ = sqrt( $3 );}
| SIN'('expression')' {$$ = sin ($3*3.142/180);}
| COS'('expression')' {$$ = cos ($3*3.142/180);}
| TAN'('expression')' {$$ = tan ($3*3.142/180);}
;
%%
main()
{
yyparse();
}
void yyerror(char *s)
{
fprintf(stderr,"%s\n",s);
}
//End of the program
// how is the execution of following block
%%
program: program statement'\n'
|
;
statement:
expression { printf("%lf\n", $1); }
;
expression:
NUM
| expression '+' expression {$$ = $1 + $3;}
| expression '-' expression {$$ = $1 - $3;}
| expression '*' expression {$$ = $1 * $3;}
| expression '/' expression {$$ = $1 / $3;}
| '~' expression {$$ = -(1) * $2;}
| SQRT'('expression')' {$$ = sqrt( $3 );}
| SIN'('expression')' {$$ = sin ($3*3.142/180);}
| COS'('expression')' {$$ = cos ($3*3.142/180);}
| TAN'('expression')' {$$ = tan ($3*3.142/180);}
;
%%
Please any suggestions are highly appreciated! Thanks a lot for all your time and support!