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

CD Lab Manual-1

The document describes a compiler design lab manual for a computer science and engineering department. It contains information about the system requirements for the lab, the objectives of the lab, and topics to be covered in the lab including designing a lexical analyzer, implementing a lexical analyzer using tools like JLex and Flex, designing predictive and LALR parsers, and converting BNF rules to YACC form to generate an abstract syntax tree. It provides details about the department, college, and year for which the lab manual is created.

Uploaded by

Bhavani Siva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

CD Lab Manual-1

The document describes a compiler design lab manual for a computer science and engineering department. It contains information about the system requirements for the lab, the objectives of the lab, and topics to be covered in the lab including designing a lexical analyzer, implementing a lexical analyzer using tools like JLex and Flex, designing predictive and LALR parsers, and converting BNF rules to YACC form to generate an abstract syntax tree. It provides details about the department, college, and year for which the lab manual is created.

Uploaded by

Bhavani Siva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 49

Department of Computer Science and Engineering

Department
Of
Computer Science & Engineering
Compiler Design Lab Manual

CHIRALA ENGINEERING
COLLEGE
Approved by AICTE :: Affiliated to JNTU, Kakinada,(Sponsored by GSR & TSR
Educational society),
Ramapuram Beach Road, Vetapalem Mandal, CHIRALA 523 157. Prakasam
District, A.P. India

Department of computer science & engineering

In-charge

Prepared by:

HOD

Approved & Reviewed


by:

Principal

Issued by:

w.e.f Date:

Department of Computer Science and Engineering

CHIRALA ENGINEERING
COLLEGE
Approved by AICTE :: Affiliated to JNTU, Kakinada,(Sponsored by GSR & TSR
Educational society),
Ramapuram Beach Road, Vetapalem Mandal, CHIRALA 523 157. Prakasam
District, A.P. India

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Lab Manual for the Academic Year 2014-15


(In accordance with JNTUK syllabus)

SUBJECT

Compiler Design LAB

STREAM

CSE

H.O.D

Department of Computer Science and Engineering

S.
No

TOPIC

System Requirements

Lab Objectives

Design a lexical analyzer for given language and


the lexical analyzer should ignore redundant
spaces, tabs and new lines

Implement the lexical analyzer using JLex, flex or


other lexical analyzer generating tools.

Design predictive parser for the given language

Design a LALR bottom up parser for the given


language

Convert the BNF rules into YACC form and write


code to generate abstract syntax tree.

Page
No.

Department of Computer Science and Engineering

System Requirements
1. Intel based destktop PC of 166MHz or faster processor with at least
64 MB RAM and 100 MB free disk space.
2. C++ compiler and JDK kit.

Department of Computer Science and Engineering

Lab Objectives
1. To

provide

an

Understanding

of

the

language

translation

peculiarities by designing complete translator for mini language.


2. To provide an understanding of the design aspect of operating
system.

Department of Computer Science and Engineering

Program No.1:
Write a Program to Design Lexical Analyzer.
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str )
==0||strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||
strcmp("static",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);
}
main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
printf("\nEnter the c program");/*gets(st1);*/
f1=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
6

Department of Computer Science and Engineering

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')
lineno++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
7

Department of Computer Science and Engineering

printf("\nThe no's in the program are");


for(j=0;j<i;j++)
printf("%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("The keywords and identifiersare:");
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("\nSpecial characters are");
while((c=getc(f3))!=EOF)
printf("%c",c);
printf("\n");
fclose(f3);
printf("Total no. of lines are:%d",lineno);
}

Department of Computer Science and Engineering

Output:
Enter the C program
a+b*c
Ctrl-D
The nos in the program are:
The keywords and identifiers are:
a is an identifier and terminal
b is an identifier and terminal
c is an identifier and terminal
Special characters are:
+*
Total no. of lines are: 1

Department of Computer Science and Engineering

