Вы находитесь на странице: 1из 30

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL

LEX PROGRAMS
1(a).Program to count the number of Characters,Words,Spaces and Lines in a given
input line
PROGRAM:
%{
int WCount=0,CCount=0,BCount=0,LCount=0;
%}
Word [^ \t\n]+
Eol [\n]
%%
{Word} { WCount++;
CCount+=yyleng; }
{Eol} { CCount++; LCount++; }
[ ]
{ BCount++; }
.
{ ECHO; CCount; }
%%
main(int argc,char *argv[])
{
if(argc!=0)
{
FILE *fp;
fp=fopen(argv[1],"r");
if(!fp)
{
fprintf(stderr,"Unable to Open File %s for Reading!!!! \n",argv[1]);
exit(1);
}
yyin=fp;
yylex();
printf("\nNumber of Blanks=%d\nNumber of Characters=%d",BCount,CCount);
printf("\nNumber of Words=%d\nNumber of Line=%d\n",WCount,LCount);
}
else
{
printf("Too Few Parameters Required\n");
}
}

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL

OUTPUT:
$ lex 1a.l
$ cc lex.yy.c -ll
$ ./a.out
Unable to Open File (null) for Reading!!!!
$ cat>s.c
B
h
a
r
a
t
h
$ ./a.out s.c
Number
Number
Number
Number

of
of
of
of

Blanks=21
Characters=14
Words=7
Line=7

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


1(b).Program to count the numbers of comment lines in a given C program.Also
eliminate them and copy the resulting program into seperate file.
PROGRAM:
%{
int Comment=0;
%}
%X COMMENT
%%
^[ \t]*"/*" {BEGIN COMMENT;}
^[ \t]*"/*".*"*/"[ \t]*\n {Comment++;}
<COMMENT>"*/"[ \t]*\n {BEGIN 0;Comment++;}
<COMMENT>"*/" {BEGIN 0;Comment++;}
<COMMENT> {fprintf(yyout," "); }
.;
%%
main(int argc,char *argv[])
{
if(argc!=3)
{
printf("Pass 3 Arguments\n");
return;
}
yyin=fopen(argv[1],"r");
yyout=fopen(argv[2],"w");
yylex();
printf("Number of Comment Lines=%d\n",Comment);
}

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL

OUTPUT:
$ lex 1b.l
$ cc lex.yy.c -ll
$ ./a.out
Pass 3 Arguments
$ cat>s1
/*Program To find sum of 3 numbers*/
/*start of program*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,sum;
/*Notify user to input the value*/
printf("Enter The Value of a,b & c");
/*Accept the input for variables for a,b,c*/
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
/*Output the result*/
printf("sum=%d\n",sum);
getch();
}
/*End of Program*/
$ ./a.out s1 s
Number of Comment Lines=6
$ cat s
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,sum;
printf("Enter The Value of a,b & c");
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
printf("sum=%d\n",sum);
getch();
}

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


2(a). Program to recognize a valid arithmetic expression and to recognize the
identifiers and operators present.Print them seperately.
PROGRAM:
%{
int iden=0,dno=0,opr=0,plus=0,minus=0,mul=0,divide=0,top=-1,valid=1;
char stack[50];
%}
%%
[0-9]+ {dno++;}
[_a-zA-Z]+ {iden++;}
[+] {opr++; plus++;}
[-] {opr++; minus++;}
[*] {opr++; mul++;}
[/] {opr++; divide++;}
\{ {stack[++top]='{';}
\} {if(stack[top--]!='{') valid=0;}
\[ {stack[++top]='[';}
\] {if(stack[top--]!='[') valid=0;}
\( {stack[++top]='(';}
\) {if(stack[top--]!='(') valid=0;}
%%
main()
{
printf("Enter Arithmetic Expression:");
yylex();
if(valid==1 && top==-1 && (dno+iden)==opr+1 || opr==0)
{
printf("Valid Input\n");
printf("Number of Identifiers:%d\n",iden);
printf("Number of Digits:%d\n",dno);
printf("Number of Plus Operator:%d\n",plus);
printf("Number of minus Operator:%d\n",minus);
printf("Number of mul Operator:%d\n",mul);
printf("Number of div Operator:%d\n",divide);
}
else
{
printf("Invalid Input\n");}
}
OUTPUT:
$ lex 2a.l
$ cc lex.yy.c -ll
$ ./a.out
Enter Arithmetic Expression:a+b-c*5/4
Valid Input
Number of Identifiers:3
Number of Digits:2
Number of Plus Operator:1
Number of minus Operator:1
Number of mul Operator:1

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


