61

Click here to load reader

Pcd Record

Embed Size (px)

Citation preview

Page 1: Pcd Record

GOVERNMENT COLLEGE OF ENGINEERING

SALEM – 636 011.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

070230069 – PRINCIPLES OF COMPILER DESIGN LABORATORY

FINAL YEAR

NAME : ______________________________

REGISTER NUMBER : ______________________________

1

Page 2: Pcd Record

GOVERNMENT COLLEGE OF ENGINEERING

SALEM – 636 011.

070230069 – PRINCIPLES OF COMPILER DESIGN LABORATORY

Certified that this is the Bonafide Record of work done by Mr. / Ms.

…………………………………………………………………….….. of SEVENTH SEMESTER

of …………….…………………………………………………………. during the Academic Year

2010 – 2011.

Staff – In – Charge

Submitted for the Practical Examination held on ………………..

His / Her University Register Number is ...……………………….

INTERNAL EXAMINER EXTERNAL EXAMINER

2

Page 3: Pcd Record

TABLE OF CONTENTS

S.NO DATE NAME OF THE EXPERIMENTPAGE

NOSIGNATURE

1Lexical Analyzer For ‘C’ Statements 4

2Lexical Analyzer For Assembly

Language Statements8

3Lexical Analyser Using Lex Tools 13

4Recursive Descent Parsing For

Arithmetic Expression Using + And *20

5Parser Implementation Using Yacc &

Lex28

6Implementing Calculator Using Yacc 32

7Simple Intermediate Code Generation 35

8Intermediate code generation

Three address code for Boolean expression

39

9Assembly Code Generation

44

3

Page 4: Pcd Record

Ex.No : 01 LEXICAL ANALYZER FOR ‘C’ STATEMENTS

Date :

AIM :

To write a ‘c’ program to implement the lexical analyzer for ‘c’ statements.

ALGORITHM :

1. Start the Program.

2. Declare the variables and main function.

3. Open a text file in the read mode and read the expression from that file.

4. In main function, if the string of the files contains reserved words go to reserved function.

5. Compare reserved words with the string print these reserved words if they appear.

6. The defined reserved words are if, then else, do, while, and for.

7. Else check whether it contains the operator such as +,-,*, /,>, <,! , =.

8. Print the operators if it matches.

9. Else take it as the string is an identifier.

10. Stop the Program.

11. Print the Result.

4

Page 5: Pcd Record

CODING :

#include<stdio.h>

#include<conio.h>

#include<string.h>

char string[20],reswords[20][20],ids[20][20],ops[20][20];

int c1=-1,c2=-1,c3=-1,i;

int res(char *word)

{

int i;

char reserved[][10]={"if","then","elso","do","while","for"};

for(i=0;i<6;i++)

if(strcmp(reserved[i],word)==0)

return(1);

return(0);

}

int op(char *word)

{

int i;

char operat[10][4]={"+","-","*"," /","=","!=",">","<"};

for(i=0;i<8;i++)

if(strcmp(operat[i],word)==0)

return(1);

return(0);

}

void main()

{

FILE *fp;

fp=fopen("src.txt","r");

clrscr();

while(fscanf(fp,"%s",string)!=EOF)

{

if(res(string)==1)

5

Page 6: Pcd Record

strcpy(reswords[++c1],string);

else if(op(string)==1)

strcpy(ops[++c2],string);

else

strcpy(ids[++c3],string);

}

printf("\n Reserved words \n ");

for(i=0;i<=c1;i++)

printf("\n %s",reswords[i]);

printf("\n Operator \n ");

for(i=0;i<=c2;i++)

printf("\n %s",ops[i]);

printf("\n Identifer \n ");

for(i=0;i<=3;i++)

printf("\n %s",ids[i]);

getch();

}

6

Page 7: Pcd Record

INPUT AND OUTPUT:

Reserved Words

if

then

else

do

Operator

+ - *

Identifiers

a b c

RESULT :

Thus the ‘c’ program to implement the lexical analyzer for ‘c’ statements is written and the output is verified.

