Sie sind auf Seite 1von 64

Ex.

No:1 IMPLEMENTATION OF SYMBOL TABLE


Date:

AIM:
To write a program in C to demonstrate symbol table management using C program.

ALGORITHM:

Step-1. Start the program for performing insert, display, search and modify option in symbol
table

Step-2. Define the structure of the Symbol Table

Step-3. Enter the choice for performing the operations in the symbol Table

Step-4. 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.

Step-5. If the entered choice is 2, the symbols present in the symbol table are displayed.

Step-6. If the entered choice is 3, the symbol is searched in the symbol table. If it is not found in
the symbol table it displays "Label Not found".

Step-7. If the entered choice is 4, the symbol to be modified is searched in the symbol table. The
address of the label can be modified.

Step-8. Enter choice 5 to exit the program

PROGRAM:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<stdlib.h>
void create();
void search();

Download Useful Materials from Rejinpaul.com


void display();
struct node
{
char data[500];
struct node *nxt;
}*start,q;
void main()
{
int ch;
clrscr();
while(1)
{
printf("enter the operation\n1.create\n2.display\n3.search\n4.exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:
goto halt;
default:
printf("enter valid choice");
break;
}

Download Useful Materials from Rejinpaul.com


}
halt:printf("Terminated");
}
void create()
{
struct node *temp,*q;
temp=malloc(sizeof(struct node));
printf("enter the data");
scanf("%s",temp->data);
temp->nxt=NULL;
if(start==NULL)
start=temp;
else
{
q=start;
while(q->nxt!=NULL)
q=q->nxt;
q->nxt=temp;
}
}
void display()
{
struct node *q;
q=start;
if(start==NULL)
{
printf("symbol table is empty\n");
}
else
{
printf("\ndata\taddress\n");

Download Useful Materials from Rejinpaul.com


while(q!=NULL)
{
printf("%s\t%p\n",q->data,q);
q=q->nxt;
}
}
}
void search()
{
struct node *q;
char x[50];
int count=1,flag=0;
printf("enter the data to be searched");
scanf("%s",x);
q=start;
while(q!=NULL)
{
if(strcmp(q->data,x)==0)
{
printf("element fount in %p address\n",q);
flag=1;
break;
}
q=q->nxt;
count=count+1;
}
if(flag==0)
printf("the element is not found in the list\n");
}

Download Useful Materials from Rejinpaul.com


OUTPUT:

RESULT:
Thus Symbol table is implemented using data structure in C and output is verified.

Download Useful Materials from Rejinpaul.com


Ex.No.2 DEVELOP A LEXICAL ANALYZER TO RECOGNIZE A FEW
Date : PATTERNS IN C

AIM:
To develop a lexical analyzer to identify identifiers, constants, comments, operators etc
using C program

ALGORITHM:

Step-1: Start the program.


Step-2: Declare all the variables and file pointers.
Step-3 : D i s p l a y t h e i n p u t p r o g r a m .
S t e p - 4 : Separate the keyword in the program and display it.
Step- 5:Display the header files of the input program
Step-6:Separate the operators of the input program and display it.
Step-7:Print the punctuation marks.
S t e p - 8:Print the constant that are present in input program.
Step-9 :Print the identifiers of the input program.

PROGRAM:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void removeduplicate();
void final();
int Isiden(char ch);
int Isop(char ch);
int Isdel(char ch);
int Iskey(char * str);
void removeduplicate();

Download Useful Materials from Rejinpaul.com


char op[8]={'+','-','*','/','=','<','>','%'};
char del[8]={'}','{',';','(',')','[',']',','};
char *key[]={"int","void","main","char","float"};

//char *operato[]={"+","-","/","*","<",">","=","%","<=",">=","++"};

int idi=0,idj=0,k,opi=0,opj=0,deli=0,uqdi=0,uqidi=0,uqoperi=0,kdi=0,liti=0,ci=0;
int uqdeli[20],uqopi[20],uqideni[20],l=0,j;
char uqdel[20],uqiden[20][20],uqop[20][20],keyword[20][20];
char iden[20][20],oper[20][20],delem[20],litral[20][20],lit[20],constant[20][20];

void lexanalysis(char *str)


