Monday, 2 December 2013

Evaluation of Boolean Expression (2013)

YACC:

%{
#include<stdio.h>
%}
%token DIGIT
%left '|'
%left '&'
%right '!'
%left '<' '>' '='

%%
input: input ans '\n' { printf("Result : %d\n",$2); }
| error '\n'         { printf("\n :( \n"); }
|
;
ans: ans '&''&' expr   { $$ = $1 && $4; }
| ans '|''|' expr                 { $$ = $1 || $4; }
| '!' ans                 { $$ = ! $2; }
| expr           { $$ = $1; }
;
expr: DIGIT '<' DIGIT { $$ = $1 < $3; }
| DIGIT '>' DIGIT         { $$ = $1 < $3; }
| DIGIT '<''=' DIGIT { $$ = $1 <= $4; }
| DIGIT '>''=' DIGIT { $$ = $1 >= $4; }
        | DIGIT '=''=' DIGIT { $$ = $1 == $4; }
| DIGIT         { $$ = $1; }
| '(' expr ')'         { $$ = $2; }
;
%%
int main()
{
printf("Enter boolean expression :\n ");
yyparse();
}
int yyerror(char *s)
{
printf("Error %s",s);
}


LEX:

%{
#include "y.tab.h"
%}
digit [0-9]+
op "&"|"|"|"!"|"<"|">"|"="
%%
{digit} { yylval = atoi(yytext); return DIGIT; }
{op} { return *yytext; }
[ \t] ;
\n { return *yytext; }
.
%%
int yywrap()
{
return 1;
}


HOW TO RUN:
$ yacc -d bool.y
$ lex bool.l
$ gcc lex.yy.c y.tab.h -o bool
$ ./bool

OUTPUT:
Enter boolean expression :
1&&1
Result : 1
1||0
Result : 1
(5<6)&&(8==8)
Result : 1

No comments:

Post a Comment