0% found this document useful (0 votes)
550 views

Experiment - 1: Aim-Develop Lexical Analyzer To Recognize Few Patterns

The document describes three experiments related to lexical analysis and code generation: 1. The first experiment develops a lexical analyzer to recognize patterns in a C program. It initializes a symbol table, reads tokens from input, and checks for keywords, identifiers, constants, and operators. 2. The second experiment writes a program to generate intermediate code in Polish notation from an infix expression. It uses a stack to convert the infix to postfix notation and then reverses the postfix notation to get the Polish notation. 3. The third experiment extends the previous one to generate three-address code by popping operators from the postfix notation and generating temporary variables for the results.

Uploaded by

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

Experiment - 1: Aim-Develop Lexical Analyzer To Recognize Few Patterns

The document describes three experiments related to lexical analysis and code generation: 1. The first experiment develops a lexical analyzer to recognize patterns in a C program. It initializes a symbol table, reads tokens from input, and checks for keywords, identifiers, constants, and operators. 2. The second experiment writes a program to generate intermediate code in Polish notation from an infix expression. It uses a stack to convert the infix to postfix notation and then reverses the postfix notation to get the Polish notation. 3. The third experiment extends the previous one to generate three-address code by popping operators from the postfix notation and generating temporary variables for the results.

Uploaded by

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

EXPERIMENT ---1

/**********************************************************************
Aim- Develop Lexical Analyzer to recognize few Patterns
**********************************************************************/
Algorithm: -
1.start.
2.Intialize the symbol table with keywords.
3.Read token by token from the input string.
4.Using finite automation check for keywords, identifiers, constants &
thenOperators successively.
5.If nothing matches print an error message.
6.Until all tokens are over, repeat above three steps.
7.Print token information.
8.Stop.

Aim:- C-program to implement Lexical Analyzer to recognize few Patterns.


Program

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char ipstr[300],temp,tmp[15],fname[50];
char parn[6]={'(',')','{','}','[',']'};
char symb[10]={'.',',',':',';','<','>','?','$','#'};
char ops[6]={'+','-','=','/','*','^'};
char keywd[8][10]={"main","if","else","switch","void","do","while","for"};
char daty[6][10]={"int","char","float","double","string","longint"}; int
pos=0,i,j,k,flagi,ip;
FILE *fid;
clrscr();

/* Input is taken from fname file*/


printf("enter filename which is to be parsed\n");
scanf("%s",fname);
fid=fopen(fname,"r");
while((ip=getc(fid))!=EOF)
ipstr[pos++]=ip;
ipstr[pos]='\0';
printf("%s",ipstr);
printf("\t\tlexicanalysis\n________________________________________\n");
for(i=0;ipstr[i]!='\0';i++)
{
if((ipstr[i]!=' ')&&(ipstr[i]!='\0')&&(ipstr[i]!='@')&&(ipstr[i]!='\n'))
{
temp=ipstr[i];
/* Check for parenthesis*/
for(j=0;j<6;j++)
{
if(temp==parn[j])
printf("\n%c \t paranthesis",temp);
}

/*Check for symbols*/


for(j=0;j<10;j++)
{
if(temp==symb[j])
printf("\n%c \t symbol",temp);
}

/* Check for operators*/


for(j=0;j<6;j++)
{
if(temp==ops[j])
printf("\n%c \t operator",temp);
}
/* Check for digits*/
if(isdigit(ipstr[i]))
{
k=0;
while((isdigit(ipstr[i]))||ipstr[i]=='.')
tmp[k++]=ipstr[i++];
tmp[k]='\0';i--;
printf("\n%s \t number",tmp);
}
/* Check for alphabets (keywords, data types, identifiers) */
if(isalpha(ipstr[i]))
{
k=0;
while(isalpha(ipstr[i]))
tmp[k++]=ipstr[i++];
tmp[k]='\0';i--;
flag i=1;
for(j=0;j<8;j++)
{
if((strcmp(tmp,keywd[j]))==0)
{ printf("\n %s keyword",tmp);
Flag i=0;
break;
}
}
for(j=0;j<6;j++)
{
if((strcmp(tmp,daty[j]))==0)
{
printf("\n %s DataType",tmp);
flag i=0;
break;
}
}
if(flagi==1)printf("\n %s \t Identifiers",tmp);
}
/*Alphabets loop closing*/
}
/*If loop closing*/
}
/* Main for loop closing*/
getch();}
OUTPUT:-
Enter file name to be parsed : compiler.txt
void min()
{
a=b-c;
234=200+34;
}
Lexical analysis