7

Page 8: Pcd Record

Ex.No : 02 LEXICAL ANALYZER FOR ASSEMBLY Date : LANGUAGE STATEMENTS

AIM :

To write a c program to implement a lexical analyzer for assembly language.

ALGORITHM :

1. Start the program.

2. Declare the variables and as string, data, arithmetic identifiers and register.

3. Define the main function. open a text file in the read mode and read the assembly language

expressions from that file.

4. In that main function, perform the following step until the file exists.

5. If the string contains data transfer code like MOV, MOVF, load and store and then compare

the string with the data transfer word and print the data transfer word.

6. Else check whether the string contains the arithmetic operators such as add, addf, mul, mulf,

sub and div. The print it as a arithmetic one.

7. Else check whether the string contain the register such as R1,R2,R3 and R4.

8. If the expressions contain those words print it and check for string contains the variables such

as A, B, C, D.

9. Else print the expression string as identifier.

10. Print the result and Stop the program.

8

Page 9: Pcd Record

CODING :

#include<stdio.h>

#include<conio.h>

#include<string.h>

Char string[20], data[20][20], arith[20][20], var[20][20], ids[20][20], reg[20][20];

int c1=-1, c2=-1,c3=-1,c4=-1,c5=-1,i;

int dat(char *word)

{

int i;

char datatransfer[][10]={ “mov ”, ” movf ”, ”store”, ”load”};

for(i=0;i<4;i++)

if(strcmp(datatranfer[i],word)==0)

return(1);

return(0);

}

int ari(char *word)

{

int i;

char arithmetic[][12]={“add”, “addf”, “mulf”,” sub”, “div” };

for(i=0;i<6;i++)

if(strmp(arithmetic[i].word)==0)

return(1);

return(0);

}

int regis(char *word)

{

int i;

char register[][12]={“R1”, “R2”, “R3”, “R4” };

for(i=0;i<4;i++)

if(strcmp(register[i],word)==0)

return(1);

return(0);

}

9

Page 10: Pcd Record

int variable(char *word)

{

int i;

char variables[][16]={“A”, “B”, “C”, “D”};

for(i=0;i<4;i++)

if(strcmp(variables[i],word)==0)

return(1);

return(0);

}

void main()

