You are on page 1of 35

Department of Computer Science & Faculty of Engineering

MEDI-CAPS UNIVERSITY
INDORE- 453331

Compiler Design

Course Code: - CS3CO27


Lab Manual

Submitted to - BY
Ms. Garima Chandore Ranu Sharma
Asst. Professor EN19CS305036
INDEX:

S. No. Program Page Date of Date of Sign/


Experiment Submission Grade
no.

01. Write a C program to check given the 03-04 20/01/2022


word is a keyword or not.

02. Write a C program to calculate the length 05-06 20/01/2022


of a string and concatenate given two
strings..

03. Write a C program to copy a string into 07-08 27/01/2022


another string and reverse the string.

04. Write a C program to identify if a given 09-10 27/01/2022


line is a comment or not.

05. Write a C program to test whether a 11-12 03/02/2022


given identifier is valid or not.

06. Write a C program to simulate a lexical 13-14 17/02/2022


analyzer for validating the operator.

07. Write a C program to identify the tokens 15-18 03/03/2022


in the given string.

08. Write a C program to recognize strings 19-21 09/03/2022


under a*, a*b+ ,abb.

09. Write a C program to classify terminals 22-23 10/03/2022


and nonterminals in given grammar.

10. Write a C program to calculate the first() 24-28 17/03/2022


and follow() of a given grammar.

11. Write a C program to Construct LR (0) 29-31 24/03/2022


parsing table.

12. Write a C program to Construct Operator 32-35 31/03/2022


Precedence parsing.

2
Experiment: 1
Aim - Write a C program to check given the word is a keyword or not.
Code:

#include<stdio.h>
#include<string.h>
intmain() {
charkeyword[32][10]=
{
"auto","double","int","struct","break","else","long",
"switch","case","enum","register","typedef","char",
"extern","return","union","const","float","short"
"unsigned","continue","for","signed","void","default",
"Goto","sizeof","voltile","do","if","static","while"
};
charstr[]="which";
intflag=0,i;
for(i = 0; i<32; i++) {
if(strcmp(str,keyword[i])==0) {
flag=1;
}
}
if(flag==1)
printf("%s is a keyword",str);
else
printf("%s is not a keyword",str);
}

3
Output :

4
Experiment: 2
Aim -Write a program to calculate the length of a string and concatenate given strings.
Code: 2.1 Length of String

#include <stdio.h>

int main()

{ char Str[1000];

int i;

printf("Enter the String: ");

scanf("%s", Str);

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

printf("Length of Str is %d", i);

return 0;

Output -

5
2.2 Concatenate the String
#include <string.h>
int main()
{ char s1[1000],s2[1000];
int i,j;
printf("Enter string1: ");
gets(s1);
printf("Enter string2: ");
gets(s2);
j=strlen(s1);
for(i=0;s2[i]!='\0';i++)
{ s1[i+j]=s2[i]; }
s1[i+j]='\0';
printf("concatenated two strings ='%s'\n",s1);
return 0;
}
Output :

6
Experiment: 3
Aim - Write a C program to copy a string into another string and reverse the string.
Code:

#include <stdio.h>
#define MAX_SIZE 100
int main()
{
char text1[MAX_SIZE];
char text2[MAX_SIZE];
int i;
printf("Enter any string: ");
gets(text1);
for(i=0; text1[i]!='\0'; i++)
{
text2[i] = text1[i];
}
text2[i] = '\0';
printf("First string = %s\n", text1);
printf("Second string = %s\n", text2);
printf("Total characters copied = %d\n", i);
return 0;
}

7
Output:

8
Experiment: 4
Aim - Write a C program to identify given line is a comment or not.
Code:

#include<stdio.h>
void main()
{
char com [30];
int i=2,a=0;
printf("\n Enter Text : ");
gets(com);
if(com[0]=='/')
{
if(com[1]=='/')
printf("\n It is a Comment. ");
else if(com [1]=='*')
{ for(i=2;i<=30;i++)
{ if(com[i]=='*'&&com[i+1]=='/')
{ printf("\n It is a Comment. ");
a=1;
break;
}
else continue;
}
if(a==0)
printf("\n It is Not a Comment. ");
}
else
printf("\n It is Not a Comment. ");
}
else
printf("\n It is Not a Comment. ");
}

9
Output:

10
Experiment: 5
Aim - Write a C program to test whether a given identifier is valid or not
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char string[50];
int count=0,i;
printf("Enter the String: ");
gets(string)
if((string[0]>='a'&&string[0]<='z') || (string[0]>='A'&&string[0]<='Z') || (string[0]=='_') ||
(string[0]=='$'))
{
for(i=1;i<=strlen(string);i++)
{
if((string[i]>='a'&& string[i]<='z') || (string[i]>='A' && string[i]<='Z') || (string[i]>='0'&&
string[i]<='9') || (string[i]=='_'))
{ count++;
} }
}
if(count==(strlen(string)-1))
{
printf("Input string is a valid identifier");
}
else
{
printf("Input string is not a valid identifier");
}
return 0;
}

