compiler designlaboratory manual … cd 16-17.pdfcomputer science and engineering compiler design...

46
Computer Science and Engineering Compiler Design Narsimha Reddy Engineering College Page -1 INSTITUTE VISION AND MISSION Vision To emerge as a destination for higher education by transforming learners into achievers by creating, encouraging and thus building a supportive academic environment. Mission To impart Quality Technical Education and to undertake Research and Development with a focus on application and innovation which offers an appropriate solution to the emerging societal needs by making the students globally competitive, morally valuable and socially responsible citizens. DEPARTMENT VISION AND MISSION Vision To emerge as a center of excellence with global reputation with adaption of rapid advancements in the field of computer specialization. Mission 1. To provide a strong theoretical and practical background in area of computer science with an emphasize on software development. 2. To inculcate Professional behavior, strong ethical values, leadership qualities, research capabilities and lifelong learning. 3. To educate students to become effective problem solvers, apply knowledge with social sensitivity for the betterment of the society and humanity as a whole. PROGRAM EDUCATIONAL OBJECTIVES (PEOs) Programme educational objectives are broad statements that describe the career and professional accomplishments that the programme is preparing graduates to achieve within 3 to 5 years after graduation. The Programme Educational Objectives of the B. Tech CSE programme are: PEO1: To apply the knowledge of mathematics, basic science and engineering solving the real world computing problems to succeed higher education and professional careers. PEO2: To develop the skills required to comprehend, analyze, design and create innovative computing products and solutions for real life problems. PEO3: To inculcate professional and ethical attitude, communication and teamwork skills, multi- disciplinary approach and an ability to relate computer engineering issues with social awareness.

Upload: duongdiep

Post on 13-Jun-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -1

INSTITUTE VISION AND MISSION

Vision

To emerge as a destination for higher education by transforming learners into achievers by creating,

encouraging and thus building a supportive academic environment.

Mission

To impart Quality Technical Education and to undertake Research and Development with a focus on

application and innovation which offers an appropriate solution to the emerging societal needs by

making the students globally competitive, morally valuable and socially responsible citizens.

DEPARTMENT VISION AND MISSION

Vision

To emerge as a center of excellence with global reputation with adaption of rapid advancements in the

field of computer specialization.

Mission

1. To provide a strong theoretical and practical background in area of computer science with an

emphasize on software development.

2. To inculcate Professional behavior, strong ethical values, leadership qualities, research capabilities

and lifelong learning.

3. To educate students to become effective problem solvers, apply knowledge with social sensitivity for

the betterment of the society and humanity as a whole.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

Programme educational objectives are broad statements that describe the career and professional

accomplishments that the programme is preparing graduates to achieve within 3 to 5 years after

graduation.

The Programme Educational Objectives of the B. Tech CSE programme are:

PEO1: To apply the knowledge of mathematics, basic science and engineering solving the real world

computing problems to succeed higher education and professional careers.

PEO2: To develop the skills required to comprehend, analyze, design and create innovative

computing products and solutions for real life problems.

PEO3: To inculcate professional and ethical attitude, communication and teamwork skills, multi-

disciplinary approach and an ability to relate computer engineering issues with social awareness.

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -2

LABORATORY OUTCOMES: CO[1] To construct the program for lexical analyzer.

CO[2] To analyze how the lex tool techniques works.

CO[3] Students will be able to demonstrate the top down parsers

CO[4] Students will be able to examine the Bottom up parsers

CO[5] Students will be able show how the Yacc translator translates the code in to the compiler.

CO[6]Students will be able to create the machine code from Abstract syntax tree generated by the

parser.

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -3

Do’s

1. Come with completed observation and record

2. Wear apron and ID card before entering into the lab.

3. Know the location of the fire extinguisher and the first aid box and how to use them in case of an emergency.

4. Read and understand how to carry out an activity thoroughly before coming to the laboratory.

5. Report any broken plugs or exposed electrical wires to your lecturer/laboratory technician immediately.

6. Write in time, out time and system details in the login register.

Don’ts

1. Do not eat or drink in the laboratory.

2. Do not operate mobile phones in the lab. Keep mobile phones either in silent or switched off mode.

3. Do not change system settings.

