YACC program for Conversion of Infix to Postfix expression

Problem: Write a YACC program for conversion of Infix to Postfix expression.

Explanation:
YACC (Yet another Compiler-Compiler) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc.

Examples:



Input: a*b+c 
Output: ab*c+

Input: a+b*d
Output: abd*+ 

Lexical Analyzer Source Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

%{
  /* Definition section */
%}
ALPHA [A-Z a-z]
DIGIT [0-9]
  
/* Rule Section */
%%
{ALPHA}({ALPHA}|{DIGIT})*  return ID;
{DIGIT}+                   {yylval=atoi(yytext); return ID;}
[\n \t]                    yyterminate();
.                          return yytext[0];
%%

chevron_right


Parser Source Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

%{
   /* Definition section */
   #include <stdio.h>
   #include <stdlib.h>
%}
  
%token    ID
%left    '+' '-'
%left    '*' '/'
%left    UMINUS
  
/* Rule Section */
%%
  
S  :  E
E  :  E'+'{A1();}T{A2();}
   |  E'-'{A1();}T{A2();}
   |  T
   ;
T  :  T'*'{A1();}F{A2();}
   |  T'/'{A1();}F{A2();}
   |  F
   ;
F  :  '('E{A2();}')'
   '-'{A1();}F{A2();}
   |  ID{A3();}
   ;
  
%%
  
#include"lex.yy.c"
char st[100];
int top=0;
  
//driver code
int main()
{
    printf("Enter infix expression:  "); 
    yyparse();
    printf("\n");
    return 0;
}
A1()
{
    st[top++]=yytext[0];
}
  
A2()
{
    printf("%c", st[--top]);
}
  
A3()
{
    printf("%c", yytext[0]);
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.