{

FILE *fp;

fp = fopen(“str. text”, ”r”);

clrscr();

while((fscanf(fp ”%s”, String)!=EOF)

{

if(dat(String)==1)

strcpy(data[++c1],String);

else if(ari(String)==1)

strcpy(arith[++c2],String);

else if(regis(String)==1)

strcpy(reg[++c3],String);

else if(variable(string)==1)

strcpy(var[++c4],string);

else

strcpy(ids[++c5],String);

}

printf(“\n DATA TRANSFERED”);

for(i=0;i<=c1;i++)

printf(“\n %s”, data[i]);

printf(“ ARITHMETIC”);

for(i=0;i<=c2;i++)

printf(“\n %s”, arith[i]);

printf(“\n REGISTER “);

10

Page 11: Pcd Record

for(i=0;i<=c3;i++)

printf(“\n %s”, reg[i]);

printf(“\n VARIABLES” \n”);

for(i=0;i<=c4;i++)

printf(“ \n %s”, var[i]);

printf(“\n IDENTIFERS”);

for(i=0;i<=c5;i++)

printf(“ \n %s”, ids[i]);

getch();

}

11

Page 12: Pcd Record

INPUT AND OUTPUT :

DATA TRANSFERRED

movf

mov

ARITHMETIC

add

mulf

REGISTERS

A

B

C

D

IDENTIFIERS

tg

RESULT :

Thus the c program to implement a lexical analyzer for assembly language is written and the

output is verified.

12

Page 13: Pcd Record

Ex.No : 03 LEXICAL ANALYSER USING LEX TOOLS

Date :

AIM :

To write a c program using of lex tool to implement the lexical analyser.

ALGORITHM :

1. Start the program.

2. Define the size, number, keywords , parenthesis, lexeme, buffer and token value

3. Declare the variables as lexemes, buffer, last char, last entry and token value.

4. Define the main function with following steps.

5. Call the initialize function declare the structure pointer.

6. Declare the keywords like if for, else, int, float, double, char, struct, return and then in array.

7. If lookahead is equal to lexeme means those to lexer function initialize the variables.

8. Get the input expression and if expression have paranthesis then return parenthesis.

9. Else if the expression as relational operator like <,>,<=,=>,!= then return relational operator.

10. Else if the expression as assignment operator return the assignment

operator get the digit in stdin and return in number.

11. If the input expression as error then return compile error.

12. If the lookahead is equal to number then print the number, then Keyword, parenthesis,

identifier, assignment operator are printed in the output.

13. If the expression given in the output then same expression will be

displayed input file.

14. Stop the program.

13

Page 14: Pcd Record

CODING :

#include<stdio.h>

#include<conio.h>

#include<ctype.h.

#include<string.h>

#include<stdlib.h>

#define SIZE 128

#define NONE -1

#define EOS ‘\0’

#define NUM 256

#define KEYWORD 257

#define PAREN 258

#define ID 259

#define ASSIGN 260

#define REL –op261

#define DONE 262

#define MAX 999

Char lexemes[max];

Char buffer[size];

int lastchar =-1;

int lastentry =0;

int token val =NONE;

int lineno =1;

struct entry

{

Char *lexptr;

int token;

}

symtable[100];

Struct entry keywords[]={“if” KEYWORD,”else” KEYWORD,”for”

KEYWORD,”int” KEYWORD,”float” KEYWORD,”double” KEYWORD,”char”

KEYWORD,”struct” KEYWORD,”return” KEYWORD,”then” KEYWORD,0,0};

14

Page 15: Pcd Record

Void Error_Message(char *m)

{

fprintf(stderr,”line %d %s \n”,lineno,m);

exit(1);

}

int look_up(char s[])

{

int k;

for(k=lastentry;k>0;k=k-1)

if(strcmp(symtable[k],lexptr,s)==0)

return k;

return 0;

}

int insert(char s[],int tok)

{

int len;

len=strlen(s);

if(lastentry+1>=MAX)

Error _Message(“lexemes array is full”);

lastentry=lastentry+1;

symtable[lastentry].token=tok;

symtable[lastentry].lexptr=&lexemes[lastchar+1];

lastchar=lastchar+len+1;

strcpy(symtable[lastentry].lexptr,s);

return lastentry;

}

Void Intialize()

{

Struct entry *ptr;

for(ptr=keywords;ptr->token;ptr++)

insert(ptr->lexptr,ptr->token);

}

int lexer()

{

15

Page 16: Pcd Record

int t;

int val,i=0;

while(i)

{

t=getchar();

if(t==’’||t==’\t’)

else if(t==’\n’)

lineno=lineno+1;

else if(t==’(‘||t==’)’)

return PAREN;

else if(t==’<’||t==’>’||t==’<=’||t==’>=’||t==’!=’)

return REL_OP;

else if(t==’=’)

return ASSIGN;

else if(is digit(t))

{

Ungetc(t,stdin);

Scanf(“%d”,&tokenval);

return NUM;

}

else if(is alpha(t))

{

While(is alnum(t))

{

buffer[i]=t;

i=i+1;

if(i>=SIZE)

Error_Message(“computer error”);

}

buffer[i]=EOS;

if(t1=EOF)

ungetc(t,stdin);

val=look_up(buffer);

if(val==0)

16

Page 17: Pcd Record

val=insert(buffer,ID);

token val=val;

return symtable[val].token;

}

else if(t==EOF)

return DONE;

else

{

token val=NONE;

return t;

}

}

}

void main()

{

int lookahead;

char ans;

clrscr();

printf(“\n\t\t program for lexical analysis \n”);

initialize();

printf(“\n enter the expression and put at the end”);

printf(“\n press ctrl z to terminate…..\n”);

lookahead=lexer();

while(lookahead!=DONE)

{

if(lookahead==NUM)

{

Printf(“\n number”);

Printf(“%d”,token val);

if(lookahead==’+’||lookahead==’-‘|| lookahead==’*’|| lookahead==’/’)

printf(“\n operator”);

if(lookahead==PAREN)

printf(“\n identifier”);

printf(“%s”symtable[tokenval],lexptr);

17

Page 18: Pcd Record

}

if(lookahead==KEYWORD)

printf(“\n keywords”);

if(lookahead==ASSIGN)

printf(“\n assignment operator”);

if(lookahead==REL_OP)

printf(“\n relational operator”);

lookahead=lexer;

}

}

}