{
int i=0;
while(str[i]!='\0')
{
if(Isiden(str[i])) //for identifiers
{
while(Isiden(str[i]))
{
iden[idi][idj++]=str[i++];
}
iden[idi][idj]='\0';
idi++;idj=0;
}
else
if(str[i]=='"') //for literals
{
lit[l++]=str[i];
for(j=i+1;str[j]!='"';j++)
{

Download Useful Materials from Rejinpaul.com


lit[l++]=str[j];
}
lit[l++]=str[j];lit[l]='\0';
strcpy(litral[liti++],lit);
i=j+1;
}
else
if(Isop(str[i])) // for operators
{
while(Isop(str[i]))
{
oper[opi][opj++]=str[i++];
}
oper[opi][opj]='\0';
opi++;opj=0;
}
else
if(Isdel(str[i])) //for delemeters
{
while(Isdel(str[i]))
{
delem[deli++]=str[i++];
}
}
else
{
i++;
}
}

removeduplicate();

Download Useful Materials from Rejinpaul.com


final();
}

int Isiden(char ch)


{
if(isalpha(ch)||ch=='_'||isdigit(ch)||ch=='.')
return 1;
else
return 0;
}

int Isop(char ch)


{
int f=0,i;
for(i=0;i<8&&!f;i++)
{
if(ch==op[i])
f=1;
}
return f;
}

int Isdel(char ch)


{
int f=0,i;
for(i=0;i<8&&!f;i++)
{
if(ch==del[i])
f=1;
}
return f;

Download Useful Materials from Rejinpaul.com


}

int Iskey(char * str)


{
int i,f=0;
for(i=0;i<5;i++)
{
if(!strcmp(key[i],str))
f=1;
}
return f;
}

void removeduplicate()
{
int i,j;
for(i=0;i<20;i++)
{
uqdeli[i]=0;
uqopi[i]=0;
uqideni[i]=0;
}
for(i=1;i<deli+1;i++) //removing duplicate delemeters
{
if(uqdeli[i-1]==0)
{
uqdel[uqdi++]=delem[i-1];
for(j=i;j<deli;j++)
{
if(delem[i-1]==delem[j])
uqdeli[j]=1;

Download Useful Materials from Rejinpaul.com


}
}
}

for(i=1;i<idi+1;i++) //removing duplicate identifiers


{
if(uqideni[i-1]==0)
{
strcpy(uqiden[uqidi++],iden[i-1]);
for(j=i;j<idi;j++)
{
if(!strcmp(iden[i-1],iden[j]))
uqideni[j]=1;
}
}
}

for(i=1;i<opi+1;i++) //removing duplicate operators


{
if(uqopi[i-1]==0)
{
strcpy(uqop[uqoperi++],oper[i-1]);
for(j=i;j<opi;j++)
{
if(!strcmp(oper[i-1],oper[j]))
uqopi[j]=1;
}
}
}

Download Useful Materials from Rejinpaul.com


void final()
{
int i=0;
idi=0;
for(i=0;i<uqidi;i++)
{
if(Iskey(uqiden[i])) //identifying keywords
strcpy(keyword[kdi++],uqiden[i]);
else
if(isdigit(uqiden[i][0])) //identifying constants
strcpy(constant[ci++],uqiden[i]);
else
strcpy(iden[idi++],uqiden[i]);
}

// printing the outputs

printf("\n\tDelemeter are : \n");


for(i=0;i<uqdi;i++)
printf("\t%c\n",uqdel[i]);

printf("\n\tOperators are : \n");


for(i=0;i<uqoperi;i++)
{
printf("\t");
puts(uqop[i]);
}

printf("\n\tIdentifiers are : \n");


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

Download Useful Materials from Rejinpaul.com


printf("\t");
puts(iden[i]);
}

printf("\n\tKeywords are : \n");


for(i=0;i<kdi;i++)
{
printf("\t");
puts(keyword[i]);
}

printf("\n\tConstants are :\n");


for(i=0;i<ci;i++)
{
printf("\t");
puts(constant[i]);
}

printf("\n\tLiterals are :\n");


for(i=0;i<liti;i++)
{
printf("\t");
puts(litral[i]);
}
}
void main()
{
char str[50];
//clrscr();
printf("\nEnter the string : ");
scanf("%[^\n]c",str);

Download Useful Materials from Rejinpaul.com


lexanalysis(str);
//getch();
}

