Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

//Title :- Recognizing ambiguous grammar from infix expression

%{
Lex file
#include "y.tab.h"
#include<stdlib.h>
#include<math.h>
void yyerro(char *s);
#undef yywrap
%}
%%
[a-z] {return NUMBER;}
[+\-*/()^]{ return *yytext; }
[\n] { return 0; }
[ \t] ; /* Ignore */
; /* Ignore */
%%
int yywrap()
{ return 1;
}
void yyerror(char *s)
{ printf("\nError \"%s\" at token : %s\n",s,yytext);
}

%{
Yacc file
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
typedef struct stack
{
char str[10];
}stack;
int sttop=0;
stack s[100];
%}
%union{
double no;
}
%token<no> NUMBER
%type<no> expr
%left '+' '-'
%left '*' '/'
%left '^'
%left '(' ')'
%%

input: expr { printf("\n S->E \n Accept\n"); popstack(); return 0; }


;expr: expr '+' expr { pushstack("E->E+E");}
| expr '-' expr { pushstack("E->E-E");}
| expr '*' expr { pushstack("E->E*E");}
| expr '/' expr { pushstack("E->E/E");}
| '(' expr ')' { }
| NUMBER { pushstack("E->ID");}
;%%
main()
{
//while(1)
yyparse();
}
void pushstack(char *str[])
{
sttop++;
strcpy(s[sttop].str,str);
}
void popstack()
{
char str[20];
while(sttop>0)
{
strcpy(str,s[sttop].str);
printf("%s\n",str);
sttop--;
}
}

//Infix_out
[root@localhost ~]# yacc -d infix.y
[root@localhost ~]# lex infix.l
[root@localhost ~]# gcc y.tab.c lex.yy.c -ll -lm -o infix
[root@localhost ~]# ./infix
[root@localhost ~]# ./infix
a*b+c
S->E
Accept
E->E+E
E->ID
E->E*E
E->ID
E->ID

You might also like