Void ------ keyword


Min ------ Identifiers
( ------ Parenthesis
) ------ Parenthesis
{ ------ parenthesis
a ------ Identifiers
= ------ Operator
b ------ Identifiers
- ------ Operator
C ------ Identifiers
; ------ Symbol
234 ------ Number
= ------ operator
200 ------ number
+ ------ Operator
34 ------ number
; ------ Symbol
} ------ Parenthesis
EXPERIMENT ---2

/**********************************************************************
Aim - Write a program to generate intermediate codes
Polish Notation
**********************************************************************/
ALGORITHM:-
1. Start
2. Read the infix expression from keyboard.
3. Assume that the infix expression you have read is stored in the character Array infix.
4. P u s h # i n t o s t a c k .
5. For each character in infix array perform the following actions read characters from last

Begin

• if character is digit or alphabet then enter the same in to post fix array(resultant array) .
•if character is closed braces then , push that into the stack
•if character is open braces then, pop the stack top elementsuntil top of the stack contains
open braces.
• if character contains any arithmetic operators,

if top of stack element is equal to # then, push theoperator into stack.

Else if the top of stack element priority is greater than or equal to the priority of the new character

then push thecharacter in to stack
Else pop the elements from stack until the priority of the topof the stack element is less
than the character priority that isto be inserted.
End
End
6. If no more characters are presented in infix expression then pop elements from Stack until top
of stack element is # and push that element in to postfix array.
7. Finally reverse the resultant array then that is the polish notation for the infix expression.
Push Function:
1. Start
2. If top of the stack is reached max size of the stack then, the stack is full.
3. Else

4. End
Pop Function:
1. start
2. if top of the stack is null then, the stack is empty
3.elseDelete the element from the stack positioned by the top
4. End
/* INTERMEDIATE CODE INTO POLISH (PREFIX) EXPRESSION */
Program

# include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<math.h>
int top=-1;
char stack[20];
main()
{
char infix[20];
clrscr();
printf("enter the infix
expression"); /* Read infix
expression */ gets(infix);
/* Convert infix to polish
notation */ intopo(infix);
getch();
}
intopo(char infix[20])
{char prefix[20],s,t;int index,pos=0,l,i,len;
l=strlen(infix);index=l-1;
push('#');
while(index>=0)
{s=infix[index];
switch(s)
{
case ')': push(s);
break;
case '(':t=pop();
while(t!=')')
{
prefix[pos++]=t;
t=pop();
}
break;
case'+':
case'-':
case'*':
case'/':
case'^':
while(pre(stack[top])<pre(s))
{
t=pop();
prefix[pos++]=t;
}
push(s);
break;
default: prefix[pos++]=s;break;
}
index--;
}
while(top>0)
{t=pop();
prefix[pos++]=t;
}
prefix[pos++]='\0';
len=strlen(prefix)-1;
for(i=len;i>=0;i--)
printf("%c",prefix[i]);
}
push(char c)
{
top++;
stack[top]=c;
}
pop()
{
char c;
c=stack[top];
top--;
return(c);
}
pre(char c )
{
if(c=='^')
return(5);
else if(c=='/'|| c=='*')
return (4);
else if( c=='+'|| c== '-')
return(3);
else
return(6);
}
OUTPUT :-
1) Enter the infix expression
a+b*c/(d^e+f)
The equivalent polish notation is….
/*+abc^d+ef

2) Enter the infix expression


a*b^c
The equivalent reverse polish notation is….
^*abc
EXPERIMENT – 3

/**********************************************************************
AIM- Write a program to generate three address code
generation
**********************************************************************/