OUTPUT:
Enter the string:
#include<stdio.h>
void main()
{ printf (“Hello”);
}
Delimiter are :
(
)
{
;
}
Operators are :
<
>
Identifiers are :
include
stdio.h
printf
Keywords are :
Void
Main
Constants are :
Literals :
“Hello”
RESULT:
Thus the few patterns are identified in lexical analyzer

Download Useful Materials from Rejinpaul.com


Ex. No: 3 LEX – SAMPLE PROGRAMS
Date:

AIM:
To write sample lex programs to illustrate basic operations.

ALGORITHM:
Step-1: Lex program is to display the all characters typed from keyboard
Step-2: Program to identify only identifiers, pattern is written in the form of Lex structure
Step-3: Lex Program to display the line no for the text which is typed from keyboard
Step-4: Program is to count no of vowels and consonants and pattern is represented in the form
of Lex

PROGRAM 1:
Write A Lex Program To Show The Function Of Echo

%%
. ECHO;
\n ECHO;
%%
int yywrap(void)
{
return 1;
}
int main()
{
yylex();
return o;
}

Download Useful Materials from Rejinpaul.com


OUTPUT:
a
a
b
b

PROGRAM 2:
Lex Program To Find Only Identifiers

ID [a-z0-9]
%%
{ID} {printf(“It is an Identifier”);}
%%
int yywrap(void)
{
return 1;
}
int main()
{
yylex();
return 0;
}

OUTPUT:

g
It is an Identifier
j
It is an Identifier

Download Useful Materials from Rejinpaul.com


PROGRAM 3:
Lex Program To Find The Line Number Of The Given Input.
%{
int l=0;
%}
%%
^(.*)\n {printf(“%d\t%s”,l++,yytext);}
%%
int yywrap(void)
{
return 1;
}
int main(int argc,char *argv[])
{
yyin=fopen(argv[],”r”);
}

OUTPUT:

Abc
0 Abc
Hai
1 Hai

PROGRAM 4:
Lex Program To Find The Number Of Vowels And Consonants

%{
int count=0;count2=0;
%}
%%

Download Useful Materials from Rejinpaul.com


“a”|”e”|”i”|”o”|”u” {++Count; printf(“\nVowel: %d”,Count);}
[a-z] {++Count2; printf(“Consonants: %d”,Count2);}
%%
int yywrap(void)
{
return 1;
}
int main()
{
yylex();
}

OUTPUT:
a
vowel 1
b
consonants 1

RESULT :
Thus the sample lex programs were executed and output was verified

Download Useful Materials from Rejinpaul.com


Ex.No:4 IMPLEMENTATION OF LEXICAL ANALYZER USING LEX TOOL
Date:

AIM:
To implement a lexical analyzer using Lex Tool.

ALGORITHM:

Step-1: Declare the variables which is used for C programs.


Step-2 : P a t t e r n t o b e w r i t t e n i n r e g u l a r e x p r e s s i o n .
S t e p - 3 : Separate the keyword in the program and display it using lex.
Step-4 :Separate the operators of the input program and display it.
Step-5:Print the punctuation marks.
S t e p - 6:Print the constant that are present in input program.
Step-7:Print the identifiers of the input program using lex tool.

