Monday, May 7, 2012

Program to Construct Interpreter for Arthemetic Expression Evaluation using Bison and Flex



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*/  

1 comments:

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.