Sunday, October 25, 2015

Parser for sample language using YACC

PROGRAM

file name: a4.l

%{
#include "y.tab.h"
#include<stdio.h>
extern int yylval;
%}

%%
[0-9]+ {yylval=atoi(yytext);return DIGIT;}
"#include <"[.a-zA-Z]*">\n" {return HEADER;}
"{"[\n]* {return STB;}
"}"[\n]* {return ENB;}
";"[\n]* {return ENDS;}
"main()"[\n]* {return MAIN;}
int|char|double {return DTYPE;}
"," {return SEP;}
[+-/*] {return OP;}
"=" {return EQ;}
"(" {return OPB;}
")" {return CLB;}
"if" {return IF;}
"else" {return ELSE;}
"printf("[^\)]*")" {printf("Function call\n");return FUNC;}
"scanf("[^\)]*")" {printf("Function call\n");return FUNC;}
[a-zA-Z][a-zA-Z0-9]* {return VAR;}
[ \t]+ ;

%%

int yywrap()
{
 return 1;
}

a4.y

%{
#include<stdio.h>
extern FILE* yyin;
%}

%token DIGIT VAR OP DTYPE EQ IF ELSE HEADER ENDS SEP OPB CLB STB ENB MAIN FUNC

%%
St: S MAIN STB stmts ENB {printf("Program within main\n");};
S: HEADER S| HEADER {printf("Headers\n");};
stmts: stmt|stmts stmt|;
stmt: IF OPB CLB STB stmts ENB {printf("IF statement\n");};
stmt: IF OPB CLB STB stmts ENB ELSE STB stmts ENB {printf("IF ELSE statement\n");};
stmt: exp|DTYPE varlist ENDS|FUNC ENDS {printf("Statement\n");};
varlist: VAR | varlist SEP VAR ;
exp: VAR EQ dv opn ENDS {printf("Expression\n");};
dv: DIGIT| VAR
opn: OP dv|OP dv opn|;
%%

void yyerror(char *s)
{
 printf("Incorrect syntax\n");
}

main()
{
char filename[20];
printf("Enter file name: ");
scanf("%s",filename);
yyin=fopen(filename,"r");
yyparse();
}


main.c

#include <stdio.h>
#include <iostream.h>
#include <math.h>
main()
{
printf("Hello");
int a,b,c;
c=5;
b=7+c;
scanf("%d",a);

if()
{
}

if()
{
}
else
{
}
}


OUTPUT

[amodi@localhost ~]$ lex a4.l
[amodi@localhost ~]$ yacc -d a4.y
yacc: 12 shift/reduce conflicts, 1 reduce/reduce conflict.
[amodi@localhost ~]$ gcc lex.yy.c y.tab.c
[amodi@localhost ~]$ ./a.out
Enter file name: main.c
Headers
Function call
Statement
Expression
Expression
Function call
Statement

IF statement


IF ELSE statement
Program within main

No comments:

Post a Comment

Perform a suitable assignment using Xen Hypervisor or equivalent open source to configure it. Give necessary GUI.

 To install kvm on Fedora:  yum install kvm  yum install virt-manager libvirt libvirt-python python-virtinst  su -c "yum install @v...