SPCC - Lab 23 24

You might also like

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

YADAVRAO TASGAONKAR INSTITUTE OF

ENGINEERING AND TECHNOLOGY

DEPARTMENT OF COMPUTER ENGINEERING

Lab Journal

SYSTEM PROGRAMMING AND COMPILER


CONSTRUCTION LAB

Class semester: TE-VI


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Index

Page
Ex. No Name of the Experiment
Number
Implement a program to count number of chars, words,
1 sentences, paragraph present in input.

2 Implement Symbol table creation in C.

3 Conversion of infix to postfix expression in C

4 Conversion of Regular expression to NFA in C

5 Implementation of scientific calculator

6 Implementation of LL(1) parser

7 Design and implement Pass I of two pass assembler

8 Study of LLVM

9 TWO PASS MACROPROCESSOR

10 SINGLE PASS MACRO PROCESSOR

11 ABSOLUTE LOADER

12 A Lexical Analyzer Generator.

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 2


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

INTRODUCTION ABOUT COMPILER

1. The Phases of a Compiler

A Language Processing System

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 3


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

The Phases of a Compiler

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 4


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Translation of a Statement

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 5


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

2. Building Languages from Grammars

Syntax Definition of a Programming Language

Grammar Components:

an alphabet of terminal and non-terminal symbols ;

a set of rules, consisting of left-hand side and right-hand side ( the left-hand side consist of a single

non-terminal and the


right-hand side has zero or more non-terminal and terminals ) ;

a start symbol.

Example:
expression expression + term
| expression - term
| term

term term * factor


| term / factor
| factor

factor Identifier
| Constant
| ( expression )

Grammar Requirements:

- for each non-terminal a rule must exist ;

- all non-terminals must be reachable from the start symbol ;

- a grammar must be unambiguous: a unique parse tree must exist for each sentence in
the language ;

- a grammar must be and deterministic: it must enable to decide which rule to use in
order to complete the parse tree or to discover that no tree can be built to accommodate the next
input.

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 6


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

INTRODUCTION ABOUT LEX TOOL


Definitions:
● The flex input file consists of three sections, separated by a line with just %% in it:

%%
rules
%%
user code
● The definitions section contains declarations of simple name definitions to simplify the
scanner specification.
● Name definitions have the form: name definition
● Example:
DIGIT [0-9]
ID [a-z][a-z0-9]*

● The rules section of the flex input contains a series of rules of the form: pattern action
● Example:
{ID} printf( "An identifier: %s\n", yytext );

● The yytext and yylength variable.


● If action is empty, the matched token is discarded.
● If the action contains a ‘{‘, the action spans till the balancing ‘}‘ is found, as in C.
● An action consisting only of a vertical bar ('|') means "same as the action for the next rule.“
● The return statement, as in C.
● In case no rule matches: simply copy the input to the standard output (A default rule).
● For example: a “<“ can be matched by “<“ and “<=“.
● The one matching most text has higher precedence.
● If two or more have the same length, the rule listed first in the flex input has higher
precedence.
● The user code section is simply copied to lex.yy.c verbatim.
● The presence of this section is optional; if it is missing, the second %% in the input file may
be skipped.
● In the definitions and rules sections, any indented text or text enclosed in %{ and %} is copied
verbatim to the output (with the %{}'s removed).

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 7


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 1 IMPLEMENT A PROGRAM TO COUNT NUMBER OF


Date: CHARS, WORDS, SENTENCES, PARAGRAPH PRESENT
IN INPUT.

AIM: Implement a program to count number of chars, words, sentences, paragraph present in input.

ALGORITHM:
Step by step descriptive logic to count characters, words and lines in a text file.
1. Open source file in r (read) mode.
2. Initialize three variables characters = 0, words = 0 and lines = 0 to store counts.
3. Read a character from file and store it to some variable say ch.
4. Increment characters count.
Increment words count if current character is whitespace character i.e. if (ch == ' ' || ch == '\t' || ch
== '\n' || ch == '\0').
Increment lines count if current character is new line character i.e. if (ch == '\n' || ch == '\0').
5. Repeat step 3-4 till file has reached end.
6. Finally after file has reached end increment words and lines count by one if total characters > 0 to
make sure you count last word and line.
Get the inputs-data types and symbols from the user in the statement

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE * file;
char path[100];

char ch;
int characters, words, lines;

/* Input path of files to merge to third file */


printf("Enter source file path: ");
scanf("%s", path);

/* Open source files in 'r' mode */


file = fopen(path, "r");

/* Check if file opened successfully */


if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 8


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

exit(EXIT_FAILURE);
}

/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;

/* Check new line */


if (ch == '\n' || ch == '\0')
lines++;

/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}

/* Increment words and lines for last word */


if (characters > 0)
{
words++; lines++;
}

/* Print file statistics */


printf("\n");
printf("Total characters = %d\n", characters); printf("Total words = %d\n",
words); printf("Total lines = %d\n", lines);

/* Close files to release resources */


fclose(file);

return 0;
}

CONCLUSION

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 9


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 2
IMPLEMENT SYMBOL TABLE CREATION IN C.
Date:

AIM: To implement symbol table creation in C

ALGORITHM:

1. Get the inputs-data types and symbols from the user in the statement

2. Data types and symbols are separated to identify the types separately.

If the data type is char, then 1 byte(8 bits) are allocated.If the data type is integer, then 2
bytes(16 bits) are allocated. If it is long then 4 bytes are allocated. If it is float 8 bytes are allocated
in the memory.
3. The addresses are allocated for each data type and are printed along with the symbols.

PROGRAM:

#include<stdio.h> #include<conio.h> void main()


