Write a program using bison that creates a sequence of simple steps (three-address code) according to a given grammar for arithmetic expressions. For example, if the input is- a + b * c + d
the program should print the output as-
T1 = b * c T2 = a + T1 T3 = T2 + d
[Hint: use a global variable, say t initialised to 1. Store its value as an attribute of the LHS grammar symbol whenever a reduce-action is performed for a simple arithmetic operation., and increment t (so that for the next use it has a different value). Use this attribute value whenever that symbol appears on the RHS for a subsequent reduce action. When printing print this value along with the letter T.]
%{
#include "parser.tab.h"
#include <stdio.h>
int t = 1; // Global variable for temporary variables
void yyerror(const char *s);
int yylex(void);
%}
%token NUM ID
%token PLUS MINUS TIMES DIVIDE LPAREN RPAREN
%%
program: expr { printf("n"); } ;
expr: term { printf("n"); }
| expr PLUS term { printf("T%d = T%d + T%dn", t, $1, $3); $$ = t++; }
| expr MINUS term { printf("T%d = T%d - T%dn", t, $1, $3); $$ = t++; }
;
term: factor { printf("n"); }
| term TIMES factor { printf("T%d = T%d * T%dn", t, $1, $3); $$ = t++; }
| term DIVIDE factor { printf("T%d = T%d / T%dn", t, $1, $3); $$ = t++; }
;
factor: NUM { printf("T%d = %dn", t, $1); $$ = t++; }
| ID { printf("T%d = %sn", t, yytext); $$ = t++; }
| LPAREN expr RPAREN { $$ = $2; }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Error: %sn", s);
}
int main(void) {
yyparse();
return 0;
}
but i got error gcc parser.tab.c -o parser -lfl parser.y: In function ‘yyparse’: parser.y:31:36: error: ‘yytext’ undeclared (first use in this function); did you mean ‘yylex’? 31 | | ID { printf("T%d = %sn", t, yytext); $$ = t++; } | ^~~~~~ | yylex parser.y:31:36: note: each undeclared identifier is reported only once for each function it appears in
Rajveer Choudhary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.