Parser for Function Definition - YACC Program - Compiler Lab



Program :

(Lex Program : fundf.l)

alpha [A-Za-z]
digit [0-9]

%%

[\t \n]             ;
int|float|void|char         return TYPE;
return                 return RETURN;
{digit}+             return NUM;
{alpha}({alpha}|{digit})*     return ID;
.                 return yytext[0];

%%


(Yacc Program : fundf.y)

%{
#include <stdio.h>
#include <stdlib.h>
%}
%token TYPE RETURN ID NUM
%right "="
%left '+' '-'
%left '*' '/'
%right UMINUS
%left '!'

%%

S    : FUN {printf("Input accepted\n"); exit(0);}
FUN    : TYPE ID '(' PARAM ')' '{' BODY '}'     
      ;
PARAM    : PARAM ',' TYPE ID
    | TYPE ID
    |
    ;         
BODY    : BODY BODY
    | PARAM ';'
    | E ';'        
        | RETURN E ';'
        |
    ;              
E    : ID '=' E
    | E '+' E
    | E '-' E
    | E '*' E
    | E '/' E       
    | ID
    | NUM   
    ;

%%

#include "lex.yy.c"
main()
{
    printf("Enter the expression:\n");
    yyparse();
 }
 
     

Output :
nn@linuxmint ~ $ lex fund.l
nn@linuxmint ~ $ yacc fund.y
conflicts: 17 shift/reduce, 11 reduce/reduce
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
Enter the expression:
float sum(int term)
{
    float result;
    result=result+term;
    return result;
}
Input accepted
nn@linuxmint ~ $


0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...