18

Page 19: Pcd Record

INPUT AND OUTPUT:

Program for lexical analysis

Enter the expression and put; at the end

Press ctrl+z at the end to terminate

If(x=y) then x

Keyword

paranthesis

Identifier: x

Assignment Operator

Identifier: y

Paranthesis

Keyword

Identifier: x

RESULT :

Thus the c program using of lex tool to implement the lexical analyser is written and the

output is verified.

19

Page 20: Pcd Record

Ex.No : 04 RECURSIVE DESCENT PARSING FOR ARITHMETICDate : EXPRESSION USING + AND *

AIM :

To write a C program to implement the recursive descent parsing.

ALGORITHM :

1. Start the program.

2. Define the variables as size, none,EOS,NUM,keywords, ID,DONE,MAX.

3. Declare the variables, lexemes, buffer, last char,last entry, token val,line no,lookahead and

structure pointer.

4. Create the function such as Error_message,lookup,insert, initialize, lexer, match, display,F(),

T(),E() and parser for perfoming various operations.

5. Check for the condition in the symbol table and lexemes array by using insert function.

6. If lookahead matches with the variable then lookahead equals lexer,else point syntax error.

7. Yet the input expression,if it matches with +, -,*, / display as arithmetic operator, if it

matches with Num display as number, or else if it is ID display as identifier.

8. If the expression matches with C symbol call the E() for checking + and – and return ‘)’ with

that expression.

9. If the lookahead doesn’t matches with DONE VALUE means then call the E() and match ; at

the end.

10. In the main, call the initialize function and then print the statements such as Enter the

expression, and place semicolon at the end. Press ctrl+z to terminate and call the parser

function.

11. Stop the program.

20

Page 21: Pcd Record

CODING :

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

#include<string.h>

#include<stdlib.h>

#define SIZE 128

#define NONE -1

#define EOS ‘\0’

#define NUM 257

#define KEYWORD 258

#define ID 259

#define DONE 260

#define MAX 999

char lexemes[MAX];

char buffer[SIZE];

int last char=-1;

int last entry=0;

int tokenval=DONE;

int lineno=1;

int lookahead;

struct entry

{

char *lexptr;

int token;

}

symtable[100];

struct entry keyword[]={“if”, KEYWORD, “else”, KEYWORD,

“for”, KEYWORD, “int”, KEYWORD, “float”, KEYWORD,

“double”,KEYWORD,“char”,KEYWORD,“struct”,KEYWORD,”return”, KEYWORD,0,0};

void Error_message(char *m)

{

fprint(stderr,”line%d%s\n”,lineno,m);

21

Page 22: Pcd Record

exit(1);

}

int look_up(char s[])