4. Do not disturb your neighbouring students. They may be busy in completing tasks.

5. Do not remove anything from the computer laboratory without permission.

6. Do not use pen drives.

7. Do not misbehave.

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -4

COMPILER DESIGN LAB

COURSE NAME: COMPILER DESIGN LAB

COURSE CODE: A50587

Objectives:

To implement Lexical Analyzer using Lex tool & Syntax Analyzer or parser using YACC

Tool

To implement front end of the compiler by means of generating Intermediate codes.

To implement code optimization techniques.

Recommended Systems/Software Requirements:

Intel based desktop PC with minimum of 166 MHZ or faster processor with at least 64 MB RAM and

100MB free disk space.

LINUX(Fedora) OS.

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -5

INDEX

SNO NAME OF PROGRAM Pg

no

1 6

Design a lexical analyzer

2 Write a program to implement lexical analyzer using JLEX,FLEX,LEX tool 9

3 12

Write a program for Predictive Parser

4 17

Design a LALR Bottom up parser

5

Convert the BNF rules into Yacc form and write code to generate ABS 20

6 29

Write a program to generate machine code from the abstract syntax tree

ADDITIONAL PROGRAMS

1 Simulate First and Follow of a Grammar 34

2 Program to compute FIRST and FOLLOW within the same program 40

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -6

WEEK1:

1. Design a lexical analyzer

AIM: Design a Lexical Analyzer.

Theory:

The lexical analyzer is the first phase of a compiler. Its main task is to read the input characters

and produce as output a sequence of tokens. Up on receiving a “get next token” command from the

parser, the lexical analyzer reads input characters until it can identify the next token. Token is a group of

characters having a collective meaning. Tokens are constants, identifier, keywords, operators, special

symbols.

Program:

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<ctype.h> void main()

{

int i,j; clrscr();

char keywords[10][10]={"BEGIN","IF","THEN","ELSE","END"}; char

operators[10][10]={"<","<=",">","=","!="};

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -7

char string[10]; int

ch,l,found=0;

printf("/n enter any data of

your choice");

scanf("%s",string);

l=strlen(string);

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

string[i]=toupper(string[i]);

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

{

if(strcmp(&keywords[i][0],string)==0)

{

found=1;

ch=1;

break;

}

}

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

{

if(strcmp(&operators[i][0],string)==0)

{

found=1;

ch=2;

break;

}

}

switch(ch)

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -8

{

case 1: if(found==1)

printf("\n you have entered keyword"); break;

case 2: if(found==1)

printf("\n you have entered relational operator");

break;

default:printf("\n you have entered default choice");

}

getch();

}

Input:-

enter any data of your choice

else

1) POST LAB QUESTIONS

What is lexical analyzer?

Which compiler is used for lexical analyzer?

What is the output of Lexical analyzer?

What is LEX source Program?

PRE LAB QUESTIONS

What is token?

What is lexeme?

What is the difference between token and lexeme?

Define phase and pass?

What is the difference between phase and pass?

What is the difference between compiler and interpreter?

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -9

WEEK 2:

2. To implement lexical analyzer using JLEX,FLEX,LEX tool.

AIM: Write a program to implement lexical analyzer using JLEX,FLEX,LEX tool.

THEORY: Lex is a unix utility which generates the lexical analyzer. The lex specification lex.l is given to

Lex compiler to produce lex.yy.c. This lex.yy.c is a C program and consists of the tabular representation of

the transition diagrams constructed for the regular expressions. The lex.yy.c is given to C compiler to produce

object program a.out. When some input stream is given to a.out then sequence of tokens get generated. Lex

specification consists of three parts:-

1) Declaration section 2) Translation rules 3) Auxiliary procedures %{

Declaration section %}

%%

Translation rules

%%

Auxiliary procedures

Program:

lex.l

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -10

%{

%}

delim [\t \n] ws {delim}+ digit

[0-9] letter [A-Z a-z]

id {letter}({letter}|{digit})* num {digit}+

num1 {digit}+.{digit}+

%%

{ws} { }

{id} {printf("identifier");}

{num} {printf("integer constant");} {num1} {printf("real

constant");} "+"|"-"|"*"|"/" {printf("arithmetic operator);}

