0% found this document useful (0 votes)
28 views37 pages

CD Manual - CSE

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views37 pages

CD Manual - CSE

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Ex No :1 IMPLEMENTATION OF LEXICAL ANALYZER USING C

Date:

AIM:
To write a c program to implement the lexical analyzer.

ALGORITHM:

Step 1: Start the program.


Step 2: Feed the program with all the operators, functions, keywords and special characters in a
separate array.
Step 3: Open the input file and start reading the words one by one.
Step 4: Compare them with all the four array if found in any one then print the character and its
specification in the output file and goto step 6.
Step 5: If not any of four arrays contains it then check whether it is a constant if not then print it as
identifier in the output file.
Step 6: Do the step 3 to 4 until end of the file.
Step 7: Stop the program.

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:

Step 1:Start the program


Step 2: Using %{ and %} declare the variables yylval
Step 3: Specify the coordinates
Step 4: In the main function, get the expression through a C program as run time arguments
Step 5: Open the given programs file with C exe and print the string is valid or not Step
6: Stop the program

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:

Step 1:Start the program


Step 2: Using %{ and %} declare the variables yylval
Step 3: Specify the coordinates
Step 4: In the main function, get the string through a C program as run time arguments
Step 5: Open the given programs file with C exe and print the string is valid or not Step
6: Stop the program

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.

PROGRAM: FOR LOOP


LEX PART :for.l
%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[\t \n]
for return FOR;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap()
{}
YACC PART :for.y
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM FOR LE GE EQ NE OR AND
%right '='
%left OR AND
%left '>' '<' LE GE EQ NE

13
%left '+''-'
%left '*' '/'
%right UMINUS
%left '!'
%%
S : ST {printf("Input accepted\n"); exit(0);}; ST
: FOR '(' E ';' E2 ';' E ')' DEF

DEF : '{' BODY '}'


| E';' | ST

BODY : BODY BODY


| E ';'
| ST

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
E '+' '+'
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 %%
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]

for.y: At top level: for.y:56:l: return type defaults to ‘int’ [

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: $ |

PROGRAM: WHILE LOOP LEX


PART :while.l
%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[\t \n]
while return WHILE;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;

">=" return GE;


"==" return EQ;

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:

while.y: At top level: while.y:47:1: warning: return type


defaults to ‘int’ [ implicit-int]
47 | main() | A -------
while.y:52:l: return type defaults to 'int' [ ]

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]

52I yyerrorf) I ’ ----------


monlca@monica-Lenovo-E41-2S: $ ./a.out Enter the exp: while(a>l){ b-1;} Input accepted. nonica@monica-Lenovo-E41-25: $

PROGRAM: IF THEN ELSE


LEX PART :if.l
%{
#include<stdio.h>
#include "y.tab.h"
%}
alpha [A-Za-z]
digit [0-9]
%%
[ \t\n]
if return IF; then
return THEN; else
return ELSE;
{digit}+ return NUM;
{alpha}({alpha}|{digit})* return ID;
"<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;
. return yytext[0];
%%
yywrap()
{}

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()

if.y:56:l: return type defaults to fint’ [ .molicit-int]


56 | yyerror() | -----
1
if.1:22:1: warning return type defaults to 'inf [ mplictt-tnt]
22 I yywraj()

y.tab.c: In function ‘yyparse’:


y.tab.c:1114:16: nt:.implicit declaration of function ‘yylex’ [ iplicit-function-declaration]
y.tab.c:1255:7: implicit declaration of function 'yyerror’; did you mean ‘yyerrok’? [ if.y: At
top level:
if.y:51:l: return type defaults to 'inf [ lolicit-irit]
51 | main()
| A -------------------
if.y:56:1: rningreturn type defaults to 'inf [ plicit-int]
56 | yyerror()

monica@monica-Lenovo-E41-25: $ ./a.out
Enter the exp: if(a<b){printf("true");}else{prtntf("False");} Entered

arithmetic expression is Invalid

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: $ |

PROGRAM: IF THEN ELSEIF THEN ELSE