11
Output:

12
Experiment: 6
Aim - Write a C program to simulate a lexical analyzer for validating the operator.
Code:
#include <stdio.h>
#include <string.h>
int main ()
{ char arithmetic[5]={'+','-','*','/','%'};
char relational[4]={'<','>','!','='};
char bitwise[5]={'&','^','~','|'};
char str[2]={' ',' '};
printf ("Enter value to be identified: ");
scanf ("%s",&str);
int i;
if(((str[0]=='&' || str[0]=='|') && str[0]==str[1]) || (str[0]=='!' && str[1]=='\0'))
{ printf("\nIt is Logical operator");
}
for(i=0;i<4;i++)
{ if(str[0]==relational[i]&&(str[1]=='='||str[1]=='\0'))
{ printf("\n It is relational Operator"); break; }
}
for(i=0;i<4;i++)
{
if((str[0]==bitwise[i] && str[1]=='\0') || ((str[0]=='<' || str[0]=='>') && str[1]==str[0]))
{ printf("\n It is Bitwise Operator"); break; }
}
if(str[0]=='?' && str[1]==':')
printf("\nIt is ternary operator");
for(i=0;i<5;i++)
{ if((str[0]=='+' || str[0]=='-') && str[0]==str[1])
{ printf("\nIt is unary operator"); break; }
else if((str[0]==arithmetic[i] && str[1]=='=') || (str[0]=='=' && str[1]==' '))
{ printf("\nIt is Assignment operator"); break; }
else if(str[0]==arithmetic[i] && str[1]=='\0')

13
{ printf("\nIt is arithmetic operator"); break; }
}
return 0;
}
Output:

14
Experiment: 7
Aim - Write a C program to identify the tokens in the given string.
Code:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
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); }
bool isOperator(char ch)
{ if (ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == '>' || ch == '<' ||
ch == '=')
return (true);
return (false); }
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); }
bool isKeyword(char* str)
{ 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")

15
|| !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); }
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); }
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);
if (str[i] == '.')
hasDecimal = true; }

16
return (hasDecimal); }
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); }
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);
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)

17
printf("'%s' IS NOT A VALID IDENTIFIER\n", subStr);
left = right; } }
return; }
// DRIVER FUNCTION
int main()
{ char str[20];
printf("ENTER YOUR PROGRAM:");
gets(str);
parse(str);
scanf("%s",str);
return (0); }
Output:

18
Experiment: 8
Aim - Write a C program to recognize strings under a*, a*b+ ,abb.
Code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char s[20],c;
int state=0,i=0;
printf("\n Enter a string:");
gets(s);
while(s[i]!='\0')
{ switch(state)
{ case 0:
c=s[i++];
if(c=='a') state=1;
else if(c=='b') state=2;
else state=6;
break;
case 1:
c=s[i++];
if(c=='a') state=3;
else if(c=='b') state=4;
else state=6;
break;
case 2:
c=s[i++];
if(c=='a') state=6;
else if(c=='b') state=2;
else state=6;
break;
case 3:

19
c=s[i++];
if(c=='a') state=3;
else if(c=='b') state=2;
else state=6;
break;
case 4:
c=s[i++];
if(c=='a') state=6;
else if(c=='b') state=5;
else state=6;
break;
case 5:
c=s[i++];
if(c=='a') state=6;
else if(c=='b') state=2;
else state=6;
break;
case 6:
printf("\n %s is not recognised.",s);
exit(0);
}
}
if((state==1)||(state==3))
printf("\n %s is accepted under rule 'a'",s);
else if((state==2)||(state==4))
printf("\n %s is accepted under rule 'a*b+'",s);
else if(state==5)
printf("\n %s is accepted under rule 'abb'",s);
return 0;
}

20
Output:

21
Experiment: 9
Aim - Write a C program to classify terminals and nonterminals in given grammar.
Code:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void main()
{
char s[20], nonTerminal[20],terminal[20];
printf("Enter the Production:");
gets(s);
int i = 0;
while (s[i] != '\0')
{
if (isupper(s[i]))
{
printf("\n%c is non terminal",s[i]);
}
if (islower(s[i])||s[i] == '#')
{
printf("\n%c is terminal",s[i]);
}
i++;
}
}

22
Output:

23
Experiment: 10
Aim - Write a program to calculate the first() and follow() of a given grammar.
Code:
#include<stdio.h>
#include<string.h>
int i,j,l,m,n=0,o,p,nv,z=0,x=0;
char str[10],temp,temp2[10],temp3[20],*ptr;
struct prod
{ char lhs[10],rhs[10][10],ft[10],fol[10];
int n;}
pro[10];
void findter()
{ int k,t;
for(k=0;k<n;k++)
{ if(temp==pro[k].lhs[0])
{ for(t=0;t<pro[k].n;t++)
{ if( pro[k].rhs[t][0]<65 || pro[k].rhs[t][0]>90 )
pro[i].ft[strlen(pro[i].ft)]=pro[k].rhs[t][0];
else if( pro[k].rhs[t][0]>=65 && pro[k].rhs[t][0]<=90 )
{ temp=pro[k].rhs[t][0];
if(temp=='S')
pro[i].ft[strlen(pro[i].ft)]='#';
findter(); } }
break; } }}
void findfol()
{ int k,t,p1,o1,chk;
char *ptr1;
for(k=0;k<n;k++)
{ chk=0;
for(t=0;t<pro[k].n;t++)
{ ptr1=strchr(pro[k].rhs[t],temp);
if( ptr1 )
{ p1=ptr1-pro[k].rhs[t];

24
if(pro[k].rhs[t][p1+1]>=65 && pro[k].rhs[t][p1+1]<=90)
{ for(o1=0;o1<n;o1++)
if(pro[o1].lhs[0]==pro[k].rhs[t][p1+1])
{ strcat(pro[i].fol,pro[o1].ft);
chk++; } }
else if(pro[k].rhs[t][p1+1]=='\0')
{ temp=pro[k].lhs[0];
if(pro[l].rhs[j][p]==temp)
continue;
if(temp=='S')
strcat(pro[i].fol,"$");
findfol();
chk++; }
Else
{ pro[i].fol[strlen(pro[i].fol)]=pro[k].rhs[t][p1+1];
chk++; } } }
if(chk>0)
break; } }
int main()
{ FILE *f;
//clrscr();
for(i=0;i<10;i++)
pro[i].n=0;
f=fopen("tab5.txt","r");
while(!feof(f))
{ fscanf(f,"%s",pro[n].lhs);
if(n>0)
{ if( strcmp(pro[n].lhs,pro[n-1].lhs) == 0 )
{ pro[n].lhs[0]='\0';
fscanf(f,"%s",pro[n-1].rhs[pro[n-1].n]);
pro[n-1].n++;
continue; } }
fscanf(f,"%s",pro[n].rhs[pro[n].n]);
pro[n].n++;

25
n++; }
printf("\n\nTHE GRAMMAR IS AS FOLLOWS\n\n");
for(i=0;i<n;i++)
for(j=0;j<pro[i].n;j++)
printf("%s -> %s\n",pro[i].lhs,pro[i].rhs[j]);
pro[0].ft[0]='#';
for(i=0;i<n;i++)
{ for(j=0;j<pro[i].n;j++)
{ if( pro[i].rhs[j][0]<65 || pro[i].rhs[j][0]>90 )
{ pro[i].ft[strlen(pro[i].ft)]=pro[i].rhs[j][0]; }
else if( pro[i].rhs[j][0]>=65 && pro[i].rhs[j][0]<=90 )
{ temp=pro[i].rhs[j][0];
if(temp=='S')
pro[i].ft[strlen(pro[i].ft)]='#';
findter(); } } }
printf("\n\nFIRST\n");
for(i=0;i<n;i++)
{ printf("\n%s -> ",pro[i].lhs);
for(j=0;j<strlen(pro[i].ft);j++)
{ for(l=j-1;l>=0;l--)
if(pro[i].ft[l]==pro[i].ft[j])
break;
if(l==-1)
printf("%c",pro[i].ft[j]); } }
for(i=0;i<n;i++)
temp2[i]=pro[i].lhs[0];
pro[0].fol[0]='$';
for(i=0;i<n;i++)
{ for(l=0;l<n;l++)
{ for(j=0;j<pro[i].n;j++)
{ ptr=strchr(pro[l].rhs[j],temp2[i]);
if( ptr )
{ p=ptr-pro[l].rhs[j];
if(pro[l].rhs[j][p+1]>=65 && pro[l].rhs[j][p+1]<=90)

26
{ for(o=0;o<n;o++)
if(pro[o].lhs[0]==pro[l].rhs[j][p+1])
strcat(pro[i].fol,pro[o].ft); }
else if(pro[l].rhs[j][p+1]=='\0')
{ temp=pro[l].lhs[0];
if(pro[l].rhs[j][p]==temp)
continue;
if(temp=='S')
strcat(pro[i].fol,"$");
findfol();
}
else
pro[i].fol[strlen(pro[i].fol)]=pro[l].rhs[j][p+1];
}
}
}
}
printf("\n\nFOLLOW\n");
for(i=0;i<n;i++)
{
printf("\n%s -> ",pro[i].lhs);
for(j=0;j<strlen(pro[i].fol);j++)
{
for(l=j-1;l>=0;l--)
if(pro[i].fol[l]==pro[i].fol[j])
break;
if(l==-1)
printf("%c",pro[i].fol[j]);
}
}
printf("\n");
//getch();
}

27
Output:

28
Experiment: 11
Aim - Write a C program to Construct LR (0) parsing table.
Code:
#include <iostream>
#include <cstring>
using namespace std;
char stack[30];
int top = -1;
void push(char c)
{ top++;
stack[top] = c; }
char pop()
{ char c;
if (top != -1)
{ c = stack[top];
top--;
return c; }
return 'x'; }
bool checkforS(char stack[])
{ bool check = true;
char str[20] = "A+B";
if (top < 2)
{ check = false; }
for (int i = 0; i <= top; i++)
{ if (stack[i] != str[i]) {
check = false; } }
return check; }
void printstat()
{ int i;
cout << "\n";
cout << "$";
for (i = 0; i <= top; i++)
cout << stack[i]; }
int main()