{
FILE *f;
int addr=1000,brace=0,i,j,len,size; char var[5],type[5],news[10]; clrscr();
printf(" &&&&&&&& OUTPUT &&&&&&&&&\n"); printf("\nstarting address : 1000\n");
printf("VAR \t\tTYPE \t\tSIZE \t\tADDRESS\n"); f=fopen("S:DECLARE.C","r");
while(!feof(f))
{
len=1;
fscanf(f,"%s %s",type,var); for(i=0;i<strlen(var);i++)
{
if(var[i]=='[')
{
brace=1; break;
}
}
if(brace==1)
{
j=0;
for(i=i+1;i<strlen(var)-1;i++)
{
news[j]=var[i]; j++;
}
len=atoi(news); brace=0;
}
if(strcmp(type,"int")==0)
{
addr=addr+(2*len); size=2*len;
}
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 10
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

if(strcmp(type,"float")==0)
{
addr+=(4*len); size=4*len;
}
if(strcmp(type,"char")==0)
{
addr+=(1*len); size=1*len;
}
if(strcmp(type,"long")==0)
{
addr=addr+(4*len); size=4*len;
}
printf("\n%s\t\t%s\t\t%d\t\t%d",var,type,size,addr);
}
getch();
}

CONCLUSION:

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 11


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 3
CONVERSION OF INFIX TO POSTFIX EXPRESSION IN C
Date:

AIM:
To write a C program to convert of infix to postfix expression in C

ALGORITHM:

1. Get the infix expression form then user.

2. In an empty stack, push the delimiter.

3. Read the character from the infix form.

4. If the character(ch) is an operand, append to the postfix form.

5. If it is a closing parenthesis then pop a character from the stack and let it be pch and append
pch value to postfix form. Repeat this process until pch equals opening paranthesis.

6. If ch=4, pop all entries from the stack and append it to the postfix form.