PROGRAM:
%{
#include<stdio.h>
int e,k,c,d,i,s;
%}
%%
include|void|main|int|float|double|scanf|char|printf {printf("keyword"); i++;}
[a-z][a-zA-Z0-9]* {printf("Identifier"); k++;}
[0-9]* {printf("digit"); e++;}
[+|-|*|/|=]* {printf("operator"); c++;}
[;|:|(|)|{|}|"|'|,|\n|\t]* {printf("delimeter"); d++;}
[#|<|>|%]* {printf("symbols"); s++;}
%%
int main(void)
{

Download Useful Materials from Rejinpaul.com


yyin=fopen("lexy.txt","r");
yylex();
printf("\nidentifier %d\n",k);
printf("Symbols %d\n",s);
printf("digits %d\n",e);
printf(" Operator %d\n",c);
printf(" keywords %d\n",i);
printf("delimeter %d\n",d);

return 1;
}
int yywrap()
{
return 1;
}

INPUT:
Lexyi.txt
int a=10;

OUTPUT:
Identifier 1
Digit 1
Keyword 1
Operator 1
Delimiter 1

RESULT:
Thus a lexical analyzer is implemented using Lex Tool and the output is verified.

Download Useful Materials from Rejinpaul.com


Ex. No: 5 YACC PROGRAM FOR IDENTIFIERS
Date:

AIM:
To write a yacc program to identify identifiers.

ALGORITHM:
Step-1:Reading an expression
Step-2: Checking the validating of the given expression according to the rule using yacc.
Step-3: Display “ identifier” or syntax error

PROGRAM:
id.l :

%{

#include "y.tab.h"

%}

%%

[a-z]+ {yylval=yytext;printf("we r in lex ");return ID;}

%%

int yywrap()

Download Useful Materials from Rejinpaul.com


{

return 1;

id.y :
%{

#include<stdio.h>

int i;

%}

%token number ID

%%

start: ID {$$=$1;printf("vaild id %s",$1);}

%%

extern FILE *yyin;

void main()

Download Useful Materials from Rejinpaul.com


do

yyparse();

}while(!feof(yyin));

int yyerror(char *s)

printf("error");

OUTPUT:
>> lex id.l
>> bison -d -y id.y
>> cc y.tab.c lex.yy.c
>>./a.out

RESULT:
Thus the yacc program to find identifier was verified

Download Useful Materials from Rejinpaul.com


Ex.No:6 PROGRAM TO RECOGNIZE A VALID ARITHMETIC
EXPRESSION THAT USESOPERATOR +, - , * AND / USING YACC
AIM:
To write a Yacc program to valid arithmetic expression using Yacc

ALGORITHM:
Step-1:Reading an expression
Step-2: Checking the validating of the given expression according to the rule using yacc.
Step-3:Using expression rule print the result of the given values

PROGRAM:
calc.y
%{
#include <stdio.h>
void yyerror(char *);
int yylex(void);
int sym[26],i=0;
%}
%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'
%%
program:
program statement '\n'
| /* NULL */
;
statement:
expression { printf("%d\n", $1); }
| VARIABLE '=' expression { printf ("Node =\t\t"); sym[$1] = $3;}
;
expression:

Download Useful Materials from Rejinpaul.com


INTEGER
| VARIABLE { $$ = sym[$1]; }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression {$$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression { $$ = $1 / $3; }
| '(' expression ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
}
calc.l
%{
#include "y.tab.h"
#include <stdlib.h>
void yyerror(char *);
%}

%%
[a-z] {
printf("Tdentifier");
return VARIABLE;
}
[0-9]+ {
yylval = atoi(yytext);
return INTEGER;
}

Download Useful Materials from Rejinpaul.com


[-+()=/*\n] { return *yytext; }
[ \t] ; /* skip whitespace */
. yyerror("Unknown character");
%%
int yywrap(void) {
return 1;
}

OUTPUT:
bison -d -y calc.y
lex calc.l
gcc lex.yy.c y.tab.c
./a.out
a+b
valid
ab-
syntax error

RESULT:
Thus the program for validating arithmetic expression was done

Download Useful Materials from Rejinpaul.com


Ex. No: 7 PROGRAM TO RECOGNIZE A VALID VARIABLE WHICH STARTS
Date : WITH A LETTER FOLLOWED BY ANY NUMBER OF LETTERS OR DIGITS

AIM :
To write a yacc program to check valid variable followed by letter or digits

ALGORITHM:
Step-1:Reading an expression
Step-2: Checking the validating of the given expression according to the rule using yacc.
Step-3:Using expression rule print the result of the given values

PROGRAM:
valid.y
%{
#include <stdio.h>
void yyerror(char *);
int yylex(void);
int sym[26],i=0;
%}
%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'
%%
program:
program statement '\n'
| /* NULL */
;
statement:
expression { printf("%d\n", $1); }
| VARIABLE '=' expression { printf ("Node =\t\t"); sym[$1] = $3;}
;

Download Useful Materials from Rejinpaul.com


expression:
INTEGER
| VARIABLE { $$ = sym[$1]; }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression {$$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression { $$ = $1 / $3; }
| '(' expression ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
}
valid.l
%{
#include "y.tab.h"
#include <stdlib.h>
void yyerror(char *);
%}

%%
[a-z] {
printf("Tdentifier");
return VARIABLE;
}
[0-9]+ {
yylval = atoi(yytext);
return INTEGER;

Download Useful Materials from Rejinpaul.com


}
[-+()=/*\n] { return *yytext; }
[ \t] ; /* skip whitespace */
. yyerror("Unknown character");
%%
int yywrap(void) {
return 1;
}

OUTPUT:
bison -d -y valid.y
lex valid.l
gcc lex.yy.c y.tab.c
./a.out
A1
valid
10a
syntax error

RESULT:
Thus the program for checking letter followed by letter or digits were done

Download Useful Materials from Rejinpaul.com


Ex. No: 8 IMPLEMENTATION OF CALCULATOR USING LEX AND YACC
Date :

AIM :
To write a yacc program to implement calculator using yacc

ALGORITHM:
Step-1:Reading an expression
Step-2: Calculate the value of given expression using yacc .
Step-3:Using expression rule print the result of the given values

PROGRAM:
valid.y
%{
#include <stdio.h>
void yyerror(char *);
int yylex(void);
int sym[26],i=0;
%}
%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'
%%
program:
program statement '\n'
| /* NULL */
;
statement:
expression { printf("%d\n", $1); }
| VARIABLE '=' expression { printf ("Node =\t\t"); sym[$1] = $3;}
;

Download Useful Materials from Rejinpaul.com


expression:
INTEGER
| VARIABLE { $$ = sym[$1]; }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression {$$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression { $$ = $1 / $3; }
| '(' expression ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
}
valid.l
%{
#include "y.tab.h"
#include <stdlib.h>
void yyerror(char *);
%}

%%
[a-z] {
printf("Tdentifier");
return VARIABLE;
}
[0-9]+ {
yylval = atoi(yytext);
return INTEGER;

Download Useful Materials from Rejinpaul.com


}
[-+()=/*\n] { return *yytext; }
[ \t] ; /* skip whitespace */
. yyerror("Unknown character");
%%
int yywrap(void) {
return 1;
}

OUTPUT:
bison -d -y valid.y
lex valid.l
gcc lex.yy.c y.tab.c
./a.out
3+5
8

35/
syntax error

RESULT:
Thus the program for checking letter followed by letter or digits were done

Download Useful Materials from Rejinpaul.com


Ex. No: 9 IMPLEMENT ANY ONE STORAGE ALLOCATION
STRATEGIES(HEAP,STACK,STATIC)
Date:

AIM:
To implement Stack storage allocation strategies using C program.

ALGORITHM:
Step-1: Initially check whether the stack is empty
Step-2: Insert an element into the stack using push operation
Step-3: Insert more elements onto the stack until stack becomes full
Step-4: Delete an element from the stack using pop operation
Step-5: Display the elements in the stack
Step-6: Top the stack element will be displayed

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5
struct stack
{
int s[size];
int top;
} st;
int stfull()
{
if (st.top >= size - 1)
return 1;
else
return 0;

Download Useful Materials from Rejinpaul.com


}

void push(int item)


{
st.top++;
st.s[st.top] = item;
}
int stempty()
{
if (st.top == -1)
return 1;
else
return 0;
}
int pop()
{
int item;
item = st.s[st.top];
st.top--;
return (item);
}
void display()
{
int i;
if (stempty())
printf("\nStack Is Empty!");
else
{
for (i = st.top; i >= 0; i--)
printf("\n%d", st.s[i]);
}

Download Useful Materials from Rejinpaul.com


}
int main()
{
int item, choice;
char ans;
st.top = -1;
printf("\n\tImplementation Of Stack");
do {
printf("\nMain Menu");
printf("\n1.Push \n2.Pop \n3.Display \n4.exit");
printf("\nEnter Your Choice");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter The item to be pushed");
scanf("%d", &item);
if (stfull())
printf("\nStack is Full!");
else
push(item);
break;
case 2:
if (stempty())
printf("\nEmpty stack!Underflow !!");
else
{
item = pop();
printf("\nThe popped element is %d", item);
}
break;

Download Useful Materials from Rejinpaul.com


case 3:
display();
break;
case 4:
goto halt;
}
printf("\nDo You want To Continue?");
ans = getche();
} while (ans == 'Y' || ans == 'y');
halt:
return 0;
}

Download Useful Materials from Rejinpaul.com


OUTPUT:

RESULT:
Thus the stack is implemented in C using arrays and output is verified.

Download Useful Materials from Rejinpaul.com


Ex.No : 10 BNF RULES INTO YACC FORM AND WRITE CODE TO GENERATE
ABSTRACT SYNTAX TREE
Date:

AIM:
To write a yacc program to change yacc form into abstract syntax Tree

ALGORITHM:
Step-1: Reading an expression.
Step-2: Calculate the value of given expression
Step-3: Display the value of the nodes based on the precedence.
Step-4: Using expression rule print the result of the given values

PROGRAM:
abs.l :
%{

#include "y.tab.h"

%}

%%

[a-z]+ {yylval=yytext;printf("we r in lex ");return ID;}

[0-9]+ {yylval=atoi(yytext);

return number;

Download Useful Materials from Rejinpaul.com


}

[+ -] {return *yytext;}

[* /] {return *yytext;}

\n return 0;

%%

int yywrap()

return 1;

abs.y :
%{

#include<stdio.h>

int i;

%}

Download Useful Materials from Rejinpaul.com


%token number ID

%%

start: ID {$$=$1;printf("vaild id %s",$1);}

|expr {printf("\n result of exprssion is %d",$$);}

expr: expr '+' term {$$=$1+$3;i=i+1;

printf("next tree node %d %d \t %c \t %d value=%d\n",i,$1,'+',$3,$$);}

|term {$$=$1;}

term: term '*' factor {$$=$1* $3;i=i+1;

printf("next tree node %d %d \t %c\t %d value=%d\n",i,$1,'*',$3,$$); }

|factor {$$=$1;}

Download Useful Materials from Rejinpaul.com


factor: number {$$=$1;

printf("leaf node %d\n",$1);}

%%

extern FILE *yyin;

void main()

do

yyparse();

}while(!feof(yyin));

int yyerror(char *s)

printf("error");

Download Useful Materials from Rejinpaul.com


OUTPUT:

>> lex abs.l


>> bison -d -y abs.y
>> cc y.tab.c lex.yy.c
>>./a.out

RESULT:

Thus, the yacc program for abstract tree was executed successfully.

Download Useful Materials from Rejinpaul.com


Ex.No: 11 IMPLEMENTATION OF TYPE CHECKING
Date:

AIM:
To write a C program to implement type checking

ALGORITHM:
Step-1: Track the global scope type information (e.g. classes and their members)
Step-2: Determine the type of expressions recursively, i.e. bottom-up, passing the
resulting types upwards.
Step-3: If type found correct, do the operation
Step-4: Type mismatches, semantic error will be notified

PROGRAM:
#include<stdio.h>
#include<string.h>
struct symTable

int type;

char var[10];

}sT[50];

int c = 0;

Download Useful Materials from Rejinpaul.com


void sep(char a[])

int len = strlen(a);

int i,j=0;

char temp[50],tp[50];

for(i = 0; i < len;++i)

if(a[i] != 32)

tp[i] = a[i];

else

break;

tp[i] = '\0';

temp[0]='\0';

++i;

Download Useful Materials from Rejinpaul.com


for(;i < len;++i)

if(a[i] != ',' && a[i] != 32 && a[i] != ';')

temp[j++] = a[i];

else

if(strcmp(tp,"int") == 0)

sT[c].type = 1;

else if(strcmp(tp,"float") == 0)

sT[c].type = 2;

strcpy(sT[c++].var,temp);

temp[0] = '\0';

j=0;

Download Useful Materials from Rejinpaul.com


}

int check(char a[])

int len = strlen(a);

int i, j = 0,key = 0,k;

char temp[50];

for(i = 0;i < len;++i)

if(a[i] != 32 && a[i] != '+' && a[i] != '=' && a[i] != ';')

temp[j++] = a[i];

else

temp[j]='\0';

for(k = 0;k < c;++k)

Download Useful Materials from Rejinpaul.com


{

if(strcmp(sT[k].var,temp) == 0)

if(key == 0)

key = sT[k].type;

else if(sT[k].type != key)

return 0;

j = 0;

return 1;

Download Useful Materials from Rejinpaul.com


void main()

int N,ans,i;

char s[50];

printf("\n Enter the total lines of declaration\n");

scanf("%d",&N);

while(N--)

scanf(" %[^\n]",s);

sep(s);

printf("Enter the expression:\n");

scanf(" %[^\n]",s);

if(check(s))

Download Useful Materials from Rejinpaul.com


printf("Correct\n");

else

printf("Semantic error\n");

OUTPUT:

RESULT:

Thus, the c program for implementation of type checking was done successfully.

Download Useful Materials from Rejinpaul.com


Ex.No: 12 . IMPLEMENTATION OF THE BACK END OF THE COMPILER
Date :

AIM:
To write a c program for implementing backend of a compiler.

ALGORITHM:

Step-1: Read the given expression


Step-2: Variables are loaded into separate registers using Load or Move Instructions
Ex. LD R,a or Mov R,a
Step-3: Arithmetic operations can be done between the registers
Ex: ADD, SUB,MUL and DIV
Step-4: Result of the operand is stored to any variable
Ex: ST x, Ro

PROGRAM:
#include<stdio.h>

#include<string.h>

int main(){

char inp[100][100];

int n,i,j,len;

int reg = 1;

printf("Enter the no of statements");

Download Useful Materials from Rejinpaul.com


scanf("%d",&n);

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

scanf("%s",&inp[i]);

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

len = strlen(inp[i]);

for(j=2; j < len; j++)

if(inp[i][j] >= 97 && inp[i][j] <= 122)

printf("LOAD R%d %c \n",reg++,inp[i][j]);

if(j == len-1 && inp[i][len-j] =='=')

j=3;

Download Useful Materials from Rejinpaul.com


if(inp[i][j] == '+')

printf("ADD R%d R%d\n",reg-2,reg-1);

printf("STORE %c R%d\n",inp[i][0],reg-2);

else if(inp[i][j]=='-')

printf("SUB R%d R%d\n",reg-2,reg-1);

printf("STORE %c R%d\n",inp[i][0],reg-2);

else if(inp[i][j]=='*')

printf("MUL R%d R%d\n",reg-2,reg-1);

printf("STORE %c R%d\n",inp[i][0],reg-2);

Download Useful Materials from Rejinpaul.com


else if(inp[i][j]=='/')

printf("DIV R%d R%d\n",reg-2,reg-1);

printf("STORE %c R%d\n",inp[i][0],reg-2);

break;

return 0;

Download Useful Materials from Rejinpaul.com


OUTPUT:

RESULT:

Thus, the c program for implementing backend of the compiler was done successfully.

Download Useful Materials from Rejinpaul.com


Ex. No : 13 IMPLEMENTATION OF SIMPLE CODE OPTIMIZATION
Date : TECHNIQUES

AIM:
To write a C program to eliminate dead code as code optimization

ALGORITHM:

Step-1: Read the input from input file


Step-2: Instructions are kept in the basic block, Consider the instructions in the same basic block
Step-3: Variables are initialized with values, If any variables are not used in the basic block,
identified such variables are unused variables
Step-4: Such unused variable will be displayed as output.

PROGRAM:
#include<stdio.h>
void main()
{
char all_var[10];
int ptr=0,dup=0,i,j,c,a=0;
FILE *file;

file = fopen( "test.txt" , "r");


if (file) {
while ((c=getc(file)) != EOF)
{
putchar(c);
if(c==';'||c==' '||(c>='0'&&c<='9')||c=='='||c=='\n'||c=='+')
continue;
else
{

Download Useful Materials from Rejinpaul.com


all_var[ptr]=c;
ptr++;
}
}
printf("\n The unused variables are: ");

for(i=0;i<=ptr;i++)
{
for(j = i+1; j <= ptr; j++)
if(all_var[i] == all_var[j])
{
dup=1;
}

if(dup==0)
{printf("%c",all_var[i]);
dup=0;
}
}
fclose(file);
}
}

INPUT:
a;
b;
c;
a;
a=34;
c=78;

Download Useful Materials from Rejinpaul.com


j=45;
r=30;

OUTPUT:
b is unused variable

RESULT:
Thus the program for code optimization was implemented

Download Useful Materials from Rejinpaul.com


Ex.No:14 CONSTRUCTION OF DAG
Date :

AIM:
To study the concept of Directed acyclic graph

PROCEDURE:
Directed acyclic graphs :
Directed acyclic graphs (DAGs) give a picture of how the value computed by each
statement in the basic block is used in the subsequent statements of the block.
Definition:
A DAG for a basic block is a directed acyclic graph with the following labels on nodes:
 leaves are labeled with either variable names or constants.
 they are unique identifiers
 from operators we determine whether l- or r-value.
 represent initial values of names. Subscript with 0.
 interior nodes are labeled by an operator symbol.
 Nodes are also (optionally) given a sequence of identifiers for labels.
 interior node º computed value
 identifiers in the sequence – have that value.

Example of DAG Representation


Corresponding DAG
Utility: Constructing a dag from 3AS is a good way of determining:
• common sub expressions (expressions computed more than once),
• which names are used inside the block but evaluated outside,
• which statements of the block could have their computed value used outside the
block
Constructing a DAG
Input : a basic block. Statements: (i) x:= y op z (ii) x:= op y (iii) x:= y
Output : a dag for the basic block containing:

Download Useful Materials from Rejinpaul.com


- a label for each node.
- For leaves an identifier - constants are permitted. For interior nodes an operator
symbol.
- for each node a (possibly empty) list of attached identifiers - constants not ermitted.
Method: Initially assume there are no nodes, and node is undefined.
(1) If node(y) is undefined: created a leaf labeled y, let node(y) be this node. In case(i) if
node(z) is undefined create a leaf labeled z and that leaf be node(z).
(2) In case(i) determine if there is a node labeled op whose left child is node(y) and right
child is node(z). If not create such a node, let be n. case(ii), (iii) similar.
(3) Delete x from the list attached to node(x). Append x to the list of identify for node n and
set node(x) to n.

Algorithm DAG: Constructing a DAG

Input : A basic block of three address statements. No pointers or array references.

Output: A DAG where each node n has a value, VALUE(n), which is an operator in the case of
an interior node or a variable name if the node is a leaf. Also, each node n has a (possibly empty)
list of identifiers attached, ID(n).

The DAG Representation of Basic Blocks The previous algorithm aims at improving the
quality of the target code,but only with respect to register utilization.There are a number
of other issues in the generation of efficient code.One of them is the elimination of
redundant computation
T1 = J * 2
Example: T2 = X[T1]
T3 = T2 + N
T4 = J * 2
T5 = Y[T4]
T6 = T5 + T3
ANS = T6
T7 = J+ 1
J = T7
ANS = J
If J<10 goto L

Download Useful Materials from Rejinpaul.com


RESULT:

Thus the DAG for the expression in basic block was studied

Download Useful Materials from Rejinpaul.com


Ex.No:15 IMPLEMENT CONTROL FLOW ANALYSIS AND DATA FLOW
ANALYSIS
Date :

AIM:
To study the concept of control flow and data flow analysis

PROCEDURE:

Download Useful Materials from Rejinpaul.com


Ex.No:16 IMPLEMENTATION OF RECURSIVE DESCENT PARSER
Date :

AIM:
To write a C program to implement recursive descent parser

ALGORITHM:
Step-1:Read the input string.
Step-2:By using the FIRST AND FOLLOW values.
Step-3: Verify the FIRST of non terminal and insert the production in the FIRST value
Step-4:If we have any @ terms in FIRST then insert the productions in FOLLOW values

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void match(char);
void b(void);
char c[10];
static int i;
void main()
{
int n;
char k;
clrscr();
printf("Recursive Descent parser \n");
printf("Grammar is \n");
printf("S->AB ; A->a ; B->b \n");
printf("enter the string ");
gets(c);
printf(" input string is %s\n",c);

Download Useful Materials from Rejinpaul.com


n=strlen(c);
printf("lengthof input string is %d\n",n);
i=0;
while(i<n)
{
printf("in main() now character is %c\n",c[i]);
if(c[i]=='a')
{
k=c[i];
match(k);
b();
printf("\n parsing completed");
}
else
{
printf("not a valid input / error\n");
break;
}
}
getch();
}
void match(char a)
{
printf("current input sumbol matched \n");
i=i+1;
}

void b(void)
{
printf("now in b()\n");
printf("now the character is %c\n",c[i]);

Download Useful Materials from Rejinpaul.com


if(c[i]=='b'||c[i]=='c')
match(c[i]);
else
{
printf("error");

}
}

OUTPUT:
Recursive Descent parser
Grammar is
S->AB ; A->a ; B->b
enter the string ab
input string is ab
lengthof input string is 2
in main() now character is a
current input sumbol matched
now in b()
now the character is b
current input sumbol matched
parsing completed

RESULT:
Thus the recursive descent parser was implemented using C program

Download Useful Materials from Rejinpaul.com

Das könnte Ihnen auch gefallen