“=” {printf(“Assign”);}

“==” {printf(“EQ”);}

“<”|”>”|”<=”|”>=” {printf(“Relational operator”);} int|char|float|double

{printf("keyword");} "("|")"|";"|"}"|"{"|","|"["|"]" {printf("special

symbol");}

%%

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -11

PRE LAB QUESTIONS:

1. List the different sections available in LEX compiler?

2. What is an auxiliary definition?

3. How can we define the translation rules?

4. What is regular expression?

5. What is finite automaton?

POST LAB QUESTIONS:

6. What is Jlex?

7. What is Flex?

8. What is lexical analyzer generator?

9. What is the input for LEX Compiler?

10. What is the output of LEX compiler?

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -12

WEEK3:

3. Write a program for Predictive Parser

AIM: Write a program for Predictive Parser

THEORY: Construction of predictive parsing involves following steps:-

1) Computation of FIRST and FOLLOW function.

2) Construct predictive parsing table using FIRST and FOLLOW functions.

3) Parse the input string with the help of parsing table.

FIRST function

First is applied for terminals and non terminals

1) If the terminal symbol is a then FIRST(a)={a}.

2) If there is a rule X->ε then FIRST(X)={ε}.

3) If there is a rules X->Aa and A->b then FIRST(X)=FIRST(A)={b}.

FOLLOW function

Follow is applied for non terminals

2) For the start symbol S place $ in FOLLOW(S).

3) If there is a production A->αBβ then everything in FIRST(β) without ε is to be placed in

FOLLOW(B).

4) If there is a production A->αBβ or A->αB and FIRST(β)={ε} then FOLLOW(A)=FOLLOW(B)

or FOLLOW(B)=FOLLOW(A). That means everything in FOLLOW(A) is in FOLLOW(B).

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -13

Program:

#include<stdio.h>

#include<conio.h>

#include<string.h>

char prol[7][10]={"S","A","A","B","B","C","C"};

char pror[7][10]={"A","Bb","Cd","aB","@","Cc","@"};

char prod[7][10]={"S->A","A->Bb","A->Cd","B->aB","B->@","C->Cc","C->@"};

char first[7][10]={"abcd","ab","cd","a@","@","c@","@"};

char follow[7][10]={"$","$","$","a$","b$","c$","d$"};

char table[5][6][10];

numr(char c)

{

switch(c)

{ case 'S': return 0;

case 'A': return 1;

case 'B': return 2;

case 'C': return 3;

case 'a': return 0;

case 'b': return 1;

case 'c': return 2; case 'd': return 3; case '$': return 4;

}

return(2); }