Number of div Operator:1
$ ./a.out
Enter Arithmetic Expression:a=b+c
=
Invalid Input

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


2(b).Program to recognize whether a given sentence is simple or compound.
PROGRAM:
%{
int cs=0;
%}
%%
[\t\n]+;
and|or|but|nor|neither|either|nevertheless {cs=1;}
.;
%%
main()
{
printf("Enter a Sentence:");
yylex();
if(cs==1)
printf("Statement is Compound\n");
else
printf("Statement is Simple\n");
}
OUTPUT:
$ lex 2b.l
$ cc lex.yy.c -ll
$ ./a.out
Enter a Sentence:this is an apple
this is an apple
Statement is Simple
$ ./a.out
Enter a Sentence:this is an apple and that is a knife
this is an apple that is a knife
Statement is Compound

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


3.Program to recognize and count the number of identifiers in a given input
file.
PROGRAM:
%{
int id=0,flag=0;
%}
%%
int|long|float|char|double {flag=1;}
[,] {if(flag) id++;}
[.] {if(flag) {flag=0,id++;} }
. {;}
%%
int main(int argc,char *argv[])
{
char sname[25];
if(argc!=2)
{
printf("Enter the Source Filename.....\n");
scanf("%s",sname);
yyin=fopen(sname,"r");
}
else
{
yyin=fopen(argv[1],"r");
}
yylex();
printf("Number of Id=%d\n",id);
return 0;
}
OUTPUT:
$ lex 3.l
$ cc lex.yy.c -ll
$ ./a.out
Enter the Source Filename.....
abc
Number of Id=11
$ cat abc
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
float d,e,f;
char g;
printf("Enter The Value of a,b & c");
scanf("%d%d%d",&a,&b,&c);
scanf("%d%d%d",&d,&e,&f);
getch();
}

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


YACC PROGRAMS
4(a).Program to recognize a valid arithmetic expression that uses operators
+,-,* and /.
PROGRAM:
LEX PART:
%{
#include "y.tab.h"
%}
%%
[a-zA-Z0-9]+ return ID;
= return EQ;
\( return LB;
\) return RB;
[-+] return SA;
[*/] return MD;
%%
YACC PART:
%{
#include<stdio.h>
%}
%token ID EQ LB RB SA MD
%%
assign:ID EQ expr|expr;
expr:term|expr SA term;
term:factor|term MD factor;
factor:ID|LB expr RB;
%%
main()
{
printf("Enter the Expression:\n");
if(yyparse()==0)
printf("Valid Expression\n");
}
yyerror()
{
printf("Invalid Expression\n");
}
OUTPUT:
$ lex 4a.l
$ yacc -d 4a.y
$ cc y.tab.c lex.yy.c -ll
$ ./a.out
Enter the Expression:
a+b-c*(4/5)
Valid Expression
$ ./a.out
Enter the Expression:

Bharath Bharadwaj B S

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


1+2-3#a
#Invalid Expression

Bharath Bharadwaj B S

10

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


4(b).Program to recognize a valid variable,which starts with a letter,followed
by any number of letters or digits.
PROGRAM:
LEX PART:
%{
#include"y.tab.h"
%}
%%
[a-zA-Z]+[0-9]+ {return VALID;}
[a-zA-Z]+ {return VALID;}
[0-9]+[a-zA-Z]+ {return INVALID;}
[0-9]+ {return INVALID;}
%%
YACC PART:
%{
#include<stdio.h>
%}
%token VALID INVALID
%%
Start:Start VALID { printf("Valid Format.....\n"); }
|Start INVALID { printf("Invalid Format.....\n"); }
|"\n"
|;
%%
main()
{
printf("Enter the Variable:");
yyparse();
}
yyerror(char *s)
{
}
OUTPUT:
$ lex 4b.l
$ yacc -d 4b.y
$ cc y.tab.c lex.yy.c -ll
$ ./a.out
Enter the Variable:abc123
Valid Format.....
$ ./a.out
Enter the Variable:123abc
Invalid Format.....

Bharath Bharadwaj B S

11

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