29
{ int i, j, k, l;
char s1[20], s2[20], ch1, ch2, ch3;
cout << "--LR PARSING--";
cout << "\nENTER THE EXPRESSION:";
cin >> s1;
l = strlen(s1);
j = 0;
cout << "$";
for (i = 0; i <= l; i++)
{ if (checkforS(stack))
{ s1[i] = 'S';
printstat();
top = -1;
push('S');
printstat(); }
else if (s1[i] == 'a')
{ s1[i] = 'A';
printstat();
cout << "a";
push('A');
printstat(); }
else if (s1[i] == 'b')
{ s1[i] = 'B';
printstat();
cout << "b";
push('B');
printstat(); }
else if (s1[i] == '+' || s1[i] == '-' || s1[i] == '*' || s1[i] == '/' || s1[i] == 'd')
{ push(s1[i]);
printstat(); } }
printstat();
l = strlen(s2);
while (l)
{ ch1 = pop();

30
if (ch1 == 'x')
{ printf("$");
break; }
if (ch1 == '+' || ch1 == '/' || ch1 == '*' || ch1 == '-')
{ ch3 = pop();
if (ch3 != 'E')
{ cout << "errror"; }
else
{ push('E');
printstat(); } }
ch2 = ch1;
}
}
Output:

31
Experiment: 12
Aim - Write a C program to Construct Operator Precedence parsing.
Code :
#include<stdio.h>
#include<string.h>
char *input;
int i=0;
char lasthandle[6],stack[50],handles[][5]={")E(","E*E","E+E","a","E^E"};
int top=0,l;
char prec[9][9]={
/input/
/*stack + - * / ^ i ( ) $ */
/* + */ '>', '>','<','<','<','<','<','>','>',
/* - */ '>', '>','<','<','<','<','<','>','>',
/* * */ '>', '>','>','>','<','<','<','>','>',
/* i */ '>', '>','>','>','>','e','e','>','>',
/* $ */ '<', '<','<','<','<','<','<','<','>',
};
int getindex(char c)
{ switch(c)
{
case '+':return 0;
//case '-':return 1;
case '*':return 2;
// case '/':return 3;
//case '^':return 4;
case 'a':return 5;
//case '(':return 6;
//case ')':return 7;
case '$':return 8; } }
int shift()
{ stack[++top]=*(input+i++);
stack[top+1]='\0';
}

32
int reduce()
{ int i,len,found,t;
for(i=0;i<5;i++)//selecting handles
{ len=strlen(handles[i]);
if(stack[top]==handles[i][0]&&top+1>=len)
{ found=1;
for(t=0;t<len;t++)
{
if(stack[top-t]!=handles[i][t])
{ found=0;
break;
}
}
if(found==1)
{
stack[top-t+1]='S';
top=top-t+1;
strcpy(lasthandle,handles[i]);
stack[top+1]='\0';
return 1;//successful reduction
}
}
}
return 0;
}
void dispstack()
{ int j;
for(j=0;j<=top;j++)
printf("%c",stack[j]);
}
void dispinput()
{
int j;
for(j=i;j<l;j++)

33
printf("%c",*(input+j));
}
void main()
{
int j;
input=(char*)malloc(50*sizeof(char));
printf("\nEnter the string\n");
scanf("%s",input);
input=strcat(input,"$");
l=strlen(input);
strcpy(stack,"$");
printf("\nSTACK\tINPUT\tACTION");
while(i<l)
{ shift();
printf("\n");
dispstack();
printf("\t");
dispinput();
printf("\tShift");
if(prec[getindex(stack[top])][getindex(input[i])]=='>')
{ while(reduce())
{ printf("\n");
dispstack();
printf("\t");
dispinput();
printf("\tReduced: S->%s",lasthandle);
}
}
}
if(strcmp(stack,"$E$")==0)
printf("\nAccepted;");
else
printf("\nNot Accepted;");
}

34
Output:

35

You might also like