Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
525 views

System Programming Lab CSE

This document provides instructions for students taking a Systems Software and Compiler Design lab exam. It outlines 6 problems to be solved using LEX and YACC as part of the exam. For the LEX problems, students will write programs to count elements in files, recognize programming language elements, and validate arithmetic expressions. For the YACC problems, students will write programs to validate arithmetic expressions and variables, evaluate expressions, and recognize formal language grammars. The document also provides background information on LEX and YACC and sample outputs for some of the problems.

Uploaded by

outrider
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
525 views

System Programming Lab CSE

This document provides instructions for students taking a Systems Software and Compiler Design lab exam. It outlines 6 problems to be solved using LEX and YACC as part of the exam. For the LEX problems, students will write programs to count elements in files, recognize programming language elements, and validate arithmetic expressions. For the YACC problems, students will write programs to validate arithmetic expressions and variables, evaluate expressions, and recognize formal language grammars. The document also provides background information on LEX and YACC and sample outputs for some of the problems.

Uploaded by

outrider
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 35

REVA ITM

Dept of Computer Science & Engg

REVA INSTITUTE OF TECHNOLOGY AND MANAGEMENT DEPT. OF COMPUTER SCIENCE AND ENGG. SYSTEMS SOFTWARE & COMPILER DESIGN LABORATORY Subject Code: 06CSL68 Sem : 6th CSE Max Marks : 50

Part A Execution of 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. Execution of 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 arguments 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. 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.

SS & CD Lab Manual

1 / 35

REVA ITM

Dept of Computer Science & Engg

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). 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 definitions of if E then S1 and if E else S2 (Refer fig. 8.23in the text book prescribed for 06CS62 (compiler design) by J D Ullman. 6) Write a yacc program that accepts a regular expression as input and produce its parse tree as output. Instructions: In the examination, a combination of one LEX and one YACC problem has to be asked from Part A for a total of 30 marks and one programming exercise from Part B has to be asked for a total of 20 marks.

SS & CD Lab Manual

2 / 35

REVA ITM

Dept of Computer Science & Engg

LEX AND YACC Block Diagram of Token Generator : Lexer

String Input

Lexer Processing

Tokens Output

Block Diagram of Syntax Analyzer: Parser Checks whether the Tokens are related as per the Grammar or not Output Processing

Token Input

Parser Grammar

SS & CD Lab Manual

3 / 35

REVA ITM

Dept of Computer Science & Engg

