Compiler Design Programs
Compiler Design Programs
PROGRAM:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main()
{
FILE *fp;
int i,j;
char arr[100],k;
char kw[10][10]={"int","float","double","end","main","void","include","printf","scanf"};
char hf[2][10]={"stdio.h","conio.h"};
char op[5]={'+','-','*','/','%'};
char punc[6]={'(',')','{','}',','};
clrscr();
fp=fopen("input.c","r");
printf("Input Program\n");
while(!feof(fp))
{
arr[0]=fgetc(fp);
printf("%c",arr[0]);
}
Page 1 of 59
fclose(fp);
printf("\nSymbol table\n");
fp=fopen("input.c","r");
printf("\nKeywords");
while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<10;i++)
{
if(strcmp(arr,kw[i])==0)
{
printf("\t%s",arr);
}
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nHeader files");
while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,hf[i])==0)
{
printf("\t%s",arr);
}
}}
fclose(fp);
fp=fopen("input.c","r");
printf("\nOperators");
while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<5;i++)
{
if(arr[0]==op[i])
// input.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,c,d;
float b=12.2;
char c='abcd';
clrscr();
a=10;
c=20;
d=a+b;
printf("D value is %d",d);
printf(" B value is %f",b);
printf("C value is %c",c);
getch();
}
OUTPUT:
RESULT:
PROGRAM:
%{
int COMMENT=0;
%}
identifier [_a-zA-Z][_a-zA-Z0-9]*
%%
#.* {printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
float |
char |
while |
for |
do |
if |
break |
continue |
void |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT=1;
printf("\n\n\t COMMENT ENDS\n");}
St.Joseph’s College of Engineering Page 6 of 59
{identifier}\( {if(!COMMENT)
printf("\n\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}
\} {if(!COMMENT) printf("\n BLOCK ENDS");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT) printf("\n %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a NUMBER",yytext);}
\)(\;)? {if(!COMMENT) printf("\n\t");ECHO; printf("\n");}
\( ECHO;
= {if(!COMMENT) printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
.|\n ;
%%
RESULT:
Thus the above program has been executed successfully
AIM: To write a program to recognize a valid arithmetic expression that uses operator +, - , *
and /.
PROGRAM:
Using Yacc Tool :
%{
#include<stdio.h>
%}
%token NUMBER ID
%left '+' '-'
%left '*' '/'
%%
exp: exp '+' exp
| exp '-' exp
| exp '*' exp
| exp '/' exp
|'_'NUMBER
|'_'ID
|'('exp')'
|NUMBER
|ID
%%
int yyerror(char *msg)
{
printf("Invalid Expression\n");
exit(0);
}
main ()
{
printf("Enter the expression\n");
yyparse();
printf("\n Expression is vaild\n");
exit(0);
}
Lex Part:
St.Joseph’s College of Engineering Page 10 of 59
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext);
return NUMBER; }
[a-zA-Z]+ {return ID;}
[\t]+;
\n { return 0 ;}
. { return yytext[0]; }
%%
OUTPUT:
root@localhost ~]# vi ex4a.l
[root@localhost ~]# lex ex4a.l
[root@localhost ~]# vi ex4a.y
[root@localhost ~]# yacc -d ex4a.y
[root@localhost ~]# cc y.tab.c lex.yy.c -ll -o ex4a.out
[root@localhost ~]# ./ex4a.out
Enter the expression
(a+c+e+40)
Expression is vaild
[root@localhost ~]# ./a.out
Enter the expression
(a++d+40)
Invalid Expression
RESULT:
Thus the above program has been executed successfully
AIM: To write a program to recognize a valid variable which starts with a letter followed by
any number of letters or digits.
ALGORITHM:
1) Start the program
2) Create a regular expression for identifier (letter)(letter/digit)*
3) In the same way,in yacc tool.
4) Stop the program
PROGRAM:
Using LEX:
%{
#include "y.tab.h"
%}
%%
[a-zA-Z] return LETTER ;
[0-9] return DIGIT ;
[\n] return 0;
. return yytext[0];
%%
Using YACC:
%{
#include<stdio.h>
int vaild=1;
%}
%token DIGIT LETTER
%%
start : LETTER s
s:LETTER s
| DIGIT s
|;
%%
int yyerror()
{
printf("Not a identifier\n");
vaild=0;
return 0;
}
OUTPUT:
[root@localhost ~]# vi ex4b.l
[root@localhost ~]# lex ex4b.l
[root@localhost ~]# vi ex4b.y
[root@localhost ~]# yacc -d ex4b.y
[root@localhost ~]# cc y.tab.c lex.yy.c -ll -o ex4b.out
[root@localhost ~]# ./ex4b.out
Enter the variable name
Naveen
The string is vaild
RESULT:
Thus the above program has been executed successfully
ALGORITHM:
1) Start the program.
2) Perform the calculation using both the lex and yacc.
3) In the lex tool, if the given expression contains numbers and letters then they are
displayed.
4) In the same way, the digits, letters and uminus are identified and displayed using yacc
tool.
5) The calculation is performed and the result is displayed.
6) Stop the program
PROGRAM:
Using LEX:
%{
#include <stdio.h>
#include "y.tab.h"
int c;
extern int yylval;
%}
%%
"" ;
[a-z] {
c = yytext[0];
yylval = c - 'a';
return(LETTER);
}
[0-9] {
c = yytext[0];
yylval = c - '0';
return(DIGIT);
}
[^a-z0-9\b] {
c = yytext[0];
return(c);
}
Using YACC:
%{
#include <stdio.h>
int regs[26];
St.Joseph’s College of Engineering Page 14 of 59
int base;
%}
%start list
%token DIGIT LETTER
%left '|'
%left '&'
%left '+' '-'
%left '*' '/' '%'
%left UMINUS /*supplies precedence for unary minus */
%% /* beginning of rules section */
list: /*empty */
|
list stat '\n'
|
list error '\n'
{
yyerrok;
}
;
stat: expr
{
printf("%d\n",$1);
}
|
LETTER '=' expr
{
regs[$1] = $3;
}
;
expr: '(' expr ')'
{
$$ = $2;
}
|
expr '*' expr
{
$$ = $1 * $3;
}
|
expr '/' expr
23+3
26
32-3
29
50/10
5
0
AIM: To write a program to convert the BNF rules into Yacc form and write code to generate
Abstract Syntax Tree.
ALGORITHM:
1) Include the necessary header files.
2) Declare the semantic rule for the identifier and number.
3) If the statement begins with main (), if else * while, the return as MAIN, IF ELSE and
WHILE.
4) If the variables are declared as int, float and char then return as VAR and NUM
5) Include the necessary header files. Initialize the err no=0 and declare like no as integer.
6) Declare the necessary tokens for the grammar.
PROGRAM:
USING LEX:
%{
#include"y.tab.h"
#include<stdio.h>
#include<string.h>
int LineNo=1;
%}
identifier [a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
main\(\) return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float return TYPE;
{identifier} {strcpy(yylval.var,yytext);
return VAR;}
{number} {strcpy(yylval.var,yytext);
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '=' EXPR{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
| VAR
| NUM
;
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST: IF '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop();
Ind=pop();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo); Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE '(' CONDITION ')'
{
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
OUTPUT:
[root@localhost ~]# vi ex1.c
[root@localhost ~]# cc ex1.c -o ex1.out
[root@localhost ~]# ./ex1.out
Expression terminated by $ : p+q+r $
Given Expression : p+q+r
Symbol Table
Symbol addr type
q 167063560 identifier
RESULT:
Thus the above program has been executed successfully
AIM:
To write a program to implement type checking
ALGORITHM:
1) Include the necessary header files.
2) Declare necessary data type(typecheck.l) for validating the type checking(eg
int,float,char ,etc)
3) Validate the given data type in parser(typecheck.y)
PROGRAM:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char* type(char[],int);
int main()
{
char a[10],b[10],mess[20],mess1[20];
int i,l;
printf( "\n\n int a,b;\n\n int c=a+b\n");
printf( "\n\n Enter a value for a\n");
scanf("%s",a);
l=strlen(a);
printf(" \n a is :");
strcpy(mess,type(a,l));
printf("%s",mess);
printf( "\n\n Enter a value for b\n\n");
scanf("%s",b);
l=strlen(b);
printf(" \n b is :");
strcpy(mess1,type(b,l));
printf("%s",mess1);
if((strcmp(mess,"int")==0)&&(strcmp(mess1,"int")==0))
printf("\n\n no type ...or");
else
printf("type error");
}
char* type(char x[],int m)
{
int i; char mes[20];
for(i=0;i<m;i++)
{
if(isalpha(x[i]))
St.Joseph’s College of Engineering Page 30 of 59
{
strcpy(mes,"alphanumeric");
goto x;
}
else if (x[i]=='.')
{
strcpy(mes,"float");
goto x;
}
}
strcpy(mes,"int");
x:
return mes;
}
OUTPUT:
int a.b:
int c=a+b;
Enter a value for a
21.5
a is ;float
Enter a value for b
35
b is ;int
type error
RESULT:
Thus the above program has been executed successfully
AIM:
To implement Control Flow Analysis and display the output graph as blocks using a C
program.
ALGORITHM:
1) Include the necessary header files.
2) Create a structure and include the pointers that are needed for operation in it.
3) Create three arrays for input data, label and for the target data.
4) Create a file pointer and read the file and copy it to the respective character arrays.
5) Get the three address code and put them in the respective blocks.
6) Print the basic blocks and output the control Flow in each blocks.
PROGRAM:
#include<stdio.h>
#include<curses.h>
#include<stdlib.h>
//#include<alloc.h>
#include<string.h>
struct Listnode
{
char data[500];
int leader,block,u_goto,c_goto;
struct Listnode *next;
char label[100],target[100];
}*temp,*cur,*first=NULL,*last=NULL,*cur1;
FILE *fpr;
void createnode(char code[500])
{
temp=(struct Listnode *)malloc(sizeof(struct Listnode));
strcpy(temp->data,code);
strcpy(temp->label,'\0');
strcpy(temp->target,'\0');
temp->leader=0;
temp->block=0;
temp->u_goto=0;
temp->c_goto=0;
temp->next=NULL;
if(first==NULL)
{
first=temp;
St.Joseph’s College of Engineering Page 32 of 59
last=temp;
}
else
{
last->next=temp;
last=temp;
}
}
void printlist()
{
cur=first;
printf("\nMIR code is \n\n");
while(cur!=NULL)
{
printf("\ncode:%s",cur->data);
printf("\nleader:%d\t",cur->leader);
printf("block:%d\t",cur->block);
printf("u_goto:%d\t",cur->u_goto);
printf("c_goto:%d\t",cur->c_goto);
printf("label:%s\t",cur->label);
printf("target:%s\n",cur->target);
cur=cur->next;
}
}
void main()
{
char codeline[50];
char c,dup[50],target[10];
char *substring,*token;
int i=0,block,block1;
int j=0;
fpr= fopen("input.txt","r");
//clrscr();
while((c=getc(fpr))!=EOF)
{
if(c!='\n')
{
codeline[i]=c;
i++;
}
Input (input.txt):
100 if a<=b goto 103
101 T:=0
102 goto 104
103 T:=1
104 return
OUTPUT:
[root@localhost ~]# vi ex7a.c
[root@localhost ~]# cc ex7a.c -o ex7a.out
[root@localhost ~]# ./ex7a.out input.txt
......Basic Blocks......
Block 0:100 if a<=b goto 103
Block 1:101 T:=0
102 goto 104
Block 2:103 T:=1
Block 3:104 return
.......Control Flow.......
Block0---TRUE--->Block0---FALSE--->Block1
RESULT:
Thus the above program has been executed successfully
AIM:
To implement Data Flow Analysis using a Available expression using a C program.
ALGORITHM:
1) Include the necessary header files.
St.Joseph’s College of Engineering Page 38 of 59
2) Declare necessary character arrays for input and output and also a structure to include
it.
3) Declare an array of structure variables to access the members.
4) Get the maximum number of expressions from the user.
5) If both the positions before and after the operand are digits store them.
6) Eliminate the expression and replace any operand that uses result of this expression.
7) If the variable is repeated again in the steps, then replace it with the expression obtained
above.
8) Print the optimized code.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void input();
void output();
void change(int p,int q,char *res);
void constant();
void expression();
struct expr
{
char op[2],op1[5],op2[5],res[5];
int flag;
}arr[10];
int n;
int main()
{
int ch=0;
input();
constant();
expression();
output();
}
void input()
{
int i;
printf("\n\nEnter the maximum number of expressions:");
scanf("%d",&n);
printf("\nEnter the input : \n");
for(i=0;i<n;i++)
{
scanf("%s",arr[i].op);
OUTPUT:
[root@localhost ~]# vi ex7b.c
[root@localhost ~]# cc ex7b.c -o ex7b.out
[root@localhost ~]# ./ex7b.out
ALGORITHM:
Push:
Suppose STACK [SIZE] is a one dimensional array for implementing the stack, which will hold
the data items. TOP is the pointer that points to the top most element of the stack. Let DATA is
the data item to be pushed.
1. If TOP = SIZE – 1, then:
(a) Display “The stack is in overflow condition”
PROGRAM:
#include<stdio.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;
}
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;
St.Joseph’s College of Engineering Page 43 of 59
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]);
}
}
int main() {
int item, choice,y;
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;
Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 1
Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice 2
Main Menu
1.Push
2.Pop
3.Display
4.exit
Enter Your Choice3
54
41
Do You want To Continue? 0
RESULT
Thus the above program has been executed successfully
AIM:
To write a program to construction of Directed Acyclic Graph(DAG)
ALGORITHM:
1)
Start the program
2)
Get the expression in the form of id1=id2 op1 id3 op2 id4.
3)
Get the expression like A=B+C+D.
4)
Leaf nodes represent identifiers, names or constants.
5)
Interior nodes represent operators.
6)
Interior nodes also represent the results of expressions or the identifiers/name
where the values are to be stored or assigned.
7) Stop the program
PROGRAM:
St.Joseph’s College of Engineering Page 46 of 59
#include<stdio.h>
#include<string.h>
struct node
{
char val;
node *rt,*lt;
};
char expr[20];
void rde()
{
printf(“\n enter the expression in the following form”);
printf(“\n\n id1=id2 op1 id3 op2 id4”);
printf(“\n\n Enter the expression:”);
scanf(“%s”,expr);
}
void main()
{
rde();
node *root=new node();
node *it1=new node();
node *newptr=new node();
node *l2=new node();
node *r2=new node();
node *newptr1=new node();
node *l3=new node();
for(int i=0;i<=strlen(expr);i++)
{
if(expr[i]==’=’)
{
root->val=expr[i];
root->lt=lt1;
lt1->val=expr[i-1];
it1->lt=NULL;
lt1->rt=NULL;
for(int j=I;j<=strlen(expr);j++)
{
if(expr[j]==’*’||expr[j]==’/’)
{
newptr->val=expr[j];
newptr->lt=l2;
RESULT:
Thus the above program has been executed successfully
EX.NO: 10 BACK END COMPILER – ASSEMBLY LANGUAGE GENERATION
AIM:
To implement the back end of the compiler which takes the three address code and produces
the 8086 assembly language instructions that can be assembled and run using a 8086 assembler.
The target assembly instructions can be simple move, add, sub, jump. Also simple addressing
modes are used.
ALGORITHM:
1) Declare the header file.
2) Create a text file for intermediate code.
3) Open a file using FILE pointer.
4) Using strcmp () to find the operator and operand.
5) If conditional statement valid print relevant assembly code.
6) Close the program.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
OUTPUT:
[root@localhost ~]# vi ex10.c
[root@localhost ~]# cc ex10.c -o ex10.out
[root@localhost ~]# ./ex10.out
Enter filename of the intermediate code: input.c
MOV R0,printf("
MOV R1,B
DIV R0,R1
MOV value,R0
MOV R0,printf("C
MOV R1,value
DIV R0,R1
RESULT:
Thus the above program has been executed successfully
ALGORITHM:
Input: Set of ‘L’ values with corresponding ‘R’ values.
Output: Intermediate code & Optimized code after eliminating common expressions.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include <termios.h>
#include <unistd.h>
struct op
{
char l;
char r[20];
}
op[10],pr[10];
void main()
{
int a,i,k,j,n,z=0,m,q;
char *p,*l;
char temp,t;
char *tem;
RESULT:
Thus the above program has been executed successfully