Program No. 2:
Write a program Implement the Lexical Analyzer Using LEX Tool.
/* program name is lexp.l */
%{
/* program to recognize a c program */
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
float |
char |
double |
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%s is a COMMENT\n",yytext);}*/
"*/" {COMMENT = 0;}
/* printf("\n\n\t%s is a COMMENT\n",yytext);}*/
10

Department of Computer Science and Engineering

{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\t%s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n\t%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);}
%%
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
printf("could not open %s \n",argv[1]);
exit(0);
}
yyin = file;
}
yylex();
printf("\n\n");
return 0;
} int yywrap()
{
return 0;
}
11

Department of Computer Science and Engineering

Input:
$vi var.c
#include<stdio.h>
main()
{
int a,b;
}
Output:
$lex lex.l
$cc lex.yy.c
$./a.out var.c
#include<stdio.h> is a PREPROCESSOR DIRECTIVE
FUNCTION
main (
)
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER
b IDENTIFIER
BLOCK ENDS

12

Department of Computer Science and Engineering

Program No. 3:
Write a Program for Implementation of Predictive Parser.
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 128
#define NONE -1
#define EOS '\0'
#define NUM 257
#define KEYWORD 258
#define ID 259
#define DONE 260
#define MAX 999
char lexemes[MAX];
char buffer[SIZE];
int lastchar=-1;
int lastentry=0;
int tokenval=DONE;
int lineno=1;
int lookahead;
struct entry
{
char *lexptr;
int token;
}
symtable[100];
struct entry
keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,
"float",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"ret
urn",KEYWORD,0,0};
void Error_Message(char *m)
{
fprintf(stderr,"line %d, %s \n",lineno,m);
13

Department of Computer Science and Engineering

exit(1);
}
int look_up(char s[ ])
{
int k;
for(k=lastentry;k>0;k--)
if(strcmp(symtable[k].lexptr,s)==0)
return k;
return 0;
}
int insert(char s[ ],int tok)
{
int len;
len=strlen(s);
if(lastentry+1>=MAX)
Error_Message("Symbpl table is full");
if(lastchar+len+1>=MAX)
Error_Message("Lexemes array is full");
lastentry=lastentry+1;
symtable[lastentry].token=tok;
symtable[lastentry].lexptr=&lexemes[lastchar+1];
lastchar=lastchar+len+1;
strcpy(symtable[lastentry].lexptr,s);
return lastentry;
}
/*void Initialize()
{
struct entry *ptr;
for(ptr=keywords;ptr->token;ptr+1)
insert(ptr->lexptr,ptr->token);
}*/
int lexer()
{
int t;
int val,i=0;
14

Department of Computer Science and Engineering

while(1)
{
t=getchar();
if(t==' '||t=='\t');
else
if(t=='\n')
lineno=lineno+1;
else
if(isdigit(t))
{
ungetc(t,stdin);
scanf("%d",&tokenval);
return NUM;
}
else
if(isalpha(t))
{
while(isalnum(t))
{
buffer[i]=t;
t=getchar();
i=i+1;
if(i>=SIZE)
Error_Message("Compiler error");
}
buffer[i]=EOS;
if(t!=EOF)
ungetc(t,stdin);
val=look_up(buffer);
if(val==0)
val=insert(buffer,ID);
tokenval=val;
return symtable[val].token;
}
else
15

Department of Computer Science and Engineering

if(t==EOF)
return DONE;
else
{
tokenval=NONE;
return t;
}
}
}
void Match(int t)
{
if(lookahead==t)
lookahead=lexer();
else
Error_Message("Syntax error");
}
void display(int t,int tval)
{
if(t=='+'||t=='-'||t=='*'||t=='/')
printf("\nArithmetic Operator: %c",t);
else if(t==NUM)
printf("\n Number: %d",tval);
else if(t==ID)
printf("\n Identifier: %s",symtable[tval].lexptr);
else
printf("\n Token %d tokenval %d",t,tokenval);
}
void F()
{
//void E();
switch(lookahead)
{
case '(' :

Match('(');
E();
Match(')');
16

Department of Computer Science and Engineering

break;
case NUM :

display(NUM,tokenval);
Match(NUM);
break;

case ID :

display(ID,tokenval);
Match(ID);
break;

default :

Error_Message("Syntax error");

}
}
void T()
{
int t;
F();
while(1)
{
switch(lookahead)
{
case '*' : t=lookahead;
Match(lookahead);
F();
display(t,NONE);
continue;
case '/' : t=lookahead;
Match(lookahead);
display(t,NONE);
continue;
default : return;
}
}
}
void E()
{
int t;
T();
17

Department of Computer Science and Engineering

while(1)
{
switch(lookahead)
{
case '+' :

t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;

case '-' :

t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;
default : return;

}
}
}
void parser()
{
lookahead=lexer();
while(lookahead!=DONE)
{
E();
Match(';');
}
}
main()
{
char ans[10];
printf("\n Program for recursive decent parsing ");
printf("\n Enter the expression ");
printf("And place ; at the end\n");
printf("Press Ctrl-Z to terminate\n");
parser();
18

Department of Computer Science and Engineering

}
Output:
Program for recursive decent parsing
Enter the expression And place ; at the end
Press Ctrl-Z to terminate
a+b*c;
Identifier: a
Identifier: b
Identifier: c
Arithmetic Operator: *
Arithmetic Operator: +
2*3;
Number: 2
Number: 3
Arithmetic Operator: *
+3;
line 5,Syntax error
Ctrl-Z

