Compiler Construction Lab File Bachelor of Technology (Computer Science and Engineering) Semester-6

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

Compiler Construction

LAB FILE

BACHELOR OF TECHNOLOGY

(Computer Science and Engineering)

SEMESTER-6

Department of Computer Science & Engineering


AMITY SCHOOL OF ENGINEERING AND TECHNOLOGY AMITY UNIVERSITY UTTAR PRADESH
NOIDA, (U.P.), INDIA

SUBMITTED TO-
Dr. Richa Tiwari

SUBMITTED BY-
Vridhi Gupta
A2305218276
CONTENT
Program Name of Programs Date of Date of Max. Marks Signature of
No. allotment evaluation Marks obtained Faculty
of exp.

1 Write a program to 2021-03-19 1


convert a Regular
Expression from Infix
to Postfix

2 Write a program to 2021-03-19 1


convert a Regular
Expression of Infix to
Prefix.

3 Write a program to 2021-03-19 1


check whether string
is accepted or not by
given grammar S->aS,
S->Sb, S->ab

4 Write a Program to 2021-03-19 1


count the number of
tokens in an
expression . O/P
Token Type- Identifier
, Operator and
Constants

5 Write a Program to 2021-03-19 1


check whether the
entered string belongs
to given regular
expression or not.

6 Write a Program to 2021-03-19 1


convert any particular
Regular Expression
into NFA (a/b)*abb
7 Write a program to 2021-03-19 1
eliminate left
recursion

8 Write a program for 2021-03-19 1


Recursive Descent
Calculator.

9 Write a program 2021-03-19 1


which accepts a
regular grammar with
no left-recursion, and
no null-production
rules, and then it
accepts a string and
reports whether the
string is accepted by
the grammar or not.
10 Write a program to 2021-03-19 1
check if a expression is
valid or invalid. If it is
valid, then evaluate it
Experiment -1

Aim: Write a program to convert a Regular Expression from Infix to Postfix

Code: #include <stdio.h>


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

struct Stack
{
int top;
unsigned capacity;
int* array;
};

struct Stack* createStack( unsigned capacity )


{
struct Stack* stack = (struct Stack*)
malloc(sizeof(struct Stack));

if (!stack)
return NULL;

stack->top = -1;
stack->capacity = capacity;

stack->array = (int*) malloc(stack->capacity *


sizeof(int));
return stack;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1 ;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}

int isOperand(char ch)


{
return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z');
}
int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

int infixToPostfix(char* exp)


{
int i, k;

struct Stack* stack = createStack(strlen(exp));


if(!stack) // See if stack was created successfully
return -1 ;

for (i = 0, k = -1; exp[i]; ++i)


{

if (isOperand(exp[i]))
exp[++k] = exp[i];

else if (exp[i] == '(')


push(stack, exp[i]);
else if (exp[i] == ')')
{
while (!isEmpty(stack) && peek(stack) != '(')
exp[++k] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1; // invalid expression
else
pop(stack);
}
else // an operator is encountered
{
while (!isEmpty(stack) &&
Prec(exp[i]) <= Prec(peek(stack)))
exp[++k] = pop(stack);
push(stack, exp[i]);
}

while (!isEmpty(stack))
exp[++k] = pop(stack );

exp[++k] = '\0';
printf( "%s", exp );
}
int main()
{
printf("Enter the code to change from Infix to Postfix \n");
printf("a+b*(c^d-e)^(f+g*h)-i \n");
printf("Postfix:\t");
char exp[] = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp);
return 0;
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B. Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -2

Aim: Write a program to convert a Regular Expression of Infix to Prefix.

Code: #include <bits/stdc++.h>


using namespace std;

bool isOperator(char c)
{
return (!isalpha(c) && !isdigit(c));
}

int getPriority(char C)
{
if (C == '-' || C == '+')
return 1;
else if (C == '*' || C == '/')
return 2;
else if (C == '^')
return 3;
return 0;
}

string infixToPostfix(string infix)


{
infix = '(' + infix + ')';
int l = infix.size();
stack<char> char_stack;
string output;

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

if (isalpha(infix[i]) || isdigit(infix[i]))
output += infix[i];

else if (infix[i] == '(')


char_stack.push('(');

else if (infix[i] == ')')


{
while (char_stack.top() != '(')
{
output += char_stack.top();
char_stack.pop();
}

char_stack.pop();
}

else {
if (isOperator(char_stack.top()))
{
while ((getPriority(infix[i])
< getPriority(char_stack.top()))
|| (getPriority(infix[i])
<= getPriority(char_stack.top()) && infix[i] == '^'))
{
output += char_stack.top();
char_stack.pop();
}

char_stack.push(infix[i]);
}
}
}
return output;
}

string infixToPrefix(string infix)


{

int l = infix.size();

reverse(infix.begin(), infix.end());

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

if (infix[i] == '(') {
infix[i] = ')';
i++;
}
else if (infix[i] == ')') {
infix[i] = '(';
i++;
}
}
string prefix = infixToPostfix(infix);

