You are on page 1of 39

1

A. Assemblers and Macro

1. Write a C program to implement pass – I of a two pass assembler.


#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

FILE *f1,*f2,*f3,*f4;

int lc,sa,l,op1,o,len;

char m1[20],la[20],op[20],otp[20];

clrscr();

f1=fopen("input.txt","r");

f3=fopen("symtab.txt","w");

fscanf(f1,"%s %s %d",la,m1,&op1);

if(strcmp(m1,"START")==0)

sa=op1;

lc=sa;

printf("\t%s\t%s\t%d\n",la,m1,op1);

else

lc=0;
2

fscanf(f1,"%s %s",la,m1);

while(!feof(f1))

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

printf("\n%d\t%s\t%s\t%s\n",lc,la,m1,op);

if(strcmp(la,"-")!=0)

fprintf(f3,"\n%d\t%s\n",lc,la);

f2=fopen("optab.txt","r");

fscanf(f2,"%s %d",otp,&o);

while(!feof(f2))

if(strcmp(m1,otp)==0)

lc=lc+3;

break;

fscanf(f2,"%s %d",otp,&o);

fclose(f2);

if(strcmp(m1,"WORD")==0)

{
3

lc=lc+3;

else if(strcmp(m1,"RESW")==0)

op1=atoi(op);

lc=lc+(3*op1);

else if(strcmp(m1,"BYTE")==0)

if(op[0]=='X')

lc=lc+1;

else

len=strlen(op)-2;

lc=lc+len;}

else if(strcmp(m1,"RESB")==0)

op1=atoi(op);

lc=lc+op1;

fscanf(f1,"%s%s",la,m1);

if(strcmp(m1,"END")==0)
4

printf("Program length =\n%d",lc-sa);

fclose(f1);

fclose(f3);

getch();

Input:
Input.txt

COPY START 1000

- LDA ALPHA

- 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
5

Optab.txt

ADD 01

SUB 05

Output:
Symtab.txt

1012 ALPHA

1017 ONE

1019 TWO

1022 BETA

COPY START 1000

1000 - LDA ALPHA

1003 - ADD ONE

1006 - SUB TWO

1009 - STA BETA

1012 ALPHA BYTE C'KLNCE

1017 ONE RESB 2

1019 TWO WORD 5

1022 BETA RESW 1

1025 - END -

Program length = 25
6

2. Write a C program to implement pass – II of a two pass assembler

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<ctype.h>

main()

FILE *fint,*ftab,*flen,*fsym;

int op1[10],txtlen,txtlen1,i,j=0,len;

char
add[5],symadd[5],op[5],start[10],temp[30],line[20],label[20],mne[10],operand[10],symtab[10],opmne[1
0];

clrscr();

fint=fopen("input.txt","r");

flen=fopen("length.txt","r");

ftab=fopen("optab.txt","r");

fsym=fopen("symbol.txt","r");

fscanf(fint,"%s%s%s%s",add,label,mne,operand);

if(strcmp(mne,"START")==0)

strcpy(start,operand);

fscanf(flen,"%d",&len);

printf("H^%s^%s^%d\nT^00%s^",label,start,len,start);
7

fscanf(fint,"%s%s%s%s",add,label,mne,operand);

while(strcmp(mne,"END")!=0)

fscanf(ftab,"%s%s",opmne,op);

while(!feof(ftab))

if(strcmp(mne,opmne)==0)

fclose(ftab);

fscanf(fsym,"%s%s",symadd,symtab);

while(!feof(fsym))

if(strcmp(operand,symtab)==0)

printf("%s%s^",op,symadd);

break;

else

fscanf(fsym,"%s%s",symadd,symtab);

break;

else

fscanf(ftab,"%s%s",opmne,op);
8

if((strcmp(mne,"BYTE")==0)||(strcmp(mne,"WORD")==0))

if(strcmp(mne,"WORD")==0)