ALGORITHM:-
1. Start
2. Read the infix expression from keyboard.
3. Assume that the input expression you have read is stored in the character Array infix.
4. P u s h # i n t o s t a c k .
5. For each character in infix array perform the following actions Begin

• if character is digit or alphabet then enter the same in to post fix array(resultant array) .
• if character is open braces then , push that into the stack
• if character is closed braces then, pop the stack top elements until top of the stack contains open
braces.
• if character contains any arithmetic
operators, Begin

if top of stack element is equal to # then, push the operator into stack.

Else if the top of stack element priority is less than the priority of the new character then push the
character in to stack.

Else pop the elements from stack until the priority of the topof the stack element is less than
the character priority that is to be inserted.

6. If no more characters are presented in infix expression then pop elements from Stack until top
of stack element is # and push that element in to postfix array.
7. For each character in postfix array do the following operation.
Begin
•If the character is alphabet push character in to stack.
•If the character is operator then pop two characters from stack andstore those in op1 and op2
variables.
begin
•Print those in the format of Ti=op1 character op2
•Increment I for generating temporary variables.
•Push the new temporary variable Ti in to stack.
End
End.

Push Function:
1. Start
2. If top of the stack is reached max size of the stack then, the stack is
full. 3.ElseInsert the element into stack
4. End
Pop Function:
1. start
2. if top of the stack is null then, the stack is empty
3.else Delete the element from the stack positioned by the top
4. End

/* INTERMEDIATE CODE TO THREE ADDRESS CODE */


Program
# include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<math.h>
int top=-1;
char stack[20],postfix[20],infix[20],ipst[20];
main()
{
int i;
clrscr();
printf("Enter infix expression\n in the form of assignment stmt like
var=exp..."); gets(ipst);
for(i=2;i<strlen(ipst);i++)
infix[i-2]=ipst[i]; infix[i-
2]='\0'; puts(infix);

intopo();
getch();
evalua();
getch();
}
intopo()
{
char s,t;
int index=0,pos=0,l;
l=strlen(infix);
push('#');
while(index<l)
{
s=infix[index];
switch(s){
case '(': push(s);
break;
case ')':t=pop();
while(t!='(')
{
postfix[pos++]=t;
t=pop();
}
break;
case'+':
case'-':
case'*':
case'/':
case'^':
while(pre(stack[top])>=pre(s))
{
t=pop();
postfix[pos++]=t;
}
push(s);
break;
default: postfix[pos++]=s;
break;
}
index++;
}
while(top>0)
{
t=pop();
postfix[pos++]=t;
}
postfix[pos++]='\0';
}
push(char c)
{
top++;stack[top]=c;
}
pop()
{
char c;
c=stack[top];
top--;
return(c);
}
pre(char c )
{
if(c=='^')
return(5);
else if(c=='/'|| c=='*')
return (4);
else if( c=='+'|| c== '-')
return(3);
else
return(2);

}
pop()
{
char c;
c=stack[top];
top--;
return(c);
}
pre(char c )
{
if(c=='^')
return(5);
else if(c=='/'|| c=='*')
return (4);
else if( c=='+'|| c== '-')
return(3);
elsereturn(2);
}
evalua()
{
char res[20],ch,ch1,ch2;
int i,t=1;
for(i=0;i<strlen(postfix);i++)
{
ch=postfix[i];
if(isalnum(ch))push(ch);
else
{
ch1=pop();
ch2=pop();
printf("\nT%d=",t);
if(ch2=='1'||ch2=='2'||ch2=='3'||ch2=='4'||ch==’5’||ch==’6’||ch=’7’||ch=’8’||ch=’9’)
printf("T%c",ch2);
else
printf("%c",ch2);
printf("%c",ch);

if(ch1=='1'||ch1=='2'||ch1=='3'||ch1=='4'||ch==’5’||ch==’6’||ch=’7’||ch=’8’||ch=’9’)
printf("T%c",ch1);
else
printf("%c",ch1);
switch(t)
{
case 1:ch='1';
break;
case 2:ch='2';
break;
case 3:ch='3';
break;
case 4:ch='4';
break;
case 5:ch='5';
break;
case 6:ch='6';
break;
case 7:ch='7';
break;
case 8:ch='8';
break;
case 9:ch='9';
break;
}
push(ch);
t++;
}
}
/* for loop closing*/
ch=pop();
printf("\n %c=T%c",ipst[0],ch);
}
OUTPUT :-
1) Enter the infix expression
In the form of assignment statement like var=exp...R=(a+b*c)-(d^e+f)
T1=b*c
T2=a+T1
T3=d^e
T4=T3+f
T5=T2-T4
R=T5