{

int k;

for(k=lastentry;k>0;k=k-1)

if(strcmp(symtable[k].lexptr,s)==0)

return k;

return 0;

int insert(char s[],int tok)

{

int len;

len=strlen(s);

if(lastentry+1>=MAX)

Error.Message(“Symbol table is full”);

if(lastchar+len+1>=MAX)

Error.Message(“Lexemes array is full”);

Symtable[lastentry].token=tok;

Symtable[lastentry].lexptr=&lexemes[lastchar+1];

lastchar=lastchar+len+1;

strcpy(symtable[lastentry].lexptr,s);

return lastentry;

}

void initialize()

{

struct entry *ptr;

for(ptr=keywords;ptr->token,ptr++)

insert(ptr->lexptr,ptr->token);

}

int lexer()

{

int i;

nt val,i=0;

while()

22

Page 23: Pcd Record

{

t=getchar();

if(t==’’||t==’\t’)

else if(t==’\t’)

lineno=lineno+1;

else if(isdigit(t))

{

ungetc(t,stdin);

scanf(“%d”,&tokenval);

return NUM;

}

else if(isalpha(t))

{

while(isalnum(t))

{

buffer[i]=t;

t=getchar();

i=i+1;

if(i>=SIZE)

Error_Message(“Compiler Error”);

}

buffer[i]=EOS;

if(t!=EOF)

ungetc(t,stdin);

val=look_up(buffer);

if(val==0)

val=insert(buffer,ID);

tokenval=val;

return symtable[val].token;

}

else if(t==EOF)

return DONE;

else

{

23

Page 24: Pcd Record

tokenval=NONE;

return t;

}

}

}

void match(int t)

{

if(lookahead==t)

ookahead=lexer;

else Error_Message(“Syntax error”);

}

void display(int t, int val)

{

if(t==’+’||t==’-’||t==’*’||t==’%’)

printf(“Arithmetic Operator:%c”,t);

else if(t==NUM)

printf(“\n Number: %d”, tval);

else if(t==ID)

printf(“\n Identifier:%s”,symtable[tval].lexptr);

else

printf(“\n Token %d token valid %d”,t,tokenval);

}

void F()

{

void E();

switch(lookahead)

case’{’:match(‘)’);E();

match(‘)’);

break;

case NUM:display(NUM,tokenval);

match(NUM);

break;

case ID:display(ID,tokenval);

match(ID);

24

Page 25: Pcd Record

break;

default:Error_Message(“Syntax Error”);

}

}

void T()

{

put t;

F();

while(1)

{

switch(lookahead)

{

case’*’: t=lookahead;

match(lookahead);

continue;

case’/’:t=lookahead;

match(lookahead);

F();

display(t,NONE);

continue;

default:return n;

}

}

}

void E()

{

int t;

T();

while(1)

{

switch(lookahead)

{

case’+’: t=lookahead;

match(lookahead);

25

Page 26: Pcd Record

T();

display(t,NONE);

continue;

case’-’:t=lookahead;

match(lookahead);

T();

display(t,NONE);

continue;

default:return n;

}

}

}

void parser()

{

lookahead=lexer;

while(lookahead!=DONE)

{

E();

match(‘i’);

}

}

void main()

{

char ans;

clrscr();

printf(“\n\n Program For Recursive Descent Parsing\n\n”);

initialize();

printf(“\n Enter the expression”);

printf(“\n And Place’;’ at the end”);

printf(“Press ctrl+z to terminate”);

parser();

getch();

}

26

Page 27: Pcd Record

INPUT AND OUTPUT :

Program for Recursive Descent parsing

Enter the expression

And place; at the end

Press ctrl + z to terminate

ax + by + cz;

Identifier =ax

Identifier : by

Arithmetic Operator: +

Identifier : cz

Arithmetic Operator : +

RESULT :

Thus the implementation of recursive descent parsing using C program is successfully

written and verified.

27

Page 28: Pcd Record

Ex.No : 05 PARSER IMPLEMENTATION USING YACC & LEXDate :

AIM :

To write a program to implement the parser using YACC and LEX tool.

ALGORITHM :

1. Start the program.

2. Create the translator programs calc1.y and calc1.l using YACC and LEX respectively.

3. Calc1.y

i. In the Declaration part, include the header files of ‘c’ and ‘lex’.

ii. Specify the token to be processed as integer.

iii. Write the translation rules for the arithmetic expressions ‘+’, ‘-‘, ‘*’,’/’.

iv. Write the error routine yyerrror().

v. In order to create Yacc lexical analyzer with lex, include lex.yy.c and call the parser