Program No: 4
19

Department of Computer Science and Engineering

Write a program to Design LALR Bottom up Parser.


<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 ;}
20

Department of Computer Science and Engineering

| 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

Program No: 5
Convert The BNF rules into Yacc form and write code to generate abstract syntax tree.
<int.l>
21

Department of Computer Science and Engineering

%{
#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);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
<int.y>
%{
#include<string.h>
#include<stdio.h>
struct quad
22

Department of Computer Science and Engineering

{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int items[100];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
| ASSIGNMENT ';'
| CONDST
23

Department of Computer Science and Engineering

| 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);
24

Department of Computer Science and Engineering

strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
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);
}
25

Department of Computer Science and Engineering

;
WHILELOOP: WHILE '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
if(argc>1)
{
fp=fopen(argv[1],"r");
if(!fp)
{
printf("\n File not found");
exit(0);
}
yyin=fp;
}
yyparse();
26

Department of Computer Science and Engineering

printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t


--------------------");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t
%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
}
printf("\n\t\t -----------------------");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0);
}
data=stk.items[stk.top--];
return data;
}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
27

Department of Computer Science and Engineering

strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
sprintf(QUAD[Index].result,"t%d",tIndex++);
strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\n Error on line no:%d",LineNo);
}
Input:
$vi test.c
main()
{
int a,b,c;
if(a<b)
{
a=a+b;
}
while(a<b)
{
a=a+b;
}
if(a<=b)
{
c=a-b;
}
else
{
c=a+b;
}
}
Output:
$lex int.l
$yacc d int.y
$gcc lex.yy.c y.tab.c ll lm
28

Department of Computer Science and Engineering

$./a.out test.c
OUTPUT:

29

Department of Computer Science and Engineering

Intermediate code generation


#include<stdio.h>
#include<conio.h>
#include<string.h>
int i=1,j=0,no=0,tmpch=90;
char str[100],left[15],right[15];
void findopr();
void explore();
void fleft(int);
void fright(int);
struct exp
{
int pos;
char op;
}k[15];
void main()
{
clrscr();
printf("\t\tINTERMEDIATE CODE GENERATION\n\n");
printf("Enter the Expression :");
scanf("%s",str);
printf("The intermediate code:\t\tExpression\n");
findopr();
explore();
getch();
}
void findopr()
{
30

Department of Computer Science and Engineering

for(i=0;str[i]!='\0';i++)
if(str[i]==':')
{
k[j].pos=i;
k[j++].op=':';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='/')
{
k[j].pos=i;
k[j++].op='/';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='*')
{
k[j].pos=i;
k[j++].op='*';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='+')
{
k[j].pos=i;
k[j++].op='+';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='-')
{
k[j].pos=i;
31

Department of Computer Science and Engineering

k[j++].op='-';
}
}
void explore()
{
i=1;
while(k[i].op!='\0')
{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos]=tmpch--;
printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right);
for(j=0;j<strlen(str);j++)
if(str[j]!='$')
printf("%c",str[j]);
printf("\n");
i++;
}
fright(-1);
if(no==0)
{
fleft(strlen(str));
printf("\t%s := %s",right,left);
getch();
exit(0);
}
printf("\t%s := %c",right,str[k[--i].pos]);
getch();
32