PART A LEX: 1) a. Program to count the number of characters, words, spaces and lines in a given input file. %{ #include<stdio.h> int cc=0,bc=0,lc=0,wc=0; %} %% [a-zA-Z]+ {wc++;cc+=yyleng;} [ ] {bc++;} [\n] {lc++;} %% int main(int argc,char *argv[]) { FILE *fp; if (argc>1) { fp=fopen(argv[1],"r"); yyin=fp; } yylex(); printf("\n no of chars=%d \n no of words=%d \n no of lines=%d \n no of blanks=%d \n",cc,wc,lc,bc); } OUTPUT $vi onea.l $lex onea.l $cc lex.yy.c ll $./a.out data1.dat no of chars=7 no of words=2 no of lines=1 no of blanks=1 $vi data1.dat Reva itm

SS & CD Lab Manual

4 / 35

REVA ITM

Dept of Computer Science & Engg

1) 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. %{ #include<stdio.h> int c=0; %} %% ("/*"[a-zA-Z0-9\n\t]*"*/") {c++;} ("//"[\n]?[a-zA-Z0-9\t]*) {c++;} .|\n {fprintf(yyout,"%s",yytext);} %% int main(int argc,char *argv[]) { if(argc!=3) { printf("\n usage:</.a.out><src file><dest file>"); return 0; } yyin=fopen(argv[1],"r"); yyout=fopen(argv[2],"w"); yylex(); printf("\n no of comment line is: %d\n",c); return 0; } OUTPUT $vi oneb.l $lex oneb.l $cc lex.yy.c ll $./a.out test1.c no of comment line is:1 $vi test1.c /*program for testing */ int main() { int a,b,c; C=a+b; }

SS & CD Lab Manual

5 / 35

REVA ITM

Dept of Computer Science & Engg

2) a. Program to recognize a valid arithmetic expression and to recognize the identifiers and operators present. Print them separately. %{ #include<stdio.h> int a=0,s=0,m=0,d=0,ob=0,cb=0; int flaga=0,flags=0,flagm=0,flagd=0; %} id [a-zA-Z]+ %% {id} {printf("\n %s is an identifier \n", yytext);} [+] {a++;flaga=1;} [-] {s++;flags=1;} [*] {m++;flagm=1;} [/] {d++;flagd=1;} [(] {ob++;} [)] {cb++;} %% int main() { printf("\n enter the expression \n"); yylex(); if(ob-cb==0) printf("valid expression \n"); else printf("invalid expression \n"); printf(" Add=%d,Sub=%d,Mul=%d,Div=%d \n",a,s,m,d); printf("operators are: \n"); if(flaga) printf("+ \n"); if(flags) printf("- \n"); if(flagm) printf("* \n"); if(flagd) printf("/ \n"); return 0; } OUTPUT $lex twoa.l $cc lex.yy.c ll $./a.out enter the expression a+b valid expression Add=1 Sub=0 Mul=0 Div=0

SS & CD Lab Manual

6 / 35

REVA ITM

Dept of Computer Science & Engg

2) b. Program to recognize whether a given sentence is simple or compound. %{ #include<stdio.h> int flag=0; %} %% ([aA][nN][dD][oO][rR][bB][uU][tT]) {flag=1;} %% main() { printf("enter sentence \n"); yylex(); if(flag==1) printf ("compound sentence \n"); else printf ("simple sentence \n"); } OUTPUT $vi twob.l $lex twob.l $cc lex.yy.c ll $./a.out enter sentence sita and geetha compound sentence

SS & CD Lab Manual

7 / 35

REVA ITM

Dept of Computer Science & Engg

3) Program to recognize and count the number of identifiers in a given input file. %{ #include<stdio.h> int count=0; %} %% ("int")|("float")|("char")|("double") { char ch; ch=input(); for(;;) { if(ch==',') {count++;} else if(ch==';') {break;} ch=input();} count++; } %% main(int agrc,char*argv[]) { yyin=fopen(argv[1],"r"); yylex(); printf("the no of identifiers %d\n",count); return 0; } OUTPUT $lex three.l $cc lex.yy.c ll $./a.out main() { int a,b,c; float d,e,f; } the no of identifiers: 6

SS & CD Lab Manual

8 / 35

REVA ITM

Dept of Computer Science & Engg

PART A YACC: 4) a. Program to recognize a valid arithmetic expression that uses operators +, -, * and /. Lex part : %{ #include "y.tab.h" %} %% [a-zA-Z]+ {return ALPHA;} [0-9]+ {return NUMBER;} [\t\n]+ . {return yytext[0];} %% Yacc part: %{ #include<stdio.h> #include<stdlib.h> %} %token NUMBER ALPHA %left '+''-' %left '*''/' %left '('')' %% expr: '+'expr |'-'expr |expr'+'expr |expr'-'expr |expr'*'expr |expr'/'expr |'('expr')' |NUMBER |ALPHA ; %% int yyerror(char *msg) { printf("\n %s is invalid expr \n",msg); exit(0); } int main() { printf("enter valid arth expr \n"); yyparse();

SS & CD Lab Manual

9 / 35

REVA ITM

Dept of Computer Science & Engg

printf("valid arth expr \n"); return 0; } OUTPUT $lex foura.l $yacc d foura.y $cc lex.yy.c y.tab.c ll $./a.out enter valid arth expr (a+b) valid arth expr

