0% found this document useful (0 votes)
9 views48 pages

Harish Compiler Desgin Lab Final

The best

Uploaded by

Sidharth V XII-B
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)
9 views48 pages

Harish Compiler Desgin Lab Final

The best

Uploaded by

Sidharth V XII-B
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/ 48

FORM NO.

-F/TL/021
REV.00Date 20.03.2020

RECORD NOTEBOOK

COMPILER DESIGN LAB-( EBCS22L06)

2024-2025 (ODD SEMESTER)

DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING

NAME : THARUN KUMAR

REGISTER NO : 221061101293

COURSE : B.TECH (CSE)

YEAR/SEM/SEC : III/V/F
FORM NO.-F/TL/021
REV.00Date 20.03.2020

BONAFIDE CERTIFICATE

Register No : 221061101293

Name of Lab : COMPILER DESIGN LAB (EBCS22L06)

Department : COMPUTER SCIENCE AND ENGINEERING

Certified that this is the bonafide record of work done by THARUN KUMAR ,

221061101293 of III Year B.Tech (CSE), Sec-F in the “COMPILER DESIGN LAB–(

EBCS22L06)” during the year 2024- 2025.

Signature of Lab-in-Charge Signature of Head of Dept

Submitted for the Practical Examination held on -------------------------

Internal Examiner External Examiner


INDEX

Exp. No. Date Title Pg. No. Sign

1 29-07-24 Implementation of symbol table 01

2 05-08-24 Develop a lexical analyzer to recognize a few


patterns in c (ex.Identifiers, constants, comments, operators 04
etc.)

3 12-08-24 Design a Lexical analyzer for the Given language should


ignore Redundant Spaces, tasks & new lines, comments 08
etc.

4 12-08-24 Program to recognize a valid variable which


starts with a letter followed by any number of letter 11
or digits

5 19-08-24 Program to implement NFAs that recognize identifiers, 13


constants, and operators of the mini language

6 24-08-24 Program to implement DFAs that recognize identifiers, 17


constants, and operators of the mini language

7 02-09-24 Program to eliminate Left Factoring 20

8 09-09-24 Program to Construct top-down parsing table 25

9 16-09-24 Program for Shift-reduce parsing algorithm 31

10 28-09-24 Program to Operator-Precedence parsing algorithm 34

11 30-09-24 Program to Construct LR-Parsing table 38

12 07-10-24 Program to Generate a code for a given intermediate code 41

13 14-10-24 Generate Machine code 43


EX.NO:1 DATE: 29-07-24

IMPLEMENTATION OF SYMBOL TABLE

AIM:

To write a program for implementing Symbol Table using C.

ALGORITHM:

Step1: Start the program for performing insert, display, delete, search and modify
option insymbol table.
Step2: Define the structure of the Symbol Table.
Step3: Enter the choice for performing the operations in the symbol Table.
Step4: If the entered choice is 1, search the symbol table for the symbol to be inserted. If the
symbol is already present, it displays “Duplicate Symbol”. Else, insert the symbol and the
corresponding address in the symbol table.
Step5: If the entered choice is 2, the symbols present in the symbol table are displayed.
Step6: If the entered choice is 3, the symbol to be deleted is searched in the symbol
table. Step7: If it is not found in the symbol table it displays “Label Not found”. Else,
the symbol isdeleted.
Step8: If the entered choice is 5, the symbol to be modified is searched in the symbol table.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
void main()
{
int i=0,j=0,x=0,n;
void *p,*add[5];
clrscr();
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $:");
while((c=getchar())!='$')
{
b[i]=c;
i++;
1
THARUNKUMAR 221061101293
}
n=i-1;
printf("Given Expression:");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol \t addr \t type");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c \t %d \t identifier\n",c,p);
x++;
j++;
}
else
{
ch=c;
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(ch);
add[x]=p;
d[x]=ch;
printf("\n %c \t %d \t operator\n",ch,p);
x++;
j++;
}}getch();
}}
2
THARUNKUMAR 221061101293
OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

3
THARUNKUMAR 221061101293
EX.NO:02 DATE: 05-08-24

DEVELOP A LEXICAL ANALYZER TO RECOGNIZE A FEW PATTERNS IN C (EX.


IDENTIFIERS, CONSTANTS, COMMENTS, OPERATORS ETC.)

AIM:
To develop a lexical analyzer to recognize a few patterns in c such as Identifiers, constants, comments,
operators

ALGORITHM:

