版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter3DescribingSyntaxandSemanticsCopyright©2023Addison-Wesley.Allrightsreserved.1-2Chapter3TopicsIntroductionTheGeneralProblemofDescribingSyntaxFormalMethodsofDescribingSyntaxAttributeGrammarsDescribingtheMeaningsofPrograms:DynamicSemanticsCopyright©2023Addison-Wesley.Allrightsreserved.1-3IntroductionSyntax:theformorstructureoftheexpressions,statements,andprogramunitsSemantics:themeaningoftheexpressions,statements,andprogramunitsSyntaxandsemanticsprovidealanguage’sdefinitionUsersofalanguagedefinitionOtherlanguagedesignersImplementersProgrammers(theusersofthelanguage)Copyright©2023Addison-Wesley.Allrightsreserved.1-4TheGeneralProblemofDescribingSyntax:TerminologyAsentenceisastringofcharactersoversomealphabetAlanguageisasetofsentencesAlexemeisthelowestlevelsyntacticunitofalanguage(e.g.,*,sum,begin)Atokenisacategoryoflexemes(e.g.,identifier)Copyright©2023Addison-Wesley.Allrightsreserved.1-5FormalDefinitionofLanguagesRecognizersArecognitiondevicereadsinputstringsoverthealphabetofthelanguageanddecideswhethertheinputstringsbelongtothelanguageExample:syntaxanalysispartofacompiler-DetaileddiscussionofsyntaxanalysisappearsinChapter4GeneratorsAdevicethatgeneratessentencesofalanguageOnecandetermineifthesyntaxofaparticularsentenceissyntacticallycorrectbycomparingittothestructureofthegeneratorCopyright©2023Addison-Wesley.Allrightsreserved.1-6BNFandContext-FreeGrammarsContext-FreeGrammarsDevelopedbyNoamChomskyinthemid-1950sLanguagegenerators,meanttodescribethesyntaxofnaturallanguagesDefineaclassoflanguagescalledcontext-freelanguagesBackus-NaurForm(1959)InventedbyJohnBackustodescribethesyntaxofAlgol58BNFisequivalenttocontext-freegrammarsCopyright©2023Addison-Wesley.Allrightsreserved.1-7BNFFundamentalsInBNF,abstractionsareusedtorepresentclassesofsyntacticstructures--theyactlikesyntacticvariables(alsocallednonterminalsymbols,orjustterminals)Terminalsarelexemesortokens
Arulehasaleft-handside(LHS),whichisanonterminal,andaright-handside(RHS),whichisastringofterminalsand/ornonterminalsBNFFundamentals(continued)NonterminalsareoftenenclosedinanglebracketsExamplesofBNFrules:
<ident_list>→identifier|identifier,<ident_list>
<if_stmt>→if<logic_expr>then<stmt>Grammar:afinitenon-emptysetofrulesAstartsymbolisaspecialelementofthenonterminalsofagrammarCopyright©2023Addison-Wesley.Allrightsreserved.1-8Copyright©2023Addison-Wesley.Allrightsreserved.1-9BNFRulesAnabstraction(ornonterminalsymbol)canhavemorethanoneRHS
<stmt>
<single_stmt>|begin<stmt_list>endCopyright©2023Addison-Wesley.Allrightsreserved.1-10DescribingListsSyntacticlistsaredescribedusingrecursion
<ident_list>
ident|ident,<ident_list>Aderivationisarepeatedapplicationofrules,startingwiththestartsymbolandendingwithasentence(allterminalsymbols)Copyright©2023Addison-Wesley.Allrightsreserved.1-11AnExampleGrammar <program>
<stmts><stmts>
<stmt>|<stmt>;<stmts><stmt>
<var>=<expr><var>
a|b|c|d<expr>
<term>+<term>|<term>-<term><term>
<var>|constCopyright©2023Addison-Wesley.Allrightsreserved.1-12AnExampleDerivation <program>=><stmts>=><stmt>=><var>=<expr>=>a=<expr>=>a=<term>+<term>=>a=<var>+<term>=>a=b+<term>=>a=b+constCopyright©2023Addison-Wesley.Allrightsreserved.1-13DerivationsEverystringofsymbolsinaderivationisasententialformAsentenceisasententialformthathasonlyterminalsymbolsAleftmostderivationisoneinwhichtheleftmostnonterminalineachsententialformistheonethatisexpandedAderivationmaybeneitherleftmostnorrightmostCopyright©2023Addison-Wesley.Allrightsreserved.1-14ParseTreeAhierarchicalrepresentationofaderivation
<program><stmts><stmt>consta<var>=<expr><var>b<term>+<term>Copyright©2023Addison-Wesley.Allrightsreserved.1-15AmbiguityinGrammarsAgrammarisambiguousifandonlyifitgeneratesasententialformthathastwoormoredistinctparsetreesCopyright©2023Addison-Wesley.Allrightsreserved.1-16AnAmbiguousExpressionGrammar<expr>
<expr><op><expr>|const<op>
/|-<expr><expr><expr><expr><expr><expr><expr><expr><expr><expr><op><op><op><op>constconstconstconstconstconst--//<op>Copyright©2023Addison-Wesley.Allrightsreserved.1-17AnUnambiguousExpressionGrammarIfweusetheparsetreetoindicateprecedencelevelsoftheoperators,wecannothaveambiguity<expr>
<expr>-<term>|<term><term>
<term>/const|const<expr><expr><term><term><term>constconstconst/-Copyright©2023Addison-Wesley.Allrightsreserved.1-18AssociativityofOperatorsOperatorassociativitycanalsobeindicatedbyagrammar<expr>-><expr>+<expr>|const(ambiguous)<expr>-><expr>+const|const(unambiguous)<expr><expr><expr><expr>constconstconst++Copyright©2023Addison-Wesley.Allrightsreserved.1-19ExtendedBNFOptionalpartsareplacedinbrackets[]
<proc_call>->ident[(<expr_list>)]AlternativepartsofRHSsareplacedinsideparenthesesandseparatedviaverticalbars
<term>→<term>
(+|-)constRepetitions(0ormore)areplacedinsidebraces{}
<ident>→letter{letter|digit}Copyright©2023Addison-Wesley.Allrightsreserved.1-20BNFandEBNFBNF
<expr>
<expr>+<term> |<expr>-<term> |<term><term>
<term>*<factor> |<term>/<factor>|<factor>EBNF
<expr>
<term>{(+|-)<term>}<term>
<factor>{(*|/)<factor>}Copyright©2023Addison-Wesley.Allrightsreserved.1-21RecentVariationsinEBNFAlternativeRHSsareputonseparatelinesUseofacoloninsteadof=>UseofoptforoptionalpartsUseofoneofforchoicesCopyright©2023Addison-Wesley.Allrightsreserved.1-22StaticSemanticsNothingtodowithmeaningContext-freegrammars(CFGs)cannotdescribeallofthesyntaxofprogramminglanguagesCategoriesofconstructsthataretrouble:-Context-free,butcumbersome(e.g.,typesofoperandsinexpressions)-Non-context-free(e.g.,variablesmustbedeclaredbeforetheyareused)Copyright©2023Addison-Wesley.Allrightsreserved.1-23AttributeGrammarsAttributegrammars(AGs)haveadditionstoCFGstocarrysomesemanticinfoonparsetreenodesPrimaryvalueofAGs:StaticsemanticsspecificationCompilerdesign(staticsemanticschecking)Copyright©2023Addison-Wesley.Allrightsreserved.1-24AttributeGrammars:DefinitionDef:Anattributegrammarisacontext-freegrammarG=(S,N,T,P)withthefollowingadditions:ForeachgrammarsymbolxthereisasetA(x)ofattributevaluesEachrulehasasetoffunctionsthatdefinecertainattributesofthenonterminalsintheruleEachrulehasa(possiblyempty)setofpredicatestocheckforattributeconsistencyCopyright©2023Addison-Wesley.Allrightsreserved.1-25AttributeGrammars:DefinitionLetX0
X1...XnbearuleFunctionsoftheformS(X0)=f(A(X1),...,
A(Xn))definesynthesizedattributesFunctionsoftheformI(Xj)=f(A(X0),...,A(Xn)),fori<=j<=n,defineinheritedattributesInitially,thereareintrinsicattributesontheleavesCopyright©2023Addison-Wesley.Allrightsreserved.1-26AttributeGrammars:AnExampleSyntax<assign>-><var>=<expr><expr>-><var>+<var>|<var><var>A|B|Cactual_type:synthesizedfor<var>and<expr>
expected_type:inheritedfor<expr>
Copyright©2023Addison-Wesley.Allrightsreserved.1-27AttributeGrammar(continued)Syntaxrule:<expr>
<var>[1]+<var>[2] Semanticrules: <expr>.actual_type
<var>[1].actual_typePredicate: <var>[1].actual_type==<var>[2].actual_type <expr>.expected_type==<expr>.actual_typeSyntaxrule:<var>
idSemanticrule: <var>.actual_type
lookup(<var>.string)Copyright©2023Addison-Wesley.Allrightsreserved.1-28AttributeGrammars(continued)Howareattributevaluescomputed?Ifallattributeswereinherited,thetreecouldbedecoratedintop-downorder.Ifallattributesweresynthesized,thetreecouldbedecoratedinbottom-uporder.Inmanycases,bothkindsofattributesareused,anditissomecombinationoftop-downandbottom-upthatmustbeused.Copyright©2023Addison-Wesley.Allrightsreserved.1-29AttributeGrammars(continued)<expr>.expected_type
inheritedfromparent<var>[1].actual_type
lookup(A)<var>[2].actual_type
lookup(B)<var>[1].actual_type=?<var>[2].actual_type<expr>.actual_type
<var>[1].actual_type<expr>.actual_type=?<expr>.expected_typeCopyright©2023Addison-Wesley.Allrightsreserved.1-30SemanticsThereisnosinglewidelyacceptablenotationorformalismfordescribingsemanticsSeveralneedsforamethodologyandnotationforsemantics:ProgrammersneedtoknowwhatstatementsmeanCompilerwritersmustknowexactlywhatlanguageconstructsdoCorrectnessproofswouldbepossibleCompilergeneratorswouldbepossibleDesignerscoulddetectambiguitiesandinconsistenciesOperationalSemantics
OperationalSemanticsDescribethemeaningofaprogrambyexecutingitsstatementsonamachine,eithersimulatedoractual.Thechangeinthestateofthemachine(memory,registers,etc.)definesthemeaningofthestatementTouseoperationalsemanticsforahigh-levellanguage,avirtualmachineisneededCopyright©2023Addison-Wesley.Allrightsreserved.1-31Copyright©2023Addison-Wesley.Allrightsreserved.1-32OperationalSemanticsAhardwarepureinterpreterwouldbetooexpensiveAsoftwarepureinterpreteralsohasproblemsThedetailedcharacteristicsoftheparticularcomputerwouldmakeactionsdifficulttounderstandSuchasemanticdefinitionwouldbemachine-dependentCopyright©2023Addison-Wesley.Allrightsreserved.1-33OperationalSemantics(continued)Abetteralternative:AcompletecomputersimulationTheprocess:Buildatranslator(translatessourcecodetothemachinecodeofanidealizedcomputer)BuildasimulatorfortheidealizedcomputerEvaluationofoperationalsemantics:Goodifusedinformally(languagemanuals,etc.)Extremelycomplexifusedformally(e.g.,VDL),itwasusedfordescribingsemanticsofPL/I.Copyright©2023Addison-Wesley.Allrightsreserved.1-34OperationalSemantics(continued)Usesofoperationalsemantics:-Languagemanualsandtextbooks-TeachingprogramminglanguagesTwodifferentlevelsofusesofoperationalsemantics:-Naturaloperationalsemantics-StructuraloperationalsemanticsEvaluation-Goodifusedinformally(languagemanuals,etc.)-Extremelycomplexifusedformally(e.g.,VDL)DenotationalSemanticsBasedonrecursivefunctiontheoryThemostabstractsemanticsdescriptionmethodOriginallydevelopedbyScottandStrachey(1970)Copyright©2023Addison-Wesley.Allrightsreserved.1-35DenotationalSemantics-continuedTheprocessofbuildingadenotationalspecificationforalanguage:
-DefineamathematicalobjectforeachlanguageentityDefineafunctionthatmapsinstancesofthelanguageentitiesontoinstancesofthecorrespondingmathematicalobjectsThemeaningoflanguageconstructsaredefinedbyonlythevaluesoftheprogram'svariablesCopyright©2023Addison-Wesley.Allrightsreserved.1-36DenotationalSemantics:programstateThestateofaprogramisthevaluesofallitscurrentvariabless={<i1,v1>,<i2,v2>,…,<in,vn>}LetVARMAPbeafunctionthat,whengivenavariablenameandastate,returnsthecurrentvalueofthevariable
VARMAP(ij,s)=vjCopyright©2023Addison-Wesley.Allrightsreserved.1-37DecimalNumbers<dec_num>
'0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'|<dec_num>('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')Mdec('0')=0,Mdec('1')=1,…,Mdec('9')=9Mdec(<dec_num>'0')=10*Mdec(<dec_num>)Mdec(<dec_num>'1’)=10*Mdec(<dec_num>)+1…Mdec(<dec_num>'9')=10*Mdec(<dec_num>)+9Copyright©2023Addison-Wesley.Allrightsreserved.1-38ExpressionsMapexpressionsontoZ
{error}Weassumeexpressionsaredecimalnumbers,variables,orbinaryexpressionshavingonearithmeticoperatorandtwooperands,eachofwhichcanbeanexpressionCopyright©2023Addison-Wesley.Allrightsreserved.1-39ExpressionsMe(<expr>,s)
=case<expr>of<dec_num>=>Mdec(<dec_num>,s)<var>=>ifVARMAP(<var>,s)==undefthenerrorelseVARMAP(<var>,s)<binary_expr>=>if(Me(<binary_expr>.<left_expr>,s)==undefORMe(<binary_expr>.<right_expr>,s)=undef)thenerrorelseif(<binary_expr>.<operator>=='+'thenMe(<binary_expr>.<left_expr>,s)+Me(<binary_expr>.<right_expr>,s)elseMe(<binary_expr>.<left_expr>,s)*Me(<binary_expr>.<right_expr>,s)...Copyright©2023Addison-Wesley.Allrightsreserved.1-40AssignmentStatementsMapsstatesetstostatesetsU{error}Ma(x:=E,s)=ifMe(E,s)==errorthenerrorelses’= {<i1,v1’>,<i2,v2’>,...,<in,vn’>},whereforj=1,2,...,n,ifij==xthenvj’=Me(E,s)elsevj’=VARMAP(ij,s)Copyright©2023Addison-Wesley.Allrightsreserved.1-41LogicalPretestLoopsMapsstatesetstostatesetsU{error}
Ml(whileBdoL,s)=
ifMb(B,s)==undefthenerrorelseifMb(B,s)==falsethenselseifMsl(L,s)==errorthenerrorelseMl(whileBdoL,Msl(L,s))Copyright©2023Addison-Wesley.Allrightsreserved.1-42LoopMeaningThemeaningoftheloopisthevalueoftheprogramvariablesafterthestatementsintheloophavebeenexecutedtheprescribednumberoftimes,assumingtherehavebeennoerrorsInessence,theloophasbeenconvertedfromiterationtorecursion,wheretherecursivecontrolismathematicallydefinedbyotherrecursivestatemappingfunctions-Recursion,whencomparedtoiteration,iseasiertodescribewithmathematicalrigorCopyright©2023Addison-Wesley.Allrightsreserved.1-43EvaluationofDenotationalSemanticsCanbeusedtoprovethecorrectnessofprogramsProvidesarigorouswaytothinkaboutprogramsCanbeanaidtolanguagedesignHasbeenusedincompilergenerationsystemsBecauseofitscomplexity,itareoflittleusetolanguageusersCopyright©2023Addison-Wesley.Allrightsreserved.1-44Copyright©2023Addison-Wesley.Allrightsreserved.1-45AxiomaticSemanticsBasedonformallogic(predicatecalculus)Originalpurpose:formalprogramverificationAxiomsorinferencerulesaredefinedforeachstatementtypeinthelanguage(toallowtransformationsoflogicexpressionsintomoreformallogicexpressions)ThelogicexpressionsarecalledassertionsCopyright©2023Addison-Wesley.Allrightsreserved.1-46AxiomaticSemantics(continued)Anassertionbeforeastatement(aprecondition)statestherelationshipsandconstraintsamongvariablesthataretrueatthatpointinexecutionAnassertionfollowingastatementisapostconditionAweakestpreconditionistheleastrestrictivepreconditionthatwillguaranteethepostconditionCopyright©2023Addison-Wesley.Allrightsreserved.1-47AxiomaticSemanticsFormPre-,postform:{P}statement{Q}Anexamplea=b+1{a>1}Onepossibleprecondition:{b>10}Weakestprecondition:{b>0}Copyright©2023Addison-Wesley.Allrightsreserved.1-48ProgramProofProcessThepostconditionfortheentireprogramisthedesiredresultWorkbackthroughtheprogramtothefirststatement.Ifthepreconditiononthefirststatementisthesameastheprogramspecification,theprogramiscorrect.Copyright©2023Addison-Wesley.Allrightsreserved.1-49AxiomaticSemantics:AssignmentAnaxiomforassignmentstatements
(x=E):{Qx->E}x=E{Q}TheRuleofConsequence:Copyright©2023Addison-Wesley.Allrightsreserved.1-50AxiomaticSemantics:SequencesAninferenceruleforsequencesoftheformS1;S2 {P1}S1{P2} {P2}S2{P3}AxiomaticSemantics:SelectionAninferencerulesforselection-ifBthenS1elseS2{BandP}S1{Q},{(notB)andP}S2{Q}
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 《危险化学品登记管理办法》解读
- 2026年度社区居民体重管理与健康饮食课件:科学体重管理健康从“秤”开始
- 山东省聊城市莘县第一中学2025-2026学年高二上学期第三次教学质量抽测物理试卷(含答案)
- 2026年9月儿童青少年营养与健康科普课件:科学饮食远离亚健康
- 30万立方米可燃冰运输物流园可行性研究报告
- 2026年工作场所检测试题及答案
- 2026年pkpm测试题及答案
- 2026年职场风格测试题及答案
- Matlab上机编程专项试题及答案梳理
- 2026年现场管理概念测试题及答案
- 2025年汽车维修工中级(汽车维修环境保护)职业技能鉴定试卷
- 2023CSCO头颈部肿瘤诊疗指南
- GB/T 35351-2025增材制造术语
- 医院外包服务管理制度
- 苏教版小学《科学》四年级上册全套课件
- 小学无神论教育主题班会
- 防止电力生产事故的二十五项重点要求
- 《言语治疗技术》课程考试复习题库及答案
- 采购合规培训
- 各专业文件准备目录-肾内科药物临床试验机构GCP SOP
- 租冷库合同模板版
评论
0/150
提交评论