Lex and Yacc program for grammar evaluation
####### pr_3.l ##########
%{
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return(id);}
[\n] {return(0);}
. {return(yytext[0]);}
%%
%{
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return(id);}
[\n] {return(0);}
. {return(yytext[0]);}
%%
######## pr_3.y #########
%{
#include<stdio.h>
int cnt=0;
%}
%token id
%left '+' '-'
%left '*' '/'
%%
edash : E {printf("\n\t\tAnswer=%d\n",$$);}
;
E : E'+'E {$$=$1+$3;printf("\n\t%d)E->E+E Rule is reduced ---- %d -> %d + %d",cnt++,$$,$1,$3);}
|
E'-'E {$$=$1-$3;printf("\n\t%d)E->E-E Rule is reduced ---- %d -> %d - %d",cnt++,$$,$1,$3);}
|
E'*'E {$$=$1*$3;printf("\n\t%d)E->E*E Rule is reduced ---- %d -> %d * %d",cnt++,$$,$1,$3);}
|
E'/'E {$$=$1/$3;printf("\n\t%d)E->E/E Rule is reduced ---- %d -> %d / %d",cnt++,$$,$1,$3);}
|
id
;
%%
int main()
{
printf("\n** We will see the execution sequence **");
printf("\n\tEnter Input = ");
yyparse();
return(0);
}
void yyerror (char *s)
{
fprintf (stderr,"%s", s);
}
/* OP
** We will see the execution sequence **
Enter Input = 10+5*2-1/1
0)E->E/E Rule is reduced ---- 1 -> 1 / 1
1)E->E-E Rule is reduced ---- 1 -> 2 - 1
2)E->E*E Rule is reduced ---- 5 -> 5 * 1
3)E->E+E Rule is reduced ---- 15 -> 10 + 5
Answer=15
pr@prashant-HP:~/LEX&YACC$
*/
0 comments:
Post a Comment