CD Likki

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

1.

Implement a lexical Analyzer for given language using C

Program:
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str
)==0||strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||strcmp("static",str)==0||strcmp("switch",
str)==0||strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}
int main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
printf("\nEnter the c Program: ");/*gets(st1);*/
f1=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c))
{
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


}
else if(c==' '||c=='\t')
printf(" ");
else if(c=='\n')
lineno++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\nThe no's in the program are");
for(j=0; j<i; j++)
printf("%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("The keywords and identifiersare:");
while((c=getc(f2))!=EOF)
{
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
}
fclose(f2);
f3=fopen("specialchar","r");
printf("\nSpecial characters are");
while((c=getc(f3))!=EOF)
printf("%c",c);
printf("\n");
fclose(f3);
printf("Total no. of lines are:%d",lineno);
return 0;
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


Output:
Enter the c Program: a+b*c
^Z
The no's in the program are
The keywords and identifiersare:
a is an identifier
b is an identifier
c is an identifier
Special characters are+*
Total no. of lines are:2.

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


2. Implementation of Lexical Analyzer using lex Tool
lex program:
( exp2.l )

%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor
directive",yytext);} int |
float |
char |
double |
while |
for |
struct |
typedef
| do |
if |
break |
continue
| void |
switch |
return |
else |
goto {printf("\n\t%s is a keyword",yytext);}
"/*" {COMMENT=1;}{printf("\n\t %s is a COMMENT",yytext);}
{identifier}\( {if(!COMMENT)printf("\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT)printf("\n BLOCK BEGINS");}
\} {if(!COMMENT)printf("BLOCK ENDS ");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT)printf("\n\t %s is a
STRING",yytext);} [0-9]+ {if(!COMMENT) printf("\n %s
is a NUMBER ",yytext);}
\)(\:)? {if(!COMMENT)printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t %s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("var.c","r")

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


; if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{
return(1);
}

Program for lexical analysis:


( var.c )

#include<stdio.h>
#include<conio.h>
void main()
{
int
a,b,c;
a=1;
b=2;
c=a+b;
printf("Sum:%d",c);
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


Output:
Compile and running
[root@home ~]# lex exp2.l
[root@home ~]# cc lex.yy.c
[root@home ~]# ./a.out
#include<stdio.h> is a preprocessor
directive #include<conio.h> is a
preprocessor directive void is a keyword
FUNCTION
main(
)
BLOCK BEGINS
int is a keyword
a IDENTIFIER,
b IDENTIFIER,
c
IDENTIFIER;
a
IDENTIFIER
= is an ASSIGNMENT
OPERATOR 1 is a NUMBER ;
b IDENTIFIER
= is an ASSIGNMENT
OPERATOR 2 is a NUMBER ;
c IDENTIFIER
= is an ASSIGNMENT OPERATOR
a IDENTIFIER+
b
IDENTIFIER;
FUNCTION
printf(
"Sum:%d" is a
STRING, c
IDENTIFIER
)
;
BLOCK ENDS

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


3a. Recognize a valid arithmetic expression that uses operator +,-,*and/.

Program:
( exp3a.l )
%{
#include "y.tab.h"
%}
%%
[a-zA-Z_][a-zA-Z_0-9]* return id;
[0-9]+(\.[0-9]*)? return
num; [+/*] return op;
. return yytext[0];
\n return 0;
%%
int yywrap()
{
return 1;
}
( exp3a.y )
Program:
%{
#include<stdio.h>
int valid=1;
%}
%token num id op
%%
start : id '=' s
';' s : id x
| num x
| '-' num x
| '(' s ')' x
;
x : op s
| '-' s
|
;
%%
int yyerror()
{
valid=0;
printf("\nInvalid expression!\n");
return 0;
}
int main()
{
printf("\nEnter the
expression:\n"); yyparse();
if(valid)
{
printf("\nValid expression!\n");
}
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


Output:
[root@home ~]# yacc -d exp3.y
[root@home ~]# lex exp3.l
[root@home ~]# gcc lex.yy.c y.tab.c
-w [root@home ~]# ./a.out
Enter the expression:
a=b*c;
Valid expression!

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


3b. Recognize a valid variable which starts with a letter followed by any number of
letters or digits

Program:
( exp3b.l )
%{
#include "y.tab.h"
%}
%%
[a-zA-Z_][a-zA-Z_0-9]* return
letter; [0-9] return digit;
. return yytext[0];
\n return 0;
%%
int yywrap()
{
return 1;
}

( exp3b.y )
%{
#include<stdio.h>
int valid=1;
%}
%token digit letter
%%
start : letter s
s : letter s
| digit s
|
;
%%
int yyerror()
{
printf("\nIts not a identifier!\n");
valid=0;
return 0;
}
int main()
{
printf("\nEnter a name to tested for identifier ");
yyparse();
if(valid)
{
printf("\nIt is a identifier!\n");
}
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


Output:
[root@home ~]# yacc -d exp3b.y
[root@home ~]# lex exp3b.l
[root@home ~]# gcc lex.yy.c y.tab.c
-w [root@home ~]# ./a.out
Enter a name to tested for identifier
_abc It is a identifier!

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


3c.Implementation of Calculator using LEX and YACC
Program:
( exp3c.l )
%{
#include<stdio.h>
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext); return NUMBER;
}
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap(){
return 1;
}
( exp3c.y )
%{
#include<stdio.h>
int flag=0;
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
%%
ArithmeticExpression: E{
printf("\nResult=%d\n",$$);
return 0;
};
E:E'+'E {$$=$1+$3;}
|E'-'E {$$=$1-$3;}
|E'*'E {$$=$1*$3;}
|E'/'E {$$=$1/$3;}
|E'%'E {$$=$1%$3;}
|'('E')' {$$=$2;}
| NUMBER {$$=$1;}
;
%%
void main(){
printf("\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction, Multiplication,
Divison, Modulus and Round brackets:\n");
yyparse();
if(flag==0)
printf("\nEntered arithmetic expression is Valid\n\n");
}
void yyerror(){
printf("\nEntered arithmetic expression is Invalid\n\n");
flag=1;
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


Output:
[root@home ~]# yacc -d exp3c.y
[root@home ~]# lex exp3c.l
[root@home ~]# gcc lex.yy.c y.tab.c
-w [root@home ~]# ./a.out
Enter Any Arithmetic Expression which can have operations Addition, Subtraction,
Multiplication, Divison, Modulus and Round brackets:
((5+6+10+4+5)/5)%2
Result=0
Entered arithmetic expression is valid

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


3d. Convert BNF rules into YACC form
Program:
( 3d.l )
%{
#include"y.tab.h"
#include<stdio.h>
#include<string.h>
int LineNo=1;
%}
identifier [a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
main\(\) return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float return TYPE;
{identifier} {strcpy(yylval.var,yytext);
return VAR;}
{number} {strcpy(yylval.var,yytext);
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
( 3d.y )
%{
#include<string.h>
#include<stdio.h>
struct quad
{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int items[100];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
| ASSIGNMENT ';'
| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '=' EXPR{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
| VAR
| NUM
;
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


;
IFST: IF '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK { strcpy(QUAD[Index].op,"GOTO"); strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop();
Ind=pop();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE'('CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
if(argc>1){
fp=fopen(argv[1],"r");
if(!fp){
printf("\n File not found");
exit(0);
}
yyin=fp;
}
yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator \tArg1 \tArg2 \tResult" "\n\t\t -------------------- ");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
}
printf("\n\t\t ");
printf("\n\n"); return 0; }
void push(int data)
{ stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0);
}
data=stk.items[stk.top--];
return data;}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
sprintf(QUAD[Index].result,"t%d",tIndex++);
strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\n Error on line no:%d",LineNo);
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


( test.c )

main()
{
int a,b,c;
if(a<b)
{
a=a+b;
}
while(a<b)
{
a=a+b;
}
if(a<=b)
{
c=a-b;
}
else
{
c=a+b;
}
}

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB


Output:
[root@home ~]# lex 3d.l
[root@home ~]# yacc -d 3d.y
[root@home ~]# gcc lex.yy.c y.tab.c -ll -lm -w
[root@home ~]# ./a.out test.c

Pos Operator Arg1 Arg2 Result

0 < a b t0
1 == t0 FALSE5
2 + a b t1
3 = t1 a
4 GOTO 5
5 < a b t2
6 == t2 FALSE10
7 + a b t3
8 = t3 a
9 GOTO 5
10 <= a b t4
11 == t4 FALSE15
12 - a b t5
13 = t5 c
14 GOTO 17
15 + a b t6
16 = t6 c

R LIKHITHA 21F41A0581 COMPILER DESIGN LAB

You might also like