SS and CD Lab - Programs

download SS and CD Lab - Programs

of 16

description

SS and CD Lab - Programs

Transcript of SS and CD Lab - Programs

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    SystemprogrammingandcompilerdesignlaboratorySubjectCode:06CSL68I.A.Marks:25Hours/Week:03ExamHours:03TotalHours:42ExamMarks:50PARTALEXandYACCPrograms:ExecutethefollowingprogramsusingLEX:1)a.Programtocountthenumberofcharacters,words,spacesandlinesinagiveninputfile.b.ProgramtocountthenumbersofcommentlinesinagivenCprogram.Alsoeliminatethemandcopytheresultingprogramintoseparatefile.2)a.Programtorecognizeavalidarithmeticexpressionandtorecognizetheidentifiersandoperatorspresent.Printthemseparately.b.Programtorecognizewhetheragivensentenceissimpleorcompound.3)Programtorecognizeandcountthenumberofidentifiersinagiveninputfile.ExecutethefollowingprogramsusingYACC:4)a.Programtorecognizeavalidarithmeticexpressionthatusesoperators+,,*and/.b.Programtorecognizeavalidvariable,whichstartswithaletter,followedbyanynumberoflettersordigits.

    5)a.Programtoevaluateanarithmeticexpressioninvolvingoperators+,,*and/.b.Programtorecognizestringsaaab,abbb,abandausingthegrammar(anbn,n>=0).6)Programtorecognizethegrammar(anb,n>=10).PARTBUnixProgramming:1.a)NonrecursiveshellscriptthatacceptsanynumberofargumentsandprintsthemintheReverseorder,(Forexample,ifthescriptisnamedrargs,thenexecutingrargsABCshouldproduceCBAonthestandardoutput).b)Cprogramthatcreatesachildprocesstoreadcommandsfromthestandardinputandexecutethem(aminimalimplementationofashelllikeprogram).Youcanassumethatnoargumentswillbepassedtothecommandstobeexecuted.2.a)Shellscriptthatacceptstwofilenamesasarguments,checksifthepermissionsforthesefilesareidenticalandifthepermissionsareidentical,outputsthecommonpermissions,otherwiseoutputseachfilenamefollowedbyitspermissions.b)Cprogramtocreateafilewith16bytesofarbitrarydatafromthebeginningandanother16bytesofarbitrarydatafromanoffsetof48.Displaythefilecontentstodemonstratehowtheholeinfileishandled.3.a)Shellfunctionthattakesavaliddirectorynamesasanargumentandrecursivelydescendsallthesubdirectories,findsthemaximumlengthofanyfileinthathierarchyandwritesthismaximumvaluetothestandardoutput.b)Cprogramthatacceptsvalidfilenamesascommandlineargumentsandforeachofthearguments,printsthetypeofthefile(Regularfile,Directoryfile,Characterspecialfile,Blockspecialfile,Symboliclinketc.)4.a)Shellscriptthatacceptsfilenamesspecifiedasargumentsandcreatesashellscriptthatcontainsthisfileaswellasthecodetorecreatethesefiles.Thusifthescriptgeneratedbyyourscriptisexecuted,itwouldrecreatetheoriginalfiles(ThisissameasthebundlescriptdescribedbyBrainW.KernighanandRobPikeinTheUnixProgrammingEnvironment,PrenticeHallIndia).b)Cprogramtodothefollowing:Usingfork()createachildprocess.

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    Thechildprocessprintsitsownprocessidandidofitsparentandthenexits.Theparentprocesswaitsforitschildtofinish(byexecutingthewait())andprintsitsownprocessidandtheidofitschildprocessandthenexits.CompilerDesign:5.WriteaCprogramtoimplementthesyntaxdirecteddefinitionofifEthenS1andifEthenS1elseS2.(ReferFig.8.23inthetextbookprescribedfor06CS62CompilerDesign,AlfredVAho,RaviSethi,JeffreyDUllman:CompilersPrinciples,TechniquesandTools,AddisonWesley,2007.)6.Writeayaccprogramthatacceptsaregularexpressionasinputandproduceitsparsetreeasoutput.Instructions:Intheexamination,acombinationofoneLEXandoneYACCproblemhastobeaskedfromPartAforatotalof25marksandoneprogrammingexercisefromPartBhastobeaskedforatotalof25marks.

    PartA(LEXandYACC)

    1a.Countcharacters,linesandwords%{ints=0,w=0,l=1,c=0%}%%[\n]*{l+=yyleng}[\t]*{s+=yyleng}[^\n\t]*[\t]{w++c+=yyleng1s++}[^\n\t]*[]{w++c+=yyleng1s++}[^\n\t]*[\n]{w++c+=yyleng1l++}[^\n\t]*{w++c+=yyleng}%%main(intargc,char**argv){if(argc!=2){printf("\nIncorrectusage!!\n")return1}yyin=fopen(*(argv+1),"r")if(!yyin){printf("\nCannotopenthefile!\n")return1}yylex()printf("\nChar=%d\nSpaces=%d\nWords=%d\nLines=%d\n",c,s,w,l)}

    1b.CommentLines

    %{intcom=0%}%%\/\*[^*]*\*(\*|([^*/][^*]*\*))*\/com++\/\/[^\n]*[\n]com++%fprintf(yyout,"%%").|[\n]fprintf(yyout,yytext)%%main(intargc,char**argv){if(argc!=3){printf("\nArgumentspassedinwrongmanner\n")return1}

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    yyin=fopen(*(argv+1),"r")yyout=fopen(*(argv+2),"w")if(!(yyin&&yyout)){printf("\nSpecifiedfilecannotbeopened!")return1}yylex()printf("\nTotlanumberofcommentlines=%d\n",com)}

    2a.Validarithmeticexpression%{#includeintvalid,i,j,k,temp,temp1,top=1,num[40]chararr[40][10],st[80],op[40]%}%%[azAZ][azAZ09]*{strcpy(arr[j++],yytext)if(st[top1]=='i')valid=1elseif(st[top1]=='o')st[top1]='i'elsest[top++]='i'}[09]+{num[k++]=atoi(yytext)if(st[top1]=='i')valid=1elseif(st[top1]=='o')st[top1]='i'elsest[top++]='i'}[\+/*%^&|]{op[temp++]=yytext[0]if(st[top1]=='i')st[top1]='o'elsevalid=1}"("{if(st[top1]=='('||st[top1]=='$'||st[top1]=='o')st[top++]='('elsevalid=1}")"{if(st[top1]=='(')topelseif(st[top1]=='i'&&st[top2]=='('){top=2if(st[top1]=='o')st[top1]='i'elseif(st[top1]=='i')valid=1elsest[top++]='i'}elsevalid=1}.valid=1\nreturn%%check(){if(!(temp|k|j))return0if(valid)return0if(top==2&&st[top1]=='i')

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    topif(top==1&&st[top1]=='$')topif(top==0)return1return0}main(){st[top1]='$'printf("\nEntertheexpression\n")yylex()if(check()){printf("\nValidexpression!\n")if(j>0)printf("\nIdentifierspresentare")for(i=0i0)printf("\nNumbersusedare")for(i=0i0)printf("\nOperatorspresentare")for(i=0i

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    break}ch=input()}}.|[\n]%%intmain(intargc,char**argv){if(argc!=2){printf("\nImproperusage!\n")return1}yyin=fopen(*(argv+1),"r")if(!yyin){printf("\nSpecifiedfilecannotbeopened!\n")return1}yylex()printf("\nTotalidentifiersis%d\n",id)}

    3.Identifiers(method2)%{#includecharch,arr[20]intid,i,jinttest(char*)%}%%^[\t]*("int"|"float"|"double"|"char")[\t]*{ch=input()while(1){if(ch=='\n'||ch==0)breakif(ch==','||ch==''){arr[i]=0i=0j=test(arr)if(j!=1){id+=jprintf("\n%sisa%s",arr,j?"identifier":"nonidentifier")}if(ch=='')breakch=input()continue}arr[i++]=chch=input()}}.|[\n]%%yywrap(){return1}intrno(char*a,intstate){if(*a=='='&&state==0&&!(*a=0))return1if(isdigit(*a)&&state==1)state=1if(*a==']'&&state==1)state=0if(*a==0&&state==0)return1if(*a=='['&&state==0)

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    state=1a++returnrno(a,state)}inttest(char*a){char*b=aintiwhile(*b=='')b++if(!isalpha(*b))return0while(*b!=0){if(*b=='='&&!(*b=0))return1if(*b=='['){i=rno(b++,1)bif(i==1)*b=0returni}if(!isalnum(*b))return0b++}return1}intmain(intargc,char**argv){if(argc!=2){printf("\nImproperusage!\n")return1}yyin=fopen(*(argv+1),"r")if(!yyin){printf("\nSpecifiedfilecannotbeopened!\n")return1}yylex()printf("\nTotalidentifiersis%d\n",id)}

    4a.Validarithmeticexpression(method1)LEXpart

    %{#include"y.tab.h"%}%%[azAZ_][azAZ_09]*returnid[09]+(\.[09]*)?returnnum[+/*]returnop.returnyytext[0]\nreturn0%%

    YACCpart

    %{#includeintvalid=1%}%tokennumidop%%start:id'='s''s:idx|numx

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    |''numx|'('s')'xx:ops|''s|%%intyyerror(){valid=0printf("\nInvalidexpression!\n")return0}intmain(){printf("\nEntertheexpression:\n")yyparse()if(valid){printf("\nValidexpression!\n")}}

    4a.Validarithmeticexpression(method2)LEXpart

    %{#include"y.tab.h"%}%%[azAZ_][azAZ_09]*returnid[09]+(\.[09]*)?returnnum[+/*]returnop.returnyytext[0]\nreturn0%%

    YACCpart

    %{#includeintvalid=1%}%tokennumidop%left''op%%start:idy'='s''y:op|''|s:xopx|x''x|'('s')'|xx:id|''num|num%%intyyerror(){valid=0printf("\nInvalidexpression!\n")return0}intmain(){printf("\nEntertheexpression:\n")yyparse()

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    if(valid){printf("\nValidexpression!\n")}}

    4b.ValidvariableLEXpart

    %{#include"y.tab.h"%}%%[azAZ]returnletter[09]returndigit.returnyytext[0]\nreturn0%%

    YACCpart

    %{#includeintvalid=1%}%tokendigitletter%%start:letterss:letters|digits|%%intyyerror(){printf("\nItsnotaidentifier!\n")valid=0return0}intmain(){printf("\nEnteranametotestedforidentifier")yyparse()if(valid){printf("\nItisaidentifier!\n")}}

    5a.EvaluatevalidarithmeticexpressionLEXpart

    %{#include"y.tab.h"intexternyylval%}%%[09]+{yylval=atoi(yytext)returnnum}.returnyytext[0]\nreturn0%%

    YACCpart

    %#includeintvalid=0,temp%}

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    %tokennum%left'+'''%left'*''/'%nonassocUMINUS%%expr1:expr{temp=$1}expr:expr'+'expr{$$=$1+$3}|expr''expr{$$=$1$3}|expr'*'expr{$$=$1*$3}|expr'/'expr{if($3==0){valid=1$$=0}else{$$=$1/$3}}|'('expr')'{$$=$2}|''expr{$$=1*$2}|num{$$=yylval}%%intyyerror(){printf("\nInvalidexpression!\n")valid=2return0}intmain(){printf("\nEntertheexpressiontobeevaluated\n")yyparse()if(valid==1){printf("\nDivisionby0!\n")}if(valid==0){printf("\nValidexpression!\n")printf("Thevalueevaluatedis%d\n",temp)}}

    5b.Languagea^nb^n(n>=0)LEXpart

    %{#include"y.tab.h"%}%%areturnAbreturnB.|[\n]return0%%

    YACCpart

    %{#includeintvalid=1%}%tokenAB%%start:AstartB|%%intyyerror(){valid=0printf("\nPatternnotmatched!\n")return0}intmain(){printf("\nEnterthepattern")yyparse()if(valid){printf("\nValidpattern!\n")

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    }}

    6.Languageoftypea^nb(n>=10)LEXpart

    %{#include"y.tab.h"%}%%areturnAbreturnB.|[\n]return0%%

    YACCpart

    %{#includeintvalid=1%}%tokenAB%%start:AAAAAAAAAAsBs:As|%%intyyerror(){valid=0printf("\nPatternnotmatched!\n")return0}intmain(){printf("\nEnterthepattern")yyparse()if(valid){printf("\nValidpattern!\n")}}

    PartB(UnixProgramming)

    1a.Nonrecursivelyprinttheargumentsinreverseordertemp=$#while[$tempge1]doevalecho\$$temptemp=`expr$temp1`done

    1b.Childprocesstoreadcommands#include#includemain(){intpidcharcmd[15]pid=fork()if(pid

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    printf(ForkError!\n)exit(0)}elseif(pid==0){printf(\nEntertheCommand:)scanf(%s,cmd)system(cmd)exit(0)}}

    2a.Filepermissionstemp1=`lsl$1|cutc110`temp2=`lsl$2|cutc110`if[$temp1=$temp2]thenechoThefileshavecommonPermissionsecho$temp1elseechoThepermissionfor$1is:echo$temp1echoThepermissionfor$2is:echo$temp2fi

    2b.Holeinthefile#include#include#includecharbuf1[]=abcdefghijklmnopcharbuf2[]=ABCDEFGHIJKLMNOPintmain(){intfdfd=create(file.dat,0)write(fd,buf1,16)lseek(fd,48,SEEK_SET)write(fd,buf2,16)system(odcfile.dat)exit(0)}

    3a.MaximumlengthlslR$1|grepv^d|sortnr+45|head1>file1#lslR$1|grepv^d|sortnrk5|headn1>file1string=`cutdf9file1`length=`cutdf5file1`echoTheMaximumlengthfile,$stringis:$string:

    3b.Typeoffile#include#include#include#includemain(intargc,char*argv[]){structstatstintifor(i=1i

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    {caseS_IFDIR:printf("directoryfile\n")breakcaseS_IFCHR:printf("characterdevicefile\n")breakcaseS_IFBLK:printf("blockdevicefile\n")breakcaseS_IFREG:printf("regularfile\n")breakcaseS_IFLNK:printf("symbolliclinkfile\n")breakcaseS_IFIFO:printf("FIFOfile\n")}}}

    4a.Bundlescriptecho#tounbundled,shthisfileforidoechoecho$i1>&2echocat>$i

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    charstrS2[45]printf("formatof'if'statement\nexample..\n")printf("if(a

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    exit(0)}main(){chararr[50],arr1[25],arr2[25],marr[25]intcntr,iprintf("\nEntertheexpression")scanf("%s",arr)if(arr[0]=='i'&&arr[1]=='f'&&arr[2]=='('){cntr=3i=0while(arr[cntr]!=')')marr[i++]=arr[cntr++]cntr++marr[i]=0}elseexitstatus()if(arr[cntr]=='t'&&arr[cntr+1]=='h'&&arr[cntr+2]=='e'&&arr[cntr+3]=='n'&&arr[cntr+4]=='('){cntr+=5i=0while(arr[cntr]!=')')arr1[i++]=arr[cntr++]cntr++arr1[i]=0if(arr[cntr]==''&&arr[cntr+1]==0)printf("59:if(%s)goto60\ngoto61\n60:(%s)",marr,arr1)elseif(arr[cntr]=='e'&&arr[cntr+1]=='l'&&arr[cntr+2]=='s'&&arr[cntr+3]=='e'&&arr[cntr+4]=='('){cntr+=5i=0while(arr[cntr]!=')')arr2[i++]=arr[cntr++]cntr++arr2[i]=0if(arr[cntr]==''&&arr[cntr+1]==0)printf("59:if(%s)goto60\ngoto62\n60:(%s)goto62\n61:(%s)\n62:",marr,arr1,arr2)elseexitstatus()}elseexitstatus()}elseexitstatus()}

    6.Parsetree%{#includecharstr[20]inti=0%}

    %tokenid%left'+''/''*'''%%E:S{infix_postfix(str)}S:S'+'T|S''T|TT:T'*'F|T'/'F|FF:id|'('S')'%%

    #includemain(){printf("\nEnteranidentifier:")yyparse()}

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    yyerror(){printf("invalid")}

    yylex(){charch=''while(ch!='\n'){ch=getchar()str[i++]=chif(isalpha(ch))returnidif(ch=='+'||ch=='*'||ch==''||ch=='/')returnch}str[i]='\0'return(0)exit(0)}

    voidpush(charstack[],int*top,charch){stack[++(*top)]=ch}

    charpop(charstack[],int*top){return(stack[(*top)])}intprec(charch){switch(ch){case'/':case'*':return2case'+':case'':return1case'(':return0default:return1}}

    voidinfix_postfix(charinfix[]){inttop=1,iptr=1,pptr=1charpostfix[20],stack[20],stksymb,cursymbpush(stack,&top,'\0')while((cursymb=infix[++iptr])!='\0'){switch(cursymb){case'(':push(stack,&top,cursymb)breakcase')':stksymb=pop(stack,&top)while(stksymb!='('){postfix[++pptr]=stksymbstksymb=pop(stack,&top)}breakcase'*':case'/':case'+':case'':while(prec(stack[top])>=prec(cursymb))postfix[++pptr]=pop(stack,&top)push(stack,&top,cursymb)breakdefault:if(isalnum(cursymb)==0){printf("Errorininput!")exit(0)}postfix[++pptr]=cursymb}}while(top!=1)

  • 66DQG&'ODE3URJUDPV

    KWWSSURJUDPVYWXZHHEO\FRPVVDQGFGODEKWPO

    postfix[++pptr]=pop(stack,&top)printf("%s\n",postfix)}

    Note:ThisisDFAforprogram1b

    Asstate20,21and22remainasitissoweobtainthestate2regularexpressionas\/\*[^*]\*(\*||([^*\][^*]*\*))*\/

    VTUFREE WEBSITE (HTTP://WWW.WEEBLY.COM/?UTM_SOURCE=INTERNAL&UTM_MEDIUM=FOOTER&UTM_CAMPAIGN=3) POWERED BY