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

System software and Compiler design laboratory

LEX & YACC PROGRAMS


1.a) Program to count the number of characters. Words. Spaces and lines in a given input file.
%{ #include<stdio.h> #include<ctype.h> int l=0,b=0,w=0,c=0; %} %% [\n] {l++;} [^" "\t\n]+ {w++;c+=yyleng;} [" "\t] {b++;c++;} %% int main() { yyin=fopen("text.dat","r"); yylex(); fclose(yyin); printf("words=%d\n,characters=%d\n,blank spaces=%d\n,lines= %d\n",w,c,b,l); return 0; }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

1.b) 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 comment=0; %} %% "/*".*"*/" "//".*"" %% {comment++;fprintf(yyout," ");} {comment++;fprintf(yyout," ");}

int main(int argc,char *argv[]) { printf("A wonderful program"); yyin=fopen(argv[1],"r"); yyout=fopen(argv[2],"w"); yylex(); printf("\nNo of comments :%d \n",comment); }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

2.a) Program to recognize a valid arithmetic expression and to recognize the identifiers and operators present . print them separately. %{ #include<stdio.h> int c=0,oper=0,b=0,id=0; %} %% [+-/*] {oper++;c++;printf("%s is an operator\n",yytext);} [A-Za-z0-9]+ {id++;c++;printf("%s is an operand\n",yytext);} [(] {b++;c++;} [)] {b--;c++;} %% int yywrap() { return 1; } int main() { printf("\nEnter the expression...\n"); yylex(); if(b!=0) { printf("\nInvalid Expression..."); exit(0); } else if(c%2 == 0) { printf("\nInvalid expression..."); exit(0); } else printf("\nValid Expression..."); printf("\nThere are %d operators",oper); printf("\nThere are %d operands\n",id); return 0; }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

2.b) Program to recognize whether a given sentence is simple or compound %{ #include<stdio.h> int simp=0,comp=0; %} %% [A-Za-z]+" "and" "[A-Za-z]+ {comp++;} [A-Za-z]+" "but" "[A-Za-z]+ {comp++;} [A-Za-z]+" "because" "[A-Za-z]+ {comp++;} [A-Za-z]+ {simp++;} %% int main() { yyin=fopen("vin1","r"); yylex(); fclose(yyin); if(comp>0) printf("Compound statement\n"); if(simp>0) printf("Simple statement\n"); return 0; }

Department of Computer Science & Engg., MITK

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; %} %% ["int"]|["float"]|["double"]|["char"] {int ch; ch=input(); for(;;) { if(ch==',') { count++; } else if(ch==';') { count++; break; } ch=input(); } } %% int yywrap() { return 1; } main(int argc,char *argv[]) { yyin=fopen(argv[1],"r"); yylex(); printf("\nThe number of identifiers is %d\n",count); }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

4.a) Program to recognize a valid arithmetic expression that uses operators +,-,*,/ Lex part: %{ #include "y.tab.h" extern int yyparse(); %} %% [0-9]+ {return NUM;} [a-zA-Z][a-zA-Z0-9]* {return IDENT;} [+-] {return ADDORSUB;} [*/] {return PROORDIV;} [)(] [\n] {return 0;} . {return yytext[0];} %% Yacc Part: %{ #include<stdio.h> #include<stdlib.h> extern int yyerror(char *s); extern int yylex(); %} %token NUM %token ADDORSUB %token PROORDIV %token IDENT %% line :'\n' |exp {printf("\nVALID\n");} |error'\n' {yyerror;} ; exp :exp ADDORSUB term |term ; term :term PROORDIV factor |factor ; Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

factor:NUM |IDENT |'('exp')' ; %% int yyerror(char *s) { printf("\nINVALID"); } int main() { yyparse(); }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

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" %} %% [0-9] [a-z] [\n] . %% Yacc Part: %{ #include<stdio.h> #include<ctype.h> %} %token digit letter; %% ident :expr'\n' {printf("\nVALID\n"); exit(0);} ; expr :letter |expr letter |expr digit |error {yyerror("\nINVALID\n"); exit(1);} ; %% main() { yyparse(); } yyerror(char *s) { printf("%s",s); } {return digit;} {return letter;} {return yytext[0];} return 0;

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

5.a] Program to evaluate an arithmetic expression involving operators +, -, * and /. %{ #include<stdio.h> #include<ctype.h> #define YYSTYPE double %} %left '+''-' %left '*''/' %token n %% list : exp '\n' {printf("\nValue = %f \n",$1);return 0;} exp:exp'+'exp {$$=$1+$3;} |exp'-'exp {$$=$1-$3;} |exp'*'exp {$$=$1*$3;} |exp'/'exp { if($3==0) yyerror("\nDivide by zero\n"); else $$=$1/$3; } | '-'exp {$$=-$2;} | '('exp')' {$$=$2;} | n {$$=$1;} %% int main() { printf("Enter the expression \n"); yyparse(); return 0; } int yylex() { char c; c=getchar(); if(isdigit(c)) { ungetc(c,stdin); scanf("%lf",&yylval); return n; Department of Computer Science & Engg., MITK

System software and Compiler design laboratory } return c; } yyerror() { printf("Expression invalid \n"); exit(0); }

