0% found this document useful (0 votes)
128 views2 pages

Lex and Yacc

This document describes a Lex and Yacc program to implement a simple calculator. The Lex file defines tokens for numbers, mathematical functions like sin, cos, tan, log, and sqrt. The Yacc file defines the grammar and precedence of operators, and implements an expression that can evaluate expressions involving these tokens and functions. It uses the tokens passed from Lex to evaluate expressions and return results.

Uploaded by

somy19jan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views2 pages

Lex and Yacc

This document describes a Lex and Yacc program to implement a simple calculator. The Lex file defines tokens for numbers, mathematical functions like sin, cos, tan, log, and sqrt. The Yacc file defines the grammar and precedence of operators, and implements an expression that can evaluate expressions involving these tokens and functions. It uses the tokens passed from Lex to evaluate expressions and return results.

Uploaded by

somy19jan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Lex and Yacc Program to Implement Simple Calculator

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 %%

//Sets the type for non - terminal

/* 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 */

sentence until the i/p runs out */

char *s; { printf("ERROR"); }

You might also like