EX NO:5 LEX YACC Uninitialized, Unused Variables
15.2.17
AIM:
Write a lex and yacc program to perform syntax analysis and do the following:
Determine the variables that are declared and not initialized
Determine the variables that are declared but not used
CODE:
LEX :
%{
#include "[Link].h"
extern int yylval;
%}
%%
(int|float|char) {return BUILTIN;}
"," {return COMMA;}
";" {return SC;}
"=" {return EQ;}
[0-9]+ {return DIGIT;}
[a-zA-Z] {yylval=yytext[0]; return ID;}
("+"|"-"|"/") {return OPR;}
"\n" {return NL;}
%%
YACC:
%{
#include<stdio.h>
extern FILE *yyin;
char ni[20];
char nu[20];
int i=0,j=0,x=0,y=0;
%}
%token BUILTIN ID COMMA SC NL EQ DIGIT OPR
%%
start :
|start BUILTIN varlist SC NL {printf("valid\n");}
|start assign SC NL {}
;
varlist:varlist COMMA id {ni[i]=$3;i++;nu[j]=$3;j++;}
|id {ni[i]=$1;i++;nu[j]=$1;j++;}
|id EQ DIGIT {nu[j]=$1;j++; printf("declared and initialised is %cn",$1);};
id: ID {$$ = $1;};
assign: id EQ eval {
for(x=0;x<i;x++)
{
if($1==ni[x])
{
printf("initialised variable present %c\n",$1);
ni[x]=0;
break;
}
}
};
eval:DIGIT {}
|id OPR id{
for(y=0;i<j;y++)
{
if($1==nu[y])
{
printf("declared variable used %c\n",$1);
nu[y]=0;
break;
}
}
for(y=0;y<j;y++)
{
if($3==nu[y])
{
printf("declared variable used %c\n",$3);
nu[y]=0;
break;
}
}
};
%%
void yyerror() {}
int yywrap() {return 1;}
void main(int argc, char *argv[])
{
yyin=fopen("[Link]","r");
yyparse();
printf("not initialised");
for(x=0;x<i;x++)
{
printf("%c\n",ni[x]);
}
printf("not used");
for(y=0;y<j;y++)
{
printf("%c\n",nu[y]);
}
}
INPUT FILE:
int a,x;
float y;
int b=10;
int c=5;
float e=5;
float m=10;
a=b+c;
x=a+m;
OUTPUT:
RESULT:
Thus the lex and yacc program to determine declared but uninitialized and unused
variables were verified successfully.