CD Manual - CSE
CD Manual - CSE
Date:
AIM:
To write a c program to implement the lexical analyzer.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h> void
main ()
{
int a,b,I,c; char*str;
char
*key[]={"int","char","for","while","void","main"};
char oper[]={'+','-','*','/','&','+','=','!'}; char
spl[]={'(',')','{','}','[',']',';',':','%'};
char
*func[]={"printf","scanf","gatch","clrscr"};
FILE *fp1,*fp2; fp1=fopen("add.c","r");
fp2=fopen("output.txt","w");
1
clrscr();
while(!feof(fp1))
{ fscanf(fp1,"%s",str);
b=0;c=0;
for(i=0;i<6;i++)
{ if(strcmp(str,key[i])==0)
{ b=1; fprintf(fp2,"%s is a keyword\n",str);
break;
} } for
(i=0;i<4;i++)
{ if(strcmp(str,func[i])==0)
{ b=1; fprintf(fp2,"%s is a function\n",str);
break;
}}
for(i=0;i<7;i++
)
{ if(str[0]==oper[i])
{ b=1; fprintf(fp2,"%s is a operator\n",str);
break;
}
}
for(i=0;i<11;i++)
{
if(str[0]==spl[i])
{ b=1; fprintf(fp2,"%s is a special character\n",str);
break;
}
} if(b==0)
{ c=atoi(str); if(c!=0) fprintf(fp2,"%s is a
constant\n",c); else fprintf(fp2,"%s is
a identifier\n",str);
2
}
}fclose(fp1
);
fclose(fp2);
getch();
}
OUTPUT:
ADD.c
void main()
{
int a=10;
printf("sample %d",a);
}
OUTPUT.TXT
void is a keyword main() is
a identifier { is a special
character int is a keyword
a=10; is a identifier
printf("sample is a identifier
%d",a); is a special character
3
RESULT:
Thus the program for implementing of lexical analysis using C was written and executed
successfully.
4
Ex No: 2 IMPLEMENTATION OF SYMBOL TABLE
Date:
AIM:
To write a C program to implement a symbol table.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the input from the user with the terminating symbol „$‟.
Step 3: Allocate memory for the variable by dynamic memory allocation function.
Step 4: If the next character of the symbol is an operator then only the memory is allocated.
Step 5: While reading, the input symbol is inserted into symbol table along with its memory address.
Step 6: The steps are repeated till „$‟ is reached.
Step 7: To reach a variable, enter the variable to the searched and symbol table has been checked for
corresponding variable, the variable along with its address is displayed as result.
Step 8: Stop the program.
PROGRAM CODING:
#include <stdio.h> #include<conio.h>
#include<ctype.h>
#include<alloc.h>
#include<string.h>
#include<math.h> void
main()
{ inti=0,j=0,x=0,n,flag=0; void
*p,*add[5]; char ch,srch,b[15],d[15],c;
clrscr(); printf("Expression terminated
by $ : "); while((c=getchar())!='$')
{ b[i]=c;
i++; }
n=i-1;
printf("
Given
Expressi
5
on : ");
i=0;
while(i<
=n) {
printf("
%c",b[i]
); i++; }
printf("\
n
Symbol
Table\n"
);
printf("
Symbol\
taddr\tty
pe");
while(j<
=n) {
c=b[j];
if(isalph
a(toascii
(c))) {
if(j==n)
{
p=mallo
c(c);
add[x]=
p;
d[x]=c;
printf("
%c\t%d\
6
tidentifi
er",c,p);
} else { ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{ p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c\t
%d\tidentifier\
n",c,p); x++;
}}} j++; }
printf("\nThe
symbol is to
be searched");
srch=getch();
for(i=0;i<=x;i
++)
{ if(srch==d[i])
{ printf("\nSymbol Found");
printf("\n%c%s%d\n",srch," @address ",add[i]);
flag=1;
} } if(flag==0)
printf("\nSymbol Not Found");
getch(); }
7
OUTPUT:
Result:
Thus the C program for implementing symbol table has been executed and verified.
8
Ex No 3 GENERATE YACC SPECIFICATION FOR A FEW SYNTACTIC CATEGORIES
Date:
a) Program to recognize a valid arithmetic expression that uses operator +, - , * and /.
b) Program to recognize a valid variable which starts with a letter followed by any number of letters or
digits.
c) Program to recognize a valid control structures syntax of C language (For loop, while loop, if-else,
ifelse-if, switch-case, etc.).
Ex 3 (a) YACC program to recognize a valid arithmetic expression that uses operators +, -, * &
/
Aim:
To write a YACC Program to recognize a valid arithmetic expression that uses operators +, -,
* and /.
Algorithm:
LEX
%{
#include"y.tab.h"
extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return NUMBER;}
[a-zA-Z]+ {return ID;}
[\t]+ ;
\n {return 0;}
. {return yytext[0];}
%%
YACC
%{
9
#include<stdio.h>
%}
%token NUMBER ID
%left '+' '-'
%left '*' '/'
%%
expr: expr '+' expr
|expr '-' expr
|expr '*' expr
|expr '/' expr
|'-'NUMBER
|'-'ID
|'('expr')'
|NUMBER
|ID
;
%%
main() {
printf("Enter the expression\n"); yyparse();
printf("\nExpression is valid\n");
exit(0); }
int yyerror(char *s)
{
printf("\nExpression is invalid");
exit(0);
}
OUTPUT
$lex ex4a.l
$yacc –d ex4a.y
$cc lex.yy.cy.tab.c –ll
$./a.out
Enter the expression
(a*b+5)
Expression is valid
$./a.out
Enter the expression
(a+6-)
Expression is invalid
RESULT:
Thus the YACC Program to recognize a valid arithmetic expression that uses operators +, -, * and /.
10
Ex 3.b) Program to recognize a valid variable which starts with a letter followed by any number of
letters or digits.
Aim:
To write a YACC Program to recognize a valid variable which starts with a letter followed by any
number of letters or digits.
Algorithm:
Program:
LEX
%{
#include"y.tab.h"
extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return DIGIT;}
[a-zA-Z]+ {return LETTER;}
[\t] ;
\n return 0;
. {return yytext[0];}
%%
YACC
%{
#include<stdio.h>
%}
%token LETTER DIGIT
%%
variable: LETTER|LETTER rest
;
rest: LETTER rest
|DIGIT rest
|LETTER
11
|DIGIT
;
%%
main() {
yyparse();
printf("The string is a valid variable\n");
}
int yyerror(char *s)
{
printf("this is not a valid variable\n"); exit(0);
}
OUTPUT
$lex p4b.l
$yacc –d p4b.y
$cc lex.yy.cy.tab.c –ll
$./a.out input34
The string is a valid variable
$./a.out
89file
This is not a valid variable
RESULT:
Thus the YACC Program to recognize a valid variable which starts with a letter followed by any number
of letters or digits.
12
Ex No 3.c Program to recognize a valid control structures syntax of C language (For loop, while
loop, if-else, if-else-if, switch-case, etc.)
AIM:
To write a yacc program to validate control structures syntax.
ALGORITHM:
Step1:Start the program.
Step2:Read the statement.
Step4:Validating the given statement according to the rule using yacc.
Step4:Using the syntax rule print the result of the given syntax.Step5:Stop
the program.
13
%left '+''-'
%left '*' '/'
%right UMINUS
%left '!'
%%
S : ST {printf("Input accepted\n"); exit(0);}; ST
: FOR '(' E ';' E2 ';' E ')' DEF
E2 : E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E OR E |E
AND E %%
main() {
14
printf("Enter
the
expression:\n"
); yyparse();
yyerror() {
printf("\nEntered arithmetic expression is Invalid\n\n"); }
OUTPUT:
$:lexfor.l
$:yaccfor.y
$:cc lex.yy.cy.tab.h$:./a.out
ronicaijimonica-Lenovo-E41-25: $ lex for.lmonica^monica-Lenovo-E41-25: $ yaccfor.yfor.y: warning: 13 shift/reduce conflicts [-Wconflicts-sr] for.y: warning: 4 reduce/reduce conflicts [-Wconflicts-rr]
for.y: note: rerun with option 1-Wcounterexamples' to generate conflict counterexamples monica@monica-Lenovo-E41-25: $ cc lex.yy.cy.tab.h In file included from for.1:3: y.tab.c: In function ‘yyparse’:
y.tab.c:1127:16: warning: implicit declaration of function ‘yylex’; did you mean 'yyless’? [ nplicit-function-declarati]
In file included from for.1:3: y.tab.c: 1268:7: implicit declaration of function ‘yyerror’; did you
mean ‘yyerrok’? [ . : claratian]
In file included from for.1:3: for.y: At top level: for.y:56:l: return type defaults to 'int’ [ plicit-int]
56 | maln() { for.y:60:l: earning: return type defaults to
‘int’ [ mplicit-int]
60 | yyerror() । --------
for.1:20:1: ning: return type defaults to ‘int’ [ icit-int]
20 | yywrapQ| --------
y.tab.c: In function 'yyparse’: y.tab.c:1127:16: implicit declaration of function 'yylex’ [ ]y.tab.c:1268:7: implicit declaration of function 'yyerror’; did you mean ‘yyerrok'? [-Wimplicit-
function-declaration]
56 | nain() { | A --
for.y:60:l: n return type defaults to ‘int’ [ pltcit-int]
60 | yyerrcr() । --------
monica@monica-Lenovo-E41-25: $ ./a.out Enter the expression: for(i=9;i<n;i++){i=i+l;} Input accepted montca@monica-Lenovo-E41-25: $ |
15
"!=" return NE; "||"
return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap() {}
YACC PART :while.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM WHILE LE GE EQ NE OR AND
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST1 {printf("Input accepted.\n");exit(0);};
ST1 : WHILE'(' E2 ')''{' ST '}'
ST : ST ST
| E';' ;
E : ID'='E
E'+'E
E'-'E E'*'E
E'/'E E'<'E E'>'E
E LE E
E GE E
E EQ E E NE E E OR E
E AND E
ID
NUM
;
E2 : E'<'E | E'>'E
| E LE E | E GE E | E EQ E | E NE E | E OR E |E AND E | ID | NUM ; %%
main() {
printf("Enter the exp: "); yyparse();
} yyerror() { printf("\nEntered arithmetic expression is
Invalid\n\n"); }
16
OUTPUT:
$:lexwhile.l
$:yaccwhile.y
$:cc lex.yy.cy.tab.h$:./a.out
[email protected]: $ lex
[email protected] - Lenovo-E41 -25: $
yaccwhile.ywhile.y: warning: 2 shift/reduce conflicts [-
Wconflicts-sr]
while.y: note: rerun with option '-Wcounterexamples 1to generate conflict counterexamples nonica@rionica-Lenovo-E41-25: $ cc lex.yy.cy.tab.h In file included from while.1:3: y.tab.c: In function
‘yyparse’: y.tab.c:1112:16: implicit declaration of function 'yylex’; did you mean ‘yyless’? [ ]
In file included from while.1:3:
y.tab.c:1253:7: implicit declaration of function ‘yyerror’; did you mean ‘yyerrok*? [ Lon]
In file included from while.1:3:
52 | yyerrorf)
| A -----------------------------
while.1:20:1: return type defaults to ‘int’ [ ]
20 | yywrapf)
| A -------------------------
y.tab.c: In function ‘yyparse’:
y.tab.c:1112:16: implicit declaration of function ‘yylex’ [ u]
y.tab.c:1253:7: implicit declaration of function ‘yyerror’; did you mean ‘yyerrok’? [• - - lanation]while.y: At top level: while.y:47:l: return type defaults to ‘int’ [-
^implicit-int]
47 ]main()while.y:52:l: warning: return type defaults to ‘int’ [-
Mtmplictt-int]
17
YACC PART :if.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM IF THEN LE GE EQ NE OR AND ELSE
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST {printf("Input accepted.\n");exit(0);};
ST : IF '(' E2 ')' THEN ST1';' ELSE ST1';'
| IF '(' E2 ')' THEN ST1';'
;
ST1 : ST
|E
E : ID'='E | E'+'E
E'-'E
E'*'E
E'/'E
E'<'E
E'>'E
E LE E
E GE E
E EQ E
E NE E
E OR E
E AND E
ID
NUM
;
E2 : E'<'E
E'>'E
E LE E
E GE E
E EQ E
E NE E
18
E OR E
E AND E
ID
NUM
;
%%
main() {
printf("Enter the exp: ");
yyparse(); } yyerror() {
printf("\nEntered arithmetic expression is Invalid\n\n"); }
OUTPUT:
$:lexif.l
$:yaccif.y
$:cc lex.yy.cy.tab.h
$:./a.out
monicagmonica-Lenovo-E41-25: $ lex
if.Imonica@monica-Lenovo-E41-25: $
yacctf.ynonica^monica-Lenovo-E41-25:-$ cc
lex.yy.cy.tab.h In file included from if.1:3:
y.tab.c: In function ‘yyparse’:
y.tab.c:1114:16: implicit declaration of function ‘yylex’; did you mean ‘yyless’? [ ]
In file included from if.1:3:
y.tab.c:1255:7: implicit declaration of function ‘yyerror’; did you mean ‘yyerrok’? [ --;. -‘ .-i]
In file included from if.1:3: i:n]
if.y: At top level:
if.y:Sl:l: return type defaults to fint' [ tnt]
51 | main()
monica@monica-Lenovo-E41-25: $ ./a.out
Enter the exp: if(a<b){printf("true");}else{prtntf("False");} Entered
monica@rnanica-Lenovo-E41-25: $ ./a.outEnter
the exp: if(a==l) then b=l; else b=2; Input
accepted. monica{amonica-Lenovo-E41-25: $ |
19
. return yytext[0];
%% yywrap() {}
YACC PART :elseif.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM IF THEN LE GE EQ NE OR AND ELSE
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left'+''-'
%left '*''/'
%right UMINUS
%left '!' %%
S : ST {printf("Input accepted.\n");exit(0);};
ST : IF '(' E2 ')' THEN ST1';' ELSEIF '(' E2 ')' THEN ST1';' ELSE ST1';' | IF '(' E2 ')' THEN ST1';' ;
ST1 : ST
| E ; E : ID'='E
E'+'E
E'-'E E'*'E
E'/'E E'<'E E'>'E
E LE E
E GE E
E EQ E E NE E E OR E
E AND E
ID
NUM
;
E2 : E'<'E
E'>'E
E LE E
E GE E
E EQ E E NE E
E OR E
E AND E
ID
| NUM
;
%%
main() {
20
printf("Enter the exp: ");
yyparse(); } yyerror() {
printf("\nEntered arithmetic expression is Invalid\n\n"); }
OUTPUT:
$:lexelseif.l
$:yaccelseif.y
$:cc lex.yy.cy.tab.h$:./a.out
montcagmornca-Lenovo-E4i-zs: 5 texvr.Lnonicai3mor:ica-Lenovo-E41-25: $ yaccif.ymonica3monica-Ltnovo-E41-25: $ cc lex.yy.cy.tab.hIn file included from if.1:3: y.tab.c: In function ‘yyparse’:
y.tab.c:1120:16: implicit declaration of function ‘yylex’; did you mean 'yyless'? [ ;
1120 | yychar= yylex();
| yyless
In file included from if.1:3: y.tab.c:1261:7: implicit declaration of function
'yyerror'; did you mean ‘yyerrok’? [ ]
1261 | yyerror(YY_("syntax error"));
| yyerrok
In file included from if.1:3: if.y: At top level:
if.y:49:l: -ninq: return type defaults to 'int' [ 1 Icit^irt]
49 | main()
PROGRAM: SWITCH
LEX PART :switch.l
%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[ \n\t]
if return IF;
then return THEN;
while return WHILE;
switch return SWITCH;
case return CASE;
default return DEFAULT;
break return BREAK;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
21
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"&&" return AND;
"||" return OR;
. return yytext[0];
%%
yywrap() {}
22
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E AND E
| E OR E
;
E : ID'='E
| E'+'E
| E'-'E
| E'*'E
| E'/'E
| E'<'E
| E'>'E
| E LE E
| E GE E
| E EQ E
| E NE E
| E AND E
| E OR E
| ID
| NUM
;
%%
main() {
printf("Enter the exp: ");
yyparse(); } yyerror() {
printf("\nEntered arithmetic expression is Invalid\n\n");
}
Result :
Thus the program to recognize valid control structures is written and verified
23
Ex No 4 THREE ADDRESS CODE GENERATION USING LEX AND YACC
Date:
AIM :
To write a C program to generate a three address code for a given expression.
ALGORITHM:
Step 1: Begin the program
Step 2 : The expression is read from the file using a file pointer
Step 3 : Each string is read and the total no. of strings in the file is calculated.
Step 4: Each string is compared with an operator; if any operator is seen then the previous string and
next string are concatenated and stored in a first temporary value and the three address code
expression is printed
Step 5 : Suppose if another operand is seen then the first temporary value is concatenated to the next
string using the operator and the expression is printed.
Step 6 : The final temporary value is replaced to the left operand value.
Step 7 : End the program.
PROGRAM:
//program for three address code generation
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h> struct
three
{
char data[10],temp[7];
}s[30]; void
main()
{ char d1[7],d2[7]="t";
int i=0,j=1,len=0; FILE
*f1,*f2; clrscr();
f1=fopen("sum.txt","r");
f2=fopen("out.txt","w");
while(fscanf(f1,"%s",s[l
24
en].data)!=EOF) len++;
itoa(j,d1,7);
strcat(d2,d1);
strcpy(s[j].temp,d2);
strcpy(d1,"");
strcpy(d2,"t");
if(!strcmp(s[3].data,"+")
)
{
fprintf(f2,"%s=%s+%s",s[j].temp,s[i+2].data,s[i+4].data);
j++; } else if(!strcmp(s[3].data,"-"))
{ fprintf(f2,"%s=%s-
%s",s[j].temp,s[i+2].data,s[i+4].data); j++; }
for(i=4;i<len-2;i+=2)
{ itoa(j,d1,7); strcat(d2,d1); strcpy(s[j].temp,d2);
if(!strcmp(s[i+1].data,"+"))
fprintf(f2,"\n%s=%s+%s",s[j].temp,s[j-1].temp,s[i+2].data);
else if(!strcmp(s[i+1].data,"-"))
fprintf(f2,"\n%s=%s-%s",s[j].temp,s[j-1].temp,s[i+2].data);
strcpy(d1,""); strcpy(d2,"t"); j++; }
fprintf(f2,"\n%s=%s",s[0].data,s[j-1].temp);
fclose(f1);
fclose(f2); getch();
}
t1=in1+in2
t2=t1+in3
t3=t2-in4 out=t3
25
RESULT:
Thus a C program to generate a three address code for a given expression is written, executed and the
output is verified.
26
Ex No 5 IMPLEMENTATION OF TYPE CHECKING
Date:
AIM :
To write a C program to implement type checking
ALGORITHM:
Step1: Track the global scope type information (e.g. classes and their members)
Step2: Determine the type of expressions recursively, i.e. bottom-up, passing the resulting types upwards.
PROGRAM CODE:
//To implement type checking
#include<stdio.h>
#include<stdlib.h>
int main() {
int n,i,k,flag=0; char
vari[15],typ[15],b[15],c; printf("Enter
the number of variables:");
scanf(" %d",&n); for(i=0;i<n;i++)
{
printf("Enter the variable[%d]:",i); scanf("
%c",&vari[i]);
printf("Enter the variable-type[%d](float-f,int-i):",i);
scanf(" %c",&typ[i]);
if(typ[i]=='f') flag=1;
}
printf("Enter the Expression(end with $):");
i=0; getchar();
while((c=getchar())!='$')
{ b[i]=c;
i++; }
k=i;
for(i=0;i<k;i++)
{
if(b[i]=='/')
{ flag=1;
break; }
}
for(i=0;i
<n;i++)
{
27
if(b[0]==vari[i])
{
if(flag==1)
{
if(typ[i]=='f')
{ printf("\nthe datatype is correctly defined..!\n");
break; } else
{ printf("Identifier %c must be a float type..!\n",vari[i]);
break; } } else
{ printf("\nthe datatype is correctly defined..!\n"); break;
} }
} return
0;
}
OUTPUT:
RESULT:
Thus a C program to implement type checking is written, executed and the output is verified.
28
Ex No 6 CODE OPTIMIZATION TECHNIQUES (CONSTANT FOLDING)
Date:
AIM
To write a program for optimization of the given input code using constant folding technique.
ALGORITHM
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h> struct
ConstFold
(
char new_Str[10]; char
str[10];
}Opt_Data[20];
29
char Buffer[100],ch;
int i=0;
In_file = fopen(“d:\\code.txt”,”r”);
Out_file = fopen(“d:\\output.txt”,”w”);
clrscr( ); while(1) { ch =
fgetc(In_file); i=0; while(1) { if(ch ==
„\n‟) break; Buffer[i++]=ch; ch =
fgetc(In_file); if(ch == EOF) break;
}//End while
return 0;
}//End main
30
strcpy(Opt_Data[New_Index].New_Str,Token[i-1]);
strcpy(Opt_Data[New_Index++].str,Token[i+1]);
}//End if
}//End if }//End for
if(!flag) {
for(i=0;i<New_index;i++)
{ for(j=0;j<n;j++) {
if(!strcmp(Opt_Data[i].new_Str,Token[j]))
strcpy(Token[j],Opt_Data[i].str);
}//End for
}//End for }//End if fflush(Out_file);
strcpy(temp,””); for(i=0;i<n;i++) /*Loop to obtain
complete tokens*/
{ strcat(tem,Token[i]);
if(Token[i+1][0]!=‟,‟|
|Token[i+1][0] != „,‟)
strcat(temp,” “);
}//End for
strcat(temp,”\n\0”);
fwrite(&temp,strlen(te
mp),1,Out_file);
}
/*The Gen_Token function breaks the input line into tokens*/ int
Gen_Token(char str[], char Token[][10])
{ inti=0;j=0,k=0;
while(str[k]!=‟\0‟
)
{ j=0;
while(str[k] ==‟ „|| str[k] ==‟\t‟)
k++; while(str[k])!=‟
31
‟&&str[k]!=‟\0‟ && str[k]!=
„=‟ && str[k] != „/‟
&& str[k]!= „+‟ && str[k] != „-‟
&& str[k]!= „*‟ && str[k] != „,‟ && str[k]!= „;‟)
Token[i][j++] = str[k++];
Token[i++][j] = „\0‟; if(str[k] == „=‟|| str[k] ==
„/‟|| str[k] == „+‟|| str[k] == „-‟|| str[k] == „*‟||
str[k] == „*‟|| str[k] == „,‟|| str[k] == „;‟) {
Token[i][0] = str[k++];
Token[i++][1] =
„\0‟; }//End if if
(str[k] == „\0‟)
break; }//End while
return i;
}
#include<stdio.h>main()
{ float
pi=3.14,r,a; a =
pi*r*r; printf(“a =
%f”,a); return 0;
}
#include<stdio.h>
main() { float pi =
3.14, r, a; a = 3.14
* r * r; printf(“a =
%f”,a); return 0;
}
32
RESULT:
Thus the program for code optimization was implemented, executed and verified.
33
Ex No: 7 IMPLEMENTATION OF BACK END OF COMPILER
Date:
AIM:
To implement the back end of the compiler which takes the three address code and produces the
8086 assembly language instructions that can be assembled and run using a 8086 assembler. The
target assembly instructions can be simple move, add, sub, jump. Also simple addressing modes are
used.
DESCRIPTION: The back end is responsible for translating the intermediate representation of the source
code from the middle-end into assembly code.
OBJECTIVE :To implement the back end of the compiler which takes the three address code and
produces the 8086 assembly language instructions that can be assembled and run using a 8086 assembly.
SYNTAXES & KEYWORDS: fopen(“d:\\codein.txt”,"r"); – this statement
opens a file(codein.txt) in read mode. printf("\t\tMOV %c,R%d\n\t",ip[i+k],j);
if(ip[i+1]=='+')
printf("\t\tADD"); // If the operator is an addition (+) then display the assembly code “MOV” “ADD”
and store the result to the corresponding R elseprintf("\t\tSUB"); // else display the assembly code
“MOV” “SUB” and store the result to the corresponding R
In the first part of the program Open a file with read mode and read the content of the file one by one and
get the first three address code. Check the arithmetic operator If the operator is an addition (+) then
display the assembly code “ADD” and store the result to the corresponding R and if the operator is a
subtraction (-) then display the assembly code “SUB” and store the result to the corresponding register
HOW TO EXECUTE THE PROGRAM :
34
This approach mitigates complexity separating the concerns of the front end, which typically revolve
around language semantics, error checking, and the like, from the concerns of the back end, which
concentrates on producing output that is both efficient and correct.
ADVANTAGES AND LIMITATIONS:
In this program, single back end is developed for single source language. It also has the advantage of
allowing the use of a single back end for multiple source languages, and similarly allows the use of
different back ends for different targets.
APPLICATIONS: This program can be used to develop a back end of a compiler using C programming
language.
ALGORITHM:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h> void
main()
{
int i=2,j=0,k=2,k1=0;
charip[10]; FILE *fp;
clrscr();
fp=fopen(“d:\\codein.txt”,"r");
if(fp==NULL)
{ printf("\nError in Opening the
file"); getch();
}
clrscr(); while(!feof(fp)) {
fscanf(fp,"%s\n",ip);
35
printf("\t\t%s\n",ip); } rewind(fp);
printf("\n------------------------------\n");
printf("\tStatement \t\t target code\n");
printf("\n------------------------------\n");
while(!feof(fp)) { fscanf(fp,"%s",ip);
printf("\t%s",ip); printf("\t\tMOV
%c,R%d\n\t",ip[i+k],j); if(ip[i+1]=='+')
printf("\t\tADD");
elseprintf("\t\tSUB"); if(islower(ip[i]))
printf("%c,R%d\n\n",ip[i+k1],j); else
printf("%c,%c\n",ip[i],ip[i+2]);
j++;k1=2;k=0;
} printf("\n-------------------------------
\n"); getch(); fclose(fp);
}
SAMPLE OUTPUT:
------------------------------
Statement target code
------------------------------
X=a-b MOV b,R0
SUBa,R0
Y=a-c MOV a,R1
SUBc,R1 z=a+b
MOV a,R2
ADDb,R2
C=a-b MOV a,R3
36
SUBb,R3
C=a-b MOV a,R4
SUBb,R4
-------------------------------
RESULT:
Thus the C Program for implementing back end of the compiler is executed and the required output is
obtained.
37