Department of Computer Science and Engineering

}
void fleft(int x)
{
int w=0,flag=0;
x--;
while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!
='-'&&str[x]!='/'&&str[x]!=':')
{
if(str[x]!='$'&& flag==0)
{
left[w++]=str[x];
left[w]='\0';
str[x]='$';
flag=1;
}
x--;
}
}
void fright(int x)
{
int w=0,flag=0;
x++;
while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!
=':'&&str[x]!='-'&&str[x]!='/')
{
if(str[x]!='$'&& flag==0)
{
right[w++]=str[x];
right[w]='\0';
33

Department of Computer Science and Engineering

str[x]='$';
flag=1;
}
x++;
}
}

Output:

34

Department of Computer Science and Engineering

Code generation:
#include"stdio.h"
#include"conio.h"
#include"string.h"
#include"stdlib.h"
struct quadraple
{
int pos;
char op;
char arg1[5];
char arg2[5];
char result[5];
}quad[15];
int n=0;
void assignment(int);
void uminus(int );
void explore();
void codegen(char op[5],int);
char tuple[15][15];
int main(void)
{
FILE *src;
int nRetInd,i;
char str[15];
clrscr();
src=fopen("int.txt","r");
fscanf(src,"%s",str);
while(!feof(src))
{
strcpy(tuple[n++],str);
fscanf(src,"%s",str);
}
printf("INPUT:\nIntermiate codes:\n");
for(i=0;i< n;i++)
printf("%s\n",tuple[i]);
explore();
getch();
clrscr();
printf("OUTPUT:\n");
printf("Quadruple: \n");
printf("pos\topr\targ1\targ2\tresult\n");
for(i=0;i< n;i++)
printf("\n%d\t%c\t%s\t%s\t
%s",quad[i].pos,quad[i].op,quad[i].arg1,quad[i].arg2,quad[i].result);
i=0;
printf("\n\ncode generated :\n");
while(i< n)
{
35

Department of Computer Science and Engineering

if(quad[i].op=='+')
codegen("ADD",i);
if(quad[i].op=='=')
assignment(i);
if(quad[i].op=='-')
if(!strcmp(quad[i].arg2,"\0"))
uminus(i);
else
codegen("SUB",i);
if(quad[i].op=='*')
codegen("MUL",i);
if(quad[i].op=='/')
codegen("DIV",i);
i++;
}
getch();
fcloseall();
return 0;
}
void codegen(char op[5],int t)
{
char str[25];
printf("MOV %s,R0\n",quad[t].arg1);
printf("%s %s,R0\n",op,quad[t].arg2);
printf("MOV R0,%s\n",quad[t].result);
}
void assignment(int t)
{
char str[25];
printf("MOV %s,%s\n",quad[t].result,quad[t].arg1);
}
void uminus(int t)
{
char str[25];
printf("MOV R0,0\n");
printf("SUB %s,R0\n",quad[t].arg1);
printf("MOV R0,%s\n",quad[t].result);
}
void explore()
{
int i,j,t,t1,t2;
for(i=0;i < n;i++)
{
quad[i].pos=i;
for(j=0,t=0;j < strlen(tuple[i])&&tuple[i][j]!='=';j++)<strlen(tuple[i])&&tuple[i][j]!='=';j+
+)></strlen(tuple[i])&&tuple[i][j]!='=';j++)>
{
quad[i].result[t++]=tuple[i][j];
}
t1=j;
quad[i].result[t]='\0';
36

Department of Computer Science and Engineering

if(tuple[i][j]=='=')
{
quad[i].op='=';
}
if(tuple[i][j+1]=='+'||tuple[i][j+1]=='-'||tuple[i][j+1]=='*'||tuple[i][j+1]=='/')
{
quad[i].op=tuple[i][j+1];
t1=j+1;
}
for(j=t1+1,t=0;j< strlen(tuple[i])&&tuple[i][j]!='+'&&tuple[i][j]!='-'&&tuple[i][j]!
='*'&&tuple[i][j]!='/';j++)
{
quad[i].arg1[t++]=tuple[i][j];
}
t2=j;
quad[i].arg1[t]='\0';
if(tuple[i][j]=='+'||tuple[i][j]=='-'||tuple[i][j]=='*'||tuple[i][j]=='/')
{
quad[i].op=tuple[i][j];
}
for(j=t2+1,t=0;j< strlen(tuple[i]);j++)
{
quad[i].arg2[t++]=tuple[i][j];
}
quad[i].arg2[t]='\0';
}
}
INPUT:
INT.TXT
t0=c+d
t1=t0*c
b=t0/c
c=-t1
t2=t3