10

5.b. Program to recognize strings aaab, abbb, ab and a using the grammar (anbn, n>= 0). %{ #include<stdio.h> #include<ctype.h> %} %token a b %% start: |a start b %% int main() { printf("\nEnter string to check the grammer\n"); yyparse(); printf("\nString is acceptable...\n"); } int yylex() { char c; c=getchar(); if(c=='a')return a; if(c=='b')return b; if(c=='\n')return 0; return c; } yyerror() { printf("String not accepted\n"); exit(0); } Department of Computer Science & Engg., MITK

System software and Compiler design laboratory 6) Program to recognize the grammar (anb, n>= 10). %{ #include<stdio.h> #include<ctype.h> %} %token a b %% start: |a start |b |"\n" %% int main() { printf("\nEnter string to check for grammer (a^n)(b)\n"); yyparse(); printf("\nString is acceptable...\n"); } int yylex() { char c; c=getchar(); if(c=='a') return a; if(c=='b') return b; if(c=='\n') return 0; return c; } yyerror() { printf("String not accepted\n"); exit(0); }

11

UNIX PROGRAMS:
Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

12

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). if [ $# -eq 0 ] then echo "Enter the arguments" else arg=" " for i in $* do arg=$1" "$arg shift done echo "Reverse arguments are $arg" fi

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

13

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.

#include<stdio.h> #include<unistd.h> int main() { int pid_t,i; char command[10]; pid_t=fork(); if(pid_t==0) { system("clear"); printf("Child process created\n"); printf("Enter the command to be executed\n"); scanf("%s",&command); system(command); } else { printf("child Process not created\n"); wait(10); exit(1); } printf("Parent Process over\n"); return 0; }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

14

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. perm1=`ls -l $1|cut -c 2-10` perm2=`ls -l $2|cut -c 2-10` if [ $perm1 = $perm2 ] then echo "Files have same permission" else echo "$1 has permission $perm1" echo "$2 has permission $perm2" fi

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

15

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.

#include<stdio.h> #include<sys/types.h> int main() { char buf1[]="abcdefghijklmnop"; char buf2[]="ABCDEFGHIJKLMNOP"; int fd=creat("fi.dat","w"); write(fd,buf1,16); lseek(fd,48,SEEK_SET); write(fd,buf2,16); system("vi fi.dat"); return 0; }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory


3.a

16

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.

echo "Enter the directory name" read dirname ls -lR $dirname|cut -c 38-43,57-64>file1 sort -n file1>file2 echo "Max size file is" tail -1 file2

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

17

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

#include<stdio.h> #include<unistd.h> #include<sys/stat.h> #include<sys/types.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("Regular file\n"); else if(S_ISCHR(buf.st_mode)) printf("Character file\n"); else if(S_ISBLK(buf.st_mode)) printf("Block file\n"); else if(S_ISDIR(buf.st_mode)) printf("Directory file\n"); else if(S_ISLNK(buf.st_mode)) printf("Symbolic link file\n"); } return 0; }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

18

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 echo >out.sh cat $1>>out.sh echo >out.t>>out.sh

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

19

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. #include<sys/types.h> #include<stdio.h> int main() { pid_t pid; if ((pid=fork())<0) printf("fork error"); if (pid==0) { printf("\nThis is child process\n"); printf("\nthe child process pid:%d\n",getpid()); printf("\nparent pid:%d\n",getppid()); exit(0); } wait(pid); printf("\n This is parent process\n"); printf("\n parent pid:%d\n",getpid()); printf("\n child pid:%d\n",pid); exit(0); }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory Compiler design:

20

5]. Write a C Program to implement the syntax directed definition of if E then SI and if E then S1 else S2 , ( Fefer Fig .8.23 in the text book prescribed for 06CS62 Compiler Design, Alfred V Aho, Ravi Sethi, Jeffrey D Ullman : Compilers Principle techniques and tools Addison Wesley, 2007) #include<curses.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> int parsencondition(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"); scanf("%s",stmt); //gets(stmt); stlen=strlen(stmt); counter=counter+2;//increment over 'if' counter=parsecondition(stmt,counter,strB,stlen); if(counter==0) { printf("Invalid\n"); return; } if(stmt[counter]==')') counter++; counter=counter+3;//increment over 'then' counter=parsecondition(stmt,counter,strS1,stlen); if(counter==0) printf("Invalid\n"); return; } if(stmt[counter+1]==';')

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