reverse(prefix.begin(), prefix.end());

return prefix;
}

int main()
{

cout<<"\nEnter the Regular Expression :\n";


cout<<"x+y*z/w+u \n";
cout<<"prefix Expression:\n";
string s = ("x+y*z/w+u");
cout << infixToPrefix(s) << std::endl;
return 0;
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -3

Aim: Write a program to check whether string is accepted or not by given grammar
S->aS

S->Sb

S->ab

Code: #include<stdio.h>
#include<string.h>
int can_be_generated(char *str)
{
int len=strlen(str);
int flag=1;
int i=0;
while(1){
if(((i+2)<=(len-1)) &&(str[i]=='a' && str[i+1]=='b' && str[i+2]=='b')){
i=i+3;
continue;
}
else if(((i+1)<=(len-1)) && (str[i]=='a' && str[i+1]=='b')){
i=i+2;
continue;
}
else if((i<=(len-1)) && (str[i]=='a')){
i=i+1;
continue;
}
else if((i==len)&&(str[i]=='\0')){
break;
}
else{
flag=0;
break;
}
}
if(flag==0){
return 0;
}
else
printf("\n accepted \n");
}

int main(){
printf("The grammar is: S->aS, S->Sb, S->ab\n");
printf("Enter the string to be checked:\n");
printf("ab");
printf(" %d ",can_be_generated("ab"));

return 0;
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -4

Aim: Write a Program to count the number of tokens in an expression . O/P Token Type-
Identifier , Operator and Constants

Code: #include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>

void main(){

int it=0,m,c=0,o=0,i,j;
char b[30],operator[30],identifier[30],constant[30];

printf("enter the string: ");


scanf("%s",&b);
for(i=0;i<strlen(b);i++){

if(isspace(b[i])){
continue;
}
else if(isalpha(b[i])){
identifier[it] =b[i];
it++;
}
else if(isdigit(b[i])){
m=(b[i]-'0');
i=i+1;
while(isdigit(b[i])){
m=m*10 + (b[i]-'0');
i++;
}
i=i-1;
constant[c]=m;
c++;
}
else{
if(b[i]=='*'){
operator[o]='*';
o++;
}
else if(b[i]=='-'){
operator[o]='-';
o++;
}
else if(b[i]=='+'){
operator[o]='+';
o++;
}
else if(b[i]=='='){
operator[o]='=';
o++;
}
else if(b[i]==':'){
operator[o]=':';
o++;
}
}
}

printf(" identifiers: ");


for(j=0;j<it;j++){
printf("%c ",identifier[j]);
}
printf("\n constants: ");
for(j=0;j<c;j++){
printf("%d ",constant[j]);
}
printf("\n operators: ");
for(j=0;j<o;j++){
printf("%c ",operator[j]);
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -5

Aim: Write a Program to check whether the entered string belongs to given regular
expression or not.

Code: print('Regular expression used is: (f+g)*cbb')


exp=input('Enter a string to be checked :')

flag=0
l=len(exp)
if l<3:
flag=-1

if exp[l-1]=='b' and exp[l-2]=='b' and exp[l-3]=='c':


flag=0
else:
flag=-1

if(l>3):
for i in range(0,l-3):
if exp[i]!='f' and exp[i]!='g':
flag=-1
break

if(flag==0):
print("String accepted")
else:
print("string not accepted")

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -6

Aim: Write a Program to convert any particular Regular Expression into NFA (a/b)*abb

Code: #include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char reg[20];
int q[20][3],i,j,len,a,b;
for(a=0;a<20;a++)
{
for(b=0;b<3;b++)
{
q[a][b]=0;
}
}
printf("Regular expression: \n");
scanf("%s",reg);
len=strlen(reg);
i=0;
j=1;
while(i<len)
{
if(reg[i]=='a'&&reg[i+1]!='/'&&reg[i+1]!='*')
{
q[j][0]=j+1;
j++;
}
if(reg[i]=='b'&&reg[i+1]!='/'&&reg[i+1]!='*')
{
q[j][1]=j+1;
j++;
}
if(reg[i]=='e'&&reg[i+1]!='/'&&reg[i+1]!='*')
{
q[j][2]=j+1;
j++;
}
if(reg[i]=='a'&&reg[i+1]=='/'&&reg[i+2]=='b')
{
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][0]=j+1;
j++;
q[j][2]=j+3;
j++;
q[j][1]=j+1;
j++;
q[j][2]=j+1;
j++;
i=i+2;
}
if(reg[i]=='b'&&reg[i+1]=='/'&&reg[i+2]=='a')
{
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][1]=j+1;
j++;
q[j][2]=j+3;
j++;
q[j][0]=j+1;
j++;
q[j][2]=j+1;
j++;
i=i+2;
}
if(reg[i]=='a'&&reg[i+1]=='*')
{
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][0]=j+1;
j++;
q[j][2]=((j+1)*10)+(j-1);
j++;
}
if(reg[i]=='b'&&reg[i+1]=='*')
{
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][1]=j+1;
j++;
q[j][2]=((j+1)*10)+(j-1);
j++;
}
if(reg[i]==')'&&reg[i+1]=='*')
{
q[0][2]=((j+1)*10)+1;
q[j][2]=((j+1)*10)+1;
j++;
}
i++;
}
printf("Transition function \n");
for(i=0;i<=j;i++)
{
if(q[i][0]!=0)
printf("\n q[%d,a]-->%d",i,q[i][0]);
if(q[i][1]!=0)
printf("\n q[%d,b]-->%d",i,q[i][1]);
if(q[i][2]!=0)
{
if(q[i][2]<10)
printf("\n q[%d,e]-->%d",i,q[i][2]);
else
printf("\n q[%d,e]-->%d & %d",i,q[i][2]/10,q[i][2]%10);
}
getch();
}
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -7