void main() {

int i,j,k; clrscr(); for(i=0;i<5;i++)

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -14

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

strcpy(table[i][j]," ");

printf("\nThe following is the predictive parsing table for the following grammar:\n"); for(i=0;i<7;i++)

printf("%s\n",prod[i]); printf("\nPredictive parsing

table is\n"); fflush(stdin);

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

{

k=strlen(first[i]);

for(j=0;j<10;j++)

if(first[i][j]!='@')

strcpy(table[numr(prol[i][0])+1][numr(first[i][j])+1],prod[i]);

}

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

{

if(strlen(pror[i])==1)

{

if(pror[i][0]=='@')

{

k=strlen(follow[i]);

for(j=0;j<k;j++)

strcpy(table[numr(prol[i][0])+1][numr(follow[i][j])+1],prod[i]);

}

}

strcpy(table[0][0]," ");

strcpy(table[0][1],"a");

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -15

strcpy(table[0][2],"b");

strcpy(table[0][3],"c");

strcpy(table[0][4],"d");

strcpy(table[0][5],"$");

strcpy(table[1][0],"S");

strcpy(table[2][0],"A");

strcpy(table[3][0],"B");

strcpy(table[4][0],"C");

printf("\n--------------------------------------------------------\n");

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

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

{

printf("%-10s",table[i][j]);

if(j==5)

printf("\n--------------------------------------------------------\n");

}

getch();

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -16

PRE LAB QUESTIONS:

1. What is top-down parsing?

2. What are the disadvantages of brute force method?

3. What is context free grammar?

4. What is parse tree?

5. What is ambiguous grammar?

6. What are the derivation methods to generate a string for the given grammar?

7. What is the output of parse tree?

POST LAB QUESTIONS

1. What is Predictive parser?

2. How many types of analysis can we do using Parser?

3. What is Recursive Decent Parser?

4. How many types of Parsers are there?

5. What is LR Parser?

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -17

WEEK 4 :

4. Design a LALR Bottom up parser

AIM: Design a LALR Bottom up parser

THEORY: Yacc stands for Yet Another Compiler Compiler which is basically the utility available from UNIX.

First we write a YACC specification file and is given to the YACC compiler then it will generate y.tab.c.

y.tab.c program will be compiled by C compiler to get a.out file. Then you can test your YACC program with

the help of some valid strings and invalid strings.

Program:

translate.y

%{

#include<ctype.h>

%}

%token DIGIT

%%

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

;

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -18

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

| term

term : term'*'factor {$$=$1*$3;}

| factor

;

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

| DIGIT

%%

yylex()

{

int c; c=getchar();

if(isdigit(c))

{

yylval=c-'0'; return DIGIT;

}

return c;

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -19

PRE-LAB QUESTIONS

1 Why bottom-up parsing is also called as shift reduce parsing?

2 What are the different types of bottom up parsers?

3 What is mean by LR (0) items?

4 Write the general form of LR(1) item?

5 What is YACC?

POST-LAB QUESTIONS:

1. What is LALR parsing?

2. What is Shift reduced parser?

3. What are the operations of Parser? 4. What is the use of parsing table?

5. What is bottom up parsing?

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -20

WEEK 5:

6 Convert the BNF rules into Yacc form and write code to generate Abstract Syntax Tree

AIM: Convert the BNF rules into Yacc form and write code to generate Abstract Syntax Tree

THEORY:

Program:

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

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -21

\n LineNo++;

. return yytext[0];

%%

<int.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; 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

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -22

;

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,$$);}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -23

| 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

;

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

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -24

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,"==");

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -25

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

};

%%

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 Arg1 Arg2 Result" "\n\t\t

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -26

--------------------");

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;

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -27

}

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

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -28

PRE-LAB QUESTIONS

1 What are the functions we use to construct a syntax tree?

2 What is Meta data?

3 How list of identifiers are represented using BNF rules?

4 What is three address code?

5 What are the record structures we use to represent three address code?

POST-LAB QUESTIONS:

1. What is Abstract Syntax tree?

2. What are BNF Rules?

3. What is DAG representation?

4. How LALR (1) states are generates?

5. In which condition the user has to supply more information to YACC?

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -29

WEEK 6:

6. Write a program to generate machine code from the abstract syntax tree

AIM: Write a program to generate machine code from the abstract syntax tree

Program:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int label[20];

int no=0; int main()