SS & CD Lab Manual

10 / 35

REVA ITM

Dept of Computer Science & Engg

4) b. 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" %} %% [a-zA-Z]+ {return LETTER;} [0-9]+ {return DIGIT;} . {return yytext[0];} %% Yacc Part : %{ #include <stdio.h> %} %token LETTER DIGIT %% k:v v:LETTER |v LETTER |v DIGIT ; %% main() { yyparse(); printf("the string is valid variable \n"); } int yyerror(char *s) { printf(" invalid variable \n"); exit(0); } OUTPUT: Reva123 the string is valid variable 123reva invalid variable

SS & CD Lab Manual

11 / 35

REVA ITM

Dept of Computer Science & Engg

5) a. Program to evaluate an arithmetic expression involving operators +, -, *,/ . Lex Part : %{ #include "y.tab.h" extern yylval; %} %% [0-9]+ {yylval=atoi(yytext); return NUM;} [\n] {return 0;} . {return yytext[0];} %% Yacc Part : %{ #include<stdio.h> %} %token NUM %left'+''-' %left'*''/' %nonassoc UMINUS %% stmt: exp {printf("%d\n",$$);} exp:exp'+'exp {$$=$1+$3;} |exp'-'exp {$$=$1-$3;} |exp'*'exp {$$=$1*$3;} |exp'/'exp {if($3==0) {yyerror("divide by zero error"); return(0);} else {$$=$1/$3;} } |'('exp')' {$$=$2;} |NUM {$$=$1;} ; %% main() { printf("enter expression \n"); yyparse(); printf("evaluation success \n"); } yyerror(char *s) { printf("evaluation failed \n"); }

SS & CD Lab Manual

12 / 35

REVA ITM

Dept of Computer Science & Engg

OUTPUT: $lex fivea.l $yacc d fivea.y $cc lex.yy.c y.tab.c ll $./a.out enter expression 2+4=6 evaluation success

SS & CD Lab Manual

13 / 35

REVA ITM

Dept of Computer Science & Engg

5 b) Program to recognize strings 'aaab', 'abbb', 'ab', 'a' using the grammer. (an bn ,n>=0) Lex Part : #include "y.tab.h" %} %% [a] {return A;} [b] {return B;} %% Yacc Part : %{ #include<stdio.h> #include<stdlib.h> %} %token A B %% S:A S B | ; %% main() { printf("enter the string \n"); yyparse(); if(yyparse()==0) printf("string is valid \n"); } yyerror(char *s) { printf("%s not a valid string \n"); } OUTPUT: $lex fiveb.l $yacc d fiveb.y $cc lex.yy.c y.tab.c ll $./a.out enter the string aabb string is valid abb not a valid string

SS & CD Lab Manual

14 / 35

REVA ITM

Dept of Computer Science & Engg