Step1: Start the program.


Step2: Declare all the variables and file pointers. Step3: Display the input program.
Step4: Separate the keyword in the program and display it.
Step5: Display the header files of the input program
Step6: Separate the operators of the input program and display it.
Step7: Print the punctuation marks.
Step8: Print the constant that are present in input program.
Step9: Print the identifiers of the input program.

PROGRAM:

#include<string.h>
#include<ctype.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str)==0||str
cmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||strcmp("printf",str)==0||
strcmp("switch",str)==0||strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}
void main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
4
THARUNKUMAR 221061101293
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
f1=fopen("input.txt","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c))
{
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else
if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);
}
else
if(c==' '||c=='\t')
printf(" ");
else
if(c=='\n')
5
THARUNKUMAR 221061101293
lineno++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\n the no's in the program are:");
for(j=0;j<i;j++)
printf("\t%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("the keywords and identifier are:");
while((c=getc(f2))!=EOF)
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
fclose(f2);
f3=fopen("specialchar","r");
printf("\n Special Characters are");
while((c=getc(f3))!=EOF)
printf("\t%c",c);
printf("\n");
fclose(f3);
printf("Total no of lines are:%d",lineno);
getch();
}

6
THARUNKUMAR 221061101293
INPUT FILE
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
cout << "You entered " << number;
return 0;
}

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified

7
THARUNKUMAR 221061101293
EX.NO:03 DATE: 12-08-24

DESIGN A LEXICAL ANALYZER FOR THE GIVEN LANGUAGE SHOULD IGNORE


REDUNDANT SPACES, TABS AND NEW LINES, COMMENTS ETC.

AIM:
To write a program to design a lexical analyzer t h a t ignores redundant spaces, tabs and
new lines, comments etc.

ALGORITHM:

1. Start.
2. Read the input program code.
3. Initialize a state variable to handle various tokens.
4. Ignore spaces, tabs, and newlines by skipping over them.
5. Ignore comments:If a comment starts (// for single-line or /*...*/ for multi-line), skip it until it
ends.
6. Recognize keywords, identifiers, numbers, and operators using the
following: Keywords: Check if the token is a reserved word.
Identifiers: Start with a letter or underscore and contain alphanumeric characters or
underscores. Numbers: Numeric tokens consist of digits.
Operators: Recognize operators like +, -, *, /, etc.
7. Print the valid tokens.
8. End.

PROGRAM:

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

// Function to check if a token is an identifier


int isIdentifier(char *token) {
int i;
if (!isalpha(token[0]) && token[0] != '_') {
return 0; // Must start with a letter or underscore
}
for ( i = 1; token[i] != '\0'; i++) {
8
THARUNKUMAR 221061101293
if (!isalnum(token[i]) && token[i] != '_') {
return 0; // Remaining characters must be alphanumeric or underscores
}
}
return 1;
}

// Function to check if a token is a constant (integer only)


int isConstant(char *token) {
int i;
for ( i = 0; token[i] != '\0'; i++) {
if (!isdigit(token[i])) {
return 0; // Each character must be a digit
}
}
return 1;
}

// Function to check if a token is an operator


int isOperator(char *token) {
if (strlen(token) == 1 && strchr("+-*/=<>!", token[0]) != NULL) {
return 1; // Check for single-character operators
}
return 0;
}

int main() {
char input[100]; // Array to store the input string
char *token; // Pointer for tokenizing the string

clrscr(); // Clear the screen in Turbo C++

printf("Enter a string of tokens: ");


gets(input); // Read the input string (use `gets` for Turbo C++)

// Split the input string into individual tokens


9
THARUNKUMAR 221061101293
token = strtok(input, " ");
while (token != NULL) {
// Determine the type of each token and print the result
if (isIdentifier(token)) {
printf("Token: %s -> Type: Identifier\n", token);
} else if (isConstant(token)) {
printf("Token: %s -> Type: Constant\n", token);
} else if (isOperator(token)) {
printf("Token: %s -> Type: Operator\n", token);
} else {
printf("Token: %s -> Type: Unknown\n", token);
}

// Move to the next token


token = strtok(NULL, " ");
}

getch(); // Wait for a key press in Turbo C++


return 0;

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

10
THARUNKUMAR 221061101293
EX.NO:04 DATE: 12-08-24

PROGRAM TO RECOGNIZE A VALID VARIABLE WHICH


STARTS WITH A LETTER FOLLOWED BY ANY NUMBER OF LETTER OR DIGITS.

AIM:
To write a program to recognize a valid variable which starts with a letter followed by
any number of letter or digits.

ALGORITHM:

1. Input the variable name* from the user.


2. Check the first character*:
- If it is a letter (a-z or A-Z), proceed to the next step.
- If not, the variable is invalid.
3. Check the remaining characters*:
- Traverse through the rest of the characters.
- Each character must either be a letter (a-z, A-Z) or a digit (0-9).
- If any character does not meet these criteria, the variable is invalid.
4. If all characters meet the above conditions, *declare the variable as valid*.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#define MAX 100
int isValidVariable(char nstr[]);
int main() {
char str[MAX];
printf("Enter a variable name: ");
scanf("%s", str);
if (isValidVariable(str)) {
printf("'%s' is a valid variable name.\n", str);
} else {
printf("'%s' is not a valid variable name.\n", str);
}
getch();
11
THARUNKUMAR 221061101293
return 0;
}
int isValidVariable(char str[]) {
int i;
// Check if the first character is a letter
if (!isalpha(str[0])) {
return 0;
}
// Check if the rest of the characters are letters or digits
for (i = 1; str[i] != 0 ; i++) {
if (!isalnum(str[i])) {
return 0;
}
}
return 1;
}

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

12
THARUNKUMAR 221061101293
EX.NO:5 DATE:19-08-24

PROGRAM TO IMPLEMENT NFAS THAT RECOGNIZE IDENTIFIERS,


CONSTANTS, AND OPERATORS OF THE MINI LANGUAGE

AIM:

To write a program to implement NFAs that recognize identifiers, constants, and operators
of the mini language.

ALGORITHM:

1. **Initialize the NFA**:


- Create different states for each type of token (identifiers, constants, and operators).
- Set initial states for each NFA.

2. **Define Transitions**:
- For identifiers, start with an alphabet or underscore and allow transitions to
other alphanumeric or underscore characters.
- For constants, allow numeric digits, and manage the presence of decimal points for
floating- point numbers.
- For operators, match specific characters (`+`, `-`, `*`, `/`, etc.) directly.

3. **Simulate NFA**:
- Read the input string character by character and determine the transitions based on the
NFA definition.
- If the input string matches the expected pattern for any token, the NFA accepts it.

4. **Final State**:
- Once the input is completely read, check if the NFA is in an accepting state.

PROGRAM:

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

int isIdentifierNFA(char *token) {


int state = 0;
int i;
for (i = 0; token[i] != '\0'; i++) {
char ch = token[i];
switch (state) {
case 0:

13
THARUNKUMAR 221061101293
if (isalpha(ch) || ch == '_') {
state = 1;
} else {
return 0;
}
break;
case 1:
if (isalnum(ch) || ch == '_') {
state = 1;
} else {
return 0;
}
break;
}
}
return state == 1;
}
int isConstantNFA(char *token) {
int state = 0;
int i;
for (i = 0; token[i] != '\0'; i++) {
char ch = token[i];
switch (state) {
case 0:
if (isdigit(ch)) {
state = 1;
} else {
return 0;
}
break;
case 1:
if (isdigit(ch)) {
state = 1;
} else {
return 0;
}
14
THARUNKUMAR 221061101293
break;
}
}
return state == 1;
}
int isOperatorNFA(char *token) {
if (strlen(token) == 1 && strchr("+-*/=<>!", token[0]) != NULL) {
return 1;
}
return 0;
}
int main() {
char input[200];
char *token;
clrscr();
printf("Enter a string of tokens: ");
gets(input);
token = strtok(input, " ");
while (token != NULL) {

if (isIdentifierNFA(token)) {
printf("Token: %s -> Type: Identifier\n", token);
} else if (isConstantNFA(token)) {
printf("Token: %s -> Type: Constant\n", token);
} else if (isOperatorNFA(token)) {
printf("Token: %s -> Type: Operator\n", token);
} else {
printf("Token: %s -> Type: Unknown\n", token);
}
token = strtok(NULL, " ");
}
getch();
return 0;
}

15
THARUNKUMAR 221061101293
OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

16
THARUNKUMAR 221061101293
EX.NO:06 DATE: 24-08-24

PROGRAM TO IMPLEMENT DFAS THAT RECOGNIZE IDENTIFIERS, CONSTANTS,


AND OPERATORS OF THE MINI LANGUAGE

AIM:
To write a program to implement DFAs that recognize identifiers, constants, and operators of
the mini language

ALGORITHM:

1. Initialize DFA: Define initial and accepting states for each token type (identifier,
constant, and operator).
2. Process Input: Read the input string and determine state transitions based on characters.
3. Final State Check: After reading the entire input, check if the DFA is in an accepting
state.
4. Output: Print whether the input is recognized as an identifier, constant, operator, or is
unrecognized.

PROGRAM:

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

int isIdentifier(char *token) {


int i;
if (!isalpha(token[0]) && token[0] != '_') {
return 0;
}
for (i = 1; token[i] != '\0'; i++) {
if (!isalnum(token[i]) && token[i] != '_') {
return 0; }
}
return 1;
}
int isConstant(char *token) {
17
THARUNKUMAR 221061101293
int i;
for (i = 0; token[i] != '\0'; i++) {
if (!isdigit(token[i])) {
return 0;
}
}
return 1;
}
int isOperator(char *token) {
if (strlen(token) == 1 && strchr("+-*/=<>!", token[0]) != NULL) {
return 1;
}
return 0;
}
int main() {
char input[100];
char *token;
clrscr();
printf("Enter a string of tokens: ");
gets(input);
token = strtok(input, " ");
while (token != NULL) {
if (isIdentifier(token)) {
printf("Token: %s -> Type: Identifier\n", token);
} else if (isConstant(token)) {
printf("Token: %s -> Type: Constant\n", token);
} else if (isOperator(token)) {
printf("Token: %s -> Type: Operator\n", token);
} else {
printf("Token: %s -> Type: Unknown\n", token);
}
token = strtok(NULL, " ");
}
getch();
return 0;

18
THARUNKUMAR 221061101293
}

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

19
THARUNKUMAR 221061101293
EX.NO:07 DATE:02-09-24

PROGRAM TO ELIMINATE LEFT FACTORING

AIM:

To write a program that implements the elimination of left factoring.

ALGORITHM:

1. Input the grammar: Input a grammar with potential left-factoring issues.


2. Check for common prefixes: Identify common prefixes in the production rules.
3. Factor out the common prefix: For each production rule that shares a common prefix,
create a new rule for the differing part.
4. Rewrite the grammar: Update the grammar to remove left-factoring by introducing new
non- terminals.

PROGRAM:

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
//Structure Declaration
struct production
{
char lf;
char rt[10];
int prod_rear;
int fl;
};
struct production prodn[20],prodn_new[20]; //Creation of object
//Variables Declaration
int b=-1,d,f,q,n,m=0,c=0;
char terminal[20],nonterm[20],alpha[10],extra[10];
char epsilon='^';
//Beginning of Main Program
void main()
{

20
THARUNKUMAR 221061101293
clrscr();
//Input of Special characters
cout<<"\nEnter the number of Special characters(except non-terminals): ";
cin>>q;
cout<<"Enter the special characters for your production: ";
for(int cnt=0;cnt<q;cnt++)
{
cin>>alpha[cnt];
}
//Input of Productions
cout<<"\nEnter the number of productions: ";
cin>>n;
for(cnt=0;cnt<=n-1;cnt++)
{
cout<<"Enter the "<< cnt+1<<" production: ";
cin>>prodn[cnt].lf;
cout<<"->";
cin>>prodn[cnt].rt;
prodn[cnt].prod_rear=strlen(prodn[cnt].rt);
prodn[cnt].fl=0;
}
//Condition for left factoring
for(int cnt1=0;cnt1<n;cnt1++)
{
for(int cnt2=cnt1+1;cnt2<n;cnt2++)
{
if(prodn[cnt1].lf==prodn[cnt2].lf)
{
cnt=0;
int p=-1;
while((prodn[cnt1].rt[cnt]!='\0')&&(prodn[cnt2].rt[cnt]!='\0'))
{
if(prodn[cnt1].rt[cnt]==prodn[cnt2].rt[cnt])
{
extra[++p]=prodn[cnt1].rt[cnt];
prodn[cnt1].fl=1;
21
THARUNKUMAR 221061101293
prodn[cnt2].fl=1;
}
else
{
if(p==-1)
break;
else
{
int h=0,u=0;
prodn_new[++b].lf=prodn[cnt1].lf;
strcpy(prodn_new[b].rt,extra);
prodn_new[b].rt[p+1]=alpha[c];
prodn_new[++b].lf=alpha[c];
for(int g=cnt;g<prodn[cnt2].prod_rear;g++)
prodn_new[b].rt[h++]=prodn[cnt2].rt[g];
prodn_new[++b].lf=alpha[c];
for(g=cnt;g<=prodn[cnt1].prod_rear;g++)
prodn_new[b].rt[u++]=prodn[cnt1].rt[g];
m=1;
break;
}
}
cnt++;
}
if((prodn[cnt1].rt[cnt]==0)&&(m==0))
{
int h=0;
prodn_new[++b].lf=prodn[cnt1].lf;
strcpy(prodn_new[b].rt,extra);
prodn_new[b].rt[p+1]=alpha[c];
prodn_new[++b].lf=alpha[c];
prodn_new[b].rt[0]=epsilon;
prodn_new[++b].lf=alpha[c];
for(int g=cnt;g<prodn[cnt2].prod_rear;g++)
prodn_new[b].rt[h++]=prodn[cnt2].rt[g];
}
22
THARUNKUMAR 221061101293
if((prodn[cnt2].rt[cnt]==0)&&(m==0))
{
int h=0;
prodn_new[++b].lf=prodn[cnt1].lf;
strcpy(prodn_new[b].rt,extra);
prodn_new[b].rt[p+1]=alpha[c];
prodn_new[++b].lf=alpha[c];
prodn_new[b].rt[0]=epsilon;
prodn_new[++b].lf=alpha[c];
for(int g=cnt;g<prodn[cnt1].prod_rear;g++)
prodn_new[b].rt[h++]=prodn[cnt1].rt[g];
}
c++;
m=0;
}
}
}
//Display of Output
cout<<"\n\n********************************";
cout<<"\n AFTER LEFT FACTORING ";
cout<<"\n********************************";
cout<<endl;
for(int cnt3=0;cnt3<=b;cnt3++)
{
cout<<"Production "<<cnt3+1<<" is: ";
cout<<prodn_new[cnt3].lf;
cout<<"->";
cout<<prodn_new[cnt3].rt;
cout<<endl<<endl;
}
for(int cnt4=0;cnt4<n;cnt4++)
{
if(prodn[cnt4].fl==0)
{
cout<<"Production "<<cnt3++<<" is: ";
cout<<prodn[cnt4].lf;
23
THARUNKUMAR 221061101293
cout<<"->";
cout<<prodn[cnt4].rt;
cout<<endl<<endl;
}
}
getche();
}

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

24
THARUNKUMAR 221061101293
EX.NO:08 DATE: 09-09-24

PROGRAM TO CONSTRUCT A TOP-DOWN PARSING TABLE

AIM:

To write a program to construct a Top-Down parsing table.

ALGORITHM:

1. Input the Grammar: Provide the grammar, including the terminals and non-terminals.

2. Calculate FIRST Sets: For each non-terminal, calculate the FIRST set.

3. Calculate FOLLOW Sets: For each non-terminal, calculate the FOLLOW set.

4. Construct Parsing Table: For each production, if a terminal from the FIRST set appears, place the
production in the corresponding cell of the table.
5. If the production can derive epsilon (ε), add the production to the cell corresponding to
the FOLLOW set.
6. Parse Table Construction:

Populate the table based on the FIRST and FOLLOW sets.

PROGRAM:

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void error()
{
cout<<"not accepted";
getch();
exit(0);
}
void main(){
clrscr();
cout<<"Enter the string in single letter such as a+a*a \n\n";
char string[10],stack[10];
int i=0,k,top=0;

25
THARUNKUMAR 221061101293
cout<<"Enter the Expression :";
cin>>string;
int j=strlen(string);
string[j]='$';
string[++j]='\0';
cout<<string<<endl;
stack[top]='E';
cout<<"$"<<stack<<"\t";
for(k=i;k<j;k++)
{
cout<<string[k];
}
cout<<endl;
top++;
while(top!=0)
{
if(stack[top-1]==string[i])
{
i++;
top--;
stack[top]='\0';
}
else if(stack[top-1]=='E')
{
if(string[i]=='a')
{
top--;
stack[top]='D';
stack[++top]='T';
top++;
stack[top]='\0';
}
else if(string[i]=='(')
{
top--;
stack[top]='D';
26
THARUNKUMAR 221061101293
stack[++top]='T';
top++;
stack[top]='\0';
}
else error();}
else if(stack[top-1]=='D')
{
if(string[i]=='+')
{
top--;
stack[top]='D';
stack[++top]='T';
stack[++top]='+';
top++;
stack[top]='\0';
}
else if(string[i]==')')
{
top--;
stack[top]='\0';
}
else if(string[i]=='$')
{
top--;
stack[top]='\0';
}
else error();
}
else if(stack[top-1]=='T')
{
if(string[i]=='a')
{
top--;
stack[top]='s';
stack[++top]='F';
top++;
27
THARUNKUMAR 221061101293
stack[top]='\0';
}
else if(string[i]=='(')
{
top--;
stack[top]='s';
stack[++top]='F';
top++;
stack[top]='\0';
}
else error();
}
else if(stack[top-1]=='s')
{
if(string[i]=='+')
{
top--;
stack[top]='\0';
}
else if(string[i]=='*')
{
top--;
stack[top]='s';
stack[++top]='F';
stack[++top]='*';
top++;
stack[top]='\0';
}
else if(string[i]==')')
{
top--;
stack[top]='\0';
}
else if(string[i]=='$')
{
top--;
28
THARUNKUMAR 221061101293
stack[top]='\0';
}
else error;
}
else if(stack[top-1]=='F')
{
if(string[i]=='a')
{
top--;
stack[top]='a';
top++;
stack[top]='\0';
}
else if(string[i]=='(')
{
top--;
stack[top]=')';
stack[++top]='E';
stack[++top]='(';
top++;
stack[top]='\0';
}
else error();
}
else error();
cout<<"$"<<stack<<"\t";
for(k=i;k<j;k++)
{
cout<<string[k];
}
cout<<endl;
}
cout<<"accepted";
getch();
}

29
THARUNKUMAR 221061101293
OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

30
THARUNKUMAR 221061101293
EX.NO:09 DATE:16-09-24

PROGRAM FOR SHIFT-REDUCE PARSING ALGORITHM

AIM:

To write a program for Shift-reduce parsing algorithm.

ALGORITHM:

1. Input the Grammar: Provide the list of grammar productions.


2. Input the String: Read the string to be parsed.
3. Initialize: Initialize an empty stack and set the input pointer to the first symbol.
4. Shift or Reduce:Shift: Push the next input symbol onto the stack.
Reduce: If the top of the stack matches the right-hand side of any production, replace it
with the corresponding non-terminal.
5. Check for Acceptance: If the stack contains only the start symbol and the input
is fully consumed, accept the string. Otherwise, reject it.

PROGRAM:

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[25],stk[25];
int i,j,t=0,l,r;
clrscr();
printf("Enter the String : ");
scanf("%s",&str);
l=strlen(str);
str[l]='$';
stk[t]='$';
printf("Stack\t\tString\t\tAction\n-----------------------------------\n ");
for(i=0;i<l;i++)
{
if(str[i]=='i')

31
THARUNKUMAR 221061101293
{
t++;
stk[t]=str[i];
stk[t+1]=str[i+1];
for(j=0;j<=t+1;j++)
printf("%c",stk[j]);
printf("\t\t ");
for(j=i+2;j<=l;j++)
printf("%c",str[j]);
printf("\t\tShift");
printf("\n ");
stk[t]='E';
i++;
}
else
{
t++;
stk[t]=str[i];
}
for(j=0;j<=t;j++)
printf("%c",stk[j]);
printf("\t\t ");
for(j=i+1;j<=l;j++)
printf("%c",str[j]);
if(stk[t]=='+' || stk[t]=='*')
printf("\t\tShift");
else
printf("\t\tReduce");
printf("\n ");
}
while(t>1)
{
if(stk[t]=='E' && (stk[t-1]=='+' || stk[t-1]=='*') && stk[t-2]=='E')
{
t-=2;
for(j=0;j<=t;j++)
32
THARUNKUMAR 221061101293
printf("%c",stk[j]);
printf("\t\t");
printf(" %c",str[l]);
printf("\t\tReduce\n ");
}
else
t-=2;
}
if(t==1 && stk[t]!='+' && stk[t]!='*')
printf("\nThe Given String is Valid\n\n");
else
printf("\nThe Given String is Invalid\n\n");
getch();
}

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

33
THARUNKUMAR 221061101293
EX.NO:10 DATE: 28-09-24

PROGRAM FOR OPERATOR-PRECEDENCE PARSING

AIM:

To write a program for implementing Operator-Precedence Parsing.

ALGORITHM:

1. Input the Grammar: Read the grammar and define the operator precedence table.

2. Initialize: Initialize the stack with the start symbol or a special symbol ($).

3. Shift or Reduce:Shift: If the input symbol has a higher precedence than the symbol on top of the
stack, push the input symbol onto the stack.
Reduce: If the symbol on top of the stack has higher precedence than the input symbol,
reduce the symbols on the stack using a production rule.
4. Check for Acceptance: If the input is completely consumed, and the stack contains the
start symbol and the $ symbol, the input is accepted. Otherwise, it's rejected.

PROGRAM:

#include<stdio.h>
#include<conio.h>
int find(char a)
{
switch(a)
{
case 'a':
return 0;
case '+':
return 1;
case '*':
return 2;
case '$':
return 3;
}
return 0;}
void display(char a[],int top1,char b[],int top2)

34
THARUNKUMAR 221061101293
{
int i;
for(i=0;i<=top1;i++)
printf("%c",a[i]);
printf("\t");
for(i=top2;i<strlen(b);i++)
printf("%c",b[i]);
printf("\n");
}
int main()
{
char table[][4]= {' ','>','>','>','<','<','<','>','<','>','<','>','<','<','<',' '};
char input[10];
char stack[10]={'$'};
int top_stack=0,top_input=0,i,j;
clrscr();
printf("operator precedence parsing for E->E+E/E*E/a\n");
printf("enter the string\n");
scanf("%s",input);
strcat(input,"$");
printf("stack\tinput\n");
display(stack,top_stack,input,top_input);
while(1){
if((stack[top_stack]=='$')&&(input[top_input]=='$'))
{
printf("string accepted");
break;
}
if(table[find(stack[top_stack])][find(input[top_input])]==' ')
{
printf("parse error");
getch();
exit(0);
}
if(table[find(stack[top_stack])][find(input[top_input])]=='<')
{
35
THARUNKUMAR 221061101293
stack[++top_stack]='<';
stack[++top_stack]=input[top_input];
top_input++;
display(stack,top_stack,input,top_input);
continue;
}
if(table[find(stack[top_stack])][find(input[top_input])]=='>')
{
stack[++top_stack]='>';
display(stack,top_stack,input,top_input);
top_stack-=3;
display(stack,top_stack,input,top_input);
}
}getch();
return 0;}

36
THARUNKUMAR 221061101293
OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

37
THARUNKUMAR 221061101293
EX.NO:11 DATE: 30-09-24

PROGRAM TO CONSTRUCT LR-PARSING TABLE

AIM:

To write a c program to construct LR-parsing table.

ALGORITHM:

1. Get the input expression and store it in the input buffer.


2. Read the data from the input buffer one at the time and convert in to corresponding Non
Terminal using production rules available.
3. Perform push & pop operation for LR parsing table construction.
4. Display the result with conversion of corresponding input symbols to production and
production reduction to start symbol. No operation performed on the operator.

PROGRAM:

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

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'; // Return 'x' if the stack is empty
}