printf("0000%s^",operand);

else

len=strlen(operand);

for(i=2;i<len;i++)

printf("%d",operand[i]);

printf("^");

fscanf(fint,"%s%s%s%s",add,label,mne,operand);

ftab=fopen("optab.txt","r");

fseek(ftab,SEEK_SET,0);

printf("\nE^00%s",start);

fclose(fint);

fclose(ftab);

fclose(fsym);

fclose(flen);
9

fclose(fout);

getch();

Input:

input.txt:

- COPY START 1000

1000 - LDA ALPHA

1003 - ADD ONE

1006 - SUB TWO

1009 - STA BETA

1012 ALPHA BYTE C'KLNCE

1017 ONE RESB 2

1019 TWO WORD 5

1022 BETA RESW 1

1025 - END -

optab.txt:

LDA 00

STA 23

ADD 01

SUB 05
10

Output:

length.txt:25

symbol.txt:

1012 ALPHA

1017 ONE

1019 TWO

1022 BETA
11

3. Write a C program to implement one pass macro processor.

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<stdlib.h>

void main()

FILE *f1,*f2,*f3,*f4,*f5;

int len,i,pos=1;

char arg[20],mne[20],opnd[20],la[20],name[20],mne1[20],opnd1[20],pos1[10],pos2[10];

clrscr();

f1=fopen("input.txt","r");

f2=fopen("namtab.txt","w+");

f3=fopen("deftab.txt","w+");

f4=fopen("argtab.txt","w+");

f5=fopen("op.txt","w+");

fscanf(f1,"%s%s%s",la,mne,opnd);

while(strcmp(mne,"END")!=0)

if(strcmp(mne,"MACRO")==0)

{
12

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

fseek(f2,SEEK_SET,0);

fprintf(f3,"%s\t%s\n",la,opnd);

fscanf(f1,"%s%s%s",la,mne,opnd);

while(strcmp(mne,"MEND")!=0)

if(opnd[0]=='&')

itoa(pos,pos1,5);

strcpy(pos2,"?");

strcpy(opnd,strcat(pos2,pos1));

pos=pos+1;

fprintf(f3,"%s\t%s\n",mne,opnd);

fscanf(f1,"%s%s%s",la,mne,opnd);

fprintf(f3,"%s",mne);

else

fscanf(f2,"%s",name);

if(strcmp(mne,name)==0)
13

len=strlen(opnd);

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

if(opnd[i]!=',')

fprintf(f4,"%c",opnd[i]);

else

fprintf(f4,"\n");

fseek(f3,SEEK_SET,0);

fseek(f4,SEEK_SET,0);

fscanf(f3,"%s%s",mne1,opnd1);

fprintf(f5,".\t%s\t%s\n",mne1,opnd);

fscanf(f3,"%s%s",mne1,opnd1);

while(strcmp(mne1,"MEND")!=0)

if((opnd[0]=='?'))

fscanf(f4,"%s",arg);

fprintf(f5,"-\t%s\t%s\n",mne1,arg);

else
14

fprintf(f5,"-\t%s\t%s\n",mne1,opnd1);

fscanf(f3,"%s%s",mne1,opnd1);

else

fprintf(f5,"%s\t%s\t%s\n",la,mne,opnd);

fscanf(f1,"%s%s%s",la,mne,opnd);

fprintf(f5,"%s\t%s\t%s",la,mne,opnd);

fclose(f1);

fclose(f2);

fclose(f3);

fclose(f4);

fclose(f5);

printf("files to be viewed \n");

printf("1. argtab.txt\n");

printf("2. namtab.txt\n");

printf("3. deftab.txt\n");

printf("4. op.txt\n");

getch();

}
15

Input.txt

EX1 MACRO &A,&B


- LDA &A
- STA &B
- MEND -
SAMPLE START 1000
- EX1 N1,N2
N1 RESW 1
N2 RESW 1
- END -

