编译原理龙书答案完整性高第二章2.2ExercisesforSection2.22.2.1Considerthecontext-freegrammar:S->SS+|SS*|aShowhowthestringaa+a*canbegeneratedbythisgrammar.Constructaparsetreeforthisstring.Whatlanguagedoesthisgrammargenerate?Justifyyouranswer.answerS->SS*->SS+S*->aS+S*->aa+S*->aa+a*L={Postfixexpressionconsistingofdigits,plusandmultiplesigns}2.2.2Whatlanguageisgeneratedbythefollowinggrammars?Ineachcasejustifyyouranswer.S->0S1|01S->+SS|-SS|aS->S(S)S|εS->aSbS|bSaS|ε⧗S->a|S+S|SS|S*|(S)answerL={0n1n|n>=1}L={Prefixexpressionconsistingofplusandminussigns}L={Matchedbracketsofarbitraryarrangementandnesting,includesε}L={Stringhasthesameamountofaandb,includesε}?2.2.3WhichofthegrammarsinExercise2.2.2areambiguousanswerNoNoYesYesYes2.2.4Constructunambiguouscontext-freegrammarsforeachofthefollowinglanguages.Ineachcaseshowthatyourgrammariscorrect.Arithmeticexpressionsinpostfixnotation.Left-associativelistsofidentifiersseparatedbycommas.Right-associativelistsofidentifiersseparatedbycommas.Arithmeticexpressionsofintegersandidentifierswiththefourbinaryoperators+,-,*,/.answer1.E->EEop|num2.list->list,id|id3.list->id,list|id4.expr->expr+term|expr-term|termterm->term*factor|term/factor|factorfactor->id|num|(expr)5.expr->expr+term|expr-term|termterm->term*unary|term/unary|unaryunary->+factor|-factorfactor->id|num|(expr)2.2.5Showthatallbinarystringsgeneratedbythefollowinggrammarhavevaluesdivisibleby3.Hint.Useinductiononthenumberofnodesinaparsetree.num->11|1001|num0|numnumDoesthegrammargenerateallbinarystringswithvaluesdivisibleby3?answerproveanystringderivedfromthegrammarcanbeconsideredtobeasequenceconsistingof11,1001and0,andnotprefixedwith0.thesumofthisstringis:sum=Σn(21+20)*2n+Σm(23+20)*2m=Σn3*2n+Σm9*2mItisobviouslycandivisibleby3.No.Considerstring"10101",itisdivisibleby3,butcannotderivedfromthegrammar.Question:anygeneralprove?2.2.6Constructacontext-freegrammarforromannumerals.Note:wejustconsiderasubsetofromannumeralswhichislessthan4k.answerwikipedia:Roman_numeralsviawikipedia,wecancategorizethesinglenomannumeralsinto4groups:I,II,III|IV|V,VI,VII,VIII|IXthengettheproduction:digit->smallDigit|IV|VsmallDigit|IXsmallDigit->I|II|III|εandwecanfindasimplewaytomapromantoarabicnumerals.Forexample:XII=>X,II=>10+2=>12CXCIX=>C,XC,IX=>100+90+9=>199MDCCCLXXX=>M,DCCC,LXXX=>1000+800+80=>1880viatheuppertworules,wecanderivetheproduction:romanNum->thousandhundredtendigitthousand->M|MM|MMM|εhundred->smallHundred|CD|DsmallHundred|CMsmallHundred->C|CC|CCC|εten->smallTen|XL|LsmallTen|XCsmallTen->X|XX|XXX|εdigit->smallDigit|IV|VsmallDigit|IXsmallDigit->I|II|III|ε2.3ExercisesforSection2.32.3.1Constructasyntax-directedtranslationschemethattranslatesarithmeticexpressionsfrominfixnotationintoprefixnotationinwhichanoperatorappearsbeforeitsoperands;e.g.,-xyistheprefixnotationforx-y.Giveannotatedparsetreesfortheinputs9-5+2and9-5*2.。
answerproductions:expr->expr+term|expr-term|termterm->term*factor|term/factor|factorfactor->digit|(expr)translationschemes:expr->{print("+")}expr+term|{print("-")}expr-term|termterm->{print("*")}term*factor|{print("/")}term/factor|factorfactor->digit{print(digit)}|(expr)2.3.2Constructasyntax-directedtranslationschemethattranslatesarithmeticexpressionsfrompostfixnotationintoinfixnotation.Giveannotatedparsetreesfortheinputs95-2*and952*-.answerproductions:expr->exprexpr+|exprexpr-|exprexpr*|exprexpr/|digittranslationschemes:expr->expr{print("+")}expr+|expr{print("-")}expr-|{print("(")}expr{print(")*(")}expr{print(")")}*|{print("(")}expr{print(")/(")}expr{print(")")}/|digit{print(digit)}AnotherreferenceanswerE->{print("(")}E{print(op)}E{print(")"}}op|digit{print(digit)}2.3.3Constructasyntax-directedtranslationschemethattranslatesintegersintoromannumeralsanswerassistantfunction:repeat(sign,times)//repeat('a',2)='aa'translationschemes:num->thousandhundredtendigit{num.roman=thousand.roman||hundred.roman||ten.roman||digit.roman;print(num.roman)}thousand->low{thousand.roman=repeat('M',low.v)}hundred->low{hundred.roman=repeat('C',low.v)}|4{hundred.roman='CD'}|high{hundred.roman='D'||repeat('X',high.v-5)}|9{hundred.roman='CM'}ten->low{ten.roman=repeat('X',low.v)}|4{ten.roman='XL'}|high{ten.roman='L'||repeat('X',high.v-5)}|9{ten.roman='XC'}digit->low{digit.roman=repeat('I',low.v)}|4{digit.roman='IV'}|high{digit.roman='V'||repeat('I',high.v-5)}|9{digit.roman='IX'}low->0{low.v=0}|1{low.v=1}|2{low.v=2}|3{low.v=3}high->5{high.v=5}|6{high.v=6}|7{high.v=7}|8{high.v=8}2.3.4Constructasyntax-directedtranslationschemethattranslatesromannumeralsintointegers.answerproductions:romanNum->thousandhundredtendigitthousand->M|MM|MMM|εhundred->smallHundred|CD|DsmallHundred|CMsmallHundred->C|CC|CCC|εten->smallTen|XL|LsmallTen|XCsmallTen->X|XX|XXX|εdigit->smallDigit|IV|VsmallDigit|IXsmallDigit->I|II|III|εtranslationschemes:romanNum->thousandhundredtendigit{romanNum.v=thousand.v||hundred.v||ten.v||digit.v;print(romanNun.v)}thousand->M{thousand.v=1}|MM{thousand.v=2}|MMM{thousand.v=3}|ε{thousand.v=0}hundred->smallHundred{hundred.v=smallHundred.v}|CD{hundred.v=smallHundred.v}|DsmallHundred{hundred.v=5+smallHundred.v}|CM{hundred.v=9}smallHundred->C{smallHundred.v=1}|CC{smallHundred.v=2}|CCC{smallHundred.v=3}|ε{hundred.v=0}ten->smallTen{ten.v=smallTen.v}|XL{ten.v=4}|LsmallTen{ten.v=5+smallTen.v}|XC{ten.v=9}smallTen->X{smallTen.v=1}|XX{smallTen.v=2}|XXX{smallTen.v=3}|ε{smallTen.v=0}digit->smallDigit{digit.v=smallDigit.v}|IV{digit.v=4}|VsmallDigit{digit.v=5+smallDigit.v}|IX{digit.v=9}smallDigit->I{smallDigit.v=1}|II{smallDigit.v=2}|III{smallDigit.v=3}|ε{smallDigit.v=0}2.3.5Constructasyntax-directedtranslationschemethattranslatespostfixarithmeticexpressionsintoequivalentprefixarithmeticexpressions.answerproduction:expr->exprexprop|digittranslationscheme:expr->{print(op)}exprexprop|digit{print(digit)}ExercisesforSection2.42.4.1Constructrecursive-descentparsers,startingwiththefollowinggrammars:S->+SS|-SS|aS->S(S)S|εS->0S1|01Answer1)S->+SS|-SS|avoidS(){switch(lookahead){case"+":match("+");S();S();break;case"-":match("-");S();S();break;case"a":match("a");break;default:thrownewSyntaxException();}}voidmatch(Terminalt){if(lookahead=t){lookahead=nextTerminal();}else{thrownewSyntaxException()}}2)S->S(S)S|εvoidS(){if(lookahead=="("){S();match("(");S();match(")");S();}}3)S->0S1|01voidS(){switch(lookahead){case"0":match("0");S();match("1");break;case"1"://match(epsilon);break;default:thrownewSyntaxException();}}ExercisesforSection2.62.6.1ExtendthelexicalanalyzerinSection2.6.5toremovecomments,definedasfollows:Acommentbeginswith//andincludesallcharactersuntiltheendofthatline.Acommentbeginswith/*andincludesallcharactersthroughthenextoccurrenceofthecharactersequence*/.2.6.2ExtendthelexicalanalyzerinSection2.6.5torecognizetherelationaloperators.2.6.3ExtendthelexicalanalyzerinSection2.6.5torecognizefloatingpointnumberssuchas2.,3.14,and.5.AnswerSourcecode:commit8dd1a9aCodesnippet(src/lexer/Lexer.java):publicTokenscan()throwsIOException,SyntaxException{for(;;peek=(char)stream.read()){if(peek==''||peek=='\t'){continue;}elseif(peek=='\n'){line=line+1;}else{break;}}//handlecommentif(peek=='/'){peek=(char)stream.read();if(peek=='/'){//singlelinecommentfor(;;peek=(char)stream.read()){if(peek=='\n'){break;}}}elseif(peek=='*'){//blockcommentcharprevPeek='';for(;;prevPeek=peek,peek=(char)stream.read()){if(prevPeek=='*'&&peek=='/'){break;}}}else{thrownewSyntaxException();}}//handlerelationsignif("".indexOf(peek)>-1){StringBufferb=newStringBuffer();b.append(peek);peek=(char)stream.read();if(peek=='='){b.append(peek);}returnnewRel(b.toString());}//handlenumber,notypesensitiveif(Character.isDigit(peek)||peek=='.'){BooleanisDotExist=false;StringBufferb=newStringBuffer();do{if(peek=='.'){isDotExist=true;}b.append(peek);peek=(char)stream.read();}while(isDotExist==true?Character.isDigit(peek):Character.isDigit(peek)||peek=='.');returnnewNum(newFloat(b.toString()));}//handlewordif(Character.isLetter(peek)){StringBufferb=newStringBuffer();do{b.append(peek);peek=(char)stream.read();}while(Character.isLetterOrDigit(peek));Strings=b.toString();Wordw=words.get(s);if(w==null){w=newWord(Tag.ID,s);words.put(s,w);}returnw;}Tokent=newToken(peek);peek='';returnt;}ExercisesforSection2.82.8.1For-statementsinCandJavahavetheform:for(exprl;expr2;expr3)stmtThefirstexpressionisexecutedbeforetheloop;itistypicallyusedforinitializingtheloopindex.Thesecondexpressionisatestmadebeforeeachiterationoftheloop;theloopisexitediftheexpressionbecomesO.Theloopitselfcanbethoughtofasthestatement{stmtexpr3;}.Thethirdexpressionisexecutedattheendofeachiteration;itistypicallyusedtoincrementtheloopindex.Themeaningofthefor-statementissimilartoexpr1;while(expr2){stmtexpr3;}DefineaclassForforfor-statements,similartoclassIfinFig.2.43.AnswerclassForextendsStmt{ExprE1;ExprE2;ExprE3;StmtS;publicFor(Exprexpr1,Exprexpr2,Exprexpr3,Stmtstmt){E1=expr1;E2=expr2;E3=expr3;S=stmt;}publicvoidgen(){E1.gen();Labelstart=newLable();Lalelend=newLable();emit("ifFalse"+E2.rvalue().toString()+"goto"+end);S.gen();E3.gen();emit("goto"+start);emit(end+":")}}2.8.2TheprogramminglanguageCdoesnothaveabooleantype.ShowhowaCcompilermighttranslateanif-statementintothree-addresscode.AnswerReplaceemit("isFalse"+E.rvalue().toString()+"goto"+after);withemit("ifNotEqual"+E.rvalue().toString()+"0goto"+after);oremit("isNotEqualZero"+E.rvalue().toString()+"goto"+after);
1