function yyparse() in the main().

4. Calc1.l

i. Include the necessary files in the declaration part.

ii. In the translation part, analyze the input characters one by one return the

corresponding values.

iii. If no one matches the pattern, then return the error message.

5. Compile calc1.y and calc1.l using yacc and lex tool respectively so that it will generate the

y.tab.c file automatically.

6. Compile y.tab.c using cc compiler and get the output.

28

Page 29: Pcd Record

CODING :

// parser.y

%{

#include <stdio.h>

int yylex(void);

void yyerror(char *);

%}

%token INTEGER

%%

program:

program expr '\n' { printf("%d\n", $2); }

|

;

expr:

INTEGER

| expr '+' expr { $$ = $1 + $3; }

| expr '-' expr { $$ = $1 - $3; }

| expr '*' expr { $$ = $1 * $3; }

| expr '/' expr { $$ = $1 / $3; }

;

%%

void yyerror(char *s)

{

fprintf(stderr, "%s\n", s);

}

#include "lex.yy.c"

int main(void)

{

yyparse();

return 0;

}

//parser.l

%{

29

Page 30: Pcd Record

#include <stdlib.h>

void yyerror(char *);

%}

%%

[0-9]+ {

yylval = atoi(yytext);

return INTEGER;

}

[+*-/\n] { return *yytext; }

[ \t] { }

. yyerror("Unknown character");

%%

int yywrap(void) {

return 1;

}

30

Page 31: Pcd Record

INPUT AND OUTPUT :

$ lex calc1.l

$ yacc calc1.y

$ cc y.tab.c

$ ./a.out

23*4

92

20*3

60

2*3+10

26

RESULT :

Thus the program to implement the parser using YACC and LEX tool is written and the

output is verified.

31

Page 32: Pcd Record

Ex.No : 06 IMPLEMENTING CALCULATOR USING YACCDate :

AIM :

To write a program to implement the calculator using YACC tool.

ALGORITHM :

1. Start the program.

2. In the Declaration part, include the header files stdio.h and ctype.h and initialize variables ‘i’

and‘t’.

3. Specify the token to be processed as DIGIT.

4. Write the translation rules for the arithmetic expressions ‘+’, ‘-‘, ‘*’,’/’ and others as ‘^’ and

‘\n’.

5. Write the error routine yyerrror().

6. Analyze the input characters one by one and convert it from ASCII values to their original

values and return it.

7. Call the parser function yyparse() in the main method.

8. Stop the program.

32

Page 33: Pcd Record

CODING :

%{

#include<stdio.h>

#include<ctype.h>

int i,t=0;

%}

%token DIGIT

%%

line : expr'\n' { printf("%d\n",$1);};

expr : expr '+' term { $$=$1+$3;}| term;

term : term '*' val{ $$=$1*$3;}| val;

val : val '-' val1 {$$=$1-$3;}|val1;

val1 : val1 '/' val2 {$$=$1/$3;}|val2;

val2 :val2 '^' factor {t=$1;for(i=0;i<$3-1;i++) $1*=t;$$=$1;} |factor;

factor:'('expr')'{$$=$2;}| DIGIT;

%%

int main(void)

{

return yyparse();

}

void yyerror(char*s)

{

fprintf(stderr,"%s\n",s);

}

yylex()

{

int c;

c=getchar();

if(isdigit(c))

{

yylval=c-'0';

return DIGIT;

}

return c;}

33

Page 34: Pcd Record

INPUT AND OUTPUT:

$ yacc calc.y

$ cc y.tab.c

$ ./a.out

2*3+5-2

9

RESULT :

Thus the program to implement the calculator using YACC tool is written and the output is

verified.

34

Page 35: Pcd Record

Ex.No : 07 SIMPLE INTERMEDIATE CODE GENERATION

Date :

AIM :

To write a ‘c’ program to generate the simple intermediate code for the given postfix

expression.

ALGORITHM :

1. Start the program.

2. Get the input expression from the user.