Argtab.txt

N1
N2

Op.txt

SAMPLE START 1000


. EX1 N1,N2
- LDA ?1
- STA ?2
N1 RESW 1
N2 RESW 1
- END -

Deftab.txt

EX1 &A,&B
LDA ?1
STA ?2
MEND

Namtab.txt

EX1
16

B. Compilers

1. Write a C program to identify tokens for an input string.

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

// Returns 'true' if the character is a DELIMITER.


bool isDelimiter(char ch)
{
if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == ',' || ch == ';' || ch == '>' ||
ch == '<' || ch == '=' || ch == '(' || ch == ')' ||
ch == '[' || ch == ']' || ch == '{' || ch == '}')
return (true);
return (false);
}

// Returns 'true' if the character is an OPERATOR.


bool isOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == '>' || ch == '<' ||
ch == '=')
return (true);
return (false);
}

// Returns 'true' if the string is a VALID IDENTIFIER.


bool validIdentifier(char* str)
{
if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||
str[0] == '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' ||
str[0] == '9' || isDelimiter(str[0]) == true)
return (false);
return (true);
}

// Returns 'true' if the string is a KEYWORD.


bool isKeyword(char* str)
{
17

if (!strcmp(str, "if") || !strcmp(str, "else") ||


!strcmp(str, "while") || !strcmp(str, "do") ||
!strcmp(str, "break") ||
!strcmp(str, "continue") || !strcmp(str, "int")
|| !strcmp(str, "double") || !strcmp(str, "float")
|| !strcmp(str, "return") || !strcmp(str, "char")
|| !strcmp(str, "case") || !strcmp(str, "char")
|| !strcmp(str, "sizeof") || !strcmp(str, "long")
|| !strcmp(str, "short") || !strcmp(str, "typedef")
|| !strcmp(str, "switch") || !strcmp(str, "unsigned")
|| !strcmp(str, "void") || !strcmp(str, "static")
|| !strcmp(str, "struct") || !strcmp(str, "goto"))
return (true);
return (false);
}

// Returns 'true' if the string is an INTEGER.


bool isInteger(char* str)
{
int i, len = strlen(str);

if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' || (str[i] == '-' && i > 0))
return (false);
}
return (true);
}

// Returns 'true' if the string is a REAL NUMBER.


bool isRealNumber(char* str)
{
int i, len = strlen(str);
bool hasDecimal = false;

if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' && str[i] != '.' ||
(str[i] == '-' && i > 0))
return (false);
18

if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}

// Extracts the SUBSTRING.


char* subString(char* str, int left, int right)
{
int i;
char* subStr = (char*)malloc(
sizeof(char) * (right - left + 2));

for (i = left; i <= right; i++)


subStr[i - left] = str[i];
subStr[right - left + 1] = '\0';
return (subStr);
}

// Parsing the input STRING.


void parse(char* str)
{
int left = 0, right = 0;
int len = strlen(str);

while (right <= len && left <= right) {


if (isDelimiter(str[right]) == false)
right++;

if (isDelimiter(str[right]) == true && left == right) {


if (isOperator(str[right]) == true)
printf("'%c' IS AN OPERATOR\n", str[right]);

right++;
left = right;
} else if (isDelimiter(str[right]) == true && left != right
|| (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);

if (isKeyword(subStr) == true)
printf("'%s' IS A KEYWORD\n", subStr);

else if (isInteger(subStr) == true)


printf("'%s' IS AN INTEGER\n", subStr);

else if (isRealNumber(subStr) == true)


printf("'%s' IS A REAL NUMBER\n", subStr);
19

else if (validIdentifier(subStr) == true


&& isDelimiter(str[right - 1]) == false)
printf("'%s' IS A VALID IDENTIFIER\n", subStr);

else if (validIdentifier(subStr) == false


&& isDelimiter(str[right - 1]) == false)
printf("'%s' IS NOT A VALID IDENTIFIER\n", subStr);
left = right;
}
}
return;
}

