Lex and Yacc
Lex and Yacc
Lex File %{ #include<math.h> #include"y.tab.h" //for left,right,up & down %} %% [0-9]+|[0-9]*\.[0-9]+ { yylval.p = atof(yytext); return num; //return nonterminal } sin {return SIN;} //return token SIN to YACC cos {return COS;} //return token COS to YACC tan return TAN; //return token TAN to YACC log return LOG; //return token LOG to YACC sqrt return SQRT; //return token SQRT to YACC [\t]; \n return 0; . return yytext[0];
%%
Yacc File
%{ #include<stdio.h> #include<math.h> %} %union //to define possible symbol types { double p;} %token<p>num %token SIN COS TAN LOG SQRT /*Defining the Precedence and Associativity*/ %left '+','-' //lowest precedence %left '*','/' //highest precedenc %nonassoc uminu //no associativity
%type<p>exp %%
/* for storing the answer */ ss: exp {printf("=%g\n",$1);} /* for binary arithmatic operators */ exp : exp'+'exp { $$=$1+$3; } |exp'-'exp { $$=$1-$3; } |exp'*'exp { $$=$1*$3; } |exp'/'exp { if($3==0) { printf("Divide By Zero"); exit(0); } else $$=$1/$3; } |'-'exp {$$=-$2;} |'('exp')' {$$=$2;} |SIN'('exp')' {$$=sin($3);} |COS'('exp')' {$$=cos($3);} |TAN'('exp')' {$$=tan($3);} |LOG'('exp')' {$$=log($3);} |SQRT'('exp')' {$$=sqrt($3);} |num; %% /* extern FILE *yyin; */ main() { do { yyparse(); /* repeatedly tries to parse the }while(1); } yyerror(s) /* used to print the error message when an error is parsing of i/p */