0% found this document useful (0 votes)
32 views

CD Iii-2 - R18

Uploaded by

shaikilyas0579
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)
32 views

CD Iii-2 - R18

Uploaded by

shaikilyas0579
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/ 16

R18 B.

TECH CSE III YEAR

CS605PC: COMPILER DESIGN LAB


III Year B.Tech. CSE II-Sem LTPC
0 0 3 1.5
Prerequisites
1. A Course on “Objected Oriented Programming through Java”

Co-requisites
1. A course on “Web Technologies”

Course Objectives
1. To provide hands-on experience on web technologies
2. To develop client-server application using web technologies
3. To introduce server-side programming with Java servlets and JSP
4. To understand the various phases in the design of a compiler.
5. To understand the design of top-down and bottom-up parsers.
6. To understand syntax directed translation schemes.
7. To introduce lex and yacc tools.

Course Outcomes
1. Design and develop interactive and dynamic web applications using HTML, CSS, JavaScript and
XML
2. Apply client-server principles to develop scalable and enterprise web applications.
3. Ability to design, develop, and implement a compiler for any language.
4. Able to use lex and yacc tools for developing a scanner and a parser.
5. Able to design and implement LL and LR parsers.

List of Experiments
Compiler Design Experiments

1. Write a LEX Program to scan reserved word & Identifiers of C Language

2. Implement Predictive Parsing algorithm

3. Write a C program to generate three address code.

4. Implement SLR(1) Parsing algorithm

5. Design LALR bottom up parser for the given language


<program> ::= <block>
<block> ::= { <variabledefinition> <slist> }
| { <slist> }
<variabledefinition> ::= int <vardeflist> ;
<vardeflist> ::= <vardec> | <vardec> , <vardeflist>
<vardec> ::= <identifier> | <identifier> [ <constant> ]
<slist> ::= <statement> | <statement> ; <slist>
<statement> ::= <assignment> | <ifstatement> | <whilestatement>
| <block> | <printstatement> | <empty>
<assignment> ::= <identifier> = <expression>
| <identifier> [ <expression> ] = <expression>
<ifstatement> ::= if <bexpression> then <slist> else <slist> endif
| if <bexpression> then <slist> endif
<whilestatement> ::= while <bexpression> do <slist> enddo
<printstatement> ::= print ( <expression> )
<expression> ::= <expression> <addingop> <term> | <term> | <addingop> <term>
<bexpression> ::= <expression> <relop> <expression>
<relop> ::= < | <= | == | >= | > | !=
<addingop> ::= + | -
<term> ::= <term> <multop> <factor> | <factor>
<multop> ::= * | /
<factor> ::= <constant> | <identifier> | <identifier> [ <expression>]
| ( <expression> )
<constant> ::= <digit> | <digit> <constant>
<identifier> ::= <identifier> <letterordigit> | <letter>
<letterordigit> ::= <letter> | <digit>
<letter> ::= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
<digit> ::= 0|1|2|3|4|5|6|7|8|9
<empty> has the obvious meaning

Comments (zero or more characters enclosed between the standard C / Java-style comment brackets

/*...*/) can be inserted. The language has rudimentary support for 1-dimensional arrays. The declaration
int a[3] declares an array of three elements, referenced as a[0], a[1] and a[2]. Note
also that you should worry about the scoping of names.

A simple program written in this language is:


{ int a[3],t1,t2;
t1=2;
a[0]=1; a[1]=2; a[t1]=3;
t2=-(a[2]+t1*6)/(a[2]-t1);
if t2>5 then
print(t2);
else {
int t3;
t3=99;
t2=-25;
print(-t1+t2*t3); /* this is a comment
on 2 lines */
}
endif
}
Experiment No:1

LEX ANALYZER

Aim: Design a Lexical Analyzer.