21

{//reached end of the statement,generate the output printf("\n Parsing the input statement"); gen(strB,strS1,strS2,elseflag); //getch(); 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 the statement if(counter==stlen) {//generate the output elseflag=1; printf("\n Parsing input statement..."); gen(strB,strS1,strS2,elseflag); //getch(); 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 ro begin search string to store rhe condition,total string length // Output:Returns 0 on failure,Nopn 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() Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

22

// * Description:This function generates three address code // * Input:Expression statenmment for the true condition,statement for the 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:\n",Bf); else { printf("\n\tgoto%d",Sn); printf("\n%d:%s",Bf,S2); printf("\n%d:\n",Sn); } }

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory

23

6]Write a Yacc Program that accepts a regular expression as input and produce parse tree as output.
%{ #include<stdio.h> #include<ctype.h> #include<string.h> char str[20]; int i=0,index1=0,pos=0,top=-1,length; char symbol,temp; char infix[20],postfix[20],stack[20]; %} %token id %% E: S {infix_postfix(str);} S: S'+'T | S'-'T |T T: T'*'F | T'/'F |F F: id |'(' S ')' ; %% main() { printf("enter an id: "); yyparse(); } yyerror() { printf("invalid\n"); } yylex() { char ch=' '; while(ch!='\n') { ch=getchar(); str[i++]=ch; if(isalpha(ch) || isdigit(ch)) return id;

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory if(ch=='+' || ch=='*'||ch=='-'||ch=='/'||ch=='('||ch==')') return ch; } str[--i]='\0'; return(0); exit(0); } void push(char symbol) { top++; stack[top]=symbol; return; } char pop() { char symbol; symbol=stack[top]; top--; return(symbol); } int preced(char symbol) { int p; switch(symbol) { case '*': case '/': p=2; break; case '+': case '-': p=1; break; case ')': case '(': p=0; break; case '#': p=-1; break; default: printf("illegal operation %c",symbol); exit(0); } return (p); } void infix_postfix(char infix[]) Department of Computer Science & Engg., MITK

24

System software and Compiler design laboratory { length=strlen(infix); push('#'); while(index1<length) { symbol=infix[index1]; switch(symbol) { case '(': push(symbol); break; case ')': temp=pop(); while(temp!='(') { postfix[pos]=temp; pos++; temp=pop(); } break; case '+': case '-': case '*': case '/' : while(preced(stack[top])>=preced(symbol)) { temp=pop(); postfix[pos]=temp; pos++; } push(symbol); break; default: postfix[pos++]=symbol; break; } index1++; } while(top>0) {

25

Department of Computer Science & Engg., MITK

System software and Compiler design laboratory temp=pop(); postfix[pos++]=temp; } printf("OUTPUT: "); printf("%s\n",postfix); return; }

26

Department of Computer Science & Engg., MITK

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