2) Enter the infix expressionin the form of assignment statement like var=exp...R=(a^b*c)-(d-e)
T1=a^b
T2=T1*c
T3=d-e
T4=T2-T3
R=T4
EXPERIMENT --- 4

/**********************************************************************
AIM- Develop a Recursive Descent parser
**********************************************************************/

ALGORITHM:-

procedure e()
beginT();
EPRIME();
endprocedure
EPRIME()
begin
if inputsymbol='+' then
begin
advance the input pointer;
T();
EPRIME();
End
;end;
procedure T()
begin
F();
TPRIME();
end;
procedure T()
beginF();
TPRIME();
end;
procedure TPRIME()
begin
if inputsymbol='*' then
begin
advance the input pointer;
F();
TPRIME();
end;
end;
procedure f()
begin
if inputsymbol = 'id' then
advance the input pointer;
else if inputsymbol='l' then
beginadvance the input pointer;
E();
if inputsymbol =')' then
advance the input pointer;
else
error();
end;
else
error();
end;
begin
/*main program */
read any terminal
stringE();
end;

/* Program to develop recursive decent parser*/


#include<stdio.h>
char *a;
main()
{
char s[10];
clrscr();
printf("ENTER THE STRING");
gets(s);
a=s;
if(E())
printf("STRING IS PARSED");
else
printf(invalid string");
getch();
}
int E()
{
T();
EPRIME()
;
}
int EPRIME()
{
if(*a=='+'' )
{
a++;
T();
EPRIME();
}
}
int T()
{
F();
TPRIME();
}
int TPRIME()
{
if(*a=='*')
{
a++;;
F();
TPRIME();
}
}
int F()
{
if(*a=='i')
a++ ;
else if(*a==')')
{
a++;;
E();
if(*a==')')
a++ ;
else
error();
}
elseerror();
}
int error()
{
return(0);
}

INPUT:-ENTER THE STRING :(i+i)


OUTPUT:-STRING IS PARSED
EXPERIMENT--- 5

/**********************************************************************
AIM- Write a program to simulate Heap storage allocation
Strategy
**********************************************************************/
ALGORITHM:-
“To implement dynamic memory allocation and deal location we areImplementing heap storage
allocation”
1.Start
2.Assume memor y size as 50 bytes
3.Allocation: ---

Read variable name and size.

If continuous available free space is greater than or equal to variable size then allocate. And make

those bits in allocation array as 1.
If space not sufficient then allocation is not possible.
4.Deallocation: ---

Read variable name

Compare variable name with variable name presented in heap allocated array. If match is found free

the memory space allocated for that variable.
Make valid bit as zero in heap array for that variable.

Allocation bits in array make as 0 for that particular variable memory.

5.Deal located memory space will be utilized when new variable requires Memory….
6. Stop.
/* Program to develop Heap Storage Allocation*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct heaps{char var[10];
int no_byte;
int st_byte;
int valid;
}
heaparr[20];
int alloc[50],harpos=0;
void main()
{int ch,i;
/* if memory allocated then alloc[pos]=1 else 0*/
for(i=0;i<50;i++)
alloc[i]=0;
while(1){
clrscr();
printf("\n enter u r choice\n");
scanf("%d",&ch);
switch(ch){
case 1:allocat();
break;
case 2:deallocat();
break;

case 3:disp();
break;
case 4: exit(0);
getch();
}
/*Closing of switch*/
}
/* Closing of while*/
}
/* Closing of main*/
allocat()
{
char vname[10],s;
int vsize,i,count,st,k;
printf("\n enter variable name:");
scanf("%s",&vname);
printf("\n enter how many bytes required for %s",vname);
scanf("%d",&vsize);
for(i=0;i<50;i++){ count=0;
while((alloc[i]==1)&&(i<50))
i++;
st=i;
while(count<vsize)
{
if(alloc[i]==0)
count++;
else
break;
i++;
}
if(count==vsize)
{
strcpy(heaparr[harpos].var,vname);
heaparr[harpos].valid=1;
heaparr[harpos].no_byte=vsize;
heaparr[harpos].st_byte=st;
for(k=st;k<st+vsize;k++)
alloc[k]=1;
harpos++;
break;

}}
/*Closing of for loop*/
if(i>50)
printf("\n Allocation is not possible\n");
else
printf("\n Allocated succesfully\n");
}
/*Closing of allocation*/
disp()
{
int i;
for(i=0;i<harpos;i++)
{
if(heaparr[i].valid==1)
{
printf("\n Name of variable %s",heaparr[i].var);
printf("\n starting byte %d",heaparr[i].st_byte);
printf("\n number of bytes
%d",heaparr[i].no_byte); }
}
}
/* Closing of display*/
deallocat()
{
int i;
char vnam[10];
int sta_byte,len_byte,end_byte;
printf("variables presented are...\t");
for(i=0;i<harpos;i++)
printf("%s",heaparr[i].var);
printf("ENTER VARIABLE NAME WHICH IS TO BEDEALLOCATED\t");
scanf("%s",vnam);
for(i=0;i<harpos;i++)
{
if(heaparr[i].valid==1)
{
if(strcmp(vnam,heaparr[i].var)==0)
break;
}
}
if(i<harpos)
{
heaparr[i].valid=0;
sta_byte=heaparr[i].st_byte;
len_byte=heaparr[i].no_byte;
end_byte=sta_byte+len_byte;
for(i=sta_byte;i<end_byte;i++)
alloc[i]=0;
}
}
/* Closing of deal location*/
OUTPUT :-

Enter u r choice 1
Enter variable name:a
Enter how many bytes required for a
10
Allocated successfully

Enter u r choice 1
Enter variable name :b
Enter how many bytes required for b
20
Allocated successfully

Enter u r choice1
Enter variable name: c
Enter how many bytes required for c
30
Allocation is not possible

Enter u r choice 3
Name of variable a
starting byte 0
number of bytes10
bytes allocated are 0..9
Name of variable b
starting byte 10
number of bytes20
bytes allocated are 10..29

Enter u r choice 1
Enter variable name: c
Enter how many bytes required for c
10
Allocated successfully

Enter u r choice 3
Name of variable a
Starting byte 0
Number of bytes10
Bytes allocated are 0..9
Name of variable b
Starting byte 10
Number of bytes20
Bytes allocated are 10..29
Name of variable cStarting byte 30
Number of bytes10
Bytes allocated are 30..39
Enter u r choice 2
variables presented are...
abc
enter variable name, which is to be deallocated
b
Deal located successfully

Enter u r choice 3
Name of variable a
Starting byte 0
Number of bytes10
Bytes allocated are 0..9
Name of variable c
Starting byte 30
Number of bytes10
Bytes allocated are 30..39
Enter u r choice 4.

You might also like