Theory:
The lexical analyzer is the first phase of a compiler. Its main task is to read the input
characters and produce as output a sequence of tokens. Up on receiving a “get next token” command
from the parser, the lexical analyzer reads input characters until it can identify the next token. Token
is a group of characters having a collective meaning. Tokens are constants, identifier, keywords,
operators, special symbols.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
int i,j;
clrscr();
char keywords[10][10]={"BEGIN","IF","THEN","ELSE","END"};
char operators[10][10]={"<","<=",">","=","!="};
char string[10];
int ch,l,found=0;
printf("/n enter any data of your choice");
scanf("%s",string);
l=strlen(string);
for(i=0;i<l;i++)
string[i]=toupper(string[i]);
for(i=0;i<5;i++)
{
if(strcmp(&keywords[i][0],string)==0)
{
found=1;
ch=1;
break;
}
}
for(i=0;i<5;i++)
{
if(strcmp(&operators[i][0],string)==0)
{
found=1;
ch=2;
break;
}
}
switch(ch)
{
case 1:
if(found==1)
printf("\n you have entered keyword");
break;
case 2:
if(found==1)
printf("\n you have entered relational operator");
break;
default:printf("\n you have entered default choice");
}
getch();
}

Output:-
enter any data of your choice
else
you have entered keyword
enter any data of your choice
>
you have entered relational operator
2. Implement Predictive Parsing algorithm