5(a).Program to evaluate an arithmetic expression involving operators +,-,*
and /.
PROGRAM:
LEX PART:
%{
#include "y.tab.h"
%}
%%
[a-zA-Z0-9]+ return ID;
\( return LB;
\) return RB;
[-+] return SA;
[*/] return MD;
%%
YACC PART:
%{
#include<stdio.h>
%}
%token LB ID RB LB SA MD OTHER
%%
expr: term|expr SA term;
term:factor|term MD factor;
factor:ID|LB expr RB|OTHER;
%%
int main()
{
printf("Enter an Arithmetic Expression:");
if(yyparse()==0){
printf("valid Expression....\n");}
return 0;
}
yyerror()
{
printf("Invalid Arithmetic Expression....\n");
}
OUTPUT:
$ lex 5a.l
$ yacc -d 5a.y
$ cc y.tab.c lex.yy.c -ll
$ ./a.out
Enter an Arithmetic Expression: a+b-c*(4/5)
valid Expression....
$ ./a.out
Enter an Arithmetic Expression:
a@b!c+d
@Invalid Arithmetic Expression....

Bharath Bharadwaj B S

12

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL

5(b).Program
(anbn,n>=0)

to

recognize

strings

aaabbb,aabb

and

ab

using

the

grammar

PROGRAM:
LEX PART:
%%{
#include "y.tab.h"
%}
%s NOAB STR
%%
[^ab\n] {BEGIN NOAB;return Z;}
<NOAB>.* {return Z;}
a {return X;}
b {return Y;}
\n {return 0;}
%%
YACC PART:
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token X Y Z
%%
exp:X exp Y
|
;
%%
main()
{
printf("Enter The String:");
yyparse();
printf("String Recognised...\n");
}
yyerror()
{
printf("String Unrecognised....\n");
exit(0);
}
OUTPUT:
$ lex 5b.l
$ yacc -d 5b.y
$ cc y.tab.c lex.yy.c -ll
$ ./a.out
Enter The String:aaabbb
String Recognised...
$ ./a.out
Enter The String:aabb

Bharath Bharadwaj B S

13

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


String Recognised...
$ ./a.out
Enter The String:ab
String Recognised...
$ ./a.out
Enter The String:a
String Unrecognised....

Bharath Bharadwaj B S

14

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


6.Program to recognize the grammar(anb,n>=10)
PROGRAM:
LEX PART:
%{
#include "y.tab.h"
%}
%s NOAB STR
%%
[^ab\n] {BEGIN NOAB;
<NOAB>.* {return Z;}
a {return X;}
b {return Y;}
\n {return 0;}
%%

return Z;}

YACC PART:
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token X Y Z
%%
exp:X X X X X X X X X X exp1 Y
;
exp1:X exp1
|
;
%%
main()
{
printf("Enter the String:");
yyparse();
printf("String is Recognised...\n");
}
int yyerror()
{
printf("String Unrecognised.....\n");
exit(1);
}
OUTPUT:
$ lex 6.l
$ yacc -d 6.y
$ cc y.tab.c lex.yy.c -ll
$ ./a.out
Enter the String:aaaaaaaaaaaaaab
String is Recognised...
$ ./a.out
Enter the String:ab
String Unrecognised.....

Bharath Bharadwaj B S

15

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


UNIX PROGRAMS
1(a).Non-recursive shell script that accepts any number of argument and prints
them in the Reverse order, (For example, if the script is named rargs,then
executing rargs A B C should produce C B A on the standard output).
PROGRAM:
if [ $# -eq 0 ]
then
echo "No Arguments Passed"
exit
fi
num=$#
while [ $num -gt 0 ]
do
eval echo \$"$num"
let num=$num-1
done
OUTPUT:
$ chmod +x 1a.sh
$ ./1a.sh M A H A R A J A
A
J
A
R
A
H
A
M

Bharath Bharadwaj B S

16

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


1(b).C program that creates a child process to read commands from the standard
input and execute them(a minimal implementation of a shell like program). You
can assume that no arguments will be passed to the commands to be executed.
PROGRAM:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
char com[10];
pid=fork();
if(pid!=0)
{
system("clear");
printf("Child Process Created\n");
printf("Enter the Command to be executed\n");
scanf("%s",com);
system(com);
}
else
{
printf("Child Process cannot be created\n");
return 0;
}
printf("Parent Process Over\n");
return 0;
}
OUTPUT:
$ chmod +x 1b.c
$ cc 1b.c
$ ./a.out
Child Process cannot be created
Child Process Created
Enter the Command to be executed
cal
April 2010
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
Parent Process Over

