arithmetic expression evaluation flex - bison or lex - yacc program
arith.lex
*********************
%{
/* Definition section*/
#include "arith.tab.h"
extern yylval;
%}
%option noyywrap
%%
[0-9]+ {
yylval = atoi(yytext);
return NUMBER;
}
[a-zA-Z]+ { return ID; }
[ \t]+ ; /*For skipping whitespaces*/
\n return 0;
. { return yytext[0]; }
%%
arith.y yacc/bison program
******************************************
%{
/* Definition section */
#include <stdio.h>
%}
%token NUMBER ID
// setting the precedence
// and associativity of operators
%left '+' '-'
%left '*' '/'
/* Rule Section */
%%
E : T {
printf("Result = %d\n", $$);
return 0;
}
T : T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%
int main() {
printf("Enter the expression\n");
yyparse();
}
/* For printing error messages */
int yyerror(char* s) {
printf("\nExpression is invalid\n");
}
Execution
$bison -d arith.y
$ flex arith.lex
$ gcc lex.yy.c arith.tab.c
$ ./a.out
Enter the expression
2+3-2/2
Result = 4
Comments
Post a Comment