void printstat() {
int i;
printf("\n\t\t\t $");
for (i = 0; i <= top; i++)
printf("%c", stack[i]);
}

38
THARUNKUMAR 221061101293
void main() {
int i, j, l;
char s1[20], ch1, ch2, ch3;

printf("\n\n\t\t LR PARSING");
printf("\n\t\t ENTER THE EXPRESSION: ");
scanf("%s", s1);
l = strlen(s1);

printf("\n\t\t $");

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


if (s1[i] == 'i' && s1[i + 1] == 'd') { // Assume 'id' is a terminal
s1[i] = ' '; // Replace 'id' with a space
s1[i + 1] = 'E'; // Map 'id' to non-terminal 'E'
printstat();
printf(" id");
push('E'); // Push non-terminal onto the stack
printstat();
} else if (s1[i] == '+' || s1[i] == '-' || s1[i] == '*' || s1[i] == '/') {
push(s1[i]); // Push operator onto the stack
printstat();
}
}

printstat();

// Process the stack until it's empty


while (top >= 0) {
ch1 = pop();

if (ch1 == 'x') { // If the stack is empty


printf("\n\t\t\t $");
break;
}

if (ch1 == '+' || ch1 == '/' || ch1 == '*' || ch1 == '-') {


ch3 = pop();
if (ch3 != 'E') { // Check if the top of the stack is 'E'
printf("error");
exit(1);
} else {
push('E'); // If 'E' is found, push it back
printstat();
}
}
ch2 = ch1; // Assign for future operations
}
getch(); // Wait for user input before closing
}

