Compiler Design: Department of Computer Science & Faculty of Engineering

You might also like

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

Department of Computer Science & Faculty of Engineering

MEDI-CAPS UNIVERSITY
INDORE- 453331

Compiler Design

Course Code: - CS3CO27


Lab Manual

Submitted to - BY
Ms. Garima Gole Ranu Sharma
EN19CS305036
INDEX:

S. No. Program Page no.

01. Write a C program to check given the word is a keyword or not.

02. Write a C program to calculate the length of a string and


concatenate given two strings..

03. Write a C program to copy a string into another string and


reverse the string.

04. Write a C program to identify given line is a comment or not.

05. Write a C program to test whether a given identifier is valid or


not.

06. Write a C program to simulate a lexical analyzer for validating


the operator.

07. Write a C program to identify the tokens in the given string.

08. Write a C program to recognize strings under a*, a*b+ ,abb.

09. Write a C program to classify terminals and nonterminals in


given grammar.

10. Write a C program to calculate the first() and follow() of a given


grammar.

11. Write a C program to Construct LR (0) parsing table.

12. Write a C program to Construct Operator Precedence parsing.


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

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 :
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;
}
Output:
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. "); }
Output:
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; }
Output:
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')
{ printf("\nIt is arithmetic operator"); break; }
}
return 0;
}
Output:
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")
|| !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; }
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)
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:
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:
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; }
Output:
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++;
}
}
Output:
Experiment: 10
Aim - Write a C program to calculate the first() and follow() of a given grammar.
Code:
#include <iostream>
#include <string>
using namespace std;
char grammer[20][20];
int sizeG = 0;
char first[20];
int firstcount = 0;
char follow[20];
int followcount = 0;
bool isTerminalorNot(char ch)
{ if (isupper(ch))
{ return false; }
if (islower(ch) || ch == '#')
{ return true; }
return false; }
bool checkEpsilon(char ch)
{ if (ch == '#')
{ return true; }
else
{ return false; } }
int FindProduction(char ch)
{ for (int i = 0; i < sizeG; i++)
{ if (grammer[i][0] == ch)
{ return i; } }
return -1; }
int FindComma(int comma[], int prodNo)
{ int commaNo = 1;
for (int i = 0; grammer[prodNo][i] != '\0'; i++)
{ if (grammer[prodNo][i] == '|')
{ comma[commaNo] = i;
commaNo++; } }
return commaNo; }
bool checkAlreadyFirst(char ch)
{ if (firstcount == 0)
{ return false; }
for (int i = 0; i < firstcount; i++)
{ if (ch == first[i])
{ return true; } }
return false; }
void deleteEpsilonFirst(char arr[])
{ int i;
for (i = 0; i < firstcount; i++)
if (arr[i] == '#')
break;
if (i < firstcount)
{ firstcount = firstcount - 1;
for (int j = i; j < firstcount; j++)
arr[j] = arr[j + 1]; } }
int First(char ch)
{ int prodNo = FindProduction(ch);
int comma[10];
int commaNo;
bool isEpsilon = false;
int check;
comma[0] = 1;
commaNo = FindComma(comma, prodNo);
if (prodNo == -1)
return -1;
else
{ for (int i = 0; i < commaNo; i++)
{ if (isTerminalorNot(grammer[prodNo][comma[i] + 1]))
{ if (checkEpsilon(grammer[prodNo][comma[i] + 1]))
{ isEpsilon = true; }
if (!checkAlreadyFirst(grammer[prodNo][comma[i] + 1]))
{ first[firstcount] = grammer[prodNo][comma[i] + 1];
firstcount++; } }
else
{ check = First(grammer[prodNo][comma[i] + 1]);
int j = 2;
while (grammer[prodNo][comma[i] + j] != '\0' && check == 1)
{ (grammer[prodNo][comma[i] + j] != '|' &&
!isTerminalorNot(grammer[prodNo][comma[i] + j]))
{ if (check == 1)
{ deleteEpsilonFirst(first);
check = First(grammer[prodNo][comma[i] + j]); } }
else if (isTerminalorNot(grammer[prodNo][comma[i] + j]))
{ if (!checkAlreadyFirst(grammer[prodNo][comma[i] + j]))
{ first[firstcount] = grammer[prodNo][comma[i] + j];
firstcount++; } }
j++; } } } }
if (isEpsilon)
{ return 1; }
else
{ return 0; } }
void printFirst(char ch)
{ cout << "First of " << ch << ":{ ";
for (int i = 0; i < firstcount; i++)
{ cout << first[i] << " "; }
cout << "}" << endl; }
int main()
{ cout << "Enter the no of productions:";
cin >> sizeG;
for (int i = 0; i < sizeG; i++)
{ cout << "Enter the production " << i + 1 << ":";
cin >> grammer[i]; }
cout<<endl;
char findFirst;
cout << "Find First of:";
cin >> findFirst;
int check = First(findFirst);
if (check == 0 || check == 1)
{
printFirst(findFirst);
}
else
{
cout << "First Not found";
}
return 0;
}
Output -
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()
{ 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();
if (ch1 == 'x')
{ printf("$");
break; }
if (ch1 == '+' || ch1 == '/' || ch1 == '*' || ch1 == '-')
{ ch3 = pop();
if (ch3 != 'E')
{ cout << "errror"; }
else
{ push('E');
printstat(); } }
ch2 = ch1;
}
}
Output -
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","i","E^E"};
//(E) becomes )E( when pushed to stack
int top=0,l;
char prec[9][9]={
/input/
/*stack + - * / ^ i ( ) $ */
/* + */ '>', '>','<','<','<','<','<','>','>',
/* - */ '>', '>','<','<','<','<','<','>','>',
/* * */ '>', '>','>','>','<','<','<','>','>',
/* / */ '>', '>','>','>','<','<','<','>','>',
/* ^ */ '>', '>','>','>','<','<','<','>','>',
/* i */ '>', '>','>','>','>','e','e','>','>',
/* ( */ '<', '<','<','<','<','<','<','>','e',
/* ) */ '>', '>','>','>','>','e','e','>','>',
/* $ */ '<', '<','<','<','<','<','<','<','>',
};
int getindex(char c)
{ switch(c)
{ case '+':return 0;
case '-':return 1;
case '*':return 2;
case '/':return 3;
case '^':return 4;
case 'i':return 5;
case '(':return 6;
case ')':return 7;
case '$':return 8; } }
int shift()
{ stack[++top]=*(input+i++);
stack[top+1]='\0'; }
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]='E';
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++)
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: E->%s",lasthandle); } } }
if(strcmp(stack,"$E$")==0)
printf("\nAccepted;\n");
else
printf("\nNot Accepted;");
}
Output:

You might also like