LEX PART :elseif.l
%{
#include<stdio.h>
#include "y.tab.h" %} alpha [A-Za-z] digit [0-9] %% [ \t\n] if return IF; then return THEN; else return ELSE;
elseif return ELSEIF; {digit}+ return NUM; {alpha}({alpha}|{digit})* return ID; "<=" return LE;
">=" return GE;
"==" return EQ;
"!=" return NE;
"||" return OR;
"&&" return AND;

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()

if.y:54:l: arning: return type defaults to 'int' [ illicit-int)


54 | yyerror() । ---
if.1:23:1: return type defaults to 'int' [ plicit-int]
23 | yywrap() | A -
y.tab.c: in function ‘yyparse’: y.tab.c:112D:16: implicit declaration of function ‘yylex’ [ ]
1120 | yychar - yylex();
I y.tab.c:1261:7: implicit declaration of function 'yyerror'; did you mean ‘yyerrok’? [ ]
1261 | yyerror (YY_("syntax error"));
| A----------
| yyerrok
if.y: At top level: if.y:49:l: rning: return type defaults to 'int' [ igli •
49 | main()

if.y:54:1: srning: return type defaults to 'int' [ rt]


54 | yyerror() | A -
monicaigmonica-Lenovo-E41-25: $ ./a.out
Enter the exp: if(a<p) then m=0; elseif(a>p) then m-1; else m=n;
Input accepted. _____________________________________________________________________________________________________________________

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() {}

YACC PART :switch.y


%{
#include<stdio.h>
#include<stdlib.h>
%}
%token ID NUM SWITCH CASE DEFAULT BREAK LE GE EQ NE AND OR IF THEN WHILE %right
'='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S : ST{printf("\nInput accepted.\n");exit(0);};
;
ST : SWITCH'('ID')''{'B'}'
;
B :C|CD
;
C:CC
| CASE NUM':'ST1 BREAK';'
;
D : DEFAULT':'ST1 BREAK';'
| DEFAULT':'ST1
;
ST1 : WHILE'('E2')' E';'
| IF'('E2')'THEN E';'
| ST1 ST1
| E';'
;
E2 : E'<'E

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();
}

Sample Input: sum.txt out


= in1 + in2 + in3 - in4
Sample Output : out.txt

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.

Step3: If type found correct, do the operation

Step4: Type mismatches, semantic error will be notified

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

STEP 1: Read the input code from a file.


STEP 2: Use fgetc() function to read the characters from the file.
STEP 3: Split those in to operators and operands.
STEP 4: Implement code optimization algorithm.
STEP 5: Print the result in the output file.

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];

void ReadInput(char Buffer[],FILE *Out_file);


int Gen_token(char str[],char Tokens[][10]); int
New_Index=0;

int main() { file


*In_file,*Out_file;

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

if(ch ==EOF) break;


Buffer[i]=‟\0‟;
ReadInput(Bufer, Out_file);//writing to the output file
}//End while

return 0;
}//End main

void ReadInput(char Buffer[ ],FILE *Out_file)


{
char temp[100],Token[10][10]; int
n,i,j,flag=0; strcpy(temp,Buffer);
n= Gen_token(temp,Token);
for(i=0;i<n;i++) {
if(!strcmp(Token[i],”=”))
{
if(isdigit(Token[i+1][0])||Token[i+1][0] == ‟.‟)
{
/*If yes then saving that number and its variable In
the Opt_Data array*/ flag=1;

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;
}

SAMPLE INPUT FILE : CODE.TXT

#include<stdio.h>main()
{ float
pi=3.14,r,a; a =
pi*r*r; printf(“a =
%f”,a); return 0;
}

OUTPUT FILE: OUTPUT.TXT

#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 :

The program can be executed by using turbo C compiler.


The program can be executed by using turbo C compiler (Alt+F9 … for compilation, Ctrl+F9 … to Run)
EXPECTED OUTPUT AND ITS FORM:
Back end of the compiler is expected to generate assembly language as the output from the intermediate
code.
USE OF THIS OUTPUT:
Many modern compilers share a common 'two stage' design. The front end translates the source language
into an intermediate representation. The second stage is the back end, which works with the internal
representation to produce code in the output language. The front end and back end may operate as
separate passes, or the front end may call the back end as a subroutine, passing it the intermediate
representation.

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:

STEP 1: Start the program.


STEP 2: Get the three variables from statements and stored in the text file k.txt.
STEP 3: Compile the program and give the path of the source file.
STEP 4: Execute the program.
STEP 5: Target code for the given statement was produced.
STEP 6: Stop the program.
PROGRAM:

#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 INPUT FILE :codein.txt


X=a-b Y=a-c
z=a+b C=a-b
C=a-b

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

You might also like