7. Else if,ch=an operator or ( , pop a character from the stack(pch).

8. If stack priority of pch is greater than or equal to the infix priority of ch,append pch to
postfix form and push ch to the stack.

9. Else push pch and ch to the stack.

10. Repeat the steps 3 to 9 until you get the delimiter.

PROGRAM:

#include<stdio.h> #include<stdlib.h> #include<ctype.h> int i=0,top=-1,n;


char stack[15],post[15]; void main()
{
void concat(char); void push(char); char pop(void); int stackpri(char); int infixpri(char); char
ch[20],item;

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 12


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

int j; clrscr(); push('#');


printf("Enter the infix string\n"); gets(ch);
j=-1;
do
{
j=j+1; if((ch[j]>='d'||ch[j]>='A')&&(ch[j]<='z'||ch[j]<='Z')) concat(ch[j]);
else
{
switch(ch[j])
{
case ')':
item=pop(); while(item!='(')
{
concat(item); item=pop();
}
break; case '#':
item=pop(); while(top>=0)
{
concat(item); item=pop();
}
break; default:
item=pop(); while(stackpri(item)>=infixpri(ch[j]))
{
concat(item); item=pop();
}
push(item);

push(ch[j]);
}
}
}while(ch[j]!='#'); printf("Required postfix string is \n"); printf("%s",post);
getch();
}
void concat(char item1)
{
post[i]=item1; i=i+1;
}
void push(char item2)
{
top=top+1; stack[top]=item2;
}
char pop()
{
char delitem; delitem=stack[top]; top=top-1; return(delitem);
}
int infixpri(char ch1)
{
int k; switch(ch1)
{
case '*':
case '/':
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 13
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

k=2;
break; case '+':
case '-': k=1;
break; case '(':
k=3;
break; case ')':
case '#':
k=0;
break;
}

return(k);
}
int stackpri(char ch2)
{
int m; switch(ch2)
{
case '*':
case '/':
m=2;
break;
case '+':
case '-': m=1;
break; case '(':
case '#':
m=0;
break;
}
return(m);
}

CONCLUSION:

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 14


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 4.
CONVERSION OF REGULAR EXPRESSION TO NFA
Date:

AIM:
To write a C program to convert regular expression to NFA.

ALGORITHM:

1. Get the input transition diagram and store it in a structure.

2. First find the e-closure of initial state.

3. If there is a final state in the above e-closure , add all these state to final state.

4. Then for each state in NFA do step 5 to 9.

5. For each input symbol the steps 6 to 9 are performed.

6. Find the ne-closure of the current state.

7. For each state in the e-closure find the move on current input.

8. Again find the e-closure for each state.

9. These are the states for the move in the new NFA for current state and input.

PROGRAM:

#include<stdio.h> #include<conio.h> #include<stdlib.h> void menu()


{
printf("\nMenu\n -- \n");
printf("1.Closure\n2.Concatenation\n3.Union\n4.Exit\n"); printf("Enter ur Choice:");
}
void main()
{
int i,i1,i2,f,f1,f2,ch,count=1,s,sym; clrscr();
printf("\nEnter the input symbol:"); scanf("%d",&sym);
i=count++; f=count++;
printf("\n states: Previous Current Input "); printf("\nThe Transitions are : %d------> %d
%d\n",i,f,sym); while(1)
{
menu(); scanf("%d",&ch); switch (ch)
{
case 1:
i1=i,f1=f; i=count++;f=count++;
printf("\nThe Added Transitions are:\n"); printf("%d----->%d e\n",i,i1);
printf("%d-----> %d e \n",f1,f);
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 15
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

printf("%d-----> %d e\n",f1,i1);
printf("%d-----> %d e\n",i,f);

break; case 2:
printf("\nEnter the new symbol : "); scanf("%d",&sym);
i1=i;f1=f; i2=count++;f2=count++;
printf("AT \n1.Front\n2.Back\nEnter ur choice :"); scanf("%d",&s);
printf("\nThe Added Transitions are :\n"); printf("%d %d %d\n",i2,sym,f2);
if (s==1)
printf("%d e %d\n",f2,i1);
else
printf("%d e %d\n",f1,i2);
break; case 3:
printf("Enter the new symbol:"); scanf("%d",&sym);
i1=i;f1=f; i2=count++;f2=count++; i=count++;f=count++;
printf("\nThe Added Transition are:\n"); printf("%d %d %d\n",i2,sym,f2); printf("%d e %d\n",i,i1);
printf("%d e %d\n",i,i2);
printf("%d e %d\n",f1,f);
printf("%d e %d\n",f2,f); break;
case 4: exit(0);
}
}
}

CONCLUSION:

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 16


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 5.
IMPLEMENTATION OF SCIENTIFIC CALCULATOR
Date:

AIM:
To write a C program to implement scientific calculator

ALGORITHM:

PROGRAM:

#include <stdio.h>
#include <math.h>
#define PI 3.14159265
float sine(float x);
float cosine(float x);
float tangent(float x);
float sineh(float x);
float cosineh(float x);
float tangenth(float x);
float logten(float x);
float squareroot(float x);
float exponent(float x);
float power(float x,float y);
int main()
{
int x,y,n,answer;
printf("What do you want to do?\n");
printf("1.sin 2.cos 3. tan 4. sinh 5.cosh 6.tanh 7.1og10 8. square root. 9.exponent 10.power.");
scanf ("%d",&n);
if (n<9 && n>0)
{
printf("\n What is x? ");
scanf("%f",&x);
switch (n)
{
case 1: answer = sine(x); break;
case 2: answer = cosine(x); break;
case 3: answer = tangent(x); break;
case 4: answer = sineh(x); break;
case 5: answer = cosineh(x); break;

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 17


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

case 6: answer = tangenth(x); break; case 7: answer = logten(x); break; case 8: answer =
squareroot(x); break; case 9: answer = exponent(x); break;
}
}
if (n==10)
{
printf("What is x and y?\n"); scanf("%f%f",&x,&y); answer = power(x,y);
}
if (n>0 && n<11) printf("%f",answer);
else
printf("Wrong input.\n"); return 0;
}
float sine(float x)
{
return (sin (x*PI/180));
}
float cosine(float x)
{
return (cos (x*PI/180));
}
float tangent(float x)
{
return (tan(x*PI/180));
}
float sineh(float x)
{
return (sinh(x));
}
float cosineh(float x)
{
return (sinh(x));
}
float tangenth(float x)
{
return (sinh(x));
}

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 18


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

float logten(float x)
{
return (log10(x));
}
float squareroot(float x)
{
return (sqrt(x));
}
float exponent(float x)
{
return(exp(x));
}
float power(float x, float y)
{
return (pow(x,y));
}

CONCLUSION:

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 19


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 6.
IMPLEMENTATION OF LL(1)
Date: PARSER

AIM:
To write a C program to implement LL(1) parser

ALGORITHM:

1. Open the input file in read format.

2. Read each line until the end of file.

3. Separate the expression and result.

4. Separate operation and operator from the expression.

5. Print the result.

6. Close the file.

PROGRAM:

#include<stdio.h> #include<conio.h> #include<string.h> void main()


{
char fin[10][20],st[10][20],ft[20][20],fol[20][20];
int a=0,e,i,t,b,c,n,k,l=0,j,s,m,p; clrscr();
printf("enter the no. of coordinates\n"); scanf("%d",&n);
printf("enter the productions in a grammar\n"); for(i=0;i<n;i++)
scanf("%s",st[i]); for(i=0;i<n;i++) fol[i][0]='\0'; for(s=0;s<n;s++)
{
for(i=0;i<n;i++)
{ j=3; l=0; a=0;
l1:if(!((st[i][j]>64)&&(st[i][j]<91)))
{
for(m=0;m<l;m++)
{
if(ft[i][m]==st[i][j]) goto s1;
}
ft[i][l]=st[i][j]; l=l+1; s1:j=j+1;
}
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 20
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

else
{
if(s>0)
{
while(st[i][j]!=st[a][0])
{ a++;
} b=0;
while(ft[a][b]!='\0')
{
for(m=0;m<l;m++)
{
if(ft[i][m]==ft[a][b]) goto s2;
}
ft[i][l]=ft[a][b]; l=l+1; s2:b=b+1;
}
}
}
while(st[i][j]!='\0')
{
if(st[i][j]=='|')
{
j=j+1; goto l1;
}
j=j+1;
}
ft[i][l]='\0';
}
}
printf("first pos\n"); for(i=0;i<n;i++)
printf("FIRS[%c]=%s\n",st[i][0],ft[i]); fol[0][0]='$';
for(i=0;i<n;i++)
{ k=0; j=3;
if(i==0) l=1;
else l=0;
k1:while((st[i][0]!=st[k][j])&&(k<n))
{
if(st[k][j]=='\0')
{ k++; j=2;
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 21
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

} j++;
}
j=j+1;
if(st[i][0]==st[k][j-1])
{
if((st[k][j]!='|')&&(st[k][j]!='\0'))
{ a=0;
if(!((st[k][j]>64)&&(st[k][j]<91)))
{
for(m=0;m<l;m++)
{
if(fol[i][m]==st[k][j]) goto q3;
}
fol[i][l]=st[k][j]; l++;
q3:
}
else
{
while(st[k][j]!=st[a][0])
{ a++;
} p=0;
while(ft[a][p]!='\0')
{
if(ft[a][p]!='@')
{
for(m=0;m<l;m++)
{
if(fol[i][m]==ft[a][p]) goto q2;
}
fol[i][l]=ft[a][p]; l=l+1;
}
else
e=1; q2:p++;
}
if(e==1)
{ e=0;
goto a1;
}
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 22
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

}
}
else
{ a1:c=0; a=0;
while(st[k][0]!=st[a][0])
{ a++;
}
while((fol[a][c]!='\0')&&(st[a][0]!=st[i][0]))
{
for(m=0;m<l;m++)
{
if(fol[i][m]==fol[a][c]) goto q1;
}
fol[i][l]=fol[a][c]; l++;
q1:c++;
}
}
goto k1;
}
fol[i][l]='\0';
}
printf("follow pos\n"); for(i=0;i<n;i++)
printf("FOLLOW[%c]=%s\n",st[i][0],fol[i]); printf("\n");
s=0;
for(i=0;i<n;i++)
{ j=3;
while(st[i][j]!='\0')
{
if((st[i][j-1]=='|')||(j==3))
{
for(p=0;p<=2;p++)
{
fin[s][p]=st[i][p];
}
t=j; for(p=3;((st[i][j]!='|')&&(st[i][j]!='\0'));p++)
{
fin[s][p]=st[i][j]; j++;
}
DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 23
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

fin[s][p]='\0';
if(st[i][k]=='@')
{ b=0; a=0;
while(st[a][0]!=st[i][0])
{ a++;
}
while(fol[a][b]!='\0')
{
printf("M[%c,%c]=%s\n",st[i][0],fol[a][b],fin[s]); b++;
}
}
else if(!((st[i][t]>64)&&(st[i][t]<91)))
printf("M[%c,%c]=%s\n",st[i][0],st[i][t],fin[s]); else
{ b=0; a=0;
while(st[a][0]!=st[i][3])
{ a++;
}
while(ft[a][b]!='\0')
{
printf("M[%c,%c]=%s\n",st[i][0],ft[a][b],fin[s]); b++;
}
} s++;
}
if(st[i][j]=='|') j++;
}
}
getch();
}
OUTPUT:

Enter the no. of co-ordinates 2


Enter the productions in a grammar S->CC
C->eC | d First pos FIRS[S] = ed FIRS[C] = ed

Follow pos FOLLOW[S] =$

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 24


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR. N. Y. TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

FOLLOW[C] =ed$

M [S , e] =S->CC
M [S , d] =S->CC
M [C , e] =C->eC
M [C , d] =C->d

CONCLUSION:

DEPT. PF COMPUTER ENGINEERING, BHIVPURO ROAD Page 25


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Exp. No. 7
DESIGN AND IMPLEMENT PASS I OF TWO
PASS ASSEMBLER
Date:

AIM:
a) Write a program to generate Machine Op-Code Table, Symbol Table and Pseudo Op- Code table during
First Pass Assembler.
b) Write a program to generate Machine Op- code table using Two pass Assembler.

