Vous êtes sur la page 1sur 2

# /* Experiment No.

## 6 : Implementation of Calculator using Lex and Yacc : /*

******* Lex file :*********88
/* Lex code for arithmetic operations */
%{
#include "y.tab.h"
#include <math.h>
%}
%%
[0-9]+(\.[0-9]+)? { yylval.dval = atof(yytext); return NUMBER; }
[ \t] ; /*Ignore white spaces */
[a-z] { yylval.index = yytext[0] - 'a' ; return NAME;}
"\$" { return 0; } /*End of input */
\n |
. return yytext[0];
%%
int yywrap(void)
{
return 1;
}
***** Yacc file : ******
/* Yacc input for arithmetic operations */
/* A variable is a lower case character from a to z of length 1 */
%{
#include <string.h>
#include <math.h>
#include <stdio.h>
double symtable[26];
%}
%union
{
double dval;
int index;
}
%token <index> NAME
%token <dval> NUMBER
%left '-' '+'
%left '*' '/'
%nonassoc UNARY
%type <dval> expr
%%
list: list statement '\n'
|
;
statement: NAME '=' expr { symtable[\$1] = \$3; }
| expr { printf("=%7.3f\n",\$1); }
;
expr: expr '+' expr { \$\$ = \$1 + \$3; }
| expr '-' expr { \$\$ = \$1 - \$3; }
| expr '*' expr { \$\$ = \$1 * \$3; }
| expr '/' expr {
if(\$3 == 0.0)
yyerror("Divide by zero");
else
\$\$ = \$1 / \$3;
}
| '-' expr %prec UNARY { \$\$ = -\$2; }
| '(' expr ')' { \$\$ = \$2 ; }
| NUMBER { \$\$ = \$1 ; }
| NAME { \$\$ = symtable[\$1];}
;

%%

/*void yyerror(char *s)
{
fprintf(stdout,"%s\n",s);
}
*/
int main()
{
yyparse();
return 0;
}

************ Commands for execution ************************
\$ lex my.l
\$ yacc d my.y
\$ cc c leyx.yy.c y.tab.c
\$ cc 0 lex lex.yy.0 y.tab.0
\$. lex