Question
Hi, I am struggling with my Yacc Program. Here are the requirements: According to the following context-free grammar, write a yacc file as a integer
Hi, I am struggling with my Yacc Program. Here are the requirements:
According to the following context-free grammar, write a yacc file as a integer calculator that can do +, -, *, /, and ^ with or without ( ).
commandexpr
exprexpr + term | exprterm | term
termterm * term2 | term / term2 | term2 |-factor
term2factor ^ term2 | factor
factor( expr ) | NUMBER
In order to run calculator on real numbers the following needs to be added in the definition section and then the rest of the program needs to be made to work on real numbers.
%token NUMBER
%union { double val;
char op; }
%type
%type
%%
THE CODE I HAVE IS:
%{ #include
%token NUMBER
%%
command : exp {printf("%d ",$1);} ;
exp : exp '+' term {$$ = $1 + $3;} | exp "-" term {$$ = $1 - $3;} | exp '^' term {$$ = pow($1,$3);} |'(' exp ')' term {$$ = $2;} | term {$$ = $1;} ;
term : term '*' factor {$$ = $1 * $3;} | term '/' factor {$$ = $1 / $3;} | factor {$$ = $1;} ;
factor : NUMBER {$$ = $1;} | '(' exp ')' {$$ = $2;} ;
%%
main() { return yyparse(); }
int yylex(void) { int c; while((c = getchar()) == ' '); if ( isdigit(c) ) { ungetc(c, stdin); scanf("%d",&yylval); return(NUMBER); } if ( c == ' ') return 0; return(c); }
int yyerror(char * s) { fprintf(stderr,"%s ",s); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started