THEORY:

FLOW CHART-PASS-1
A. PROGRAM

import java.io.*;
import java.lang.*;

class ass12
{
int lc=0;
int l[]=new int[50];
int val[]=new int[50];
int lval[]=new int[50];
int x=1,m=0,n=0;
String sym[]=new String[50];
DEPT. OF COMPUTER ENGINEERING
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

String lit[]=new String[50];

void lex(String imp)


{
int i,j,k,nu=0;
k=0;
char ch;
String l1=null;
String l2=null;
String l3=null;
String l4=null;
String as;
String bs;
String pot[]={"start","equ","using","DC","DS","end"};
String mot[]={"mov","add","sub","ST","SR","A","L"};
int mot1[]={4,4,4,4,2,4,4};
int y=0;

if(!imp.equals("end"))
{
for(i=0;i<imp.length();i++)
{
ch=imp.charAt(i);
if(ch!=' ')
{
y++;
}
else
{
break;
}
}
bs=imp.substring(0,y);
as=imp.substring((y+1));
}
else
{
bs=imp;
as=null;
}
for(i=0;i<pot.length;i++)
{
if(bs.equals(pot[i]))
{
l2=bs;
}
}
for(i=0;i<mot.length;i++)
DEPT. OF COMPUTER ENGINEERING
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

{
if(bs.equals(mot[i]))
{
l2=bs;
}

if(l2==null)
{
l1=bs;
for(i=0;i<pot.length;i++)
{
if(as.equals(pot[i]))
{
l2=as;
}
}
for(i=0;i<mot.length;i++)
{
if(as.equals(mot[i]))
{
l2=as;
}
}
}

if(l2==null)
{
for(i=0;i<as.length();i++)
{
ch=as.charAt(i);
if(ch!=' ')
{
nu++;
}
else
{
break;
}
}

bs=as.substring(0,nu);
as=as.substring((nu+1));
l2=bs;
}

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

if(as!=null && l2!=as)


{
for(i=0;i<as.length();i++)
{
ch=as.charAt(i);
if(ch!=' ' && ch!=',')
{
k++;
}
else
{
break;
}
}
bs=as.substring(0,k);
l3=bs;
for(i=0;i<as.length();i++)
{
ch=as.charAt(i);
if(ch==',')
{
as=as.substring((k+1));
l4=as;
}
}
}

for(i=0;i<mot.length;i++)
{
if(l2.equals(mot[i]))
{
lc=lc+mot1[i];
}
}

if(l2.equals("DC") || l2.equals("DS"))
lc=lc+4;

l[(x++)]=lc;
System.out.println(imp+" "+l[(x-2)]);

if(l1!=null)
{
sym[m]=l1;
val[m]=l[x-2];
m++;
}

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

if(l4!=null)
{
if(l4.charAt(0)=='=')
{
lit[n]=l4;
lval[n]=l[(x-2)];
n++;
}
}

if(l2.equals("end"))
{
System.out.println("\n\n*****************Symbol Table**********************");
System.out.println("\n\nSymbol value");
for(i=0;i<m;i++)
System.out.println(sym[i]+" "+val[i]);

System.out.println("\n\n*****************Literal Table**********************");
System.out.println("\n\nLiteral value");

for(i=0;i<n;i++)
System.out.println(lit[i]+" "+lval[i]);

}
}
}

class tables
{
public static void main(String args[]) throws IOException
{
FileInputStream fin=new FileInputStream("D:\\java-assembler\\P2\\prg.txt");
DataInputStream in=new DataInputStream(fin);

String imps=new String();

ass12 d=new ass12();


System.out.println("\n\nInstruction Location Counter\n");

while(in.available()!=0)
{
imps=in.readLine();
d.lex(imps);
}

in.close();
}
}
DEPT. OF COMPUTER ENGINEERING
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

/*
OUTPUT :

C:\Java\jdk1.6.0\bin>java tables

Instruction Location Counter

exp2 start 0
using *,15 0
mov 1,four 0
sub 1,four 4
add 1,FIVE 8
mov 1,=F'7' 12
mov 1,=F'5' 16
FIVE DC F'5' 20
four DC F'4' 24
TEMP DS '1'F 28
end 32

*****************Symbol Table**********************

Symbol value
exp2 0
FIVE 20
four 24
TEMP 28

*****************Literal Table**********************

Literal value
=F'7' 12
=F'5' 16

C:\Java\jdk1.6.0\bin>

*/

B. PROGRAM

import java.io.*;

class Pass2
DEPT. OF COMPUTER ENGINEERING
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

{
public static void main(String args[])throws IOException
{
int i,j,k;

//source prog in terms of tokens


String Label[]={"pg"," "," "," "," "," ","four","five","temp"," "};
String Opcode[]={"start","using","l","a","a","st","dc","dc","ds","end"};
String op1[]={" ","*","2","2","2","2","f'4'","f'5'","'1'f"," "};
String op2[]={" ","15","four","five","=f'7'","temp"," "," "," "," "};

//Mnemonic Opcode table


String mne[]={"l","a","st"};
int mlen[]={4,4,4};
String mformat[]={"rx","rx","rx"};

//psuedo opcode table


String psue[]={"start","using","end","ltorg","dc","ds"};
String radd[]={"100","101","102","103","104","105"};

//Symbol table
String sym[]={"pg","four","five","temp"};
int sval[]={0,20,24,28};
int slen[]={1,4,4,4};
char sreloc[]={'R','R','R','R'};
int nos=sym.length;

//Literal Table
String Lit[]={"=f'7'"};
int lval[]={32};
int llen[]={4};
char lreloc[]={'R'};
int nol=Lit.length;

//Base Table
int reg[]=new int[15];
int avail[]=new int[15];
int value[]=new int[15];
for(i=0;i<15;i++)
{
reg[i]=i+1;
avail[i]=value[i]=0;
}

//print program of tokens


System.out.println("The program splitted in terms of tokens is:");
System.out.println("------------------------------------------------");
System.out.println("Label\tOpcode\tOP1\tOP2");

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

for(i=0;i<10;i++)
System.out.println(Label[i]+"\t"+Opcode[i]+"\t"+op1[i]+"\t"+op2[i]);
System.out.println();

System.out.println();

//print mnemonic opcode table


System.out.println("The mnemonic Opcode Table is:");
System.out.println("------------------------------------------------");
System.out.println("Mne\tBinary\tInstr.\tInstr.");
System.out.println("Opcode\tOpcode\tLength\tFormat");
for(i=0;i<mne.length;i++)
System.out.print(mne[i]+"\t\t"+mlen[i]+"\t"+mformat[i]+"\n");
System.out.println();

//print psuedo opcode table


System.out.println("The Psuedo Opcode table is:");
System.out.println("----------------------------------------------");
System.out.println("Psuedo Opcode\tAddress of Routine");
for(i=0;i<psue.length;i++)
System.out.println(psue[i]+"\t\t"+radd[i]);
System.out.println();

//print Symbol Table


System.out.println("The Symbol table is:");
System.out.println("----------------------------------------------");
System.out.println("Symbol\tValue\tLenght\tR/A");
for(i=0;i<nos;i++)
System.out.println(sym[i]+"\t"+sval[i]+"\t"+slen[i]+"\t"+sreloc[i]);
System.out.println();

//print Literal table


System.out.println("The Literal table is:");
System.out.println("----------------------------------------------");
System.out.println("Literal\tValue\tLenght\tR/A");
for(i=0;i<nol;i++)
System.out.println(Lit[i]+"\t"+lval[i]+"\t"+llen[i]+"\t"+lreloc[i]);
System.out.println();

//print assembled program


System.out.println();
System.out.println("-------------------------------------------");
System.out.println("Assembled program is : ");
System.out.println();

System.out.println("LC \t Instruction");

int lc=0;

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

//Assembling the instructions


for(i=0;i<Label.length;i++)
{
for(j=0;j<psue.length;j++)
if(Opcode[i].equalsIgnoreCase(psue[j]))
break;
if(j<psue.length)
{
switch(j)
{
case 0: //start
lc=0;
System.out.println(lc);
break;
case 1: //using
int r=Integer.parseInt(op2[i]);
avail[r-1]=1;
if(op1[i].equalsIgnoreCase("*"))
value[r-1]=0;
else
value[r-1]=Integer.parseInt(op1[i]);
System.out.println(lc);
break;
case 2: //end
for(k=0;k<nol;k++)
System.out.println(lc+"\t\t"+Lit[k].charAt(3));
break;
case 3: //ltorg
System.out.println(lc);
break;
case 4: //dc
System.out.println(lc+"\t\t"+op1[i].charAt(2));
lc=lc+4;
break;
case 5: //ds
System.out.println(lc);
lc=lc+4;
break;
}
}//end of if
else //opcode present in
{
for(j=0;j<mne.length;j++)
if(Opcode[i].equalsIgnoreCase(mne[j])) break;
if(j<mne.length)
{
int t1=0;

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

for(k=0;k<nos;k++)
if(op2[i].equals(sym[k]))
{
t1=sval[k];
break;
}

for(k=0;k<nol;k++)
if(op2[i].equals(Lit[k]))
{
t1=lval[k];
break;
}
for(k=0;k<16;k++)
if(avail[k]==1) break;

System.out.println(lc+"\t"+Opcode[i]+"\t"+op1[i]+" , "+t1+"
( 0 , "+(k+1)+" )");
lc = lc+mlen[j];
} }//end of else
}
//print the base table
System.out.println("The base table is");
System.out.println("-----------------------------");
System.out.println("Register\tAvailability\tContent");
for(i=0;i<15;i++)
System.out.println(reg[i]+"\t\t"+avail[i]+"\t\t"+value[i]);
System.out.println();
}//end of main
}//end of class

OUTPUT:
Input:
Input.txt

COPY START 1000

- LDA ALPHA

Input.txt

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

- ADD ONE

- SUB TWO

- STA BETA

ALPHA BYTE C'KLNCE

ONE RESB 2

TWO WORD 5

BETA RESW 1

- END -

Optab.txt

LDA 00

STA 23

ADD 01

SUB 05

Output:
Symtab.txt

1012 ALPHA

1017 ONE

1019 TWO

1022 BETA

COPY START 1000

1000 - LDA ALPHA

1003 - ADD ONE

COPY START 1000

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

1006 - SUB TWO

1009 - STA BETA

1012 ALPHA BYTE C'KLNC


E
1017 ONE RESB 2

1019 TWO WORD 5

1022 BETA RESW 1

1025 - END -

Program
length = 25

CONCLUSION:

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 8
STUDY OF LLVM
Date:

AIM: To study of LLVM

Introduction:
The LLVM compiler infrastructure project is a "collection of modular and reusable
compiler and toolchain technologies"[3] used to develop compiler front ends and back ends.

LLVM is written in C++ and is designed for compile-time, link-time, run-time, and "idle- time"
optimization of programs written in arbitrary programming languages. Originally implemented
for C and C++, the language-agnostic design of LLVM has since spawned a wide variety of
front ends: languages with compilers that use LLVM include ActionScript,
Ada, C#, Common Lisp, Crystal, CUDA, D, Delphi, Fortran, Graphical G Programming
Language, Halide, Haskell, Java bytecode, Julia, Kotlin, Lua, Objective-C, OpenGL Shading
Language, Pony, Python, R, Ruby, Rust, Scala, Swift, and Xojo.

Features:
1. LLVM can provide the middle layers of a complete compiler system, taking intermediate
representation (IR) code from a compiler and emitting an optimized IR. This new IR can then be
converted and linked into machine-dependent assembly language code for a target platform.
LLVM can accept the IR from the GNU Compiler Collection (GCC) toolchain, allowing it to be
used with a wide array of extant compilers written for that project.

2. LLVM can also generate relocatable machine code at compile-time or link-time or even
binary machine code at run-time.

3. LLVM supports a language-independent instruction set and type system

4. The LLVM JIT compiler can optimize unneeded static branches out of a program at
runtime, and thus is useful for partial evaluation in cases where a program has many options,
most of which can easily be determined unneeded in a specific environment. This feature
is used in the OpenGL pipeline of Mac OS X Leopard (v10.5) to provide support for missing
hardware features

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Components
Front ends
Intermediate representation Back ends
Linker
C++ Standard Library Debugger

CONCLUSION:

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 9
TWO PASS MACROPROCESSOR
Date:

AIM: To implement two pass macro processor in C language.

Theory: -
The program which is responsible for processing of macro i.e. group of instructions.
Function of macro processor:
1. Recognize macro definition
2. Store the macro definition
3. Recognize the macro call
4. Perform macro expansion
The purpose of pass2 is to recognize the macro call and perform
The macro expansion.
Database required for pass2:
1. The copy of the input macro source deck.
2. The output expanded source deck to be used as input to the assembler.
3. The Macro Definition Table (MDT) created by pass1.
4. The Macro Name Table (MNT) created by pass1.
5. The Macro Definition Table Pointer (MDTP) used to indicate the next line of text to be used
during macro expansion.
6.The Argument List Array (ALA) used to substitute macro call argument for the index markers in
the stored macro definition.

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

ALGORITHM:
1. Get the statement from the input file
2. If the statement has the directive “MACRO”, then the number of macro “n” will be
incremented by 1

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

3. Repeat the steps 1 and 2 until an end of file is encountered


4. Open “n” number of macro files in write mode and rewind the input file pointer
5. If the directive is “MACRO” then, do the following
5.1 Enter the macro name present in the operand fiel
5.2 Write the line to the expanded output fil
5.3 Enter the lines in the body of each macro in to the corresponding files already opened
in step 4 5.4 Write the body of each macro to the expanded output files until a “MEND” is
reached 6. Write the remaining lines directly to the expanded file.
PROGRAM:
/* program to Perform pass2 of macro*/
#include <stdio.h>
char optable[50][20];
char argtab[20][10];
int cnt = 0;
int def_cnt = 0,nam_cnt = 0,arg_cnt = 0;
FILE *exp;
struct definition {
char instruction[20];
char operand[30];
}deftab[30]; struct name {
char MacroName[20];
int beg;
int end;
}namtab[5]; void initialize() {
FILE *optab,*deftable,*namtable;
char mnemonic[20],opcode[20];
optab = fopen("optab.txt","r");
deftable = fopen("deftab.txt","r");
namtable = fopen("namtab.txt","r");
do {
fscanf(optab,"%s %s",mnemonic,opcode);
strcpy(optable[cnt++],mnemonic);
}
while(!feof(optab)); do {
fscanf(deftable,"%s %s",deftab[def_cnt].instruction,deftab[def_cnt].operand);

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

def_cnt++;
}while(!feof(deftable));
do
{
fscanf(namtable,"%s%d%d",namtab[nam_cnt].MacroName,
&namtab[nam_cnt].beg,&namtab[nam_cnt].end);
nam_cnt++; }
while(!feof(namtable));
fclose(deftable);
fclose(optab);
fclose(namtable);
}
int ismacro
(char *str)
{
int i;
for(i=0;i<nam_cnt;i++)
if(!strcmp(namtab[i].MacroName,str))
return 1;
return 0;
}
int iskeyword(char *str)

{ int i;
for(i=0;i<cnt;i++)
if(!strcmp(optable[i],str))
return 1; return 0;
}
void expand(char *name,char *args) {
FILE *argtbl;
int beg,end,i,j,index;
char operand[30],tmp[20];
argtbl = fopen("argtab.txt","a+"); for(i=0;i<nam_cnt;i++)
{
if(!strcmp(namtab[i].MacroName,name))

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

{
beg = namtab[i].beg; end = namtab[i].end; } }arg_cnt = 1; i=0; do {
j=0;
do
{
argtab[arg_cnt][j++] = args[i++];
}while(args[i] != ',' && args[i] != '\0');
argtab[arg_cnt][j] = '\0';
arg_cnt++;
}while(args[i++] != '\0');
fprintf(argtbl,"\n%s :",name);
for(i=0;i<arg_cnt;i++)
{
fprintf(argtbl,"%s",argtab[i]);
}for(i=beg+1;i<=end;i++)
{ fprintf(exp,"\t%s\t",deftab[i].instruction);
strcpy(operand,deftab[i].operand);
for(j=0;j<strlen(operand);j++)
{
if(operand[j] == '?') {
operand[j] = '%';
index = operand[j+1]-48;
operand[j+1] = 's';
sprintf(tmp,operand,argtab[index]);
strcpy(operand,tmp);
}
}
fprintf(exp,"%s\n",operand);
}
fclose(argtbl);
getch();
}
void main()
{
FILE *source,*argtbl;

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

char str[30],str1[30],str2[30];
int i;
source = fopen("prog.txt","r");
argtbl = fopen("argtab.txt","w+");
exp = fopen("exppgm.txt","w+");
fclose(argtbl);
initialize(); do { fscanf(source,"%s %s",str,str1); beg:
if(feof(source)){}
else if(!strcmp(str1,"MACRO"))
{
strcpy(optable[cnt++],str); fscanf(source,"%s",str2); do { fscanf(source,"%s %s",str,str1);
}while(strcmp(str,"MEND")); strcpy(str,str1);
fscanf(source,"%s",str1);
goto beg;
}else if(iskeyword(str)) { if(ismacro(str)) {
fprintf(exp,".\t%s\t%s\n",str,str1);
expand(str,str1);
}else fprintf(exp,"\t%s\t%s\n",str,str1); }else {
fscanf(source,"%s",str2);
if(ismacro(str1))
{
fprintf(exp,".%s\t%s\t%s\n",str,str1,str2);
fprintf(exp,"%s",str);
expand(str1,str2);
}else fprintf(exp,"%s\t%s\t%s\n",str,str1,str2); }
}while(!feof(source));
fclose(source);
}

CONCLUSION:
Thus two pass macro processor is implemented in C language.

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 10
SINGLE PASS MACRO PROCESSOR
Date:

AIM: To implement a single pass macro processor in C language.


Theory:- The program which is responsible for processing of macro i.e. group of instructions.
Function of macro processor:
1. Recognize macro definition
2. Store the macro definition
3. Recognize the macro call
4. Perform macro expansion
The purpose of pass 1 is to recognize macro definition and store the macro definition.
Database required for pass1:
1. The copy of the input macro source deck.
2. The output expanded source deck copy for use by pass2.
3. The Macro Definition Table (MDT) used to store the body of macro definitions.
4. The Macro Name Table (MNT) used to store the names of defined macros.
5. The Macro Definition Table Counter (MDTC) used to indicate the next available entry in MDT.
6. The Macro Name Table Counter (MNTC) used to indicate the next available entry in MNT.
7. The Argument List Array (ALA) used to substitute index markers for arguments before storing
a macro definition.
ALGORITHM:
1. Get the statement from the input file
2. If the statement has the directive “MACRO”, then the number of macro “n” will be incremented
by 1
3. Repeat the steps 1 and 2 until an end of file is encountered
4. Open “n” number of macro files in write mode and rewind the input file pointer
5. If the directive is “MACRO” then, do the following
5.1 Enter the macro name present in the operand field
5.2 Write the line to the expanded output file
5.3 Enter the lines in the body of each macro in to the corresponding files already opened in
step 4 5.4 Write the body of each macro to the expanded output files until a “MEND” is reached 6.

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Write the remaining lines directly to the expanded file.


6. EXIT.

CONCLUSION:
Thus a single pass macro processor is implemented in C language.
PROGRAM:
/* C Program to implement SINGLE PASS MACRO PROCESSOR */

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{int n,flag,i;
char ilab[20],iopd[20],oper[20],NAMTAB[20][20];
FILE *fp1,*fp2,*DEFTAB;
clrscr();
fp1=fopen("macroin.dat","r");
fp2=fopen("macroout.dat","w");
n=0;
rewind(fp1);
fscanf(fp1,"%s%s%s",ilab,iopd,oper);
while(!feof(fp1))
{if(strcmp(iopd,"MACRO")==0)
{
strcpy(NAMTAB[n],ilab);
DEFTAB=fopen(NAMTAB[n],"w");
fscanf(fp1,"%s%s%s",ilab,iopd,oper);
while(strcmp(iopd,"MEND")!=0)

{
fprintf(DEFTAB,"%s\t%s\t%s\n",ilab,iopd,oper);
fscanf(fp1,"%s%s%s",ilab,iopd,oper);
}fclose(DEFTAB); n++; }else {
flag=0;
for(i=0;i<n;i++)
{
if(strcmp(iopd,NAMTAB[i])==0) {
flag=1;
DEFTAB=fopen(NAMTAB[i],"r");
fscanf(DEFTAB,"%s%s%s\n",ilab,iopd,oper);
while(!feof(DEFTAB))
{

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

fprintf(fp2,"%s\t%s\t%s\n",ilab,iopd,oper); fscanf(DEFTAB,"%s%s%s",ilab,iopd,oper);
}break; } }
if(flag==0)
fprintf(fp2,"%s\t%s\t%s\n",ilab,iopd,oper); }fscanf(fp1,"%s%s%s",ilab,iopd,oper);
}
fprintf(fp2,"%s\t%s\t%s\n",ilab,iopd,oper);
getch();
}
MACROIN.DAT M1
MACRO ** **
LDA N1 **
ADD N2 **
STA N3 **
MEND ** M2
MACRO ** **
LDA N1 **
SUB N2 **
STA N4 **
MEND ** M3
MACRO ** **
LDA N1 **
MUL N2 **
STA N5 **
MEND ** **
START 1000 **
M3 ** **
M2 ** **
M1 ** **
END **

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 11
ABSOLUTE LOADER
Date:

AIM: To implement an Absolute loader in C language.


Theory:-
The assembler punches the machine language translation of the source program on cards. The loader in
turn accepts the machine language text and places it into core at the site prescribed by assembler.
Absolute loader requires two types of card:
1. Text Cards:- They contain the machine instructions that the assembler has created along with the
assigned core location.

Card Type Count Address Contents


0

2. Transfer Card:- It contains the entry point of the program, which where the loader is to transfer
control when all instruction are loaded.

Card Type Count Address Contents

1 0 -

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

INITIALIZE

READ CARD

Set CURLOC to

Address Field

Type=0 Type=1
Card
Type

Transfer to location
Set LNG to COUNT
CURLOC
field

Move LNG bytes of


contents to CURLOC

ALGORITHM:
1. Read the Header record
2. Verify program name and length
3. Read first Text record from the input file
DEPT. OF COMPUTER ENGINEERING
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

4. Process the following steps until an End record is reached


5.1 If object code is in character form, convert it to internal hexadecimal representation.
5.2 Move objects codes to specified locations in memory.
5.3 Write the starting location counter value of a block of object code and the
Corresponding internal representation to the output file
5.4 Read next Text record from the input file
5. Go to the address specified in End record
6. Close all the files and exit.

CONCLUSION:
Thus an Absolute loader is implemented in C language

PROGRAM:
/* C Program to implement ABSOLUTE LOADER */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char input[10];
int start,length,address;
FILE *fp1,*fp2;
clrscr();
fp1=fopen("input.dat","r");
fp2=fopen("output.dat","w");
fscanf(fp1,"%s",input);
while(strcmp(input,"E")!=0)
{
if(strcmp(input,"H")==0) {
fscanf(fp1,"%d",&start);
fscanf(fp1,"%d",&length);
fscanf(fp1,"%s",input);
}else if(strcmp(input,"T")==0) {
fscanf(fp1,"%d",&address);

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

fscanf(fp1,"%s",input);
fprintf(fp2,"%d\t%c%c\n",address,input[0],input[1]);
fprintf(fp2,"%d\t%c%c\n",(address+1),input[2],input[3]);
fprintf(fp2,"%d\t%c%c\n",(address+2),input[4],input[5]);
address+=3;
fscanf(fp1,"%s",input);
}else {
fprintf(fp2,"%d\t%c%c\n",address,input[0],input[1]);
fprintf(fp2,"%d\t%c%c\n",(address+1),input[2],input[3]);
fprintf(fp2,"%d\t%c%c\n",(address+2),input[4],input[5]);
address+=3;
fscanf(fp1,"%s",input);
} }fclose(fp1); fclose(fp2);
printf("FINISHED");
getch();
}
INPUT.DAT: H 1000 232
T 1000 142033 483039 102036
T 2000 298300 230000 282030 302015

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

Ex. No. 12
A Lexical Analyzer Generator.
Date:

AIM: Study of Lex- A Lexical Analyzer Generator.

THEORY:
Lex is a program generator designed for lexical processing of character input streams. It accepts
a high level, problem-oriented specification for character string matching and produces a program in a
general-purpose language which recognizes regular expressions. The user in the source specifications
given to lex specifies the regular expressions. The Lex written code recognizes these expressions in an
input stream and partitions the input stream into strings matching the expressions. At the boundaries
between strings program sections provided by the user are executed. The Lex source file associates the
regular expressions and the program fragments. As each expression appears in the input to the program
written by lex , the corresponding fragment is executed.

Lex turns the user’s expressions and actions (called source in this memo) into the host general purpose
language; the generated program is named yylex. The yylex program will recognize expressions in a
stream ( called input in this memo) and perform the specified actions for each expression as it is detected.

+--------------+

Source -> | Lex | ->yylex

+-------------+

+------------+

Input -> | yylex | -> Output

+ ----------- + An

Working of LEX :
Summary of Source Format.

The general form of a Lex source file is:


{ definitions}
%%
{ rules}

DEPT. OF COMPUTER ENGINEERING


SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

%%
{ user subroutines}

The definitions section contains a combination of


1) Definitions, in the form “ name space translation “
2) Included code, in the form “ space code”
3) Include code , in the form

