Ambiguous CFG to recognize an infix expression and implement a parser that recognizes the infix expression using YACC
###### pr.h #########
struct holder
{
char name[10];
int val;
}st[20];
###### pr_4.l #######
%{
#include<stdio.h>
#include "y.tab.h"
#include "pr.h"
extern int yylval;
int var_cnt=0,i;
%}
%%
[0-9]+ {yylval=atoi(yytext);return(id);}
[a-z]+[a-z0-9]* {
for(i=0;i<var_cnt;i++)
if(strcmp(st[i].name,yytext)==0)
break; //already present variable
yylval=i; // in any case(found/not found)value remain same ie = i
if(i==var_cnt) //indicate new var encounter so insert in struct
{
strcpy(st[var_cnt++].name,yytext);
return(newvar);
}
else
return(oldvar);
}
[\n] {return('\n');}
. {return(yytext[0]);}
%%
struct holder
{
char name[10];
int val;
}st[20];
###### pr_4.l #######
%{
#include<stdio.h>
#include "y.tab.h"
#include "pr.h"
extern int yylval;
int var_cnt=0,i;
%}
%%
[0-9]+ {yylval=atoi(yytext);return(id);}
[a-z]+[a-z0-9]* {
for(i=0;i<var_cnt;i++)
if(strcmp(st[i].name,yytext)==0)
break; //already present variable
yylval=i; // in any case(found/not found)value remain same ie = i
if(i==var_cnt) //indicate new var encounter so insert in struct
{
strcpy(st[var_cnt++].name,yytext);
return(newvar);
}
else
return(oldvar);
}
[\n] {return('\n');}
. {return(yytext[0]);}
%%
####### pr_4.y ########
/*
3) Write an ambiguous CFG to recognize an infix expression and implement a parser that
recognizes the infix expression using YACC. Provide the details of all conflicting
entries in the parser table generated by LEX and YACC and how they have been
resolved.
Input : Infix expressions with variables
Output: a]Stepwise evaluation of expression,
b] Symbol table
c] explanation of conflicting entries in y.output file
d] explanation for resolving the ambiguities
*/
%{
#include<stdio.h>
int cnt=0,i;
#include "pr.h"
%}
%token id newvar oldvar
%%
edash : E '\n'
|
edash E '\n'
;
E : E'='E {st[$$].val=$3;$$=$3;}
|
E'+'E {$$=$1+$3;}
|
E'-'E {$$=$1-$3;}
|
E'*'E {$$=$1*$3;}
|
E'/'E {$$=$1/$3;}
|
oldvar {$$=st[$1].val;}
|
newvar {cnt++;}
|
id
;
%%
int main()
{
printf("\nEnter Inputs \n ");
yyparse();
printf("\n\tSymbol table\n\tVariable\tValue");
for(i=0;i<cnt;i++)
printf("\n\t%s\t\t%d\n",st[i].name,st[i].val);
return(0);
}
void yyerror (char *s)
{
fprintf (stderr,"%s", s);
}
1 comments:
so much errors
Post a Comment