Vipin Parakkat
Vipin Parakkat

Reputation: 646

Convert infix to postfix in YACC(Bison)

I have been trying to convert an infix expression to postfix expression using YACC(Bison) with no success. I would like to know how it can be done? Sample code will be awesome :)

Upvotes: 0

Views: 14107

Answers (1)

george
george

Reputation: 149

This is my solution:

gram.l file:

%{
#include"y.tab.h"
extern int yylval;
%}
%%
[0-9]+  {yylval=atoi(yytext); return NUM;}
\n      return 0;
.       return *yytext;
%%

int yywrap(){
    return 1;
}

gram.y file:

%{
#include<stdio.h>
%}
%token NUM
%left '+' '-'
%left '*' '/'
%right NEGATIVE
%%
S:  E {printf("\n");}
    ;
E:  E '+' E {printf("+");}
    |   E '*' E {printf("*");}
    |   E '-' E {printf("-");}
    |   E '/' E {printf("/");}
    |   '(' E ')'
    |   '-' E %prec NEGATIVE {printf("-");}
    |   NUM     {printf("%d", yylval);}
    ;
%%

int main(){
    yyparse();
}

int yyerror (char *msg) {
    return printf ("error YACC: %s\n", msg);
}

shell:

yacc -d gram.y
flex gram.l
cc lex.yy.c y.tab.c
./a.out

example input and output:

2+6*2-5/3
262*+53/-

Upvotes: 9

Related Questions