Calculator bison flex

calc.flex :

%{

#include “calc.tab.h”

#include <stdlib.h>

%}

 

%%

 

[0-9]+[.]?[0-9]*           {

yylval.p = atof(yytext);

return NUM;

}

 

“sin”                             { return SIN;}

 

“cos”                            { return COS;}

 

“tan”                            { return TAN;}

 

“sqrt”                           { return SQRT;}

 

“log”                            { return LOG;}

 

[-+*()=/\n]      return *yytext;

 

[ \t]       ; /* skip whitespace */

 

.           yyerror(“invalid character”);

 

%%

 

int yywrap(void) {

return 1;

}

calc.y :

%{

#include <stdio.h>

#include<math.h>

#include<stdlib.h>

void yyerror(const char *s);

%}

 

%union

{

double p;

}

 

 

%token NUM SIN COS TAN SQRT LOG

%start prog

 

%type <p> NUM exp

%left ‘+”-‘

%left ‘*”/’

 

%nonassoc UMINUS

 

%%

prog:prog S ‘\n’

|

;

S          : exp    {printf(“=%g\n”,$1);}

|

;

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 %prec UMINUS {$$=-$2;}

|'(‘exp’)’                        {$$=$2;}

|SIN'(‘exp’)’                 {$$=sin($3);}

|COS'(‘exp’)’                {$$=cos($3);}

|TAN'(‘exp’)’                {$$=tan($3);}

|LOG'(‘exp’)’                {$$=log($3);}

|SQRT'(‘exp’)’              {$$=sqrt($3);}

|NUM ;

 

%%

 

void yyerror(const char *s) {

printf(“%s\n”, s);

}

 

int main(void) {

yyparse();

return 1;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s