Arithmetic expressions are common in programming languages,this program is a sample implementation of an Interpreter to evaluate basic arithmetic expressions like a*b,a+b etc .This is accomplished by using compiler construction tools Flex(Lex) and Bison(Yacc) in Linux operating system environment.The following are complete source codes for two Flex and Bison Programs to create an evaluator for Arithmetic Expressions
/*YACC PROGRAM*/
%{
#include<stdio.h>
%}
%token num alpha END
%left '+''-'
%left '*''/'
%right '^'
%nonassoc UMINUS
%%
S:E END{printf("\n The given expression is valid\n");exit(0);}
E:E'+'E
|E'-'E
|E'*'E
|E'/'E
|'-'E %prec UMINUS
|'('E')'
|E'^'E
|num
|alpha
;
%%
#include"lex.yy.c"
int main()
{
yyparse();
yylex();
return 0;
}
yyerror(char *s)
{
printf("\nerror\n");
}
/*LEX PROGRAM*/
%{
#include "pgm2.tab.h"
%}
%%
[0-9]+ {return num;}
[a-z]+ {return alpha;}
[ \t] ;
[\n] ;
"$" {return END;}
. {return yytext[0];}
%%
/*OUTPUT
r+x
$
The given expression is valid
d++c
$
error*/
No comments:
Post a Comment