Bharath Bharadwaj B S

17

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


2(a).Shell script that accepts two file names as arguments,checks if the
permissions for these files are identical and if the permissions are identical,
outputs the common permissions, otherwise outputs each file name followed by its
permissions.
PROGRAM:
if [ ! -e $1 ]
then
echo "File 1 doesnot exist"
exit
fi
if [ ! -e $2 ]
then
echo "File 2 doesnot exist"
exit
fi
if [ $# -ne 2 ]
then
echo "2 Arguments are not given"
exit
fi
ls -l $1 | cut -c 2-10 > t
ls -l $2 | cut -c 2-10 > s
cmp t s
if [ $? -eq 0 ]
then
echo "Common File Permission"
cat t
else
echo "File 1"
cat t
echo "File 2"
cat s
fi
OUTPUT:
$ chmod +x 2a.sh
$ ./2a.sh
2 Arguments are not given
$ cat>file1
MIT
$ cat>file2
MYSORE
$ ./2a.sh file1 file2
Common File Permission
rw-r--r-$ chmod +x file1
$ ./2a.sh file1 file2
t s differ: byte 3, line 1
File 1
rwxr-xr-x
File 2
rw-rr--

Bharath Bharadwaj B S

18

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


2(b).C program that takes a valid directory names as an argument and recursively
descends all the subdirectories, finds the maximum length of any file in that
hierarchy and writes this maximum value to the standard output.
PROGRAM:
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
char buf1[100]="abcdefghijklmnop";
char buf2[100]="ABCDEFIJKLMNOP";
int fd=creat("fi.dat","w");
write(fd,buf1,16);
lseek(fd,50,SEEK_SET);
write(fd,buf2,16);
system("vi fi.dat");
return 0;
}
OUTPUT:
$ chmod +x 2b.c
$ cc 2b.c
$ ./a.out
abcdefghijklmnop^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
^@^@ABCDEFIJKLMNOP
~
~
~
~
~
~
~
~
~
~
~
~
~
"fi.dat" [Incomplete last line] 1 line, 64 characters
Note:You will be in vi editor mode so to get back to command prompt just press
':' then type in 'x' and press enter.

Bharath Bharadwaj B S

19

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


