Saturday, May 12, 2012

Program to create Parser for IF-ELSE Statement using Flex(Lex) and Bison(Yacc)



'IF -ELSE' Statement is commonly used in all programming languages to implement various logical operations.
The control flows by checking a specific condition-if('cond) then expression if the condition is not satisfied the control flows 
to the else statement else-expression.


Parsing if-else statement is done by definitions of a grammar which uses Regular expressions.Compiler construction tools Flex(Lex) and Bison(Yacc) in Linux(Ubuntu) are used to define the grammar and basic operations .On compilation a c program is generated which is actually the parser for 'IF-ELSE' statement.A parser generates a Parse tree for Intermediate code generation.


Following are complete source codes for Flex and Bison programs to create a Parser for 'IF-ELSE' Statement which accepts valid 'IF-ELSE' Statements
 /*PARSER FOR IF ELSE STATEMENT*/  
 //c-madeeasy.blogspot.com  
 /*YACC PROGRAM*/  
 %{  
 #include<stdio.h>  
 #include<stdlib.h>  
 %}  
 %token num alpha LT GT EQ LE GE NE AND OR INC DEC END  
 %left '+''-'  
 %left '*''/'  
 %right '^'  
 %right '='  
 %nonassoc UMINUS  
 %nonassoc IF  
 %nonassoc ELSE  
 %left GE NE LT GT LE EQ  
 %left AND OR  
 %%  
 S:ST END{printf("\n Accepted\n");exit(0);}  
 ST:IF'('F')''{'ST'}'%prec IF  
  |IF'('F')''{'ST'}'ELSE'{'ST'}'  
  |E';'  
  |E';'ST  
  F:C LO C  
  |C  
 LO:AND  
  |OR  
  C:E RELOP E  
  |E  
  E:alpha '='E  
  |E'+'E   
  |E'-'E   
  |E'*'E   
  |E'/'E  
  |E'^'E  
  |'('E')'   
  |'-'E %prec UMINUS  
  |alpha  
  |num  
  |alpha INC  
  |alpha DEC  
 RELOP:LT  
    |GT  
    |EQ  
    |LE  
    |GE  
    |NE  
   ;  
 %%  
 #include"lex.yy.c"  
 int main()  
 {   
 yyparse();  
 yylex();  
 return END;  
 }  
 yyerror(char *s)  
 {  
  printf("\nError");  
 }  
 /*LEX PROGRAM*/  
 %{  
 #include"pgm4.tab.h"  
 %}  
 %%  
 "if" {return IF;}  
 "else" {return ELSE;}  
 "&&" {return AND;}  
 "||" {return OR;}  
 "<=" {return LE;}  
 ">=" {return GE;}  
 ">" {return GT;}  
 "<" {return LT;}  
 "!=" {return NE;}  
 "++" {return INC;}  
 "--" {return DEC;}  
 "==" {return EQ;}  
 [0-9]+ {return num;}  
 [a-zA-Z]+ {return alpha;}  
 [\t];  
 [\n];   
 "$" {return END;}  
 .  {return yytext[0];}  
 %%  
 /*OUTPUT  
 if(i>0)  
 {  
 a=0;  
 c++;  
 }  
 else  
 {  
 h;  
 }  
 $  
 Accepted  
 if(a>l)   
 {  
 w;  
 }  
 $  
 Accepted*/  


0 comments:

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.