Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
INDEX
Experiment Name
Page No.
PART - A
LEX AND YACC PROGRAMS:
Execute the following programs using LEX:
1) a. Program to count the number of characters, words, spaces and lines
in a given input file.
b.Program to count the numbers of comment lines in a given C program.
Also eliminate them and copy the resulting program into separate file.
2) a. Program to recognize a valid arithmetic expression and to recognize
the identifiers and operators present. Print them separately.
b. Program to recognize whether a given sentence is simple or
compound.
3) Program to recognize and count the number of identifiers in a given
input file.
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
Execute the following programs using YACC:
4) a. Program to recognize a valid arithmetic expression that uses
operators +, -, * and /.
b. Program to recognize a valid variable, which starts with a letter,
followed by any number of letters or digits.
5) a. Program to evaluate an arithmetic expression involving operators +,
-, * and /.
b. Program to recognize strings ‘aaab’, ‘abbb’, ‘ab’ and ‘a’ using the
grammar (anbn, n>= 0).
6) Program to recognize the grammar (anb, n>= 10).
PART - B
UNIX PROGRAMMING:
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).
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
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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
b) C program to create a file with 16 bytes of arbitrary data from the
beginning and another 16 bytes of arbitrary data from an offset of 48.
Display the file contents to demonstrate how the hole in file is handled.
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 output
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.)
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).
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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.
COMPILER DESIGN:
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: Compilers- Principles, Techniques and Tools,
Addison-Wesley, 2007.)
6. Write a yacc program that accepts a regular expression as input and
produce its parse tree as output.
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
1) A. PROGRAM TO COUNT THE NUMBER OF CHARACTERS, WORDS, SPACES AND LINES
IN A GIVEN INPUT FILE.
%{ #include<stdio.h> int ch=0,wrd=0,spc=0,ln=0; %} %% [^ \t\n]+ {wrd++; ch=ch+yyleng; } \n {ln++;} . {spc++;} %% int main(int argc,char *argv[]) { if(argc==2) { FILE *fp; fp=fopen(argv[1],"r"); if(!fp) { printf("\n\nError Opening File %s\n",argv[1]); exit(0); } yyin=fp; } yylex(); printf("\n\nThe Number of\n"); printf("Characters=%d\nWords=%d\nLines=%d\nSpaces=%d\n",ch,wrd,ln,spc); return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
1B:PROGRAM TO COUNT THE NUMBER OF COMMENT LINES IN A GIVEN C PROGRAM.ALSO ELIMINATE THEM AND COPY THE RESULTING PROGRAM INTO SEPARATE FILE.
%{ #include<stdio.h> int cc=0; char ch; %} %% "/*" { for(;;) { while((ch=input())!='*' && (ch!=EOF)); if(ch=='*') { while((ch=input())=='*'); if(ch=='/') { cc++; break; } } if(ch==EOF) { printf("End of File Encountered\n\n"); break; } } } %% int main(int argc,char *argv[]) { if(argc==3) { FILE *fp1,*fp2;
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
fp1=fopen(argv[1],"r"); if(!fp1) { printf("Error Opening File %s\n\n",argv[1]); exit(0); } yyin=fp1; fp2=fopen(argv[2],"w"); if(!fp2) { printf("Error Opening File %s\n\n",argv[2]); exit(0); } yyout=fp2; } yylex(); printf("\n\nThe Number of Comment Lines in the file %s is %d\n\n",argv[1],cc); return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
2A:PROGRAM TO RECOGNIZE A VALID ARITHMETIC EXPRESSION AND TO RECOGNIZE THE IDENTIFIERS AND OPERATORS PRESENT.PRINT THEM SEPARATELY.
%{ #include<stdio.h> int id=0,op=0,a=0,s=0,d=0,m=0,ob=0,cb=0,flag=1; %} %% [a-zA-z][a-zA-Z0-9]* {id++;printf("\n\n%s is an identifier",yytext);} "+" {op++;a++;printf("\n%s is an Operator",yytext);} "*" {op++;m++;printf("\n%s is an Operator",yytext);} "-" {op++;s++;printf("\n%s is an Operator",yytext);} "/" {op++;d++;printf("\n%s is an Operator",yytext);} "(" {ob++;} ")" {if(ob>cb) cb++; else flag=0; } . {flag=0;} %% int main() { printf("\n\nEnter the Arithmetic Expression:"); yylex(); int b=ob+cb; if((id==op+1) && (b%2==0) && (ob==cb) && (flag==1)) { printf("The Expression is a Valid Expression"); printf("\n\nNo: of\n"); printf("Addition Op=%d\nSubtraction Op=%d\nMultiplication Op=%d\nDivision Op=%d\nOpen
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
Brackets=Closed Brackets=%d\n,Identifiers=%d\n",a,s,m,d,ob,id); } else { printf("\n\nThe Expression is a Invalid Expression\n\n"); exit(0); } return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
PROGRAM TO RECOGNIZE WHETHER A GIVEN SENTENCE IS SIMPLE OR COMPOUND.
%{ #include<stdio.h> int flag=0; %} %% .|\n {;} "or"|"and"|"OR"|"BUT"|"AND"|"but" {flag=1;} [a-z]* {;} %% int main() { printf("Enter the Sentence : "); yylex(); if(flag==0) printf("Sentence is Simple\n\n"); else printf("Sentence is Compound\n\n"); return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
3:PROGRAM TO RECOGNIZE AND COUNT THE NUMBER OF IDENTIFIERS IN A GIVEN INPUT FILE
%{ #include<stdio.h> int count=0; char ch; %} %% .|\n {;} "int"|"float"|"double"|"char" { ch=input(); for(;;) { if(ch==',') { count++; } else if(ch==';') { count++; break; } ch=input(); } } [a-zA-z0-9]* {;} %% int main(int argc,char *argv[]) { if(argc>1) { FILE *fp; printf("%d",argc); fp=fopen(argv[1],"r");
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
if(!fp) { printf("Error Opening File %s\n\n",argv[1]); exit(0); } yyin=fp; } yylex(); printf("\n\nThe Number of Identifiers in the given input file is %d\n",count); return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
4A:PROGRAM TO RECOGNIZE A VALID ARITHMETIC EXPRESSION THAT USES OPERATORS ‘+’,’‐‘,’*’,’/’.
LEX PART:
%{ #include"y.tab.h" %} %% [0-9]+ {return NUMBER;} [a-zA-z][0-9a-zA-Z]* {return ID;} [ \t]+ {;} . {return yytext[0];} \n {return 0;} %%
YACC PART:
%{ #include<stdio.h> %} %token NUMBER ID %left '+' '-' %left '*' '/' %right UMINUS %% stmt :expr ; expr :expr'+'expr |expr'-'expr |expr'*'expr |expr'/'expr |'('expr')' |NUMBER |ID |'-'expr %prec UMINUS ;
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
%% int main() { printf("Enter the Arithmetic Expression : "); yyparse(); printf("The Entered Arithmetic Expression is Valid\n\n"); return 0; } int yyerror() { printf("Invalid Expression\n"); exit(0); }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
4B:PROGRAM TO RECOGNIZE A VALID VARIABLE,WHICH STARTS WITH A LETTER,FOLLOWED BY ANY NUMBER OF LETTERS OR DIGITS .
LEX PART:
%{ #include"y.tab.h" %} %% [0-9] {return DIGIT;} [a-z] {return LETTER;} . {return yytext[0];} \n {return 0;} %%
YACC PART:
%{ #include<stdio.h> %} %token LETTER DIGIT %% stmt :A A :LETTER B |LETTER ; B :LETTER B |DIGIT B |LETTER |DIGIT ; %% int main() { printf("Enter an Identifier : ");
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
yyparse(); printf("\n\nValid Identifier\n\n"); return 0; } int yyerror() { printf("Invalid Identifier\n\n"); exit(0); }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
5A:PROGRAM TO EVALUATE AN ARITHMETIC EXPRESSION INVOLVING OPERATORS ‘+’,’*’,’‐‘,’/’.
LEX PART:
%{ #include"y.tab.h" extern int yylval; %} %% [0-9]+ {yylval=atoi(yytext); return NUMBER;} [ \t]+ {;} . {return yytext[0];} \n {return 0;} %%
YACC PART:
%{ #include<stdio.h> int result=0,flag=0; %} %token NUMBER %left '+' '-' %left '*' '/' %right UMINUS %% stmt :expr {result=$1;} ; expr :expr'+'expr {$$=$1+$3;} |expr'-'expr {$$=$1-$3;} |expr'*'expr {$$=$1*$3;} |expr'/'expr {if($3==0) flag=1;
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
else $$=$1/$3;} |'('expr')' {$$=$2;} |'-'expr %prec UMINUS {$$=-$2;} |NUMBER ; %% int main() { printf("Enter the Arithmetic Expression : "); if(flag!=1) { yyparse(); printf("\n\nResult = %d\n\n",result); } else { printf("Divide by Zero Error\n\n"); } return 0; } int yyerror() { printf("Invalid Arithmetic Expression\n\n"); exit(0); }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
5B:PROGRAM TO RECOGNIZE STRINGS ‘AAAB’,’ABBB’,’AB’ AND ‘A’ USING THE GRAMMER(AⁿBⁿ,N>=0).
LEX PART:
%{ #include"y.tab.h" %} %% "a"|"A" {return A;} "b"|"B" {return B;} . {return yytext[0];} \n {return 0;} %%
YACC PART:
%{ #include<stdio.h> %} %token A B %% stmt :S ; S :A S B |; %% int main() { printf("\n\nEnter a String that belongs to the Grammer (aⁿbⁿ,n>=0) : "); yyparse(); printf("\n\nValid String\n\n"); return 0; } int yyerror()
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
{ printf("Invalid String\n\n"); exit(0); }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
6:PROGRAM TO RECOGNIZE THE GRAMMER(AⁿB,N>=10).
LEX PART:
%{ #include"y.tab.h" %} %% "a"|"A" {return A;} "b"|"B" {return B;} . {return yytext[0];} \n {return 0;} %%
YACC PART:
%{ #include<stdio.h> %} %token A B %% stmt :S ; S :A A A A A A A A A A X B ; X :A X |; %% int main() { printf("\n\nEnter the String that belongs to the Grammer (aⁿb,n>=10) : "); yyparse(); printf("\n\nValid String\n\n"); return 1; } int yyerror() {
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
printf("\n\nInvalid String"); exit(0); }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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).
var="" if [ $# -eq 0 ] then echo -e "\nUsage sh 1a.sh<arg_list>\n" exit fi echo -e "Given order of arguments:\n$*\n" echo -e "Reverse order of arguments\n" for i in $* do rev=$i""$rev done echo -e "$rev\n"
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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
#include<sys/types.h> #include<stdio.h> int main() { char cmd[10]; int i=0; pid_t pid; if((pid=fork())<0) printf("Fork Failed"); wait(100); if(pid==0) { do { printf("Enter the Command to Execute\n"); scanf("%s",cmd); system(cmd); printf("Enter 1 to Continue or 0 to exit"); scanf("%d",&i); }while(i); } return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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
x=$1 y=$2 set -- `ls -l $x` p1=$1 set -- `ls -l $y` p2=$1 if [ $p1 == $p2 ] then echo -e "\nPermission for both the files are same\n" echo -e ":$p1\n" else echo -e "\nPermission are different\n" echo -e "\n$x:$p1\n" echo -e "\n$y:$p2\n" fi
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
B) C PROGRAM TO CREATE A FILE WITH 16 BYTES OF ARBITRARY DATA FROM THE
BEGINNING AND ANOTHER 16 BYTES OF ARBITRARY DATA FROM AN OFFSET OF 48.
DISPLAY THE FILE CONTENTS TO DEMONSTRATE HOW THE HOLE IN FILE IS HANDLED.
#include<unistd.h> #include<fcntl.h> int main() { char buf1[17]="helloworldimback"; char buf2[17]="HELLOWORLDIMBACK"; int fd=open("k1",O_RDWR|O_CREAT|O_EXCL,0755); write(fd,buf1,16); lseek(fd,32,SEEK_CUR); write(fd,buf2,16); close(fd); system("vi k1"); return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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 OUTPUT.
cd $1 set -- `ls -lR|grep -v "^d"|sort -k5 -rn` echo -e "Size of the Largest File $8 is $5 blocks\n"
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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.)
#include<sys/stat.h> #include<stdio.h> int main(int argc,char *argv[]) { int i=0; struct stat stbuf; char ptr[25]; if(argc<2) printf("Usage : ./a.out<filename(s)>\n"); else { for(i=1;i<argc;i++) { if((lstat(argv[i],&stbuf)==-1)) printf("File does not exist\n"); else if(S_ISREG(stbuf.st_mode)) printf("Regular File\n"); else if(S_ISFIFO(stbuf.st_mode)) printf("FIFO File\n"); else if(S_ISDIR(stbuf.st_mode)) printf("Directory File\n"); else if(S_ISCHR(stbuf.st_mode)) printf("Character Device File\n"); else if(S_ISBLK(stbuf.st_mode)) printf("Block Device File\n"); else if(S_ISLNK(stbuf.st_mode)) printf("Symbolic Link File\n"); else printf("Unknown File Type\n\n"); } }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
return 0; }
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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).
echo "" >create.sh for var in $* do echo "cat>$var<<EOF">>create.sh cat $var>>create.sh echo "EOF">>create.sh done
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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. #include<sys/types.h> #include<stdio.h> #include<unistd.h> int main() { pid_t pid; if((pid=vfork())<0) printf("Vfork Failed"); if(pid==0) { printf("\nChild Process\n"); printf("pid=%d\n",getpid()); printf("ppid=%d\n",getppid()); printf("Child Process with pid=%d is Terminating..\n",getpid()); _exit(0); } if(waitpid(pid,NULL,0)!=pid) printf("Wait PID Failed\n"); printf("\n\nParent Process\n\n"); printf("pid=%d\n",getpid()); printf("ppid=%d\n",getppid()); printf("\n\nThe Child Process Id is %d\n",pid); printf("\n\nParent Process with pid=%d is Terminating..\n",getpid()); return 0; }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
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: COMPILERS‐ PRINCIPLES, TECHNIQUES AND TOOLS,
ADDISON‐WESLEY, 2007.)
#include<stdio.h> #include<stdlib.h> #include<string.h> #define n 100; int parse(char [],int,char *,int); void generate(char [],char [],char *,int); int main() { int count=0,strln=0,elseflag=0; char input[100],strb[50],s1[50],s2[50]; printf("General Format of 'if' statement\n\n"); printf("if (Condition) then (stmt);\nif(Condition) then (stmt) else (stmt);\n\n"); printf("Example : if (a<b) then (s=a);\n\nif (a<b) then (s=a) else (s=b);\n\n"); printf("\n\nEnter the User Specified 'if' Construct\n\n"); scanf("%[^\n]s",input); strln=strlen(input); count+=2; count=parse(input,count,strb,strln); if(input[count]==')') count++;
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
count+=4; count=parse(input,count,s1,strln); if(input[++count]==';') { printf("\nParsing the Input...\n\n"); generate(strb,s1,NULL,elseflag); return 0; } if(input[count]==')') count++; count+=4; count=parse(input,count,s2,strln); if(input[++count]==';') { elseflag=1; printf("\nParsing the Input...\n\n"); generate(strb,s1,s2,elseflag); return 0; } printf("\nSyntax Error\n"); return 0; } int parse(char src[],int count,char *dest,int strln) { int index=0,pos=0; while(src[count]!='(' && count<=strln) count++; if(count>=strln) return 0; index=count; while(src[count]!=')')
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
count++; if(count>=strln) return 0; while(index<=count) dest[pos++]=src[index++]; dest[pos]='\0'; return count; } void generate(char cond[],char stmt1[],char *stmt2,int flag) { int label1=100,label2=200; if(flag==0) { printf("Addr Stmt\n\n"); printf("100 %s\n\n",stmt1); printf("if %s then goto addr %d\n",cond,label1); } else { printf("Addr Stmt\n\n"); printf("100 %s\n",stmt1); printf("200 %s\n",stmt2); printf("\nif %s then goto addr %d else goto addr %d\n\n",cond,label1,label2); } }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
6. WRITE A YACC PROGRAM THAT ACCEPTS A REGULAR EXPRESSION AS INPUT AND
PRODUCE ITS PARSE TREE AS OUTPUT.
%{ /** Yacc program to recognise a regular expression and produce a parse tree as output */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> /* To store the productions */ #define MAX 100 int getREindex ( const char* ); signed char productions[MAX][MAX]; int count = 0 , i , j; char temp[MAX + MAX] , temp2[MAX + MAX]; %} %token ALPHABET %left '|' %left '.' %nonassoc '*' '+' %% S : re '\n' { printf ( "This is the rightmost derivation‐‐\n" ); for ( i = count ‐ 1 ; i >= 0 ; ‐‐i ) { if ( i == count ‐ 1 ) {
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
printf ( "\nre => " ); strcpy ( temp , productions[i] ); printf ( "%s" , productions[i] ); } else { printf ( "\n => " ); j = getREindex ( temp ); temp[j] = '\0'; sprintf ( temp2 , "%s%s%s" , temp , productions[i] , (temp + j + 2) ); printf ( "%s" , temp2 ); strcpy ( temp , temp2 ); } } printf ( "\n" ); exit ( 0 ); } re : ALPHABET { temp[0] = yylval; temp[1] = '\0'; strcpy ( productions[count++] , temp ); } | '(' re ')' { strcpy ( productions[count++] , "(re)" ); } | re '*' { strcpy ( productions[count++] , "re*" ); } | re '+' { strcpy ( productions[count++] , "re+" ); } | re '|' re {strcpy ( productions[count++] , "re | re" );} | re '.' re {strcpy ( productions[count++] , "re . re" );} ; %% int main ( int argc , char **argv ) { /* Parse and output the rightmost derivation,
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
from which we can get the parse tree */ yyparse(); return 0; } yylex() { signed char ch = getchar(); yylval = ch; if ( isalpha ( ch ) ) return ALPHABET; return ch; } yyerror() { fprintf(stderr , "Invalid Regular Expression!!\n"); exit ( 1 ); } int getREindex ( const char *str ) { int i = strlen ( str ) ‐ 1; for ( ; i >= 0 ; ‐‐i ) { if ( str[i] == 'e' && str[i‐1] == 'r' ) return i‐1; } }
Department of Computer Science. Sub Code:06CSL68
SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY
OUTPUT:
$a.out a+|b*|(b.c*) This is the rightmost derivation‐‐ re => re | re => re | (re) => re | (re . re) => re | (re . re*) => re | (re . c*) => re | (b . c*) => re | re | (b . c*) => re | re* | (b . c*) => re | b* | (b . c*) => re+ | b* | (b . c*) => a+ | b* | (b . c*)