6) Program to recognize the grammer (anb, n>=0) Lex Part : %{ #include "y.tab.h" %} %% [a] {return A;} [b] {return B;} %% Yacc Part : %{ #include<stdio.h> #include<stdlib.h> %} %token A B %% S:A A A A A A A A A A C C:A C |B ; %% main() { printf("enter the string \n"); if(yyparse()==0) printf("string is valid \n"); } yyerror(char *s) { printf("not a valid string \n"); } OUTPUT: $lex six.l $yacc d six.y $cc lex.yy.c y.tab.c ll $./a.out enter the string aaaaaaaaaab string is valid aaabbbbbb not a valid string

SS & CD Lab Manual

15 / 35

REVA ITM

Dept of Computer Science & Engg

PART B Unix Programming: Shell Programming : The Shell is one of the major components of the Unix system. As a command interpreter, it provides an interface between the user and the operating system. The shell is also a programming language that executes shell scripts in the interpretive mode one line at a time. The Shell programs or shell scripts are executable text files that contain UNIX commands. The Unix Systems offers a variety of shells like Bourne shell , C shell, Korn shell and bash(born again shell) shell for you to choose. Shell scripts are typically written when: there is a command or string of commands that you will use more than once. you want access to command line arguments you need looping and testing. Writing and running a Shell Script 1. 2. Use your vi editor to create the shell script To run the script, use sh followed by the name of the shell script. For example, $ sh filename.sh When used in this way, the script doesnt need to have executable permission. OR To run the script, make it executable and invoke the script name. For example, $ chmod +x filename.sh $ filename.sh

Simple Shell script Shell script (named first) that displays the current date, the users on the system and a welcome message for the user logged in. date who echo Welcome $LOGNAME $ sh first.sh Sat Sep 30 14:42:39 PDT 2007 root tty01 Sep 30 13:32 welcome root
SS & CD Lab Manual

16 / 35

REVA ITM

Dept of Computer Science & Engg

1a) Write a non-Recursive shell Script which accepts any number of arguments & prints them in reverse order (for example, if the script is named rags, then executing rags A B C should produce C B A on standard output) #1a.sh clear rev=" " for var in $* do rev="$var $rev" done echo -e "The original args are: $*" echo -e "\nReversed command line args are: $rev" OUTPUT: $ sh 1a.sh a b c d e The original args are: a b c d e Reversed command line args are:

e d c b a

SS & CD Lab Manual

17 / 35

REVA ITM

Dept of Computer Science & Engg

1b) 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. #1b.c #include<stdio.h> #include<stdlib.h> #include<sys/wait.h> #include<unistd.h> #include<sys/types.h> int main() { char cmd[20]; pid_t pid; int choice, status; pid=fork(); if(pid==0) { do { system("clear"); printf("enter command:\t"); scanf("%s",cmd); system(cmd); printf("\nenter 1 to continue and 0 to exit:"); scanf("%d",&choice); } while(choice!=0); } wait(&status); } OUTPUT: $ gcc 1b.c $ ./a.out enter command: cal February 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 enter 1 to continue and 0 to exit:1 enter command: date Tue Feb 9 13:40:27 IST 2010 enter 1 to continue and 0 to exit:0

SS & CD Lab Manual

18 / 35

REVA ITM

Dept of Computer Science & Engg

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. #2a.sh clear ls -l $1 $2 p1=`ls -l $1 | cut -c 2-10` p2=`ls -l $2 | cut -c 2-10` if test $p1 = $p2 then echo -e "\n Permissions are Equal : $p1\n" else echo -e "\n Permissions are not-Equal \n" echo -e " hence \t$1 permissions are:$p1" echo -e " \t$2 permissions are:$p2\n" fi OUTPUT: $ sh 2a.sh 1a.sh 2a.sh -rwxr--r-- 1 yogish yogish 508 Feb 9 11:57 1a.sh -rw-r--r-- 1 yogish yogish 578 Feb 4 09:01 2a.sh Permissions are not-Equal hence 1a.sh permissions are:rwxr--r-2a.sh permissions are:rw-r--r-$ sh 2a.sh 3a.sh 2a.sh -rw-r--r-- 1 yogish yogish 578 Feb 4 09:01 2a.sh -rw-r--r-- 1 yogish yogish 305 Feb 2 12:45 3a.sh Permissions are Equal: rw-r--r--

SS & CD Lab Manual

19 / 35

REVA ITM

Dept of Computer Science & Engg

2 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. #2b.c #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> int main() { int fd; char buf1[]="Department of IS"; char buf2[]="Department of CS"; fd=creat("ise",0777); if(fd<0) { printf("fails to create a file"); exit(0); } write(fd,buf1,16); lseek(fd,48,SEEK_SET); write(fd,buf2,16); return 0; } OUTPUT: $ gcc 2b.c $./a.out $vi ise Department IS^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@ ^@^@^@^@Department of CS

of

SS & CD Lab Manual

20 / 35

REVA ITM