3. Scan the expression one by one until ‘=’ is found.

4. Increment the i value by one when the character is alphabet.

5. Call the codegen().

6. Codegen() analyses the input stream and generates the intermediate

code.

7. The process exits when ‘\0’ character is encountered.

8. Stop the program.

35

Page 36: Pcd Record

CODING :

#include<stdio.h>

#include<ctype.h>

#include<string.h>

void codegen();

char exp[20];

int i=0,t=49;

void main()

{

int j;

printf("Enter the postfix expression ending with ’=’:");

scanf("%s",exp);

while(exp[i]!='=')

{

while(isalpha(exp[i]))

i++;

codegen();

}

printf("%c %c t\%c\n\n",exp[0],exp[2],exp[1]);

getch();

}

void codegen()

{

int j,k;

if(isdigit(exp[i-1]))

printf("t%c %c t%c %c\n\n",t,exp[i],exp[i-1],exp[i-2]);

else if (isdigit(exp[i-2]))

printf("t%c %c %c t%c\n\n",t,exp[i],exp[i-1],exp[i-2]);

else

printf("t%c %c %c %c\n\n",t,exp[i],exp[i-1],exp[i-2]);

exp[i-2]=t;

k=i-1;

j=i+1;

while(exp[j]!='\0')

36

Page 37: Pcd Record

{

exp[k]=exp[j];

k++;

j++;

}

exp[k]='\0';

i=i-1;

t++;

}

37

Page 38: Pcd Record

INPUT AND OUTPUT :

Enter the postfix exp:

abcd*+e- = z

t1 * d c

t2 + t1 b

t3 - e t2

a = t3

RESULT :

Thus the ‘c’ program to generate the simple intermediate code for the given postfix

expression is written and the output is verified.

38

Page 39: Pcd Record

Ex.No : 08 INTERMEDIATE CODE GENERATION THREE ADDRESSDate : CODE FOR BOOLEAN EXPRESSION

AIM :

To write a ‘c’ program to generate the three address code for Boolean expression.

ALGORITHM :

1. Start the program.

2. Create the input file ‘inp.txt’ containing input code to be given.

3. Open the file by specifying the path and scan the input streams one by one and print it.

4. Then analyze the characters one by one whether it is an integer, keyword, operator or

identifier and generates the three address code accordingly.

5. Stop the program.

39

Page 40: Pcd Record

CODING :

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

FILE *in;

char temp[20],a[20],inp[20];

int i,j,k,f,f1;

clrscr();

i=0;

in=fopen("c:\\inp.txt","r");

printf(“\n Input file contains…”);

while((fscanf(in,"%s\n",inp))!=EOF)

{

printf("\n%s",inp);

}

rewind(in);

printf("\n\n Three Address Code\n");

while((fscanf(in,"%s\n",inp))!=EOF)

{

if((inp[i]=='i')&&(inp[++i]=='f'))

{

printf("1 if");

i=i+2;

do

{

printf("%c",inp[i]);

i++;

}

while(inp[i]!=')');

printf("goto 5\n");

fscanf(in,"%s",a);

f=1;

40

Page 41: Pcd Record

}

else if(strcmp(inp,"else")==0)

{

i=0;

fscanf(in,"%s",temp);

while(temp[i]!='=')

{

i++;

}

k=i;

printf("2 t=");

for(j=k+1;j<strlen(temp)-1;j++)

{

printf("%c",temp[j]);

}

printf("\n3 %c=t",temp[0]);

printf("\n4 goto 7");

f1=1;

}

if(f==1 && f1==1)

{

i=0;

k=0;

while(a[i]!='=')

{

i++;

}

k=i;

printf("\n5 t1=");

for(j=k+1;j<strlen(a)-1;j++)

{

printf("%c",a[j]);

}

printf("\n6 %c =t1\n",a[0]);

41

Page 42: Pcd Record

}

}

getch();

}

42

Page 43: Pcd Record

INPUT AND OUTPUT :

Inp.txt

if(b<c)