39
THARUNKUMAR 221061101293
OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

40
THARUNKUMAR 221061101293
EX.NO: 12 DATE: 07-10-24

PROGRAM TO GENERATE A CODE FOR A GIVEN INTERMEDIATE CODE

AIM:

To write a program to Generate a code for a given intermediate code.

ALGORITHM:

1. Start.
2. Get address code sequence.
3. Determine current location of 3 using. address (for 1st operand).
4. If current location not already exist. generate move (B,O).
5. Update address of A(for 2nd operand).
6. If current value of B and () is null,exist.
7. If they generate operator () A,3 ADPR.
8. Store the move instruction in memory.

PROGRAM:

# include<stdio.h>
# include<conio.h>
# include<ctype.h>
char s[20],t[20];
void main()
{
clrscr();
printf("Enter the expression: ");
scanf("%s",&t);
if(isalpha(t[2])&&isalpha(t[0])&&isalpha(t[4]))
{
printf("Mov%c,R \n",t[2]);
}
else
printf("Enter correct exp: ");
switch(t[3])
{
case '*':
printf("MUL%c,R \n",t[4]);
printf("MOVR,%c \n",t[0]);
break;

41
THARUNKUMAR 221061101293
case '+':
printf("ADD%c,R \n",t[4]);
printf("MOVR,%c \n",t[0]);
break;
case '-':
printf("SUB%c,R \n",t[4]);
printf("MOVR,%c \n",t[0]);
break;
case '/':
printf("DIV%c,R \n",t[4]);
printf("MOVR,%c \n",t[0]);
break;
default:
printf("INVALID OPERATOR");
break;
}
getch();
}

