Is it possible to construct a simple arithmetic calculator in lex and Yacc?
If yes, please enlist the concepts/methods I should understand before proceeding.
Note : Before posting a question you should search about it,The following answer that I am gonna post is obtained from the above link, which I obtained from a google search.
The following code is used to implement calculator program using YACC and LEX.
cal.l
DIGIT [0-9]+\.?|[0-9]*\.[0-9]+
%option noyywrap
%%
[ ]
{DIGIT} { yylval=atof(yytext); return NUM;}
\n|. {return yytext[0];}
cal.y
%{
#include<ctype.h>
#include<stdio.h>
#define YYSTYPE double
%}
%token NUM
%left ‘+’ ‘-‘
%left ‘*’ ‘/’
%right UMINUS
%%
S : S E ‘\n’ { printf(“Answer: %g \nEnter:\n”, $2); }
| S ‘\n’
|
| error ‘\n’ { yyerror(“Error: Enter once more…\n” );yyerrok; }
;
E : E ‘+’ E { $$ = $1 + $3; }
| E’-‘E { $$=$1-$3; }
| E’*’E { $$=$1*$3; }
| E’/’E { $$=$1/$3; }
| ‘(‘E’)’ { $$=$2; }
| ‘-‘E %prec UMINUS { $$= -$2; }
| NUM
;
%%
#include “lex.yy.c”
int main()
{
printf(“Enter the expression: “);
yyparse();
}
yyerror (char * s)
{
printf (“% s \n”, s);
exit (1);
}