a=c-b;

else

a=b-c;

Three Address Code

1 ifb<cgoto 5

2 t=b-c

3 a=t

4 goto 7

5 t1=c-b

6 a =t1

RESULT :

Thus the ‘c’ program to generate the three address code for Boolean expression is written and

the output is verified.

43

Page 44: Pcd Record

Ex.No : 09 ASSEMBLY CODE GENERATIONDate :

AIM :

To write a ‘c’ program to generate the assembly code for the given input.

ALGORITHM :

1. Start the program.

2. Create the input file ‘instrn.txt’ containing input code to be given.

3. Get the choice of whether the input should be given manually or to be read from the input.

4. If the input to be get manually, then get number of statements and run the ‘for’ loop

accordingly and get the input statements.

5. Save the input statements in the file named ‘userinp.txt’ and open the file.

6. If the input to be read from the file, then open ‘instrn.txt’.

7. Then analyze the characters one by one whether it is an integer, keyword, operator or

identifier and generates the assembly code accordingly.

8. Stop the program.

44

Page 45: Pcd Record

CODING :

#include<stdio.h>

#include<conio.h>

char* findinstrn(char);

void main()

{

int i,j,k,m,n,f,t,p=1;

char a,a1,l,op,tas[20],instrn[20];

FILE *f1,*f2,*f3;

clrscr();

f1=fopen("c:\\instrn.txt","r");

f2=fopen("c:\\userinp.txt","w");

i=1;

while(p==1)

{

rewind(f1);

printf("\n\nTo give input directly press 1 or To take from a file press 0:");

scanf("%d",&t);

if(t==1)

{

printf("\n\nEnter the no of statements:");

scanf("%d",&n);

printf("\n\nNow enter the statements\n\n");

for(i=0;i<n;i++)

{

scanf("%s",tas);

fprintf(f2,"\n%s",tas);

}

fclose(f2);

f3=fopen("userinp.txt","r");

}

else

f3=fopen("c:\\instrn.txt","r");

while(!feof(f3))

45

Page 46: Pcd Record

{

fscanf(f3,"%s",tas);

f=0;

if(strlen(tas)==5)

{

l=tas[0];

a=tas[2];

op=tas[3];

a1=tas[4];

f=1;

}

else

{

l=tas[0];

a=tas[2];

}

if(f==1)

{

printf("\nMOVE\tR%d,%c",i,a);

strcpy(instrn,findinstrn(op));

printf("\n%s\tR%d,%c",instrn,i,a1);

printf("\nMOVE\t %c,R%d",l,i);

i++;

}

else

printf("\nMOVE\t %c,%c",l,a);

}

printf("\n\nDo U want to continue(y=1/n=0):");

scanf("%d",&p);

}

fcloseall();

getch();

}

char* findinstrn(char c)

46

Page 47: Pcd Record

{

if(c=='+')

return "ADD";

else if(c=='-')

return "SUB";

else if(c=='/')

return "DIV";

else if(c=='*')

return "MUL";

else

return "";

}

47

Page 48: Pcd Record

INPUT FILE:

instrn.txt

A=c*d

B=e/f

C=b+A

D=C-B

a=D

OUTPUT:

To give inputs directly press 1 or to take from a file press 0:0

MOVE R1,c

MUL R1,d

MOVE A,R1

MOVE R2,e

DIV R2,f

MOVE B,R2

MOVE R3,b

ADD R3,A

MOVE C,R3

MOVE R4,C

SUB R4,B

MOVE D,R4

MOVE a,D

Do U want to continue(y=1/n=0):1

To give input directly press 1 or To take from a file press 0:1

Enter the no of statements:3

Now enter the statements

A=b*c

B=A+d

a=B

MOVE R3,b

MUL R3,c

MOVE A,R3

48

Page 49: Pcd Record

MOVE R4,A

ADD R4,d

MOVE B,R4

MOVE a,B

RESULT :

Thus the ‘c’ program to generate the assembly code for the given input is written and the

output is verified.

49