Dept of Computer Science & Engg

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. #3a.sh clear ls -lR $1 | tr -s ' ' | sort -t" " -nk 5 |tail -1 | cut -d" " -f 5,9 OUTPUT: $sh 3a.sh directory_name 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.) #3b.c #include <stdio.h> #include <sys/stat.h> #include <unistd.h> int main(int argc, char *argv[]) { int i; struct stat buf; for(i=1;i<argc;i++) { printf("The File %s is ",argv[i]); stat(argv[i],&buf); if(S_ISREG(buf.st_mode)) printf(" Regular file\n"); if(S_ISDIR(buf.st_mode)) printf(" Directory file \n"); if(S_ISCHR(buf.st_mode)) printf(" Character Device file\n"); if(S_ISBLK(buf.st_mode)) printf(" Block Device file\n"); if(S_ISLNK(buf.st_mode)) printf(" Symbolic Link file\n"); } return (0); } OUTPUT: $gcc 3b.c $ ./a.out 3b.c The File 3b.c is Regular file $ ./a.out USP The File USP is Directory file $ ./a.out /dev/tty The File /dev/tty is Character Device file

SS & CD Lab Manual

21 / 35

REVA ITM

Dept of Computer Science & Engg

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). #bundle.sh clear for var in $* do echo "echo $var 1>&2" echo "cat >$var<<'END $var'" cat $var echo "END $var" done OUTPUT: # create at least two files before executing the script $ cat >f1 this is fil1 f1 $ cat >f2 a file f2 $ ls bundl.sh f1 f2 #Execute the script $ sh bundl.sh f1 f2 > rebundl.sh #remove the files f1 and f2 $ rm f1 f2 $ ls bundl.sh rebundl.sh # Now execute the newly created bundle script # it re creates the files f1 and f2 $ sh rebundl.sh f1 f2 $ cat f1 this is fil1 f1 $ cat f2 a file f2

SS & CD Lab Manual

22 / 35

REVA ITM

Dept of Computer Science & Engg

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. #4b.c #include<sys/types.h> #include <unistd.h> #include<stdio.h> int main() { int status; pid_t pid; if((pid=fork())<0) printf("fork error"); if (pid==0) printf("\nChild PID=%d, Parent PID=%d\n", getpid(), getppid()); if(pid > 0) { wait(&status); printf("\nParent PID=%d, Child PID=%d \n",getpid(),pid ); } return 0; } OUTPUT: $ gcc 4b.c $ ./a.out Child PID=4013, Parent PID=4012 Parent PID=4012 Child PID=4013

SS & CD Lab Manual

23 / 35

REVA ITM

Dept of Computer Science & Engg