Aim: Write a program to eliminate left recursion

Code: import java.util.*;


public class Main {
public static void main (String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("No. of productions u want- ");
int n = s.nextInt();
s.nextLine();
List<String> lhs = new ArrayList<>();
List<String> rhs = new ArrayList<>();
for(int i = 0; i < n; i++) {
System.out.println("Enter Production " + (i+1) + ": ");
System.out.println("Enter the LHS: ");
lhs.add(s.nextLine());
System.out.println("Enter the RHS: ");
rhs.add(s.nextLine());
}
for(int i = 0; i < n; i++) {
if(lhs.get(i).charAt(0) == rhs.get(i).charAt(0)) {
rhs.set(i, rhs.get(i).replaceFirst(lhs.get(i), lhs.get(i) + "'"));
lhs.add(lhs.get(i) + "'");
rhs.add(rhs.get(i).substring(2) + lhs.get(i) + "'");
lhs.add(lhs.get(i) + "'");
rhs.add("e");
}
}

System.out.println("Left Recursion has been removed :-");


for(int i = 0; i < lhs.size(); i++) {
System.out.println(lhs.get(i) + " --> " + rhs.get(i));
}
}
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -8

Aim: Write a program for Recursive Descent Calculator.

Code:
#include <stdio.h>
#include <string.h>

void A();
void B();
void C();
void As();
void Bs();

char input[100];
int i,error;

int main()
{
printf("Enter the input\n");
gets(input);
A();
if (i==strlen(input) && error == 0)
{
printf("String is accepted\n");
}
else
{
printf("String is not accepted\n");
}
}

void A()
{
B();
As();
}

void B()
{
C();
Bs();
}

void As()
{
if (input [i] =='+')
{
i++;
B();
As();
}
}

void Bs()
{
if (input [i] =='*')
{
i++;
C();
Bs();
}
}

void C()
{
if (input [i] =='a')
{
i++;
}
else if (input [i] =='(')
{
i++;
B();
if (input [i] ==')')
{
i++;
}
else
{
error = 1;
}
}
else
{
error = 1;
}
}

Output:
Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment
Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -9
Aim: Write a program which accepts a regular grammar with no left-recursion, and no null-
production rules, and then it accepts a string and reports whether the string is accepted by the
grammar or not.

Code:
#include<iostream>
#include <string.h>
using namespace std;
string l;
string z;
int flag;
int j=0;
int E();
int Edash();
void match(string t);
int main()
{ cout<<"enter the input string = ";
cin>>l;
E();
if (flag == 1)
{
cout<<"Parsing unSuccessful"; }
else if (l[j] == '$')
{
cout<<"Parsing Successful"; }
}
int E()
{ if (l[j] == 'i')
{
match("i");
Edash();
}
}
void match(string t)
{
z=l[j];
if(z==t)
{
j=j+1;
}
else
flag=1;
}
int Edash()
{
if(l[j]=='+')
{
match("+");
match("i");
Edash();
}
else
return 0;
}
Output:

Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment


Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 
Experiment -10
Aim: Write a program to check if a expression is valid or invalid. If it is valid,
then evaluate it

Code:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int flag=0;
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);

flag=-1;
}
else if (validIdentifier(subStr) == false
&& isDelimiter(str[right - 1]) == false)
printf("'%s' IS NOT A VALID IDENTIFIER\n",
subStr);
left = right;
}
}
return;
}
int main()
{
char str[100] = "float c = d + e; ";
int flag=0;
parse(str);

if(flag==0)
{ int c,d,e;

printf("Enter value of d");


scanf("%d",&d);
printf("Enter value of e");
scanf("%d",&e);
c=d+e;
printf("Result is %d",c);

return 0;
}
Output:

Internal Assessment (Mandatory Experiment) Sheet for Lab Experiment


Department of Computer Science & Engineering
Amity University, Noida (UP)

Programme B.Tech-CSE Course Name Compiler Construction lab 

Course Code CSE304 Semester 6th

Student Name Vridhi Gupta Enrolment No. A2305218276

Marking Criteria

Criteria Total Marks Marks Obtained Comments

Concept (A) 2    

Implementation (B) 2    

Performance (C) 2    

Total 6
 

You might also like