3(a).Shell function that takes a valid directory names as an argument and
recursively descends all the subdirectories, finds the maximum length of any
file in that hierarchy and writes this maximum value to the standard input.
PROGRAM:
if [ $# -ne 1 ]
then
echo "No Arguments Passed"
exit
fi
ms=`ls -lR $1 | grep '^-' | tr -s ' ' | cut -d ' ' -f 5,8 | sort -n | tail -1`
echo "The maximum Size is $ms"
OUTPUT:
$ chmod +x 3a.sh
$ ./3a.sh
No Arguments Passed
$ ./3a.sh SHELL
The maximum Size is 8456 a.out

Bharath Bharadwaj B S

20

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


3(b).C program that accepts valid file names as command line arguments and for
each of the arguments, prints the type of the file (Regular file,Directory
file,character special file,Block special file,Symbolic link etc.)
PROGRAM:
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<stdio.h>
int main(int argc,char *argv[])
{
int i;
struct stat buf;
for(i=1;i<argc;i++)
{
lstat(argv[i],&buf);
if(S_ISREG(buf.st_mode))
printf("File is
else if(S_ISDIR(buf.st_mode)) printf("File is
else if(S_ISLNK(buf.st_mode)) printf("File is
else if(S_ISFIFO(buf.st_mode)) printf("File
return 0;
}
return 0;
}

Regular\n");
Directory\n");
Link\n");
is FIFO\n");

OUTPUT:
$ ls
3b.c
a.out
Desktop
Documents
Downloads
fifo_pipe
Pictures Public Templates TEST TEST1 Videos
$ cc 3b.c
$ ./a.out TEST1
File is Regular
$ ./a.out TEST
File is Directory
$ ./a.out Link_to_TEST
File is Link
$ ./a.out fifo_pipe
File is FIFO

Bharath Bharadwaj B S

21

Link_to_TEST

Music

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


4(a).Shell script that accepts file names specified as arguments and creates a
shell script that contains this file as well as the code to recreate these
files. Thus if the script generated by your script is executed, it would
recreate the original files(This is same as the Bundle script described by
Brain W. Kernighan and Rob Pike in The UNIX Programming Environment,Prentice
Hall India).
PROGRAM:
echo '# to bundle,sh this file'
for i in $*
do
echo "echo $i 1>&2"
echo "cat>$i<<'end of $i'"
cat $i
echo "end of $i"
done
OUTPUT:
$ chmod 777 4a.sh
$ cat > file1
$ cat > file2
$ sh 4a.sh file1 file2 > new.sh
$ rm file1
$ rm file2
$ chmod 777 new.sh
$ sh new.sh
file1
file2

Bharath Bharadwaj B S

22

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


4(b). C program to do the following:Using fork() create a child process. The
child process prints its own process-id and id of its parent and then exits. The
parent process waits for its child to finish(by executing the wait()) and prints
its own process-id and the id of its child process and then exits.
PROGRAM:
#include<sys/types.h>
#include<stdio.h>
int main()
{
pid_t pid;
if((pid=fork())<0)
printf("FORK ERROR\n");
if(pid==0)
{
printf("This is a Child Process\nThe Child Process ID=%d\nThe Parent Process ID:
%d\n",getpid(),getppid());
return 0;
}
wait(pid);
printf("This is parent Process\nThe Parent Process ID:%d\nThe Child Process ID:
%d\n",getpid(),pid);
return 0;
}
OUTPUT:
$ chmod +x 4b.c
$ cc 4b.c
$ ./a.out
This is a Child Process
The Child Process ID=3200
The Parent Process ID:3199
This is parent Process
The Parent Process ID:3199
The Child Process ID:3200

Bharath Bharadwaj B S

23

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


COMPILER DESIGN PROGRAMS
5). Write a C program to implement the syntax directed definition of if E then
S1 and if E then S1 else S2. (Refer Fig 8.23 in the text book prescribed for
06CS62 Compiler Design, Alfred V Aho, Ravi Sethi, Jeffrey D Ullman:
Compiler-Principles, Techniques and Tools, Addison-Wesley, 2007)
/* Input to the program is assumed to be syntactically correct. The expression
of if statement, statement for true condition and statement for false
condition are enclosed in parenthesis */
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int parsecondition(char[],int,char*,int);
void gen(char [],char [],char[],int);
int main()
{
int counter = 0,stlen =0,elseflag=0;
char stmt[60]; // contains the input statement
char strB[54]; // holds the expression for 'if' condition
char strS1[50]; // holds the statement for true condition
char strS2[45]; // holds the statement for false condition
printf("Format of if statement \n Example ...\n");
printf("if (a<b) then (s=a);\n");
printf("if (a<b) then (s=a) else (s=b);\n\n");
printf("Enter the statement \n");
gets(stmt);
stlen = strlen(stmt);
counter = counter + 2; // increment over 'if'
counter = parsecondition(stmt,counter,strB,stlen);
if(stmt[counter]==')')
counter++;
counter = counter + 3;

// increment over 'then'

counter = parsecondition(stmt,counter,strS1,stlen);
if(stmt[counter+1]==';')
{ // reached end of statement, generate the output
printf("\n Parsing the input statement....");
gen(strB,strS1,strS2,elseflag);
return 0;
}
if(stmt[counter]==')')
counter++;
// increment over ')'
counter = counter + 3;
// increment over 'else'
counter = parsecondition(stmt,counter,strS2,stlen);
counter = counter + 2; // move to the end of statement
if(counter == stlen)

Bharath Bharadwaj B S

24

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


{

//generate the output


elseflag = 1;
printf("\n Parsing the input statement....");
gen(strB,strS1,strS2,elseflag);
return 0;

}
return 0;
}
/* Function : parsecondition
Description : This function parses the statement from the given index to get the
statement enclosed in ()
Input : Statement, index to begin search, string to store the condition, total
string length
Output : Returns 0 on failure, Non zero counter value on success
*/
int parsecondition(char input[],int cntr,char *dest,int totallen)
{
int index = 0,pos = 0;
while(input[cntr]!= '(' && cntr <= totallen)
cntr++;
if(cntr >= totallen)
return 0;
index = cntr;
while (input[cntr]!=')')
cntr++;
if(cntr >= totallen)
return 0;
while(index<=cntr)
dest[pos++] = input[index++];
dest[pos]='\0'; //null terminate the string
return cntr; //non zero value
}
/* Function : gen ()
Description : This function generates three address code
Input : Expression, statement for true condition, statement for
false condition, flag to denote if the 'else' part is present in
the statement
output :Three address code
*/
void gen(char B[],char S1[],char S2[],int elsepart)
{
int Bt =101,Bf = 102,Sn =103;
printf("\n\tIf %s goto %d",B,Bt);
printf("\n\tgoto %d",Bf);
printf("\n%d: ",Bt);
printf("%s",S1);
if(!elsepart)
printf("\n%d: ",Bf);
else
{ printf("\n\tgoto %d",Sn);
printf("\n%d: %s",Bf,S2);
printf("\n%d:",Sn);
}

Bharath Bharadwaj B S

25

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


}
OUTPUT:
$ chmod +x 5.c
$ cc 5.c
$ ./a.out
Format of if statement
Example ...
if (a<b) then (s=a);
if (a<b) then (s=a) else (s=b);
Enter the statement
if (a<b) then (s=a);
Parsing the input statement....
If (a<b) goto 101
goto 102
101: (s=a)
102:
$ ./a.out
Format of if statement
Example ...
if (a<b) then (s=a);
if (a<b) then (s=a) else (s=b);
Enter the statement
if (a<b) then (s=a) else (s=b);
Parsing the input statement....
If (a<b) goto 101
goto 102
101: (s=a)
goto 103
102: (s=b)
103:

Bharath Bharadwaj B S

26

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


6. Write a yacc program that accepts a regular expression as input and produce
its parse tree as output.
PROGRAM:
%{
#include"y.tab.h"
#include<ctype.h>
char str[20];
int i=0;
%}

%token id
%left '+''/''*''-'

%%
E:S

{infix_postfix(str);}

S:S'+'T |S'-'T
|T
T:T'*'F| T'/'F
|F
F:id |'('S')'
;
%%

#include<stdio.h>
main()
{
printf("\nEnter an identifier:");
yyparse();
}

Bharath Bharadwaj B S

27

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL

yyerror()
{
printf("invalid\n");
}
yylex(){
char ch=' ';
while(ch!='\n'){
ch=getchar();
str[i++]=ch;
if(isalpha(ch)) return id;
if(ch=='+'||ch=='*'|| ch=='-'||ch=='/') return ch;}
str[--i]='\0';
return(0);
exit(0);
}

void push(char stack[],int *top,char ch)


{
stack[++(*top)]=ch;
}
char pop(char stack[],int *top)
{
return(stack[(*top)--]);
}

int prec(char ch)


{

switch(ch)
{

Bharath Bharadwaj B S

28

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL


case '/':
case '*': return 2;
case '+':
case '-': return 1;
case '(': return 0;
default: return -1;
}
}

void infix_postfix(char infix[])


{
int top=-1,iptr=-1,pptr=-1;
char postfix[20],stack[20],stksymb,cursymb;
push(stack,&top,'\0');
while((cursymb=infix[++iptr])!='\0')
{
switch(cursymb)
{

case '(': push(stack,&top,cursymb);


break;
case ')': stksymb=pop(stack,&top);
while(stksymb!='(')
{
postfix[++pptr]=stksymb;
stksymb=pop(stack,&top);
}
break;
case '*':
case '/':
case '+':

Bharath Bharadwaj B S

29

MIT,Mysore

SYSTEM SOFTWARE AND COMPILER DESIGN LABOURATORY MANUAL

case '-': while(prec(stack[top])>=prec(cursymb))


postfix[++pptr]=pop(stack,&top);
push(stack,&top,cursymb);break;
default:

if(isalnum(cursymb)==0)
{printf("Error in input!"); exit(0);}

postfix[++pptr]=cursymb;
}
}
while(top!=-1)
postfix[++pptr]=pop(stack,&top);
printf("%s\n",postfix);
}
OUTPUT:
$ yacc -d 6.y
$ cc y.tab.h
$ cc y.tab.c -ll
$ ./a.out

Enter an identifier:a+b-c
ab+c$ ./a.out

Enter an identifier:a/(b+c)*d
abc+/d*
$ ./a.out

Enter an identifier:a+1-2
invalid

Bharath Bharadwaj B S

30

MIT,Mysore

Вам также может понравиться