OUTPUT:

RESULT:

Thus the program is executed successfully and the output was verified .

42
THARUNKUMAR 221061101293
EX.NO:13 DATE: 14-10-24

GENERATE MACHINE CODE

AIM:

To write a program to generate the machine code.

ALGORITHM:

1. START
2. Input source code.
3. Perform Lexical Analysis: Tokenize the source code.
4. Perform Syntax Analysis: Build a parse tree and Ensure the syntax is correct.
5. Perform Semantic Analysis: Check types and declarations.
6. Generate Intermediate Code: Convert parse tree to an intermediate representation (e.g., three-
address code).
7. Optimize Intermediate Code (Optional): Apply optimization techniques.
8. Generate Machine Code: Map each intermediate operation to a machine instruction and
Assign registers and memory addresses.
9. Output the Machine Code.
10. END

PROGRAM:

#include <stdio.h>
#include<conio.h>
#include <string.h>

void generate_code(char opcode[], char arg1[], char arg2[], char result[]) {


if (strcmp(opcode, "ADD") == 0) {
printf("MOV AX, %s\n", arg1); // Move arg1 to AX register
printf("ADD AX, %s\n", arg2); // Add arg2 to AX register
printf("MOV %s, AX\n", result); // Store the result
}
else if (strcmp(opcode, "SUB") == 0) {
printf("MOV AX, %s\n", arg1);
printf("SUB AX, %s\n", arg2);
printf("MOV %s, AX\n", result);

43
THARUNKUMAR 221061101293
}
else if (strcmp(opcode, "MUL") == 0) {
printf("MOV AX, %s\n", arg1);
printf("MOV BX, %s\n", arg2); // Move arg2 to BX for multiplication
printf("MUL BX\n"); // Multiply AX by BX
printf("MOV %s, AX\n", result);
}
else if (strcmp(opcode, "DIV") == 0) {
printf("MOV AX, %s\n", arg1);
printf("MOV BX, %s\n", arg2); // Move arg2 to BX for division
printf("DIV BX\n"); // Divide AX by BX
printf("MOV %s, AX\n", result);
}
else {
printf("Unsupported operation: %s\n", opcode);
}
}

int main() {
char opcode[10], arg1[10], arg2[10], result[10];
int n, i;
clrscr();
printf("Enter the number of instructions: ");
scanf("%d", &n);

for (i = 0; i < n; i++) {


printf("Enter instruction %d (format: OPCODE ARG1 ARG2 RESULT): ", i + 1);
scanf("%s %s %s %s", opcode, arg1, arg2, result);
generate_code(opcode, arg1, arg2, result);
}
getch();
return 0;
}

44
THARUNKUMAR 221061101293
OUTPUT:

RESULT :

Thus the program is executed successfully and the output was verified .

45
THARUNKUMAR 221061101293

You might also like