5) Write a c program to implement the syntax directed definitions of if E then S1 and if E else S2 (Refer fig. 8.23in the text book prescribed for 06CS62 (compiler design) by J D Ullman. /* Input to the program is assumed to be syntactically correct. The expression of if statement, for true condition and statement for false condition are enclosed in parenthesis */ #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]; char strB[54]; char strS2[45]; // contains the input statement // holds the expression for 'if' condition // holds the statement for false condition

char strS1[50]; // holds the statement for true 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]==';')

SS & CD Lab Manual

24 / 35

REVA ITM

Dept of Computer Science & Engg

//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) { //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)

SS & CD Lab Manual

25 / 35

REVA ITM

Dept of Computer Science & Engg

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

SS & CD Lab Manual

26 / 35

REVA ITM

Dept of Computer Science & Engg

OUTPUT 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 (x=a) else (x=b); Parsing the input statement.... If (a<b) goto 101 goto 102 101: (x=a) goto 103 102: (x=b) 103:

SS & CD Lab Manual

27 / 35

REVA ITM

Dept of Computer Science & Engg

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 ) { printf ( "\nre => " ); strcpy ( temp , productions[i] ); */

SS & CD Lab Manual

28 / 35

REVA ITM

Dept of Computer Science & Engg

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 ')' | re '*' | re '+' | re '|' re | re '.' re ; %% int main ( int argc , char **argv ) { /* Parse and output the rightmost derivation, from which we can get the parse tree */ yyparse(); return 0; { strcpy ( productions[count++] , "(re)" ); } { strcpy ( productions[count++] , "re*" ); } { strcpy ( productions[count++] , "re+" ); } { strcpy ( productions[count++] , "re | re" ); } { strcpy ( productions[count++] , "re . re" ); }

SS & CD Lab Manual

29 / 35

REVA ITM

Dept of Computer Science & Engg

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

SS & CD Lab Manual

30 / 35

REVA ITM

Dept of Computer Science & Engg

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*)

SS & CD Lab Manual

31 / 35

REVA ITM

Dept of Computer Science & Engg

VIVA Questions Part-A (Lex and Yacc) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. What is Lexer or define Lexer What are different segments of Lexer program What are different segments of Yacc program What is parser? Or Define Parser What are the significance of the following : a) y.tab.h b) yylval c) yyparse() d) yyerror What is Grammar What are Regular Expressions What are Productions What is Shift/Reduce Parsing What is Symbol Table? What information is stored in it Briefly explain about Parser-Lexer Communication Expand Yacc What is Character Class Explain the action of the following symbol within Regular Expression i) . ii) * iii) [ ] iv) ^ v) $ vi) { } vii) \ viii) + ix) ? x) | xii) / xiii) () What is Parse Tree ? what for it is used What is lex.yy.c Explain the logic of the given Program Define Assembler Briefly state two phases of an Assembler What is a compiler Define Loader Explain the significance of yyerror() Explain the significance of yytext

xi) .

SS & CD Lab Manual

32 / 35

REVA ITM

Dept of Computer Science & Engg

Part-B 1. Explain the feature of Unix OS. 2. What is process? Explain the parent child relationship. 3. What are the main functions of shell? 4. What are the steps involved in creating child process? 5. What are positional parameters? 6. What are environmental variables? 7. What is $*,$#,$$,$_,$! 8. Where do you use expr in shell scripts? 9. What is shell script? How it is different form c program? 10. What do you mean by exit status of a command? 11. Where do you use cut command? 12. Differentiate head and tail? 13. What is set command? 14. What is the function of lseek ( ) ? 15. What are types of files in Unix? 16. How can you change the file permissions? 17. What is fork ( ) ? 18. What is the purpose of wait ( ) ? 19. What is the purpose pf getenv ( ) ? 20. Who is the parent of all processes? 21. Explain the mechanism of process creation? 22. List the file attributes? 23. What are shell variables? Give an example. 24. What does sed command do?

SS & CD Lab Manual

33 / 35

REVA ITM

Dept of Computer Science & Engg

Instructions for Compilation LEX: If Program name is p1.l $ lex p1.l $ cc lex.yy.c lfl $ ./a.out YACC: If Program name is p1.y $ yacc -d p1.y $ cc y.tab.,c ly $ ./a.out Yacc with Lex program If Program name is p1.l, p1.y $ lex p1.l $ yacc d p1.y $ cc y.tab.c lex.yy.c lfl $ ./a.out SHELL Program : If Program name is p1.sh $ Shell p1.sh

SS & CD Lab Manual

34 / 35

REVA ITM

Dept of Computer Science & Engg

Bibliography 1. Aho, Alfred V., Ravi Sethi and Jeffrey D. Ullman [1986]. Compilers, Principles, Techniques and Tools. Addison-Wesley, Reading, Massachusetts. 2. Leland.L.Beck [1997],System Software, 3rd Edition, Addison-Wesley. 3. John.R.Levine, John R Levine, Tony Mason and Doug Brown, Lex and Yacc 2 Edition , O'Reilly, SPD, 1999 4. System Programming by Donovan

SS & CD Lab Manual

35 / 35

You might also like