IMPLEMENTATION OF CALCULATOR USING YACC

AIM:
To write a program for implementing a calculator for computing the given expression using semantic rules of the YACC tool.

ALGORITHM:
1.A Yacc source program has three parts as follows:
Declarations
%%
translation rules
%%
supporting C routines
2.Declarations Section:
This section contains entries that:
i.Include standard I/O header file.
ii.Define global variables.
iii.Define the list rule as the place to start processing.
iv.Define the tokens used by the parser.
v.Define the operators and their precedence.
3.Rules Section:
The  rules  section  defines  the  rules  that  parse  the  input  stream. Each  rule  of  a  grammar production  and  the  associated  semantic action.
4.Programs Section:
The  programs  section  contains  the  following  subroutines.  Because these subroutines are included in this file, it is not necessary to use the yacc library when processing this file.
5.Main-The  required  main  program  that  calls  the  yyparse  subroutine  to start the program.
6.yyerror(s) -This  error-handling  subroutine  only  prints  a  syntax  error message
7.yywrap -The wrap-up subroutine that returns a value of 1 when the end of input occurs. The calc.lex file contains include statements for standard input and output, as programmar file information if we use the -d flag with the yacc command. They.tab.h file contains definitions for the tokens that the parser program uses.
8.calc.lex contains the rules to generate these tokens from the input stream.

PROGRAM:
Cal.l
%{
#include<stdio.h>
#include<math.h>
#include"y.tab.h"
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?)
{yylval.dval=atof(yytext);
return NUMBER;}
MEM {return MEM;}
[\t];
\$ {return 0;}
\n {return yytext[0];}
. {return yytext[0];}
%%
Cal.y
%{
#include<stdio.h>
#include<math.h>
double memvar;
%}
%union
{
double dval;
}
%token<dval> NUMBER
%token<dval> MEM
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%type<dval> expression
%%
start:statement '
\n'|start statement '
\n'statement:MEM '=' expression {memvar=$3;}
|expression
{printf("answer=%g
\n",$1);};
expression:expression'+'expression {$$=$1+$3;}
|expression'-'expression {$$=$1-$3;}
|expression'*'expression {$$=$1*$3;}
|expression'/'expression {if($3==0)
yyerror("divide by zero");
else
$$=$1/$3;
};
expression:'-'expression
%prec UMINUS {$$= -$2;}
|'('expression')' {$$=$2;}
|NUMBER {$$=$1;}
|MEM {$$=memvar;};
%%
int main(void)
{
printf("Enter the expression");
yyparse();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
int yyerror(char *error)
{
printf("%s\n",error);
return 0;
}

OUTPUT:
[CSE@localhost ~]$ lex cal.l
[CSE@localhost ~]$ yacc -d cal.y
[CSE@localhost ~]$ cc
lex.yy.c y.tab.c -ll
[CSE@localhost ~]$ ./a.out
Enter the expression5+3
answer=8
[cse@NFSSERVER ~]$ ./a.out
Enter the expression5+-5
answer=0
[cse@NFSSERVER ~]$ ./a.out
Enter the expression+5/
syntax error

RESULT:
Thus the program for implementation of Calculator using YACC tool is executed and verified.