/*top down parser parses a given string for an input string which may match the table which is printed
at the beginning of the program.
some of the input strings it may take are a+b$ and a+b*c$
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
char str[10],out,in,output[10],input[10],temp;
char tl[10]={'x','+','*','(',')','$','@'};
char ntl[10]={'E','e','T','t','F'};
int err=0,flag=0,i,j,k,l,m;
char c[10][10][7]={{{"Te"},{"ERROR!"},{"ERROR!"},{"Te"},{"ERROR!"},{"ERROR!"}},
{"ERROR!","+Te","ERROR!","ERROR!","@","@"},
{"Ft","ERROR!","ERROR!","Ft","ERROR!","ERROR!"},
{"ERROR!","@","*Ft","ERROR!","@","@"},
{"x","ERROR!","ERROR!","(E)","ERROR!","ERROR!"}};
struct stack
{
char sic[10];
int top;
};
void push(struct stack *s,char p)
{
s->sic[++s->top]=p;
s->sic[s->top+1]='\0';
}
char pop(struct stack *s)
{
char a;
a=s->sic[s->top];
s->sic[s->top--]='\0';
return(a);
}

char sttop(struct stack *s)


{
return(s->sic[s->top]);
}

void pobo(struct stack *s)


{
m=0;
while(str[m]!='\0')
m++;
m--;
while(m!=-1)
{
if(str[m]!='@')
push(s,str[m]);
m--;
}
}
void search(int l)
{
for(k=0;k<7;k++)
if(in==tl[k])
break;
if(l==0)
strcpy(str,c[l][k]);
else if(l==1)
strcpy(str,c[l][k]);
else if(l==2)
strcpy(str,c[l][k]);
else if(l==3)
strcpy(str,c[l][k]);
else
strcpy(str,c[l][k]);
}
void main()
{
struct stack s1;
struct stack *s;
s=&s1;
s->top=-1;
clrscr();

printf("\t\tPARSING TABLE\n~
\t========================================\n\n\tx\t+\t*\t(\t)\t$\n");
printf(" \t=============================================\n\n");
for(i=0;i<5;i++)
{
printf("%c\t",ntl[i]);
for(j=0;j<6;j++)
if(strcmp(c[i][j],"ERROR!")==0)
printf("ERROR!\t");
else
printf("%c->%s\t",ntl[i],c[i][j]);
printf("\n\n");
}
printf(" \t=============================================\n\n");
push(s,'$');
push(s,'E');
printf("\nENTER THE INPUT STRING: ");
scanf("%s",input);
printf("\n\nTHE BEHAVIOUR OF THE PARSER FOR GIVEN INPUT STRING IS:\n\n");
printf("STACK\tINPUT\tOUTPUT\n");
i=0;
in=input[i];
printf("%s\t",s->sic);
for(k=i;k<strlen(input);k++)
printf("%c",input[k]);
if(strcmp(str,"")!=0)
printf("\t%c->%s",ntl[j],str);
printf("\n");
while((s->sic[s->top]!='$')&&err!=1&&strcmp(str,"ERROR!")!=0)
{
strcpy(str,"");
flag=0;
for(j=0;j<7;j++)
if(in==tl[j])
{
flag=1;
break;
}
if(flag==0)
in='x';
flag=0;
out=sttop(s);

for(j=0;j<7;j++)
if(out==tl[j])
{
flag=1;
break;
}
if(flag==1)
{
if(out==in)
{
temp=pop(s);
in=input[++i];
if(str=='@')
temp=pop(s);
}
else
{
strcpy(str,"ERROR!");
err=1;
}
}
else
{
flag=0;
for(j=0;j<5;j++)
if(out==ntl[j])
{
flag=1;
break;
}
if(flag==1)
{
search(j);
temp=pop(s);
pobo(s);
}
else
{
strcpy(str,"ERROR!");
err=1;
}
}
if(strcmp(str,"ERROR!")!=0)
{
printf("%s\t",s->sic);
for(k=i;k<strlen(input);k++)
printf("%c",input[k]);
if((strcmp(str,"")!=0)&&(strcmp(str,"ERROR!")!=0))
printf("\t%c->%s",ntl[j],str);
printf("\n");
}
}
if(strcmp(str,"ERROR!")==0)
printf("\n\nTHE STRING IS NOT ACCEPTED!!!!");
else printf("$\t$\tACCEPT\n\n\nTHE STRING IS ACCEPTED!!!");
getch();
}
Output:
3. Write a C program to generate three address code.

#include<stdio.h>
#include<string.h>
void pm();
void plus();
void div();
int i,ch,j,l,addr=100;
char ex[10], exp[10] ,exp1[10],exp2[10],id1[5],op[5],id2[5];
void main()
{
clrscr();
while(1)
{
printf("\n1.assignment\n2.arithmetic\n3.relational\n4.Exit\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the expression with assignment operator:");
scanf("%s",exp);
l=strlen(exp);
exp2[0]='\0';
i=0;

while(exp[i]!='=')
{
i++;
}
strncat(exp2,exp,i);
strrev(exp);
exp1[0]='\0';
strncat(exp1,exp,l-(i+1));
strrev(exp1);
printf("Three address code:\ntemp=%s\n%s=temp\n",exp1,exp2);
break;

case 2:
printf("\nEnter the expression with arithmetic operator:");
scanf("%s",ex);
strcpy(exp,ex);
l=strlen(exp);
exp1[0]='\0';
for(i=0;i<l;i++)
{
if(exp[i]=='+'||exp[i]=='-')
{
if(exp[i+2]=='/'||exp[i+2]=='*')
{
pm();
break;
}
else
{
plus();
break;
}
}
else if(exp[i]=='/'||exp[i]=='*')
{
div();
break;
}
}
break;
case 3:
printf("Enter the expression with relational operator");
scanf("%s%s%s",&id1,&op,&id2);
if(((strcmp(op,"<")==0)||(strcmp(op,">")==0)||(strcmp(op,"<=")==0)||(strcmp(op,">=")==0)||(strcmp(o
p,"==")==0)||(strcmp(op,"!=")==0))==0)
printf("Expression is error");
else
{
printf("\n%d\tif %s%s%s goto %d",addr,id1,op,id2,addr+3);
addr++;
printf("\n%d\t T:=0",addr);
addr++;
printf("\n%d\t goto %d",addr,addr+2);
addr++;
printf("\n%d\t T:=1",addr);
}
break;
case 4:
exit(0);
}
}
}
void pm()
{
strrev(exp);
j=l-i-1;
strncat(exp1,exp,j);
strrev(exp1);
printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j+1],exp[j]);
}
void div()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}
void plus()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}
Output :

1. assignment
2. arithmetic
3. relational
4. Exit
Enter the choice:1
Enter the expression with assignment operator:
a=b
Three address code:
temp=b
a=temp

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a+b-c
Three address code:
temp=a+b
temp1=temp-c

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a-b/c
Three address code:
temp=b/c
temp1=a-temp

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:
a*b-c
Three address code:
temp=a*b
temp1=temp-c

1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:2
Enter the expression with arithmetic operator:a/b*c
Three address code:
temp=a/b
temp1=temp*c
1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:3
Enter the expression with relational operator
a
<=
b

100 if a<=b goto 103


101 T:=0
102 goto 104
103 T:=1
1.assignment
2.arithmetic
3.relational
4.Exit
Enter the choice:4
4. Implement SLR(1) parsing algorithm

#include<stdio.h>
#include<string.h>
int i,j,k,m,n=0,o,p,ns=0,tn=0,rr=0,ch=0;
char read[15][10],gl[15],gr[15][10],temp,templ[15],tempr[15][10],*ptr,temp2[5],dfa[15][15];
struct states
{
char lhs[15],rhs[15][10];
int n;
}I[15];

int compstruct(struct states s1,struct states s2)


{
int t;
if(s1.n!=s2.n)
return 0;
if( strcmp(s1.lhs,s2.lhs)!=0 )
return 0;
for(t=0;t<s1.n;t++)
if( strcmp(s1.rhs[t],s2.rhs[t])!=0 )
return 0;
return 1;
}

void moreprod()
{
int r,s,t,l1=0,rr1=0;
char *ptr1,read1[15][10];
for(r=0;r<I[ns].n;r++)
{
ptr1=strchr(I[ns].rhs[l1],'.');
t=ptr1-I[ns].rhs[l1];
if( t+1==strlen(I[ns].rhs[l1]) )
{
l1++;
continue;
}
temp=I[ns].rhs[l1][t+1];
l1++;
for(s=0;s<rr1;s++)
if( temp==read1[s][0] )
break;
if(s==rr1)
{
read1[rr1][0]=temp;
rr1++;
}
else
continue;
for(s=0;s<n;s++)
{
if(gl[s]==temp)
{
I[ns].rhs[I[ns].n][0]='.';
I[ns].rhs[I[ns].n][1]=NULL;
strcat(I[ns].rhs[I[ns].n],gr[s]);
I[ns].lhs[I[ns].n]=gl[s];
I[ns].lhs[I[ns].n+1]=NULL;
I[ns].n++;
}
}
}
}

void canonical(int l)
{
int t1;
char read1[15][10],rr1=0,*ptr1;
for(i=0;i<I[l].n;i++)
{
temp2[0]='.';
ptr1=strchr(I[l].rhs[i],'.');
t1=ptr1-I[l].rhs[i];
if( t1+1==strlen(I[l].rhs[i]) )
continue;
temp2[1]=I[l].rhs[i][t1+1];
temp2[2]=NULL;
for(j=0;j<rr1;j++)
if( strcmp(temp2,read1[j])==0 )
break;
if(j==rr1)
{
strcpy(read1[rr1],temp2);
read1[rr1][2]=NULL;
rr1++;
}
else
continue;
for(j=0;j<I[0].n;j++)
{
ptr=strstr(I[l].rhs[j],temp2);
if( ptr )
{
templ[tn]=I[l].lhs[j];
templ[tn+1]=NULL;
strcpy(tempr[tn],I[l].rhs[j]);
tn++;
}
}
for(j=0;j<tn;j++)
{
ptr=strchr(tempr[j],'.');
p=ptr-tempr[j];
tempr[j][p]=tempr[j][p+1];
tempr[j][p+1]='.';
I[ns].lhs[I[ns].n]=templ[j];
I[ns].lhs[I[ns].n+1]=NULL;
strcpy(I[ns].rhs[I[ns].n],tempr[j]);
I[ns].n++;
}

moreprod();
for(j=0;j<ns;j++)
{
//if ( memcmp(&I[ns],&I[j],sizeof(struct states))==1 )
if( compstruct(I[ns],I[j])==1 )
{
I[ns].lhs[0]=NULL;
for(k=0;k<I[ns].n;k++)
I[ns].rhs[k][0]=NULL;
I[ns].n=0;
dfa[l][j]=temp2[1];
break;
}
}
if(j<ns)
{
tn=0;
for(j=0;j<15;j++)
{
templ[j]=NULL;
tempr[j][0]=NULL;
}
continue;
}
dfa[l][j]=temp2[1];
printf("\n\nI%d :",ns);
for(j=0;j<I[ns].n;j++)
printf("\n\t%c -> %s",I[ns].lhs[j],I[ns].rhs[j]);
getch();
ns++;
tn=0;
for(j=0;j<15;j++)
{
templ[j]=NULL;
tempr[j][0]=NULL;
}
}
}

void main()
{
FILE *f;
int l;
clrscr();
for(i=0;i<15;i++)
{
I[i].n=0;
I[i].lhs[0]=NULL;
I[i].rhs[0][0]=NULL;
dfa[i][0]=NULL;
}
f=fopen("tab6.txt","r");
while(!feof(f))
{
fscanf(f,"%c",&gl[n]);
fscanf(f,"%s\n",gr[n]);
n++;
}
printf("THE GRAMMAR IS AS FOLLOWS\n");
for(i=0;i<n;i++)
printf("\t\t\t\t%c -> %s\n",gl[i],gr[i]);
I[0].lhs[0]='Z';
strcpy(I[0].rhs[0],".S");
I[0].n++;
l=0;
for(i=0;i<n;i++)
{
temp=I[0].rhs[l][1];
l++;
for(j=0;j<rr;j++)
if( temp==read[j][0] )
break;
if(j==rr)
{
read[rr][0]=temp;
rr++;
}
else
continue;
for(j=0;j<n;j++)
{
if(gl[j]==temp)
{
I[0].rhs[I[0].n][0]='.';
strcat(I[0].rhs[I[0].n],gr[j]);
I[0].lhs[I[0].n]=gl[j];
I[0].n++;
}
}
}
ns++;
printf("\nI%d :\n",ns-1);
for(i=0;i<I[0].n;i++)
printf("\t%c -> %s\n",I[0].lhs[i],I[0].rhs[i]);
for(l=0;l<ns;l++)
canonical(l);
printf("\n\n\t\tPRESS ANY KEY FOR DFA TABLE");
getch();
clrscr();
printf("\t\t\tDFA TABLE IS AS FOLLOWS\n\n\n");
for(i=0;i<ns;i++)
{
printf("I%d : ",i);
for(j=0;j<ns;j++)
if(dfa[i][j]!='\0')
printf("'%c'->I%d | ",dfa[i][j],j);
printf("\n\n\n");
}
printf("\n\n\n\t\tPRESS ANY KEY TO EXIT");
getch();
}
5. Design LALR bottom up parser for the given language.

<parser.l>

%{
#include<stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval.dval=atof(yytext);
return DIGIT;
}
\n|. return yytext[0];
%%

<parser.y>
%{
/*This YACC specification file generates the LALR parser for the program
considered in experiment 4.*/
#include<stdio.h>
%}
%union
{
double dval;
}
%token <dval> DIGIT
%type <dval> expr
%type <dval> term
%type <dval> factor
%%
line: expr '\n' {
printf("%g\n",$1);
}
;
expr: expr '+' term {$$=$1 + $3 ;}
| term
;
term: term '*' factor {$$=$1 * $3 ;}
| factor
;
factor: '(' expr ')' {$$=$2 ;}
| DIGIT
;
%%
int main()
{
yyparse();
}
yyerror(char *s)
{
printf("%s",s);
}

Output:
$lex parser.l
$yacc –d parser.y
$cc lex.yy.c y.tab.c –ll –lm
$./a.out
2+3

5.0000

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy