Compiler Construction: Assignment # 02
Compiler Construction: Assignment # 02
Total Marks: 05
Obtained Marks:
Compiler Construction
Assignment # 02
Instructions: Copied or shown assignments will be marked zero. Late submissions are not
entertained in any case.
Question
Write a LEX/FLEX and YACC/BISON program to implement a simple arithmetic calculator.
It should be able to recognize negative numbers and add, subtract, multiply, divide and group
sub-expressions. Sample expressions to test the program are given below. Give the source
code and the runtime screen.
2+2*2
(2+2)*2
12/2+3
2*25/3
Solution
Lex code
%{
/* Definition section */
#include<stdlib.h>
#include "y.tab.h"
extern int yylval;
%}
/* Rule Section */
%%
[0-9]+ {
yylval=atoi(yytext);
return NUMBER;
}
'<=' return LE;
'>=' return GE;
'!=' return NE;
'==' return EQ;
[\t] ;
[\n] return 0;
. return yytext[0];
%%
Yacc code
%{
/* Definition section */
#include<stdio.h>
int flag=0;
%}
%nonassoc UMINUS
/* Rule Section */
%%
ArithmeticExpression: E{
printf("Result=%d", $$);
return 0;
};
E:E '+' E {$$=$1+$3;}
|E '-' E {$$=$1-$3;}
|E '*' E {$$=$1*$3;}
|E '/' E {$$=$1/$3;}
|E '%' E {$$=$1%$3;}
| NUMBER {$$=$1;}
|E GE E {$$=$1 >= $3 ;}
|E LE E {$$=$1 <= $3 ;}
|E NE E {$$=$1 != $3 ;}
|E EE E {$$=$1 == $3 ;}
|UMINUS E {$$=-$1 ;}
;
%%
//driver code
int main()
{
//printf("\nEnter the Expression:\n");
yyparse();
//if(flag==0)
//printf("\nEntered arithmetic expression is Valid\n\n");
// return 0;
}
int yyerror()
{
Output :
---
---
---