Using lex-yacc implement bc like application of unix.
YACC FILE
Source Code:
%{
#include
#include
int yylex(void);
void yyerror(char *);
int s[26];
%}
%token INTEGER VAR S
%left '+' '-'
%left '*' '/'
%%
program :program stmt '\n'
|
;
stmt :e { printf("%d\n", $1); }
|VAR '=' e { s[$1]=$3;}
;
e :e '+' t { $$=$1 + $3;}
|e '-' t { $$=$1 - $3;}
|t {$$=$1;}
;
t :t '*' f { $$=$1 * $3;}
|t '/' f { $$=$1 / $3;}
|f { $$=$1;}
;
f : '(' e ')' { $$=$2;}
|INTEGER { $$=$1;}
|VAR {$$=s[$1];}
|S '(' INTEGER ')' {$$=sqrt($3);}
;
%%
void yyerror(char *s)
{
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
return 0;
}
Lex FILE
Source Code:
%{
#include
void yyerror(char *);
#include "y.tab.h"
%}
%%
"sqrt" {return S;}
[0-9]+ {yylval = atoi(yytext);return INTEGER;}
[a-z] {yylval=*yytext-'a';return VAR;}
[-+*/()=\n] return *yytext;
[ \t] ; /* skip whitespace */
. yyerror("invalid character");
%%
int yywrap(void) {
return 1;
}
OUTPUT:
[cmsa2@localhost ~]$ yacc -d calculator.y
[cmsa2@localhost ~]$ lex calculator.l
[cmsa2@localhost ~]$ cc lex.yy.c y.tab.c -lm -o cal
[cmsa2@localhost ~]$ ./cal
a=5
b=sqrt(49)
c=(a*b)-4
c
31
0 comments