%{
code

%}
4) Start conditions, given in the form
%S name1 name2………..
5) Character set tables , in the form
%T
number space character-string
……
%T
6) Changes to internal array sizes, in the form
%x num
Where num is a decimal integer representing an array size and x selects the parameter as follows.
Letter Parameter P Positions n States
e tree nodes
a transitions
k packed character classes ooutput array size

Lines in the rules section have the form “ expression action “ where the action may be continued on
succeeding lines by using braces to delimit it.

Regular expression in Lex use the following operators. x the character “x”
“x” an “x” , even if x is an operator
\x an “x”, even if x is an operator. [xy] the character x or y
[x-z] the characters x, y or z
[ ^x] any character but x.
. any character but newline
^x an x at the beginning of a line.
<y>x an x when lex is in start condition y. x$ an x at the end of a line.
x? an optional x.
x* 0,1,2,……..instances of x. x+ 1,2,3,…….. instances of x.
x| y an x or a y.
(x) an x
x/ y an x but only if followed by y
DEPT. OF COMPUTER ENGINEERING
SARASWATI EDUCATION SOCIETY’S

YADAVRAO TASGAONKAR INSTITUTE OF ENGINEERING &TECHNOLOGY


DR.N.Y.TASGAONKAR EDUCATIONAL COMPUS, CHANDHAI, POST:-NASAPURE, TAL:-KARJAT, DIST:-RAIGAD

{ xx } the translation of xx from the definitions section. x{ m ,n } m through n occurrences of x.

CONCLUSION:

Hence, we have successfully studied the LEX Compiler.

DEPT. OF COMPUTER ENGINEERING

You might also like