OUTPUT:

37

Department of Computer Science and Engineering

38

Department of Computer Science and Engineering

To parse a string using Operator Precedence parsing in C++ Programming


#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int getOperatorPosition(char );
#define node struct tree1
int matrix[5][5]={
{1,0,0,1,1},
{1,1,0,1,1},
{0,0,0,2,3},
{1,1,3,1,1},
{0,0,0,3,2}};
int tos=-1;
void matrix_value(void);
//node create_node(char,*node);void show_tree( node *);
int isOperator(char );
struct tree1
{
char data;
node *lptr;
node *rptr;
}*first;
struct opr
{
char op_name;
node *t;
}oprate[50];
char cur_op[5]={'+','*','(',')','['};
char stack_op[5]={'+','*','(',')',']'};
void main()
{
char exp[10];
int ssm=0,row=0,col=0;
node *temp;
// clrscr();
printf("Enter Exp : ");
scanf("%s",exp);
matrix_value();
while(exp[ssm] != '\0')
39

Department of Computer Science and Engineering

{
if(ssm==0)
{
tos++;
oprate[tos].op_name = exp[tos];
}
else
{
if(isOperator(exp[ssm]) == -1)
{
oprate[tos].t = (node*) malloc (sizeof(node));
oprate[tos].t->data = exp[ssm];
oprate[tos].t->lptr = '\0';
oprate[tos].t->rptr = '\0';
}
else
{
row = getOperatorPosition(oprate[tos].op_name);
col = getOperatorPosition(exp[ssm]);
if(matrix[row][col] == 0)
{
tos++;
oprate[tos].op_name = exp[ssm];
}
elseif(matrix[row][col] == 1)
{
temp = (node*) malloc (sizeof(node));
temp->data = oprate[tos].op_name;
temp->lptr = (oprate[tos-1].t);
temp->rptr = (oprate[tos].t);
tos--;
oprate[tos].t = temp;
ssm--;
}
elseif(matrix[row][col] == 2)
{
//temp = (node*) malloc (sizeof(node));
temp = oprate[tos].t;
tos--;
oprate[tos].t = temp;
}
elseif(matrix[row][col] == 3)
{
printf("\nExpression is Invalid...\n");
printf("%c %c can not occur simultaneously\n",oprate[tos].op_name,exp[ssm]);
break;
}
}

40

Department of Computer Science and Engineering

}
ssm++;
}
printf("show tree \n\n\n");
show_tree(oprate[tos].t);
printf("Over");
getch();
getch();
}
int isOperator(char c)
{
int i=0;
for(i=0;i<5;i++)
{
if (c==cur_op[i] || c==stack_op[i])
break;
}
if(i==5)
return (-1);
elsereturn i;
}
int getOperatorPosition(char c)
{
int i;
for(i=0;i<5;i++)
{
if (c==cur_op[i] || c==stack_op[i])
break;
}
return i;
}
void show_tree(node *start)
{
if(start->lptr != NULL)
show_tree(start->lptr);
if(start->rptr != NULL)
show_tree(start->rptr);
printf("%c \n",start->data);
}
void matrix_value(void)
{
int i,j;
41

Department of Computer Science and Engineering

printf("OPERATOR PRECEDENCE MATRIX\n");


printf("===========================\n ");
for(i=0; i<5; i++)
{
printf("%c ",stack_op[i]);
}
printf("\n");
for(i=0;i<5;i++)
{
printf("%c ",cur_op[i]);
for(j=0;j<5;j++)
{
if(matrix[i][j] == 0)
printf("< ");
elseif(matrix[i][j] == 1)
printf("> ");
elseif(matrix[i][j] == 2)
printf("= ");
elseif(matrix[i][j] == 3)
printf(" ");
}
printf("\n");
}
}
/***********************************
OUTPUT:
***********************************/
Enter Exp : [a+b*c]
OPERATOR PRECEDENCE MATRIX
===========================
+*()]
+ ><<>>
* >><>>
( <<<=
) >> >>
[ <<< =
show tree
a
b
c
*
+
Over
Enter Exp : [a+(b*c)+d]
OPERATOR PRECEDENCE MATRIX
42

Department of Computer Science and Engineering

===========================
+*()]
+ ><<>>
* >><>>
( <<<=
) >> >>
[ <<< =
show tree
a
b
c
*
+
d
+
Over
Enter Exp : [)]
OPERATOR PRECEDENCE MATRIX
===========================
+*()]
+ ><<>>
* >><>>
( <<<=
) >> >>
[ <<< =
Expression is Invalid...
[ ) can not occur simultaneously
show tree
.
Over

43

Department of Computer Science and Engineering

PROGRAM FOR COMPUTATION OF FIRST


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char t[5],nt[10],p[5
][5],first[5][5],temp;
int i,j,not,nont,k=0,f=0;
clrscr();
printf("\nEnter the
no. of Non-terminals in the grammer:");
scanf("%d",&nont);
printf("\nEnter the Non-terminals in the grammer:\n");
for(i=0;i<nont;i++)
{
scanf("\n%c",&nt[i]);
}
printf("\nEnter the no. of Te
rminals in the grammer: ( Enter e for absiline ) ");
scanf("%d",&not);
printf("\nEnter the Terminals in the grammer:\n");
for(i=0;i<not||t[i]=='$';i++)
{
scanf("\n%c",&t[i]);
}
for(i=0;i<nont;i++)
{
p[i][0]=nt[i];
first[i][0]=nt[i];
}
printf("\nEnter the productions :\n");
for(i=0;i<nont;i++)
{
scanf("%c",&temp);
printf("\nEnter the pr
oduction for %c ( End the production with '$' sign )
:",p[i][0]);
for(j=0;p[i][j]!='$';)
{
j+=1;
scanf("%c",&p[i][j]);
}
}
for(i=0;i<nont;i++)
{
printf("\nThe production
for %c -> ",p[i][0]);
for(j=1;p[i][j]!='$';j++)
{
44

Department of Computer Science and Engineering

printf("%c",p[i][j]);
}
}
for(i=0;i<nont;i++)
{
f=0;
for(j=1;p[i][j]!='$';j++)
{
for(k=0;k<not;k++)
{
if(f==1)
break;
if(p[i][j]==t[k])
{
first[i][j]=t[k];
first[i][j+1]='$';
f=1;
break;
}
else if(p[i][j]==nt[k])
{
first[i][j]=first[k][j];
if(first[i][j]=='e')
continue;
first[i][j+1]='$';
f=1;
break;
}
}
}
}
for(i=0;i<nont;i++)
{
printf("\n\nThe first of %c -> ",first[i][0]);
for(j=1;first[i][j]!='$';j++)
{
printf("%c\t",first[i][j]);
}
}
getch();
}
OUTPUT
Enter the no. of Non-terminals in the
grammer:3
Enter the Non-terminals in the grammer:
ERT
Enter the no. of Terminals in
the grammer: ( Enter e for absiline ) 5
Enter the Terminals in the grammer:
ase*+
Enter the productions :
Enter the production for E ( End the production
45

Department of Computer Science and Engineering

with '$' sign ) :a+s$


Enter the production for R ( End the production
with '$' sign ) :e$
Enter the production for T ( End the production
with '$' sign ) :Rs$
The production for E -> a+s
The production for R -> e
The production for T -> Rs
The first of E -> a
The first of R -> e
The first of T -> e s
PROGRAM FOR COMPUTATION OF FOLLOW
#include<stdio.h>
#include<string.h>
int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
void follow(char c);
void first(char c);
int main()
{
int i,z;
char c,ch;
printf("Enter the no.of productions:");
scanf("%d",&n);
printf("Enter the productions(epsilon=$):\n");
for(i=0;i<n;i++)
scanf("%s%c",a[i],&ch);
do
{
m=0;
printf("Enter the element whose FOLLOW is to be found:");
scanf("%c",&c);
follow(c);
printf("FOLLOW(%c) = { ",c);
for(i=0;i<m;i++)
printf("%c ",f[i]);
printf(" }\n");
printf("Do you want to continue(0/1)?");
scanf("%d%c",&z,&ch);
}
while(z==1);
}
void follow(char c)
{
if(a[0][0]==c)f[m++]='$';
for(i=0;i<n;i++)
{
for(j=2;j<strlen(a[i]);j++)
46

Department of Computer Science and Engineering

{
if(a[i][j]==c)
{
if(a[i][j+1]!='\0')first(a[i][j+1]);
if(a[i][j+1]=='\0'&&c!=a[i][0])
follow(a[i][0]);
}
}
}
}
void first(char c)
{
int k;
if(!(isupper(c)))f[m++]=c;
for(k=0;k<n;k++)
{
if(a[k][0]==c)
{
if(a[k][2]=='$') follow(a[i][0]);
else if(islower(a[k][2]))f[m++]=a[k][2];
else first(a[k][2]);
}
}
}

/*
SAMPLE OUTPUT:
productions:
E=TD
D=+TD
D=$
T=FS
S=*FS
S=$
F=(E)
F=a
FOLLOW(E)=FOLLOW(D)={),$}
FOLLOW(T)=FOLLOW(S)={+,),$}
FOLLOW(F)={+,*,),$}
Calculator using Yacc
/******************************************************
47

Department of Computer Science and Engineering

* Problem Statement :Assignment To implement a simple Calculator using Yacc


********************** calci.l *************************/
%{
#include<stdio.h>
#include<math.h>
#include "y.tab.h"
%}
%%
[0-9]+ {
yylval.dval=atoi(yytext);
return NUMBER;
}
[t];
n return 0;
. {return yytext[0];}
%%
void yyerror(char *str)
{
printf("n Invalid Character...");
}
int main()
{
printf("Enter Expression => ");
yyparse();
return(0);
}
********************** calci.y ***********************
%{
#include<stdio.h>
int yylex(void);
%}
%union
{
float dval;
}
%token <dval> NUMBER
%left '+' '-'
%left '*' '/'
%nonassoc UMINUS
%type <dval> exp
%%
state : exp {printf("Answer = %fn",$1);}
;
exp : NUMBER
| exp '+' exp {$$=$1+$3;}
| exp '-' exp {$$=$1-$3;}
| exp '*' exp {$$=$1*$3;}
| exp '/' exp {$$=$1/$3;}
| '('exp')' {$$=$2;}
| '-' exp %prec UMINUS {$$=-$2;}
;
48

Department of Computer Science and Engineering

%%
********************** Output ***********************
[a40@localhost ~]$ lex calci.l
[a40@localhost ~]$ yacc -d calci.y
[a40@localhost ~]$ cc lex.yy.c y.tab.c -ll
[a40@localhost ~]$ ./a.out
Enter Expression => 10+7
Answer = 17

49

You might also like