{

FILE *fp1,*fp2;

char fname[10],op[10],ch;

char operand1[8],operand2[8],result[8];

int i=0,j=0;

printf("\n Enter filename of the intermediate code”); scanf("%s",&fname);

fp1=fopen(fname,"r");

fp2=fopen("target.txt","w"); if(fp1==NULL || fp2==NULL)

{

printf("\n Error opening the file"); exit(0);

}

while(!feof(fp1))

{

fprintf(fp2,"\n");

fscanf(fp1,"%s",op);

i++; if(check_label(i))

fprintf(fp2,”\nlabel#%d”,i);

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -30

if(strcmp(op,”print”)==0)

{fscanf(fp1,”%s”,result);

fprintf(fp2,”\n\tOUT%s”,result);

}

if(strcmp(op,”goto”)==0)

{

fscanf(fp1,"%s %s",operand1,operand2);

fprintf(fp2,"\n\tJMP%s,label#%s",operand1,operand2);

label[no++]=atoi(operand2);

}

if(strcmp(op,"[]=")==0)

{

fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n\t STORE

%s[%s],%s",operand1,operand2,result);}

if(strcmp(op,”minus)==0)

{

fscanf(fp1,"%s %s",operand1,result); fprintf(fp2,"\n\t

LOAD -%s,R1",operand1); fprintf(fp2,"\n\t STORE

R1,%s",result);

}

switch(op[0])

{

case '*': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t

LOAD",operand1);

fprintf(fp2,"\n \t LOAD %s,R1",operand2);

fprintf(fp2,"\n \t MUL R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result);

break;

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -31

case '+': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t

LOAD %s,R0",operand1);

fprintf(fp2,"\n \t LOAD %s,R1",operand2);

fprintf(fp2,"\n \t ADD R1,R0"); fprintf(fp2,"\n \t STORE

R0,%s",result); break;

case '-': fscanf(fp1,"%s %s %s",operand1,operand2,result);

fprintf(fp2,"\n \t LOAD %s,R0",operand1);

fprintf(fp2,"\n \t LOAD %s,R1",operand2);

fprintf(fp2,"\n \t SUB R1,R0"); fprintf(fp2,"\n \t STORE

R0,%s",result); break;

case '/': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t

LOAD %s,R0",operand1);

fprintf(fp2,"\n \t LOAD %s,R1",operand2);

fprintf(fp2,"\n \t DIV R1,R0"); fprintf(fp2,"\n \t STORE

R0,%s",result); break;

case '%': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t

LOAD %s,R0",operand1);

fprintf(fp2,"\n \t LOAD %s,R1",operand2);

fprintf(fp2,"\n \t DIV R1,R0"); fprintf(fp2,"\n \t STORE

R0,%s",result); break;

case '=': fscanf(fp1,"%s %s",operand1,result); fprintf(fp2,"\n \t

STORE%s%s",operand1,result); break;

case '>': j++;

fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t

LOAD %s,R0",operand1); fprintf(fp2,"\n\t JGT

%s,label#%s",operand2,result); label[no++]=atoi(result);break;

case '<': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t

LOAD %s,R0",operand1);

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -32

fprintf(fp2,"\n \t JLT %s,label#%d",operand2,result);

label[no++]=atoi(result);break;

}

}

fclose(fp2);

fclose(fp1);

fp2=fopen(“target.txt”,”r”);

if(fp2==NULL)

{

printf(“Error opening the file\n”); exit(0);

}

do

{

ch=fgetc(f2);

printf(“%c”,ch);

}while(ch!=EOF);

fclose(fp1); return 0;

}

int check_label(int k)

{

int i; for(i=0;i<no;i++){

if(k==label[i]) return 1;}

return 0;

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -33

PRE-LAB QUESTIONS

1 What are the different forms of object code?

2 What is mean by relocatable object code?

3 What is the cost of register to register operation?

4 What is address descriptor? 5 What is register descriptor?

POST-LAB QUESTIONS

1. What is target code?

2. What is machine code?

3. What is Cross compiler?

4. Give the example for cross compiler?

5. What is the difference between syntax & Semantics?

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -34

ADDITIONAL PROGRAMS

1. Simulate First and Follow of a Grammar.

Aim: Simulate First and Follow of a Grammar.

Theory:

FIRST function is used to find out the terminal symbols that are possible from both terminal and non-terminal symbols. The

application of this function is widely seen in designing the Predictive parser tables that are used in designing compilers for

various languages. Even the first compiler C, has an in built predictive parser which is operated through the calculation of the

first and follow functions.

Description:

FIRST function is applied to both terminal symbols and non-terminal symbols such that its definition has certain rules to be

employed. They are as follows:

1)FIRST of any terminal symbol „a‟ is the terminal „a‟ itself.

2)FIRST of non terminal „A‟ = FIRST of „@‟, where A -> @ such that @ is a string containing terminals and non-terminals.

FIRST of any entinty is given by FIRST(a) for terminal „a‟ and FIRST(A) for non-terminal „A‟. The following program code

simulates and computes the FIRST of the Grammar defined by the user at the compile time.

Program for finding only FIRST:

/* Terminals of the grammar */

char T[20];

/* Non Terminals of the grammar */

char NT[20];

/* Table consisting of the FIRST of allNon Terminals */

char FT[10][20];

/* Array consisting of productions of the grammar */

char P[20][10];

/* Number of Productions */

int NOP=0;

/* Number of Non Terminals */

int NONT;

/* Number of Terminals */

int NOT;

/* Function to read grammar from the user */

void getGrammar()

{

int i;

/* Production */

char prod[30];

printf("Enter the grammar::(Type e for epsilon)\n");

printf("Press Enter when completed::\n");

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -35

while(1)

{

gets(prod);

if(strcmp(prod,"")==0)

{

break;

}

strcpy(P[NOP++],prod);

}

}

/* Function to get all the terminals and Non terminals of the grammar */

void getTerminalsAndNonTerminals()

{

printf("Enter the Non Terminal symbols used in the grammar::\n");

printf("Dont use any seperators in between::\n");

gets(NT);

NONT = strlen(NT);

printf("Enter the Terminal symbols used in the grammar::\n");

printf("Dont use any seperators in between::\n");

gets(T);

strcat(T,"e");

NOT = strlen(T);

}

int getIndex(char A[],char c)

{

int i=0;

for(i=0;i<strlen(a);i++)

{

if(A[i]==c)

return i;

}

return -1;

}

void addEpsilon(char c)

{

FT[getIndex(NT,c)][strlen(T)-1]='e';

}

int hasEpsilon(char c)

{

if(FT[getIndex(NT,c)][strlen(T)-1]=='e')

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -36

return(1);

return(0);

}

int isNonTerminal(char c)

{

int i;

for(i=0;i<strlen(nt);i++)

{

if(NT[i]==c)

{

return 1;

}

}

return 0;

}

int isTerminal(char c)

{

int i=0;

for(i=0;i<strlen(t)-1;i++)

{

if(T[i]==c)

return 1;

}

return 0;

}

void computeFirst()

{

int added=0,i,j,k;

char X,elm1,elm2;

clrscr();

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

{

for(j=0;j<not;j++)

{

FT[i][j]='\0';

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -37

}

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

{

X = P[i][3];

if(X=='e')

{

addEpsilon(P[i][0]);

}

else if(isTerminal(X))

{

FT[getIndex(NT,P[i][0])][getIndex(T,X)]=X;

}

}

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

{

X = P[i][3];

if(isNonTerminal(X))

{

for(j=3;j<strlen(p[i]);j++)

{

X=P[i][j];

if(isTerminal(X))

{

FT[getIndex(NT,P[i][0])][getIndex(T,X)]=X;

break;

}

for(k=0;k<not;k++)

{

elm1=FT[getIndex(NT,P[i][0])][k];

elm2=FT[getIndex(NT,X)][k];

if((elm1!=elm2) && elm2!='e')

{

if(elm2!='\0')

{

added=1;

FT[getIndex(NT,P[i][0])][k]=elm2;

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -38

}

}

if(!hasEpsilon(X))

{

break;

}

}

if(j==strlen(P[i]))

{

added=1;

FT[getIndex(NT,P[i][0])][5]='e';

}

}

if(i==(NOP-1))

{

if(added)

{

i=-1;

added=0;

}

}

}

}

void main()

{

int i,j,k;

clrscr();

getGrammar();

getTerminalsAndNonTerminals();

computeFirst();

printf("THE GIVEN GRAMMAR IS::\n");

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

{

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

}

printf("\nThe FIRST for all grammar symbols::\n");

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

{

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -39

printf("FIRST(%c)={",NT[i]);

for(j=0;j<not;j++)

{

if(FT[i][j]!='\0')

printf("%c,",FT[i][j]);

}

printf("\b}\n");

}

getch();

}

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -40

2) Program to compute FIRST and FOLLOW within the same program

char T[]="+*()de";

char NT[]="EATBF";

char FT[5][6];

char FLWT[5][6];

char P[8][10]={ "E->TA",

"A->+TA",

"A->e",

"T->FB",

"B->*FB",

"B->e",

"F->(E)",

"F->d" };

int getIndex(char A[],char c)

{

int i=0;

for(i=0;i<strlen(a);i++)

{

if(A[i]==c)

return i;

}

return -1;

}

void addEpsilon(char c)

{

FT[getIndex(NT,c)][5]='e';

}

int hasEpsilon(char c)

{

if(FT[getIndex(NT,c)][5]=='e')

return(1);

return(0);

}

int isNonTerminal(char c)

{

int i;

for(i=0;i<strlen(nt);i++)

{

if(NT[i]==c)

{

return 1;

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -41

}

}

return 0;

}

int isTerminal(char c)

{

int i=0;

for(i=0;i<strlen(t)-1;i++)

{

if(T[i]==c)

return 1;

}

return 0;

}

void ComputeFollow()

{

int len,i,j,k,added=0;

char sym1,sym2,elm1,elm2,sym;

FLWT[getIndex(NT,'E')][5]='$';

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

{

len=strlen(P[i]);

for(j=3;j<len;j++)

{

sym1=P[i][j];

sym2=P[i][j+1];

if(isNonTerminal(sym1) && isTerminal(sym2))

{

FLWT[getIndex(NT,sym1)][getIndex(T,sym2)]=sym2;

}

}

}

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

{

len=strlen(P[i]);

for(j=3;j<len;j++)

{

sym1=P[i][j];

sym2=P[i][j+1];

if(isNonTerminal(sym1) && isNonTerminal(sym2))

{

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -42

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

{

elm1=FLWT[getIndex(NT,sym1)][k];

elm2=FT[getIndex(NT,sym2)][k];

if(elm1!=elm2)

{

if(elm2!='\0' && elm2!='e')

{

FLWT[getIndex(NT,sym1)][k]=elm2;

}

}

}

}

}

}

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

{

sym1=P[i][strlen(P[i])-1];

if(isNonTerminal(sym1))

{

sym2=P[i][0];

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

{

elm1=FLWT[getIndex(NT,sym1)][k];

elm2=FLWT[getIndex(NT,sym2)][k];

if(elm1!=elm2)

{

if(elm2!='\0' && elm2!='e')

{

added=1;

FLWT[getIndex(NT,sym1)][k]=elm2;

}

}

}

}

sym=P[i][strlen(P[i])-1];

if(isNonTerminal(sym) && hasEpsilon(sym))

{

sym1=P[i][strlen(P[i])-2];

if(isNonTerminal(sym1))

{

sym2=P[i][0];

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -43

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

{

elm1=FLWT[getIndex(NT,sym1)][k];

elm2=FLWT[getIndex(NT,sym2)][k];

if(elm1!=elm2)

{

if(elm2!='\0' && elm2!='e')

{

added=1;

FLWT[getIndex(NT,sym1)][k]=elm2;

}

}

}

}

if(i==7)

{

if(added)

{

i=-1;

added=0;

}

}

}

}

}

void ComputeFirst()

{

int added=0,i,j,k;

char X,elm1,elm2;

clrscr();

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

{

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

{

FT[i][j]='\0';

}

}

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

{

X = P[i][3];

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -44

if(X=='e')

{

addEpsilon(P[i][0]);

}

else if(isTerminal(X))

{

FT[getIndex(NT,P[i][0])][getIndex(T,X)]=X;

}

}

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

{

X = P[i][3];

if(isNonTerminal(X))

{

for(j=3;j<strlen(p[i]);j++)

{

X=P[i][j];

for(k=0;k<5;k++)

{

elm1=FT[getIndex(NT,P[i][0])][k];

elm2=FT[getIndex(NT,X)][k];

if(elm1!=elm2)

{

if(elm2!='\0')

{

added=1;

FT[getIndex(NT,P[i][0])][k]=elm2;

}

}

}

if(!hasEpsilon(X))

{

break;

}

}

if(j==strlen(P[i]))

{

added=1;

FT[getIndex(NT,P[i][0])][5]='e';

}

}

if(i==7)

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -45

{

if(added)

{

i=-1;

added=0;

}

}

}

}

void main()

{

int i,j;

ComputeFirst();

printf("THE GIVEN GRAMMAR IS::\n");

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

{

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

}

printf("\nThe FIRST for all grammar symbols::\n");

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

{

printf("FIRST(%c)={",NT[i]);

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

{

if(FT[i][j]!='\0')

printf("%c,",FT[i][j]);

}

printf("\b}\n");

}

ComputeFollow();

printf("\nThe FOLLOW for all grammar symbols::\n");

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

{

printf("FOLLOW(%c)={",NT[i]);

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

{

if(FLWT[i][j]!='\0')

printf("%c,",FLWT[i][j]);

}

printf("\b}\n");

}

getch();

Computer Science and Engineering Compiler Design

Narsimha Reddy Engineering College Page -46

}