// DRIVER FUNCTION
int main()
{
// maximum legth of string is 100 here
char str[100] = "int a = b + 1c; ";

parse(str); // calling the parse function

return (0);
}

Output:
'int' IS A KEYWORD
'a' IS A VALID IDENTIFIER
'=' IS AN OPERATOR
'b' IS A VALID IDENTIFIER
'+' IS AN OPERATOR
'1c' IS NOT A VALID IDENTIFIER
20

2. Write a C program to remove left factoring from a grammar

#include<stdio.h>

#include<string.h>

int main()

char gram[20],part1[20],part2[20],modifiedGram[20],newGram[20],tempGram[20];

int i,j=0,k=0,l=0,pos;

printf("Enter Production : A->");

gets(gram);

for(i=0;gram[i]!='|';i++,j++)

part1[j]=gram[i];

part1[j]='\0';

for(j=++i,i=0;gram[j]!='\0';j++,i++)

part2[i]=gram[j];

part2[i]='\0';

for(i=0;i<strlen(part1)||i<strlen(part2);i++)

if(part1[i]==part2[i])

modifiedGram[k]=part1[i];

k++;

pos=i+1;

for(i=pos,j=0;part1[i]!='\0';i++,j++){
21

newGram[j]=part1[i];

newGram[j++]='|';

for(i=pos;part2[i]!='\0';i++,j++){

newGram[j]=part2[i];

modifiedGram[k]='X';

modifiedGram[++k]='\0';

newGram[j]='\0';

printf("\n A->%s",modifiedGram);

printf("\n X->%s\n",newGram);

Output:
22

3. Write a C Program to remove left recursion from a grammar.

#include<stdio.h>

#include<string.h>

#define SIZE 10

int main () {

char non_terminal;

char beta,alpha;

int num;

char production[10][SIZE];

int index=3; /* starting of the string following "->" */

printf("Enter Number of Production : ");

scanf("%d",&num);

printf("Enter the grammar as E->E-A :\n");

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

scanf("%s",production[i]);

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

printf("\nGRAMMAR : : : %s",production[i]);

non_terminal=production[i][0];

if(non_terminal==production[i][index]) {

alpha=production[i][index+1];

printf(" is left recursive.\n");

while(production[i][index]!=0 && production[i][index]!='|')

index++;
23

if(production[i][index]!=0) {

beta=production[i][index+1];

printf("Grammar without left recursion:\n");

printf("%c->%c%c\'",non_terminal,beta,non_terminal);

printf("\n%c\'->%c%c\'|E\n",non_terminal,alpha,non_terminal);

else

printf(" can't be reduced\n");

else

printf(" is not left recursive.\n");

index=3;

Output:
24

4. Write a C Program to implement recursive descent parser for following


grammar.
E→ T E’ E’→+ T E’ E’ →ε T→F T’

T’→* F T’ T’→ ε F→( E ) F→ id

#include<stdio.h>
#include<conio.h>
int n,i=0;
char s[20];
void E(void);
void E1(void);
void T(void);
void T1(void);
void F(void);
void error(void);
int main()
{
//clrscr();
printf("The given grammar is\n");
printf("E -> TE1\n");
printf("E1 -> +TE1/#\n");
printf("T -> FT1\n");
printf("T1 -> *FT1/#\nF -> (E)/d\n");
printf("Enter the string you want to parse:\n");
scanf("%s",&s);
E();
if(s[i]==NULL)
printf("string is valid\n");
else
printf("string is invalid\n");
getch();
}
void E()
{
T();
E1();
}
void E1()
{
if(s[i]=='+')
{
i++;
T();
E1();
25

}
else if(s[i]=='#')
i++;
else
error();
}
void T()
{
F();
T1();
}
void T1()
{
if(s[i]=='*')
{
i++;
F();
T1();
}
else if(s[i]=='#')
i++;
else
error();
}
void F()
{
if(s[i]=='(')
{
i++;
E();
if(s[i]==')')
i++;
else
error();
}
else if(s[i]=='d')
i++;
else
error();
}
void error()
{
printf("string is invalid\n");
getch();
//exit(0);
}
26

5. Write a C program to for LL(1) parsing for the grammar of 4.

//To Implement Predictive Parsing

#include<string.h>

#include<conio.h>

char a[10];

int top=-1,i;

void error(){

printf("Syntax Error");

void push(char k[]) //Pushes The Set Of Characters on to the Stack

for(i=0;k[i]!='\0';i++)

if(top<9)

a[++top]=k[i];

char TOS() //Returns TOP of the Stack

return a[top];

void pop() //Pops 1 element from the Stack

if(top>=0)

a[top--]='\0';
27

void display() //Displays Elements Of Stack

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

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

void display1(char p[],int m) //Displays The Present Input String

int l;

printf("\t");

for(l=m;p[l]!='\0';l++)

printf("%c",p[l]);

char* stack(){

return a;

int main()

char ip[20],r[20],st,an;

int ir,ic,j=0,k;

char t[5][6][10]={"$","$","TH","$","TH","$",

"+TH","$","e","e","$","e",

"$","$","FU","$","FU","$",

"e","*FU","e","e","$","e",

"$","$","(E)","$","i","$"};
28

clrscr();

printf("\nEnter any String(Append with $)");

gets(ip);

printf("Stack\tInput\tOutput\n\n");

push("$E");

display();

printf("\t%s\n",ip);

for(j=0;ip[j]!='\0';)

if(TOS()==an)

pop();

display();

display1(ip,j+1);

printf("\tPOP\n");

j++;

an=ip[j];

st=TOS();

if(st=='E')ir=0;

else if(st=='H')ir=1;

else if(st=='T')ir=2;

else if(st=='U')ir=3;

else if(st=='F')ir=4;

else {
29

error();

break;

if(an=='+')ic=0;

else if(an=='*')ic=1;

else if(an=='(')ic=2;

else if(an==')')ic=3;

else if((an>='a'&&an<='z')||(an>='A'&&an<='Z')){ic=4;an='i';}

else if(an=='$')ic=5;

strcpy(r,strrev(t[ir][ic]));

strrev(t[ir][ic]);

pop();

push(r);

if(TOS()=='e')

pop();

display();

display1(ip,j);

printf("\t%c->%c\n",st,238);

else{

display();

display1(ip,j);

printf("\t%c->%s\n",st,t[ir][ic]);

}
30

if(TOS()=='$'&&an=='$')

break;

if(TOS()=='$'){

error();

break;

k=strcmp(stack(),"$");

if(k==0 && i==strlen(ip))

printf("\n Given String is accepted");

else

printf("\n Given String is not accepted");

return 0;

}
31

6. Write a C program to generate intermediate code form an input expression


#include<stdio.h>

#include<conio.h>

#include<string.h>

int i=1,j=0,no=0,tmpch=90;

char str[100],left[15],right[15];

void findopr();

void explore();

void fleft(int);

void fright(int);

struct exp

int pos;

char op;

}k[15];

void main()

clrscr();

printf("\t\tINTERMEDIATE CODE GENERATION\n\n");

printf("Enter the Expression :");

scanf("%s",str);

printf("The intermediate code:\t\tExpression\n");

findopr();

explore();

getch();
32

void findopr()

for(i=0;str[i]!='\0';i++)

if(str[i]==':')

k[j].pos=i;

k[j++].op=':';

for(i=0;str[i]!='\0';i++)

if(str[i]=='/')

k[j].pos=i;

k[j++].op='/';

for(i=0;str[i]!='\0';i++)

if(str[i]=='*')

k[j].pos=i;

k[j++].op='*';

for(i=0;str[i]!='\0';i++)

if(str[i]=='+')

k[j].pos=i;
33

k[j++].op='+';

for(i=0;str[i]!='\0';i++)

if(str[i]=='-')

k[j].pos=i;

k[j++].op='-';

void explore()

i=1;

while(k[i].op!='\0')

fleft(k[i].pos);

fright(k[i].pos);

str[k[i].pos]=tmpch--;

printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right);

for(j=0;j<strlen(str);j++)

if(str[j]!='$')

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

printf("\n");

i++;

fright(-1);
34

if(no==0)

fleft(strlen(str));

printf("\t%s := %s",right,left);

getch();

exit(0);

printf("\t%s := %c",right,str[k[--i].pos]);

getch();

void fleft(int x)

int w=0,flag=0;

x--;

while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!='-


'&&str[x]!='/'&&str[x]!=':')

if(str[x]!='$'&& flag==0)

left[w++]=str[x];

left[w]='\0';

str[x]='$';

flag=1;

x--;

}
35

void fright(int x)

int w=0,flag=0;

x++;

while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!='-


'&&str[x]!='/')

if(str[x]!='$'&& flag==0)

right[w++]=str[x];

right[w]='\0';

str[x]='$';

flag=1;

x++;

}
36

7. Write a Lex program to implement lexical analyzer for tokens.

Input.l
%option noyywrap

%{
#include <stdio.h>
int keyword=0,ids=0,posint=0,posfloat=0,negint=0,negfloat=0,opertor=0,space=0,linebk=0;
%}

%%
if|else|switch|for|while {keyword++; return(4);}
[A-Za-z_][A-Za-z0-9_]+? {ids++; return(5);}
\+|\-|\*|\/|\^|\>|\>=|\<|\<=|\=|\==|\!= {opertor++;return(3);}

\+?[0-9]+ {posint++;return(6);}
\+?[0-9]+"."[0-9]+ {posfloat++;return(6);}
-[0-9]+ {negint++;return(6);}
-[0-9]+"."[0-9]+ {negfloat++;return(6);}
[] {space++; return(1);}
[\n] {linebk++; return(2);}
. {return(0);}
%%

int main(int argc, char **argv)


{
FILE *fp;
int val;
if((fp = fopen(argv[1],"r"))==NULL)
yyin=stdin;
else
yyin = fp;

while(val=yylex())
{
if(val>3)
printf("\nLexeme=%s \t Length= %d",yytext,yyleng);
}

printf("\nKeywords:- %d",keyword);
printf("\nIDs:- %d",ids);
37

printf("\n+ve int:- %d",posint);


printf("\n+ve float:- %d",posfloat);
printf("\n-ve int:- %d",negint);
printf("\n-ve float:- %d",negfloat);
printf("\nOperators:- %d",opertor);
printf("\nSpaces:- %d",space);
printf("\nLine breaks:- %d\n",linebk);
}

Inputdata.txt

This is as Lex program of Scanner

23.56 is a Float number

if is a keyword

10 is positive

-20 is negative
38

8. Write a Yacc program to implement syntax analyzer for arithmetic expressions.

Input.l
%option noyywrap
%{
#include"y.tab.h"
extern yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext); return NUMBER;}
[a-zA-Z]+ {return ID;}
[\t]+ ;
\n {return 0;}
. {return yytext[0];}
%%

input.y
%{
#include<stdio.h>
%}
%token NUMBER ID
%left '+' '-'
%left '*' '/'
%%
expr: expr '+' expr
|expr '-' expr
|expr '*' expr
|expr '/' expr
|'-'NUMBER
|'-'ID
|'('expr')'
|NUMBER
|ID
;
%%
main()
{
printf("Enter the expression\n");
yyparse();
printf("\nExpression is valid\n");
39

exit(0);
}
int yyerror(char *s)
{
printf("\nExpression is invalid");
exit(0);
}

You might also like