1IntroductionMosttraditionalseparatecompilationmethodsrelyonmanuallycreatedcontextsegModula3interfacesincludelesinCandAdapackagespecicationstoenforcetypecorrectnessacrossmoduleboundaries ID: 411668
Download Pdf The PPT/PDF document "SmartestRecompilationZhongShaoAndrewW.Ap..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
SmartestRecompilationZhongShaoAndrewW.Appelzsh@princeton.eduappel@princeton.eduCS-TR-395-92PrincetonUniversityOctober1992AbstractToseparatelycompileaprogrammoduleintraditionalstatically-typedlanguages,onehastomanuallywritedownanimportinterfacewhichexplicitlyspeciesalltheexternalsymbolsreferencedinthemodule.Wheneverthedenitionsoftheseexternalsymbolsarechanged,themodulehastoberecompiled.Inthispaper,wepresentanalgorithmwhichcanautomaticallyinferthe\minimum"importinterfaceforanymoduleinlanguagesbasedontheDamas-Milnertypediscipline(e.g.,ML).By\minimum",wemeanthattheinterfacespeciesasetofassumptions(forexternalsymbols)thatarejustenoughtomakethemoduletype-checkandcompile.Bycompilingeachmoduleusingits\minimum"importinterface,wegetaseparatecompilationmethodthatcanachievethefollowingoptimalproperty:Acompilationunitneverneedstoberecompiledunlessitsownimplementationchanges.AshortversionofthispaperwillappearintheTwentiethAnnualACMSIGPLAN-SIGACTSymposiumonPrinciplesofProgrammingLanguages,January,1993. 1IntroductionMosttraditionalseparatecompilationmethodsrelyonmanuallycreatedcontexts(e.g.,Modula-3interfaces,\include-les"inC,andAdapackagespecications)toenforcetypecorrectnessacrossmoduleboundaries.Usingthepropercontexts,thecompilercancheckthateachmoduleusesitsimportedinterfacesproperly,andimplementsitsexportedinterfaceasexpected.Thedisadvantageofusingthesemanuallycreatedcontextsisthattoguaranteeconsistency,allmodulesusingachangedcontextmustberecompiled,nomatterhowsmallthechangeis.Theconventionalrecompilationrule(asdescribedinTichy[30])isstatedasfollows:compilationunitmustberecompiledwheneveritsownimplementationchanges,oracontextchangesuponwhichthecompilationunitdepends."Thisisobviouslynotsatisfactorybecauseaddingacommentoraddinganewdeclarationtoapervasivecontextmaycausetheunnecessaryrecompilationoftheentiresystem.Tichy[30]presentsaneectivetechniquecalled\smartrecompilation"thateliminatesmostoftheredundantrecompilationstriggeredby(2).InTichy'sscheme,acompilationunitisrecompiledonlyifitsimplementationchanges,orifitreferencesasymboldenedelsewherewhosedenitionhaschanged.SchwankeandKaiser[29]dene\smarterrecompilation"whichcaneliminateevenmore(butnotall)redundantrecompilationscausedby(2).Soanaturalquestiontoaskis:Canweeliminateallredundantrecompilations?thatis,canweachievethefollowingsmartestrecompilationruleAcompilationunitneverneedstoberecompiledunlessitsownimplementation(sourcecode)changesStandardML(SML)[20]hasaratherelaboratemodulesystem,butSMLcompilershavenotsupportedseparatecompilationverywell.TheproblemisthatinSML,modulessuchasstructuresandfunctorscanliberallyreferenceexternallydenedidentierswithoutevenmentioningwhataretheirspecications.Forexample,byusing\qualied"(dotted)identiers,astructurecanuseBAR.QUX.ftoreferencethefunctiondenedinthesubstructureofthestructure,withoutevenknowingwhatthetypeofis.Becauseofthelackofexplicitimportinterfaces,structuresandfunctorswithfreevariables(let'scallthemopen-formedmodules)arenotconsideredasseparatelycompilableunits.Sohowcanweseparatelycompileopen-formedmodulesinSML?Thispaperpresentsanewseparatecompilationmethodwhichactuallyanswersbothoftheabovetwoquestions.Surprisingly,notonlycanweseparatelycompilearbitrarystructuresandfunctorsinSML,butwecanalsoaccomplishthe\smartestrecompilationrule."Ourideaissimple:inordertoseparatelycompileamodulewithreferencestoexternalidentiers,wehavetoknowthespecications(e.g.,types)oftheseexternalidentiers;sincetheyarenotexplicitlyspecied,weinferthembylookingathowtheseexternalidentiersareusedinsidethemodule;thenwecompilethemodulebyusingthisinferredimportinterfaceasitscontext;nally,whenallthemodulesarelinkedtogether,cross-moduletypeerrorsarereportedbycheckingwhetherthesurroundingsmatch(orsatisfy)thespecicationsineachinferredimportinterface.Thecatchhereisthatinordertoachievethe\smartestrecompilationrule",wehavetoinferthe\minimum"importinterface.Informallyspeaking,this\minimum"importinterfacespeciesasetofassumptions(onthoseexternalidentiers)thatarejustenoughtomakethemoduletype-checkandcompile;atlinktime,ifthemodule'ssurroundingssatisfythissetofassumptions,thecompiledcodecanbereused,otherwisetheremustbecross-moduletypeerrors.Theinferencealgorithmisdiscussedindetailinsection2and3.Nowlet'sseeanexampleofhowourmethodworks.FromthefollowingSMLstructuredeclaration,structureFOO=structvalx=BAR.fvaly=(BAR.g4,BAR.gtrue)weknowthatinordertocompile,thecontextshouldcontainastructurenamed.Inside,there shouldbeatleasttwodeclarations:oneis,whichcanhaveanytype,say;theotheris,whichshouldbeafunctionthatcanbeappliedtobothintegersandbooleans,thatis,shouldhaveatypemoregeneralintbool.Here,arejusttypevariablesweusedtodenoteunknowntypes.FOOinthisinferredinterfacewillresultinastructurewithtwocomponents:thevariabletypeandthevariablehastype.NowsupposethattherealstructureBARisdenedasfollows:structureBAR=structvalf=3valh=truevalg=fnz=zendthenatlinktime,whentherealismatchedagainsttheimportinterfaceof,wendthatthetypevariablesshouldbeshouldbebool,thusFOO.xwillhavetypewillhavetypebool.ThisisexactlywhatwewillgetifwecompileintheenvironmentthatwouldresultfromToachievethe\smartestrecompilationrule",thebackendofthecompilermustuseonlythetypeinforma-tionspeciedinthemodule'sinferredimportinterface.Thislimitationisnotabigproblem.ThebackendofthecurrentSML/NJcompiler[4]usesalmostnotypeinformationfromthefrontendbutitstillproducesquiteecientcode.Manyoptimizationtechniquesthatdousethetypeinformation,suchasLeroy'srepresentationanalysis[17],canstillbepartiallyincorporatedintoourseparatecompilationsystem.Thedetailswillbedescribedinsection4and5ofthispaper.Ourseparatecompilationmethodimmediatelyhasthefollowingadvantagesovertraditionalmethods:Becauseofthesmartestrecompilationrule,eachmoduleneverneedstoberecompiledunlessitsownimplementationchanges;somaximumreusabilityisachieved.Becauseallmodulesarecompiledindependentlyofeachother,theycanbecompiledinanyorder.Thisalsomeansthatprogrammersneednolongermaintaindependencyles(e.g.,Makefile[9]).Open-formedmodulescanalsobeseparatelycompiled.Cross-moduletypeerrorsarenowsymmetric.Intraditionalmethods,ifmodulereferencesidentiersdenedinmodule,typeinconsistenciesbetweenmoduleandmodulewillshowupwhencompiled.Iftheprogrammerxestheerrorbyediting,bothmustberecompiled.Butinourmethod,becausecross-moduletypeerrorsarereportedatlinktime,onlywillberecompiled.Thecompilerbasedonourmethodwillautomaticallybeastandalonecompiler.Asfarasweknow,noonehasyetbuiltastandalonecompilerforthecompleteSMLmodulesystem.1.1Closedvs.Open-formedModulesStandardMLallowsprogramminginopen-formedmodules.Theessentialdierencebetweenclosedandopen-formedmodulescanbeseenfromrewritingtheaboveopen-formedstructureinclosedform,theSML functorFOO'(BAR:sigvalf:intvalg:'a-'aend)=structvalx=BAR.fvaly=(BAR.g4,BAR.gtrue)Thisshowsthatprogrammershavetogiveassumptionsaboutthetypesofbasedonaproformaimplementationofthestructuredeclaration.Iflater,ischangedtohaveatypescheme,theabovedeclarationwillnolongerbeusefulandwillhavetobemodiedandrecompiled.Anopen-formedmodulesuchasstructuredoesnothavethisproblembecauseitdoesnotrequirethatthespecicationsofimportedidentiersbeexplicitlygiven.Peoplemaywanttowriteusingitsminimumimportinterfaceasitsargumentsignature,butthis\minimum"isnotexpressibleintheSMLtypesystem.Moreover,inferringtheminimumimportinterfacecannotbeeasilydonebyhand.Wedonotadvocatewritinglargeprogramsallinopen-formedmodules.SMLstronglyencouragesthateverystructuredeclarationshouldbewrittenwitharesultsignatureconstraint(asitsexportinterface).Programmerscanwritetheirprogramsallintheformofclosedfunctorssuchas.Ontheotherhand,inpractice,wenditextremelyconvenientand\rexibletowritepartsofourprogramsasopen-formedmodules.ForlanguagesbasedontheDamas-Milnertypediscipline[7]suchasSMLandHaskell[11],thereisanotherreasoninfavorofwritingcertainmodulesinopenedforms.OneofthemostimportantfeaturesoftheDamas-Milnertypedisciplineisthatthemostgeneraltypeforarbitraryexpressionscanbeautomaticallyinferredbycompilers.Itis,however,nontrivialtoinferthemostgeneraltypesimplybyhand,especiallywiththepresenceofpolymorphicreferencesinSMLortypeclassesinHaskell.Thismakesitalsonontrivialtowriteexplicitimportinterfacesformanymodules.TheSMLcommentary[19]alsosuggeststhatprogrammerswillprobablyneedtowritedownmanysharingequationsiftheywanttocloseeverymoduleandthatitwillbetoorestrictivetowriteeverythinginclosedfunctors.2AssumptionInferenceinCoreMLMLhasasophisticatedtypeinferencesystem.GivenanMLexpression+1),eventhoughthetypeofnewlyintroducedvariableisnotspecied,wecanstillndthemostgeneraltypeofifweknowthetypeand+.Forexample,ifhastypeand+hastypewillhavetypeMilner'stypeinference(ortypereconstruction)algorithm(asinTofte[31])takestwoarguments,atypeenvironmentandanMLexpression;allthefreevariablesin(suchasand+)mustbespeciedwithatypein,and;e)willreturnthemostgeneraltypeforTosupport\smartestrecompilation,"wefacethechallengeofdoingtypeinferencewithoutevenknowingthetypeofexternalidentiers.Forexample,canwendoutthemostgeneraltypeoftheaboveexpressionifwedonotknowthetypeofand+?Thisseemsimpossible.Butinthecaseofseparatecompilation,weassumethatthetypesofexternalidentierswillbeknownatlinktime.Wecandividethetypeinferenceintotwophases:rst(atcompiletime),weinferatypeandasetofassumptionsforthefreevariablesin,whichessentiallymeansthatwillhavetypeifthefreevariablesinsatisfytheconstraintsin;then(atlinktime)whenthetypesofthosefreevariables(i.e.,)areknown,wematchthemagainstthoseinand\magically"recoverthemostgeneraltypeof.TodistinguishitfromusualMLtypeinference,wecalltheinferencedoneintherstphase\assumptioninference". Inthissectionandsection3wediscussthedetailsofourassumptioninferencealgorithmandshowhowthematchingdoneatlinktimecansuccessfullyrecoverthecorrecttypeforeachexpression.Tosimplifythepresentations,wedivideouralgorithmsintotwoparts:thissectionforCoreMLandthenextsectionfortheMLmodulelanguage.Weonlygivethedetailsofouralgorithmforthemini-MLlanguageExpandtheskeletalmodulelanguageModLusedbyTofte[31].HoweveritiseasytoextendouralgorithmtotherestofSML.Theexpressionsinthemini-MLlanguagearedenedbythefollowinggrammar:letHereisabriefreviewofthenotation.SupposeTyVarisaninnitesetoftypevariablesandTyConisasetofnullarytypeconstructors,thesetoftypes,Type,rangedoverbyandthesetoftypeschemes,TypeScheme,rangedoverbyaredenedbyj8.Atypeenvironmentisanitemapfromprogramvariablestotypeschemes.)and)arethesetoftypevariablesthatoccurfreerespectively.Atypeisagenericinstanceofatypescheme;:::;writtenas,ifthereexistsasubstitutionwithitsdomainbeingasubsetof;:::;Atypeschemeismoregeneralthan,denotedas,ifallgenericinstancesofarealsogenericinstancesof.Thegeneralizationofatypeinatypeenvironmentisdenotedby;),itisthetypescheme;:::;;:::;).ThecoreMLtypesystem,intheformoftypedeductionrulesas,islistedintheappendixattheendofthispaper.ItisdirectlycopiedfromTofte'sthesis[31].2.1TheassumptioninferencealgorithmW*Wedeneatypeassumptiontobeapair()whereisaprogramvariableandisatype.Anenvironment,rangedoverby,isasetoftypeassumptions;itisusuallyrepresentedbyanitemappingfromprogramvariablestolistsoftypes.Inthefollowing,weusetodenotethesetoftypeassumptionsinexceptthoseforvariable,and)todenotethesetoftypesassociatedwithvariable.WealsousetodenoteRobinson'soriginalunicationalgorithmonclassicaltermalgebras[26].takesasetofpairsoftypesandreturnsasubstitution(themostgeneralunier).Figure1givestheassumptioninferencealgorithmandthematchingalgorithmtakesanMLexpression,andreturnsatypeandanassumptionenvironment.takesanMLtypeenvironmentandanassumptionenvironment,andreturnsasubstitution.Theothertwoproceduresingure1aretakesatypeandasetoftypes,andreturnsasubstitution.takestwoarguments:atripleofaTyVarsetandatypeandanassumptionenvironment,andasetoftypes;itreturnsasubstitutionandanassumptionenvironment.GivenanMLexpression)delaysthetype-checkingofallfreevariablesinbyrecordingtheirmonomorphictypeinstancesinanassumptionenvironment.Inthecaseoflambdaabstraction,thetypeistreatedasmonomorphic;theprocedurecheckswhetherthesetofassumptionscollectedforsatisesthisconstraint.Onetheotherhand,intheexpression,thetypeoftreatedaspolymorphic;foreachuseof,thetypeandtheassumptionenvironmentfromisrenamedwithnewtypevariables;theprocedurethenchecksthetypingofandmergestheassumptionenvironmentscollectedfrom.Whentherealtypeenvironmentforthefreevariablesisknown(atlinktime),thematchingalgorithm;A)preciselyrecoverseverything,includingtheresulttypeofelaborating )=case;TS)=;:::;beanewtypevariable;;;:::;;;;A;TS)=beanewtypevariable;;:::;;A)=foreachTS;A;;:::;benewtypevariablesnf=1;:::;nnS(A0)aae1e2)aP=P[fS;A)=;A;A)=beanewtypevariable;;A)=;SSA2))aletP=;aaaforeach;:::;;A)=;;:::;benewtypevariables;A)==1;:::;nntyvars(A1)aP=P[fSS;A)=;;A;AAS(A[(A2nfFigure1:TheInferenceAlgorithmForexample,givenanexpression=\x:fxgg",thefreevariableof)willreturnanassumptionenvironmentandatype.Iftherealtypeenvironment7!8;A)willresultinthesubstitution.Thustheexpressionwillhavethetype)=().ThisisexactlywhatwewillgetifweapplyTofte'salgorithmInfactwecanshowthatthealgorithmisequivalenttoMilner's[31]inthefollowingsense:Theorem2.1GivenatypeenvironmentTEandanexpression,thenS;)=;esucceedsifandonlyifboth;A)=;Asucceed;Moreover,thereexiststwosubstitutions,suchthatthefollowingaretrue:(1)ID;(2);)=(;S;(3);)=;SProofBystructuralinductionontheexpression.Fordetails,seeappendix.Noticethattheorem2.1isnottryingtoshowthesoundnessandcompletenessofdirectly.Itisjustprovingthattheresultofisequivalenttotheresultof.Provingthiskindofequivalenceis relativelyeasier.Fromthesoundnessandcompletenessofthealgorithm(whichisprovedinDamas'sPh.Dthesis[6]),andtheabovetheorem2.1,wecaneasilygetthefollowingsoundnessandcompletenessresultsforouralgorithmCorollary2.2(SoundnessofGivenatypeenvironmentTEandanMLexpression,ifboth;A)=;Asucceed,thenCorollary2.3(CompletenessofGivenatypeenvironmentTEandanMLexpression,supposethatandTE,thenboth;A)=;Awillsucceed;MoreoverthereexistsasubstitutionsuchthatTE(gen(;SThealgorithmitselfisinteresting.Recursivecallstointhealgorithmwillnotinterferewitheachothersotheycanbecalledinanyorder.Ifconcurrencyisused,canbeecientlyimplemented.Thecasefortheexpressionimpliesthatwecanlinktwopiecesofprograms,i.e.,,eventhoughbothofthemcontainfreevariables;thisisdonebythealgorithmingure1.Theassumptionenvironmentreturnedfrommaybebig.Apossibleoptimizationistoinsertasimplifyingprocedureateachrecursivecalltointhealgorithm.Thissimplifyingprocedurewillidentifyall\isolated"typeassumptionsin.Given(;A)=),wedeneanequivalencerelationontypevariables:\ifthereexistsatypesuchthateitheror(x;forsomeistrue,andbotharetypevariablesof."Letbethetransitiveclosureof)under,thenallpairsx;t)inaredenotedas\isolated"assumptions.Alltypevariablesoccurredin\isolated"assumptionsneednottoberenamedinandmostredundant\isolated"assumptionscanbeeliminated.2.2TheassumptioninferencealgorithmDOnedisadvantageofisthatitssequentialimplementationmaybenotveryecientinpractice.Inmostcompilers,thereisapervasivebasis(orinitiallibrary)whichtendstobereferencedveryfrequentlybyuserprograms,thustheresultingassumptionenvironmentfrommaybequitebig(evenifitusescertainoptimizationsmentionedabove).ItturnsoutthatthisproblemcanbeelegantlysolvedbyextendingMLtypeswithtypepredicatesandassumptions.Thisextension,whichiscalled\constrainedtype"inKaes[13]and\qualiedtype"inJones[12],isnormallyusedtoreasonabouttheMLtypesysteminthepresenceofoverloadingandsubtyping.ThealgorithmpresentedinthissectionisthetypereconstructionalgorithmforKaes'sconstrainedtypesystem.Byusingaspecialsetoftypepredicates,thealgorithmcanecientlysolvetheassumptioninferenceproblemevenwhenthereisapervasivebasis.2.2.1AnextensionofMLwithconstrainedtypesTheextensionofMLtypesystemwithconstrainedtypes(denotedasML)isdiscussedindetailbyKaes[13]andJones[12]tosolvethetypeinferenceprobleminlanguagesthatsupportoverloadingandsubtyping.Itturnsoutthatitcanalsobeusedtosolveourassumptioninferenceproblem.Thelanguagesyntaxtheyuseisessentiallysameasthemini-MLlanguage.Inthefollowing,wegiveaquickreviewofKaes'sframeworkofextendingMLwithconstrainedtypes.Toeasethenotation,isusedtodenoteasequence;:::;x Denition2.1Letbeanite-indexedfamilyofpredicatesymbols.ThesetofpredicateconstraintsTypeisdenedas;Typewhere=1;:::;n.Aninterpretationofisafamilyoftotalcomputablefunctions(^,suchthatfor:(Type)Denition2.2Asetofconstraintsisifthereexistsasubstitutionsuchthatifistrue.SatisablitywillbedenotedasDenition2.3Asubstitutionisa,ifforallsubstitutions.Asolutioncalledthemostgeneralsolutionofaconstraintset,ifforanysolution,thereexistsasubstitution,suchthat.Inmostcases,themostgeneralsolutiondoesnotexist.relationonconstraintsets,written``,maybedenedonceaparticularpredicatesystemisgiven.Inthefollowing,weonlyconsiderthosepredicatesystemswhichsatisfythefollowingproperties:if``Denition2.4constrainedtypeisapair,consistingofatypeandasetofconstraints.Aconstrainedtypeschemeisoftheform.Aconstrainedtypeenvironmentisnowjustanitemapfromvariablestoconstrainedtypeschemes.Denition2.5Aconstrainedtypeisagenericinstanceofaconstrainedtypeschemewrittenas,ifthereexistsasubstitutionwithdomainbeingasubsetofsuchthat``.Wealsodenoteifallgenericinstancesofaregenericinstancesof;andTypabilityofanexpressioninMLisexpressedasajudgementC;,whichcanbereadas\typeunder(constrained)typeenvironment,providedissatisable."Thegeneralizationofaconstrainedtypeinthecontextofatypeenvironmentisdenotedby;),itistheconstrainedtypescheme;:::;)andDenition2.6AtypingC;moregeneral,ifthereexistsasubstitutionsuchthat(1)dom(2)gen;;Kaes[13]presentedthetypedeductionrules(alsolistedintheappendixattheendofthispaperforreference)andthetypeinferencealgorithm(asingure2)fortheaboveextension.Itcanbeprovedthathistypeinferencealgorithmissoundand(syntactically)completeinthefollowingsense:Theorem2.4Letaninstanceofaconstraintbasedinferencesystembegiven,beanexpression,TEandbetypeenvironments.Supposeforcertainsubstitution,foreachisavalidtyping,thenS;)=;esucceeds.Moreover,C;Sisvalidandmoregeneralthan2.2.2ApplicationtoassumptioninferenceWecanusetheaboveextensiontosolveourassumptioninferenceproblem.Thesetofpredicatesweuse,denotedby,is)whereisanyprogramvariable.Theinterpretationofis\^)=trueif ;e)=)=benewtypevariablesand=1;:::;nbeanewtypevariableand(;)=fj;g;e,(;)=;e)and(;)=;ebeanewtypevariableand;C2)))letx=e1ine2)let(S1;)=;e)and(;)=f;;e;C2))Figure2:TheTypeInferenceAlgorithmD andonlyif,assumingthatthetypeofisaclosedMLtypescheme."Theentailmentrelationonconstraintsetsisdenedas:``ifandonlyifissatisableand.Thisrelationisdecidableforourparticularpredicatesystembecauseofthefollowinglemma:Lemma2.5Foranyconstraintsetformedinthepredicatesystem,eitherthereisnosolutionorthereexistsamostgeneralsolutionProofIfweconsidereach)asanassumption(x;),alsoassumethatthetypeofisknown,thealgorithmingure1canbeusedtondthemostgeneralsolutionof.ThelemmathenfollowsfromRobinson'sunicationtheorem.GivenaclosedMLtypescheme,itcanbewrittenasMLconstrainedtypeschemesj;jf,butobviouslyinMLThegreatthingaboutthealgorithmisthatwhenitisrunning,itdoesnotneedanyknowledgeabouttheinterpretationofthepredicatesystem.Thisleadstothefollowingtheorem:Theorem2.6GivenatypeenvironmentTE,whereDom(Dom()=)=,weconstructaconstrainedtypeenvironmentTEwhereTEj;whereDom(andTEandTE7!8jfwhereDom(andtheinterpretationofis\=trueifandonlyif".ThenS;)=;esucceedsifandonlyif;)=;esucceedsandthereexistsamostgeneralsolution.Moreover,thereexiststwosubstitutions,suchthatthefollowingaretrue:(1)ID;(2);)=(;S;(3);)=;SProofFollowsfromlemma2.5andtheorem2.4.Fordetails,seetheappendix.Inpracticealgorithmwillbemoreusefulthanbecauseitresemblesthealgorithmanditalsoworksmoreecientlywhenthetypesofsomefreevariablesareknown.Moreover,canbeeasilyextendedto decstrdecNameSet=Fin(StrName)strdecdec1SigEnv=SigIdFunEnv=FunIdFunSigstrexpStrEnv=StrIdstructdecendor(m;EStr=StrNameEnvstrexp.stridEnv=StrEnvfctid(strexp)or(Sig=NameSetS;NFunSig=NameSetstrdecstrid=strexpBasis=NamesetSigEnvFunEnvEnvFigure3:SemanticobjectsworkonvariousextensionsoftheMLtypesystemwithoverloadingandsubtypingsuchasthoseinKaes[13].3AssumptionInferenceintheSMLModuleLanguageInthissection,wepresentanassumptioninferencealgorithmfortheSMLmodulelanguage.Tosimplifythepresentation,weonlyconsidertheskeletallanguageModL(asinTofte[31])ingure3.Noticethatsignatureexpressionsanddeclarationsareintentionallyleftoutbecausetheirelaborationscanbedelayedtolinktime,thusareirrelevanttoourassumptioninference.Functordeclarationsarenotconsideredinourlanguageeitherbecauseonlytheirbody,whichisastructureexpression,iselaboratedatcompiletime.However,functorapplicationsareconsideredinourlanguagebecausetheyarestructureexpressionswhichmustbeelaboratedatcompiletime.ThestaticsemanticsofModLisdiscussedindetailinthedenition[20]andTofte[31].Itsdeductionruleisintheformof\phrase"meaningthatphraseiselaboratedintoasemanticobjectinthebasis.Thesemanticobjectsarealsodenedingure3.TheappendixattheendofthispaperliststhesetofstaticsemanticrulesforModL.Herewegiveaquickreviewonthemainconceptsusedinthestaticsemantics.Denition3.1structureSisapairm;E,whereisthenameofthestructureandisanenvironment,whichgivesthestaticinformationaboutthecomponentsofthestructure.Tomakethepresentationclear,fromnowon,weshalluse)todenoteastructure().Aisanobjectoftheform,whereisastructureandisanitesetofnames.AfunctorsignatureisanobjectoftheformS;Nwhereistheprincipalsignaturefortheparametersignatureexpressionofthefunctorandisthebodystructureofthefunctor,thenamesboundinarethenamesinwhichhavetobegeneratedafreshuponeachfunctorapplication.Denition3.2structureenvironmentSEisanitemapfromstructureidentierstostructures,similarlysignatureenvironmentGEfunctorenvironmentFE Denition3.3(Names)isaninnitesetofnames:namesthatarespeciedinasignatureex-pressionandarenotsharedwithalreadydeclaredstructuresarecalled\rexiblenames,denotedasnamesofdeclaredstructuresarecalledrigidnames,denotedasDenition3.4(Realization)realizationisanitemappingfrom,andare-namingrealizationwhere=1;:::;kisarealizationwheresaredistinctrigidnames.Denition3.5(Enrichment)Astructure)enrichesastructureandthestructureenvironmentSEenrichestheSE.AstructureenvironmentSEenrichesastructureenvironmentSEDom(Dom(andforeachDom(,SEenrichesSEDenition3.6(SignatureMatching)Astructurematchesasignature=ifthereexistsarealizationsuchthatBecausetheSMLmodulelanguageisexplicitlytyped,theelaborationofamoduleexpressionsimplyinvolvestype-checking.ThestaticsemanticsintheDenition[20]canbeviewedasatypecheckingalgorithm.Givenastructureexpressionwithfreeidentiers,wewanttoinfertheminimumconstraintsonthesefreeidentierswithwhichtheexpressionwilljusttype-check.Againtheminimumconstraintsarenotexpressibleifweonlyusesemanticobjectsingure3.Weintroduceanewkindofstructurevariablewhichissimilartorowvariablesusedintypingrecordcalculi.LetStrVarbeaninnitesetofstructurevariables;structuresandstructureenvironmentsarenowextendedasStr=(StrNameStrEnvvStrVarandStrEnv=StrId.Eachstructurevariablemusthaveakind.Kindsaredenedas(StrNameKindEnv)whereKindEnvisjustanitemappingStrIdStrIdStrVar).Todistinguishitfromstructures,akind(isrepresentedas).Akindassignmentisanitemappingfromstructurevariablestokinds.Am;SE)hasthekindunderthekindassignment,writtenas,ifitisderivablefromthefollowingsetofkindingrules:),if)=)::)ifDom()andDom()=Asubstitutionnowconsistsoftwoparts:onefromStrVartoStr,anotherfromFlexStrNametoStrName(i.e.,realization).Akindedsubstitutionisapairconsistingofakindassignmentandasubstitution.Akindedsubstitution()respectsakindassignmentif,forallindom()::))isaderivablekinding.Akindedsubstitution()ismoregeneralthan()ifforsomesuchthat()respects.Akindedsubstitution()isanunierofakindedsetofequations)ifitrespects)=)forall(;t)inFigure4givesourinferencealgorithmsstrexponstructureexpressions,decondeclarations,fctidfunctoridentiers,strdeconstructuredeclarationsandthematchingalgorithmModlMatch.Theargumentrecordsthosealready-usedstructurevariablesand\rexiblenames.Allfunctorapplicationsaredonebythematchingalgorithmatlinktime.The\thinningeect"infunctorapplications(ontheargumentsignature)isachievedbythesetofconstraintsgeneratedbytheGenRecalgorithm.Theinferredassumptionenvironmentautomaticallyrecordsthe\minimum"sharingconstraintsrequiredtomakethestructureexpressionelaborate. strexp;V;M)=decd;V;M)=strdec;V;Mt=m=sdd[f;M[f;Env;A;V;M)=strdec;V;MEnv;Env;A;V;M)=dec;V;M)=;:::;t;u;A;V;M)=strexp;V;M=(((A2nf;t,and;m;t;:::;;t[f)==K2;P[fEnvEnv[f;t[f;m)=GenRec;K;VforeachDom(;u;A;V;M)=;V;M=[f;u;A;V;M)=strexp;V;MK;V)=GenRec;;K;Vt=;m=f[f;M[ffK2[f[f)=K;VVA2),V3,M3)aaaaaastructdendModlMatch)=;Env;A;V;M)=decN;)=m=;M[fK;u;A;V;M)=Envforeachx;t[ff;V;M)=foreachx;tFunId;N))=;t;m=[f[f;t[f;m;:::;mmN01aaK=ft1::STR(m1,;),t2::STR(m2,;)gam01;:::;mK;t;V;M[f;:::;m=1;:::;kstrdec;V;M)=[f;tstructures=seK;V)=GenRec;';K;V;u;A;V;M)=strexp;V;M;R)=K;PFigure4:AssumptionInferenceinModL K;P)=K;P;P[ft;t;P;P[f;t;P[f;t;t[f;P[fcheckDom(),otherwisefail;m)=;m)and)and=()and[fj8Dom(;R)=;P;R[f;t;P[f;t;m)=;m)and=()and)andand(Env01nDom([f[fj8Dom(Dom(;R)=;P;R;P[fcheckDom()=Dom(),otherwisefail;m)=;m)and)and)and[fj8Dom;R)=;P;R;m)=elseif;melseif;m;mFigure5:Kindedunicationalgorithm 13 Figure5givestheunicationalgorithms.ThekindedunicationalgorithmpresentedthereextendstheoneinOhori[24]withconsiderationsonMLstructurenames.ThefollowingtheoremcanbeprovedinthesamewayasOhori[24].Theorem3.1Givenanykindedsetofequations,thealgorithmKindUnifycomputesamostgeneralunierifoneexistsandreportsfailureotherwise.Thefollowinglemmashowshowthe\thinning"eectisachievedinouralgorithm.Lemma3.2Givenasignature=andastructure,supposethatdoesnotcontainany\rex-iblenames;letbeastructurevariableandbeanysetofstructurevariables;supposethatK;V)=GenRec;S;;V,thenKindUnifyK;;Ssucceedsifandonlyifthestructurematchesthesigna-ture.Moreover,ifK;;S,thenThefollowingtheoremcanbeprovedbystructuralinductiononstructureexpressions.Theorem3.3Givenanbasisandastructureexpressionstrexp,thenstrexpsucceedsifandonlyifbothK;u;A;V;M)=strexpstrexpRigStrName)ModlMatchB;K;u;A;V;Msucceed.Moreover,thereexistsarenamingrealizationsuchthatThealgorithmstrexppossessesmostpropertiesthathas.Itcanalsobemodiedtotakeabasisitsargument(justasalgorithm)sothatitcanworkmoreecientlywhenwecompileastructureexpressioninthepervasivebasis.4CodeGenerationIssuesAcompilingprocessusuallycontainstwoparts:elaboration(i.e.,typeinferenceortype-checking)andcodegeneration(alsocodeoptimization).Theassumptioninferencealgorithmspresentedinthelasttwosectionssuccessfullysolvetheproblemintheelaborationphase.Inordertoachievethe\smartestrecompilationrule",ourcompilershouldgeneratecodethatwillbereusableaslongasthesurroundingssatisfythe\minimum"importinterface(i.e.,matchtheassumptionenvironment).Thisrequiresthatourcodegeneratorshouldusenomoretypeinformationthanisspeciedinthe\minimum"importinterface.FortunatelythereareveryfewdependenciesbetweenthestaticsemanticsandthedynamicsemanticsinSML.Moreover,althoughLeroy'srepresentationanalysis[17]showsthatthecompilercanbenetalotbyusingtypeinformationinthefrontend,theSML/NJcompiler[4]usesalmostnotypeinformationinitsbackendbutitstillproducesquiteecientcode.InSML/NJ,theonlythingsthatthebackendneedstoknowfromthefrontendarethecorrespondingdynamicinterfaceforeachsignatureandtheidentierstatusforeachidentier.Bydelayingthesedependenciestoberesolvedatlinktime,aprogramcanbetranslatedintomachinecodeevenbeforeitiselaborated.Inthefollowing,weonlyinformallydiscussthesolutionstotheseissues.FunctorapplicationInSML,afunctorwithargumentsignaturecanbeappliedtoanystructurematchesSIG.Astructuredoesnothavetoagreeexactlywithasignatureinorderforittomatchthesignature,insteaditcancontainmorecomponentsthanrequired.Insuchcases,signaturematching willcoercethestructureagainstthesignature,producinga\thinned"structurethatexactlyagreeswiththesignatureintermsofnumberofcomponentsandtheirtypes.Supposethecorrespondingdynamiccodeforthefunctorandthestructure,thecodegeneratedforafunctionapplication)willbe))whereisathinningfunctionfrom.Inourseparatecompilationscheme,itispossiblethatwestilldonotknowtheargumentsignatureofortheexactspecicationofwhenwehavetogeneratecodeforthefunctorapplication).Thisissimplysolvedbyaddinganabstractionon,andthecodebecomes).Thecorrectthinningfunctionislledinatlinktimewhentherealspecicationsofareknown.PatternmatchingIntheSML/NJcompiler,therepresentationofauserdeneddatatypeisdeterminedbyitsdenition.Forexample,structureA=structdatatypecolor=RED|GREEN|BLUE|MIXofreal*real*realendstructureB=structfunredp(A.RED)=1.0|redp(A.MIX(x,_,_))=x|redp(_)=0.0thedatatypecolormayberepresentedwithintegertags0,1,2,3forthedataconstructorsGREEN,and.HoweverthisimposessomeproblemsifwewanttoseparatelycompilestructureWhatrepresentationsarewegoingtouseforinthefunction?Againthisissolvedbymakingtherepresentationofdataconstructorsabstract(asinAitkenandReppy'srecentwork[2]).A\constant"dataconstructor(suchas)iscompiledasavariable.Avaluecarryingconstructor(suchas)iscompiledasapairofinjectionandprojectionfunctions.Thesedetailsarelledinatlinktimewhenthedenitionofthedatatypeisknown.PolymorphicequalityfunctionsNothingneedstobedonetosupportourseparatecompilationschemeiftheequalityfunctionisimplementedasitcurrentlyisintheSML/NJcompiler.InSML/NJ(asinallMLcompilerstoourknowledge),thepolymorphicequalityfunctionisimplementedasaruntime\equalityinterpreter"whichchecksequalityoftwoobjectsbasedontheirruntimetags.Anotherwaytoimplementpolymorphicequality,whichisusedinHaskell[11],istopassanequalityfunctionforeachformalparameterthatisapolymorphicequalitytypevariable.Thecodeproducedbythisschemecloselydependsonthederivationtreeoftheelaborationphase.Inourseparatecompilationscheme,becausethetypesofsomeexternalidentiersarenotknownatcompiletime,thederivationtreewegetatcompiletimeisnotaccurate.Forexample,funfx=S.g(3,x)fromassumptioninference,weknow'stypemustbeintheformof'sintheform.Becausemaywanttotesttheequalityonits2ndargument,thefunctionherehastobeimplementedwithanequalityfunctionfortypeasitsextraargument.Thiswillhavesomeruntimeoverheadinthecommoncasethatactuallyneverdoesequalitytestonits2ndargument.RepresentationanalysisLeroy[17]presentedaprogramtransformationthatallowspolymorphiclanguagestobeimplementedwithunboxed,multi-worddatarepresentation.Themainideaistointroducecoer-cionsbetweenvariousrepresentationsbasedonthetypingderivationtree.Inourseparatecompilationsystem,accuratetypeinformationforexternalidentiersarenotavailableatcompiletime,sothetypingderivationtreeisnotveryspecic.Howevertherepresentationanalysiscanstillbecarriedoutsincealltypeinstancesofexternalidentiersarerecordedintheassumptionenvironment.Atlinktime,the matchingalgorithmwillndouttheaccuratetypeinformationofallexternalidentiersandco-ercethemintodierenttypeinstancesintheassumptionenvironment.Forexample,theabovefunctionwillbeimplementedasapolymorphicfunction.Whenwendthathastypehastobecoercedtotypehastobecoercedfrom.Thecodeproducedinthiswaywillbelessecient,butitshouldbeacceptableifinpracticetherearenottoomanyexternalidentiersinamodule(especiallywhenweusealgorithmOpendeclarationdeclarationinSMLcausesseveralnastyproblemsforourseparatecompilationscheme.Forexample,inthefollowingstructuredeclaration,thereisnowaytogureouttheidentierstatusofwithoutlookingatthedenitionofstructurestructureS=structopenAfunredt(RED)=RED|redt_=BLUEcaneitherbeadataconstructorifitisdenedinadatatypedeclarationinstructure,orcouldsimplybeapatternvariableifitisnotdenedelsewhere(thisisoneoftheugliestfeaturesinML).Asolutiontothisproblemistointroduceabooleanstatusvariableforeach\ambiguous"identier.Thisstatusvariablespecieswhethertheidentierisadataconstructororapatternvariable.Assumestatus-REDisthestatusvariableof,thentheabovefunctioncanberewrittenasfollows:valredt=ifstatus-REDthenfnx=x(*REDisnotaconstructor*)else(fnRED=RED(*REDisaconstructor*)|_=BLUE)Howeverthissolutionmaycausecodeexplosionifnotcareful.Anothersolutionistointroduceapredicateforeachambiguousidentier.Assumethatisthecorrespondingpredicateforthenatlinktime,willbesettofnx=trueisapatternvariable,andfnx=(x=RED)otherwise.Thentheabovefunctioncanberewrittenasfollows:funredt(x)=ifpred-RED(x)thenxelseBLUEThissolutionmayincursomeruntimeoverheadforthecasethatisapatternvariable.Butinthatcase,theabovecodeiswritteninsuchabadstylethatitwelldeservessuchapenalty.Othernastyproblemsrelatedwithcanbesolvedinthesamewaybyresolvingcertaininformationatlinktime.Thesesolutionsmayincreasethecomplexityofcompilingandlinkingbutmostofthemdonotincuranyruntimeoverhead(however,theymaystopsomeinline-expansionoptimizations).5ImplementationWearecurrentlyprototypingaseparatecompilationsystembasedonouralgorithmsintotheSML/NJcom-piler.Inoursystem,alargeMLprogramiscomposedofasetoftop-levelstructuredeclarations,signaturedeclarationsandfunctordeclarations.Notwotop-levelstructures(orsignatures,functors)canhavethesameidentiernamesothatwecanuniquelydeterminewhichdenitioneachexternalidentierrefersto.Everytop-leveldeclarationisconsideredasacompilationunit.Becausesignaturesareusuallysmallandcompilingsignaturedeclarationsdoesnottakemuchtime,theirelaborationsaredelayedtobedoneatlinktime.Tocompileastructureorfunctordeclaration,weapplytheassumptioninferencealgorithmtoitsbody(whichisalwaysastructureexpression),generatethemachinecodeforthebody,andthenwriteboththeinferred interface(i.e.,theassumptionenvironment)andthemachinecodeintoitsbinaryle.Thenallinkingphaseisdoneincertainorderaccordingtothedependencyrelationamongdierentmodules.Thisdependencyrelationhasbeenalreadyrecordedintheinferredinterfaceineachbinaryle.Foreachmodule,thelinkersimplyreadsthebinaryle,elaborateseverysignatureexpression,appliesthematchingalgorithm(i.e.,ModlMatch)torecoverthecorrectstaticenvironmentanddetectcross-moduletypeerrorsifthereareany,andthenconcatenatesthemachinecodewithcorrectthinningfunctions.6RelatedWorkMostdynamically-typedlanguagessuchasLispalsoallowindependentcompilationsandcanachievethesamekindof\smartestrecompilation"inthesensethatamoduleneverneedstoberecompiledunlessitsimplementationchanges.However,thisisbasedonabigsacrice:cross-moduletypeerrorswillbedetectedonlyatruntime.Ourmethod,however,willdetectallcross-moduletypeerrorsatlinktime.Levy[18]presentsaseparatecompilationmethodverysimilartooursforPASCAL-likelanguages.Itscompileralsoautomaticallyinferstheimportinterfaceforeachcompilationunit.Cross-moduletypeerrorsarereportedatlinktime.Howeverhedoesnotmentionwhetherheachievesthesmartestrecompilationrule,andthetypesystemsofPASCAL-likelanguagesaremuchsimplerthanthatofSML.Traditionalseparatecompilationsystemsadoptedinmoststaticallytypedlanguagesallusemanuallycreatedinterfaceles.Eachcompilationunitcontainsanimplementationplusseveralinterfaceles.Ithastobefullycloseduptothepervasivebasissothatthespecicationsofallexternalsymbolswillbefoundatcompiletime.Themakesystem[9]isthesimplestonealongthisline.Itwilltriggerrecompilationsiftheinterfaceleamoduledependsonchanges.Tichy[30]andSchwanke[29]eliminatedmostrecompilationsbyexaminingner-levelsofdependencyrelationsbetweeninterfacesandimplementations.Intheirmethods,iftheinterfaceleamoduledependsonchanges,butthesetofsymbolsthemoduleimportsdoesnotchange,thenthemoduledoesnotneedtoberecompiled.SRCModula-3[22,14]implementsexactlythesameidea:aversionstampwhichencodesthespecicationofasymbolisproducedforeachexportedsymbolinaninterface;modulesimporttheversionstampsofthesymbolsthattheyimport;amoduleonlyneedstoberecompiledifanyofitsimportedversionstampsarenolongerexported.LanguageswithverypowerfulmodulesystemssuchasMesa[21],theSystemModellerinCedar[15],andFX-87[8]alsoadoptsimilarseparatecompilationmethodswhichareonlyapplicabletoclosedmodules.ThecompilerforRussell[5]doespartiallysupportseparatecompilationson\open-formed"expressions,howeverits\modulesystem"isveryrestrictiveandall\modules"mustbeloadedandcompiledinanorderdeterminedbytheirdependencies.Insummary,thesepreviousmethodscannotachievethesmartestrecompilationrule,neithercantheybeappliedtocompileopen-formedmodulesinSML.InSML,twokindsofseparatecompilationmethodshavebeenproposed:RothwellandTofte'simportscheme[28]andRollins'sSourceGroupscheme[27];bothmethodsapplyonlytoclosedfunctors.Recently,EmdenGansner[10]isimplementinga-likeseparatecompilationsystemforopen-formedmodulesintheinteractiveSML/NJcompiler.Inhismethod,allmodulesareloadedandcompiledinatoplevelenvironmentinanorderdeterminedbytheirdependencies.Wheneveramoduleiscompiled,anewtimestampisgenerated;boththebinaryandthetimestamparethenwrittenouttothebinaryle.Amodulehastoberecompiledwheneveritssourcechangesoranyofitspredecessors(inthedependencygraph)havebeenrecompiled.Gansnerisalsoplanningtoexportthestaticsemanticsofeachmoduleintothebinarylesothatredundantrecompilationscanbedetectedandavoidedifthestaticsemanticsofamodulehasnotbeenchanged. AdityaandNikhil[1]havebeenworkingonsimilarkindsofassumptioninferencealgorithmsfortheirincrementalcompilerforId[23].Howeverasfarasweknow,theiralgorithmdoesnotinfertheminimumconstraints,thusfailstoachieveourtheorem2.1.Becausetheirsystemallowsmutuallyrecursivetop-leveldeclarations,itcannotfullyrecoverthecorrecttypeinformationbysimplyusingourassumptioninferenceandmatchingalgorithm.IntheSMLmodulelanguage,however,top-leveldeclarationscannotbemutuallyrecursive.Damas[6]gaveaninferencealgorithmcalledwhichisverysimilartoourinsection2.Histypesystempermitsthatavariablecanbeboundtoseveraldistincttypesinthetypeenvironment(justlikeourassumptionenvironment).Howeversincehemainlyusedthesystemtohandleoverloading,hedidnottrytoproveourtheorem2.1.Thesoundnessandsyntacticcompletenessresultsheprovedforareonlyforhisparticulartypesystem,notfortheusualMLtypesystem[31],sotheyarenotinthesamesenseasourcorollary2.2and2.3.ThealgorithminLeivant[16]isjustDamas'srestrictedtothetypesystemwithoutML-polymorphism.Itsextensionisforthepolymorphicdisciplineofrank2andtherelationbetweenisnotclear.OnthesideoftheSMLmodulelanguage,Aponte[3]presentedatypecheckingalgorithmModLbasedonRemy'sapproachtorecordtyping[25].Herapproachisveryelegant;however,inpracticeitisprobablyverydiculttoimplementeciently.Itisalsonotclearwhetherheralgorithmcanbemodiedtodoourassumptioninference.7ConcludingRemarksWehavepresentedaseparatecompilationmethodthatachievesthe\smartestrecompilationrule"foropen-formedmodulesinStandardML.Inourmethod,eachmoduleiscompiledindependentlywithoutknowingthespecicationsofitsexternalidentiers;itsimportinterface,instead,isinferredbylookingathoweachexternalidentierisusedinsidethemodule.Cross-moduletypeinconsistenciesaredetectedatlinktimebysimplymatchingtherealspecicationsagainsttheinferredimportinterface(thisprocessshouldbeveryfastbecauseitonlyinvolvesanunicationofasetoftypes).Theindependentcompilationofeachmodulemaydisablesomeinter-moduleoptimizations,butwebelievethatthecodegeneratedbyourrecompilationmethodwillbecomparabletothequiteecientcodegeneratedbythecurrentSML/NJcompiler[4].WeplantoimplementandmeasureouralgorithminSML/NJinthefuture.ThesmartestrecompilationtechniqueinthispaperispresentedintheframeworkofSML;however,itcanbeeasilyappliedtootherpolymorphiclanguagesbasedontheDamas-Milnertypediscipline.ItshouldbestraightforwardtoextendthealgorithmDinsection2.2toworkontheextensionofMLtypesystemwithparametricoverloadings[13].Theassumptioninferencealgorithmspresentedinsection2and3canalsobeusedasabasistobuildincrementalcompilersforsimilarlanguages.Ontheotherhand,westilldonotknowhowtoextendthealgorithmforModLtoworkontheextensionofMLmodulesystemwithhigh-orderfunctors[32].ThesmartestrecompilationtechniqueshouldalsobeapplicabletolanguagesintheAlgolfamily.ThetypesysteminthoselanguagesaremuchsimplerthanthatinML,soitisnothardtoinferthe\minimum"importinterfaceforeachmodule.However,thecodeproducedbysmartestrecompilationwillbelessecientbecausethecodegeneratorsoftheselanguagesusuallyrelymuchmoreontheinter-proceduretypeanddata\rowinformationthanthoseofpolymorphiclanguages.Forapplicationswherereusabilityandrecongurationaremoreimportantthaneciency,thesmartestrecompilationpropertyisstillverydesirable. AcknowledgementsWewouldliketothankWilliamAitken,CarlGunter,andQingMingMaformanyvaluablecommentsonanearlyversionofthispaper.WearealsogratefultoDavidMacQueenandPierreCregutforinterestingdiscussionsonrelatedsubjects.ThisresearchissupportedbytheNationalScienceFoundationGrantCCR-9002786andCCR-9200790,andbytherstauthor'ssummerresearchinternshipatAT&TBellLaboratories.References[1]ShailAdityaandRishiyurS.Nikhil.Incrementalpolymorphism.InTheFifthInternationalConferenceonFunctionalProgrammingLanguagesandComputerArchitecture,pages378{405,NewYork,August1991.Springer-Verlag.[2]WilliamE.AitkenandJohnH.Reppy.Abstractvalueconstructors.InACMSIGPLANWorkshoponMLanditsApplications,June1992.[3]MariaVirginiaAponte.Typaged'unsystemedemodulesparametriquesavecpartage:uneapplicationdel'unicationdanslestheoriesequationnelles.PhDthesis,UniversitedeParis,February1992.[4]AndrewW.AppelandDavidB.MacQueen.StandardMLofNewJersey.InMartinWirsing,editor,ThirdInt'lSymp.onProg.Lang.ImplementationandLogicProgramming,pages1{13,NewYork,August1991.Springer-Verlag.[5]HansBoehmandAlanJ.Demers.ImplementingRussell.InSymposiumonCompilerConstruction,pages186{195.ACMSigplan,June1986.[6]LuisDamas.TypeAssignmentinProgrammingLanguages.PhDthesis,UniversityofEdinburgh,DepartmentofComputerScience,Edinburgh,UK,1985.[7]LuisDamasandRobinMilner.Principaltype-schemesforfunctionalprograms.InNinthAnnualACMSymp.onPrinciplesofProg.Languages,NewYork,Jan1982.ACMPress.[8]DavidK.Giordetal.FX-87referencemanual.TechnicalReportMIT/LCS/TR-407,M.I.T.LaboratoryforComputerScience,September1987.[9]StuartI.Feldman.Make{aprogramformaintainingcomputerprograms.Software{PracticeandExperience9(4):255{265,Apirl1979.[10]EmdenR.Gansner.AT&TBellLabs,personalcommunication,1992.[11]PaulHudak,SimonPeytonJones,andPhilipWadleretal.ReportontheprogramminglanguageHaskellanon-strict,purelyfunctionallanguageversion1.2.SIGPLANNotices,21(5),May1992.[12]MarkP.Jones.Atheoryofqualiedtypes.InThe4thEuropeanSymposiumonProgramming,pages287{306,Berlin,February1992.Spinger-Verlag.[13]StefanKaes.Typeinferenceinthepresenceofoverloading,subtypingandrecursivetypes.In1992ACMConfer-enceonLispandFucntionalProgramming,NewYork,June1992.ACMPress.[14]BillKalsowandEricMuller.SRCModula-3version1.6manual,February1991.[15]ButlerW.LampsonandEricS.Schmidt.Praticaluseofapolymorphicapplicativelanguage.InTenthAnnualACMSymp.onPrinciplesofProg.Languages,NewYork,Jan1983.ACMPress.[16]DanielLeivant.Polymorphictypeinference.InTenthAnnualACMSymp.onPrinciplesofProg.Languages,NewYork,Jan1983.ACMPress.[17]XavierLeroy.Unboxedobjectsandpolymorphictyping.InNineteenthAnnualACMSymp.onPrinciplesofProg.Languages,NewYork,Jan1992.ACMPress.[18]MichaelR.Levy.Typechecking,separatecompilationandreusability.SIGPLANNotices(Proc.Sigplan'84Symp.onCompilerConstruction),19(6):285{289,June1984. [19]RobinMilnerandMadsTofte.CommentaryonStandardML.MITPress,Cambridge,Massachusetts,1991.[20]RobinMilner,MadsTofte,andRobertHarper.TheDenitionofStandardML.MITPress,Cambridge,Mas-sachusetts,1990.[21]J.Mitchell,W.Maybury,andR.Sweet.Mesalanguagemanual.TechnicalReportCSL-79-3,XeroxPaloAltoResearchCenter,PaloAlto,CA,1979.[22]GregNelson,editor.SystemsprogrammingwithModula-3.PrenticeHall,EnglewoodClis,NJ,1991.[23]RishiyurS.Nikhil.Idversion90.0referencemanual.TechnicalReportTR-CSG-Memo284-1,MITLaboratoryforComputerScience,1990.[24]AtsushiOhori.AcompilationmethodforML-stylepolymorphicrecordcalculi.InNineteenthAnnualACMSymp.onPrinciplesofProg.Languages,NewYork,Jan1992.ACMPress.[25]DidierRemy.TypecheckingrecordsandvariantsinanaturalextensionofML.InSixteenthAnnualACMSymp.onPrinciplesofProg.Languages,pages77{87,NewYork,Jan1989.ACMPress.[26]J.Robinson.Amachine-orientedlogicbasedontheresolutionprinciple.JournaloftheACM,12(1):23{41,1965.[27]EugeneJ.Rollins.SourceGroup:AselectiverecompilationsystemforSML.InThirdInternationalWorkshoponStandardML,Pittsburgh,September1991.CarnegieMellonUniversity.[28]NickRothwellandMadsTofte.Importcommandsourcecode.withStandardMLofNewJerseyreleases0.65.[29]RobertW.SchwankeandGailE.Kaiser.Smarterrecompilation.ACMTransactionsonProgrammingLanguagesandSystems,10(4):627{632,October1988.[30]WalterTichy.Smartrecompilation.ACMTransactionsonProgrammingLanguagesandSystems,8(3):273{291,July1986.[31]MadsTofte.OperationalSemanticsandPolymorphicTypeInference.PhDthesis,UniversityofEdinburgh,Edinburgh,UK,November1987.[32]MadsTofte.Principalsignaturesforhigh-orderMLfunctors.InNineteenthAnnualACMSymp.onPrinciplesofProg.Languages,NewYork,Jan1992.ACMPress.8Appendix:ProofofTheorem2.1Theproofoftheorem2.1isorganizedinveparts:therstpartintroducessomenotationsandlemmasusedlaterintheproofs;therestfourpartsgivethedetailedproofs.8.1NotationsandLemmasBeforeweproceed,let'sintroducesomenewnotationsandlemmas:Denition8.1isanitemapfromtypevariablestotypes.Theofasubstitution,denotedas),isthesetoftypevariablessuchthat.Theofasubstitutiondenotedas),istheunionofalltyvars()forallDom(.Asubstitutioniscalledavariable-substitutionifforallTyVarisatypevariable.Theoftwosubstitutionsdenotedas,is\se."Assumethatisasetoftypevariables,thesubstitutiondenotesthesubstitutionwithitsdomainrestrictedtoDom(Wedeneanobjecttobeeitheratype,atypescheme,atypeenvironment,oratupleofotherobjects.Thesetoftypevariablesoccurredfreeinanobjectisdenotedas Denition8.2Givenanobject,arenamingsubstitutionforthisobjectisavariable-puresubstitution=1;:::;nsuchthat=1;:::;ng),thesaredistinctand(tyvars(=1;:::;n\f=1;:::;nDenition8.3Twotypesarecalledvariantsifthereexistsubstitutionssuchthat,wecanalsodenevariantsrelationssimilarlyontypeschemes,typeenvironments,orobjectswithsameshapes.ThevariantrelationisdenotedasThevariantsrelationisobviouslyre\rexive,symmetricandtransitive,thusitisanequivalencerelation.\Vari-ants"isveryimportantincomparingtwoobjectsbecauseofthefollowinglemma:Lemma8.1Iftwoobjectsarevariants,thenthereexistarenamingsubstitutionandarenamingsubstitutionsuchthat=ID.Fromlemma8.1,toprovethesecondpartofthetheorem2.1,weonlyneedshowthat(TE;)and;S)arevariants.Herearesomeotherlemmaswearegoingtouseintheproof:Lemma8.2Givenanitesetofpairsoftypes,supposebotharethemostgeneraluniersof,thenforanyobjectsarevariants.Lemma8.3Givenanitesetofpairsoftypes,thenthefollowingstatementsaretrue:IfUnifysucceeds,itwillreturnamguIfUnifysucceedsand,thenUnifyalsosucceeds;moreover,ififP2andS1isamguof,thenUnifyalsosucceeds.SupposeoseP2,Unifysucceedsandisamguof,andUnifysucceedsandamguof,thenUnifysucceedsandisamguofGivenarenamingsubstitution,supposeisaninversesubstitutionofinthesensethatID,thenUnifysucceedsifandonlyifUnifysucceeds.Moreover,ifisamguofPthen()isamguofInthegure6wereviewTofte[31]'sversionoftheclassicalMLtypeinferencealgorithm.ThefollowinglemmacaneasilybeprovedbystructuralinductionontheexpressionLemma8.4GivenTEand,ifS;)=;esucceeds,and;issimplytheresultofanotherrunofthealgorithmonTEandbychoosingdierentnewtypevariables,then;;arevariants.WeuseTyVartodenotethesetofnewtypevariablesusedinrunning;e)plusthosetypevariablesoccurredfreein.ThenweletonlyusenewtypevariablesfromTyVarTyVar.Fromlemma8.4,whicheversetofnewtypevariablesisusing,theresulting(;)isalwaysavariantofeachother.Thusitsucestoprovethattheorem2.1istruewhenareusingdierentsetofnewtypevariables.Inthenextforsections,weshowitbystructuralinductionontheexpression Def;e)=)=benewtypevariablesand=1;:::;nbeanewtypevariableand(;)=f;e;)=;e)and(;)=;ebeanewtypevariableand;;)=;e)and(;)=f;;e;Figure6:TheclassicalMLTypeInferenceAlgorithm 8.2Case1:variable(Part1);x)willsucceedonlywhenDom(),inwhichcaseboth()=)and)willsucceed,viceversa(Part2)Nowsuppose(;A)=(\r;)and)=,then;x)=(;S)where=1;:::;nandallarenewtypevariables.Ontheotherhand,;A)==1;:::;nandallarenewtypevariables.Thuslet'schoose,thenobviously()and()arevariantsthrough8.3Case2:lambdaabstraction(Part1)Suppose;e)succeeds,wewanttoprovethatboth(;A)=)and;Awillalsosucceed.beanewtypevariableusedin,then(;)=f;e)shouldalsosucceed.Thereforebyinduction,both(;A)=)andf;A)willsucceedtoo.Letthesetoftypeassumptionsforbe=1;:::;kandletbeanewtypevariableusedinandlet;A)),thenobviouslyissimply;t=1;:::;n).Let,bylemma8.3,becauseboth)=)=aretrue,f;A)willalsosucceedandisoneofitsmgu.Ontheotherhand,becausef;A)succeeds,bylemma8.3,;t=1;:::;n)shouldalsosucceed.Thus;t=1;:::;n)willsucceedtoo.Thusbecause)=istrue,bylemma8.3,;Snf))willalsosucceed.Thereversedirectioncanbeprovedinthesamewayusinglemma8.3.(Part2)Let'sstillusethenotationsinpart1,byinduction,weknowthatthereexiststwosubstitutions suchthatthefollowingaretrue:f !f)and !f12 !f)and !Thenwecandeducethefollowingbyusinglemma8.3andlemma8.2,;S;Snf;S;Snf)(;f;A))(;f;A))(;f;A)(;f;A))(;Thusweprovethat;S))and())arevariants.8.4Case3:application(Part1)Suppose;e)succeeds,wewanttoprovethatboth(;A)and;Awillalsosucceed.;e)succeeds,both(;)=;e)and(;)=;e)willalsosucceed.beanewtypevariableusedin,then;)willsucceed.Byinductionweknowthatboth()and()willsucceed.Thecorrespondingunications)and;A)willsucceedtoo.Moreoverthereexistsfour(renaming)substitutionssuchthatthefollowingaretrue:,and !)and ! !)and ! !))and ! !))and !Firstweprove))=).SupposeTTisthesetofpairsoftypestobeuniedinrunning;ATTwillcontaintypevariablesfromfromtyvars(A2)andsomenewtypevariables.Fromthedenitionofamgu,)shouldbetheidentityonalltypevariablesexceptthosein).BecausewearerunningRobinson'soriginalunicationalgorithm,Reg()isasubset).Similarlyfromthedenitionofrenamingsubstitutions,shouldbetheidentityonalltype variablesexceptthoseinReg().Wealsoknowwillbetheidentityon))because)willbe))plussomenewtypevariables.Thuswehave))=Nowbecause;)succeeds,;R))))shouldalsosuc-ceed.Bylemma8.3,;S))willsucceedtooand()isoneofitsmgu.;A)succeeds,bylemma8.3,f;A[fwillalsosucceed(hereisusedtoeasethenotation;itisanunusedprogramvariable).Moreoveralsobylemma8.3,=(willbeoneofitsmgu.Becauseweareusingdierentnewtypevariablesin,andthecallof)and)areusingtotallydierenttypevariables,thefollowingequationsareobviouslytrue:)=)and)=f;A[f)succeedsandisoneofitsmgu,bylemma8.3,f;AAA2[f)willalsosucceed.Moreover=(isoneofitsmgu.bethenewtypevariableusedin,let'sdene.Againbylemma8.3,f;AAA2[f)willalsosucceed.Moreover,willbeoneofitsmgu.Thusagainbylemma8.3,;)alsosucceeds.Let'sassumebethemguproducedwhenrunning.Thusbecause)=istrue,;SSA2)alsosucceeds.Thereversedirectioncanbeprovedinthesamewayasabovebykeepingapplyinglemma8.3.(Part2)Let'sstillusethenotationsintroducedinpart1,wecangetthefollowingbyusinglemma8.3andlemma8.2:;S;SSA2)))(TE;S;SSA2)))(S3(TE);Sf;AAA2[f))(;)(;;;;R;;;R;;SThusweprovethat;S))and(;S)arevariants.8.5Case4:letexpression(Part1)Wewanttoprovethatif;e)succeeds,thenboth(;A)=)and;A)willalsosucceed.Suppose;e)succeeds,thenboth(;)=;e)and(;)=f;;e)willalsosucceed.Byinduction,both(),()and ;A)andf;;A)willsucceedtoo.Moreover,thereexistsfourrenamingsubstitutionssuchthatthefollowingistrue:,and !)and ! !)and !f; !f;)and !f; !f;)and !Firstwedenethefollowingnotations:letthetypeassumptionsforbe)==1;:::;ktyvars)be=1;:::;mtyvars)be=1;:::;ug[f=1;:::;v;weassumethatcontainssometypevariablesandsomenewtypevariables.Assumethat,where=1;:::;k=1;:::;m,arenewtypevariables,foreach=1;:::;k,wedenearenamingsubstitution=1;:::;m,anda=1;:::;m.Let.Assumethat,where=1;:::;k=1;:::;v,arenewtypevariables,foreach=1;:::;k,wedenearenamingsubstitution=1;:::;v.Alsowedenoteforeach=1;:::;kUsingtheabovenotations,(;A)==TVA1;;A;A))isequivalenttothat;t=1;:::;k)andand:::[CkA1.Therefore,toprovethatboth;t=1;:::;k)and;AAS3(A3[A2nf))succeed,bylemma8.3,wesimplyneedtoprovethatf=1;:::;k;AAC1A1[:::[CkA1[A2)succeeds.Hereweinformallyusetomeanthedierentinstancesof,correspondingtothoseWearegoingtoprovethatf=1;:::;k;AAC1A1[:::[CkA1[A2)succeedsinthefollowingtwosteps:Step1.1First,weprovethattheunication;AAC1A1[:::[CkA1)succeeds.Weshallconstructsuchmgu;AAssumethatwhendoing;A),thesetofnewtypevariablesintroducedbyinstantiatingboundvariablesin=1;:::;n.Let,where=1;:::;n=1;:::;k,benewtypevariables.Allthesetypevariablesvirtuallycorrespondstodierentinstantiationsofboundvariablesinwhendoing;AAC1A1[:::[CkA1).Let'sdeneasubstitutionforeach=1;:::;ksuchthat=1;:::;n.Wealsodenesubstitutions=1;:::;nforeach=1:::;k.Let'sdenotethesetoffreetypevariablestyvars)inby;:::;\r.Suppose;A)=Unify;y=1;:::;q).Thedomainofwillbe;:::;[f;:::;g[f;:::;\r.Theregionofwillbeasubsetof.Thereforeweknowforall)=.Wealsodene[fij=1;:::;n=1;:::;kg[f=1;:::;m=1;:::;kBecauseDom()=,wedeneasubstitutiontobetobeforeach=1;:::;k.Now;AAC1A1[:::[CkA1)isessentiallyequivalentto)where=(;y=1;:::;qg[[j=1f(Bjxi;C=1;:::;qThesubstitutionisconstructedasfollows,notethatthedomainofandtheregionofisasubsetofFirstwedeneasubstitutionforeach=1;:::;ksuchthat )=then=1;:::;m)==1;:::;n)==1;:::;pWedeneasubstitution)suchthat)==1;:::;m)==1;:::;n)==1;:::;pWealsodene.ObviouslywehaveNowwecandenethesubstitution)=)where=1;:::;m)=()where=1;:::;m=1;:::;k)=)where=1;:::;n)=()where=1;:::;n=1;:::;k)=)where=1;:::;p.Noticeherewealsohave))=)foreach=1;:::;kbecausetyvars))isasubsetof.Wecaneasilyprovethefollowingseveralstatements:isanunierofProof)=)=)=)where=1;:::;qFromthedenitionof,weknowforeachtypevariable))=Thusforeach=1;:::;k,wehave)=))=))=)where=1;:::;qThesubstitution))isamostgeneralunierof;C=1;:::;qProofWeknowforeachtypevariable))=)).ThusandthereforeGivenanunier;C=1;:::;q,since)=)foreach=1;:::;qalsoanunierof;y=1;:::;q.ThusthereexistsasubstitutionsuchthatThuswecanget=(Thisexactlymeansthatisamostgeneralunier;C=1;:::;qisamostgeneralunierofProofGivenanunierwillbeanunierfor;y=1;:::;qforeach=1;:::;k)isanunierof;C=1;:::;q.Thusfromthedenitionofmgu,thereexists+1substitutions=0;:::;ksuchthatforeach=1;:::;k.Sincetheregionofisasubsetof,andforeach=1;:::;ktheregionofisasubsetof),wecanconstructasubstitution=0;:::;kfollows:Foreach),because)=,wedene)= Forall=Reg(),wesimplydene)=Nowit'seasytoseeforall)=)),thatis,,thusisamostgeneralunierofFromthedenitionof,weknowthatthefollowingaretrue:)=)=)=)=)=))=)))=(=1;:::;kStep1.2Weprovethattheunicationf=1;:::;k;S)alsoWedenote=1;:::;mg[f=1;:::;ng[f=1;:::;vforeach=0;:::;k.Let==j=1tyvars))==1;:::;rNoticethatifReg(),then)=thus.Because !),lettheimage)afterbedenotedby.Obviouslywehavetyvars))= ==1;:::;rtyvars))=.Indoingtheunicationf;;Athereareinstantiationsofthetype;).Suppose;),foreach=1;::;k,wedeneasubstitution=1;:::;sarejustnewtypevariablesusedin.Andnowtheinstantiationsofthetype;)willbesimplyj;:::;kNoteDom())=andReg())=.Wealsodenesubstitutions=1;:::;sforeach=1;:::;kandasubstitution.Because isthesetoffreetypevariablesin),foreach=1;:::;k,thesetoftypevariablesinisessentiallyasubsetPV= [f.wecanconstructthefollowingrenamingsubstitutionfor=(PVWemakethefollowingtwoobservationsonNoticethatReg()==tyvars(S11)isasubsetofTV0.Foreachwillbemappedtosomefreetypevariablein)by.Thusdierentboundtypevariables;)willbemappedbytodierenttypevariablesin.Alsoforeach=1;:::;naccordingtothedenitionof,dierenttypevariablesinwillbemappedtodierenttypevariablesinby().ThusisarenamingsubstitutionforbecauseitvirtuallymapsdierenttypevariablestodierenttypevariablesinForallfreetypevariables in)=).Thisisbecauseforidentitiesonalltypevariablesinandisanidentityonalltypevariablesin .Becauseallshaveconsistentdenitiononalltypevariablesin ,wecanalsodeneSimilarlywelettodenotetheinversesubstitutionofsuchthatNowthatwehavealreadyknownthatf=1;:::;k;A)succeedsbyinductions,bylemma8.3,f=1;:::;k;Q))willalsosucceed, moreoverwillbeoneofitsmostgeneralunier.Because))=))=)and)=1))=))and)=,wealsogetthatf=1;:::;k;S)succeedsandisoneofitsmostgeneralunier.Thereforefromtheabovetwosteps,weprovethat=1;:::;k;AAC1A1[:::[CkA1[A2)succeeds,moreoverbylemma8.3,(isoneofitsmostgeneralunier.Thusboth;t=1;:::;k)and;AAS3(A3[A2nf))willsucceed.Thereversedirectioncanbeprovedinthesimilarway.(Part2)Let'sstillusethenotationsinpart1,wecandeducethefollowingbyusinglemma8.3andtheresultsinpart1:;S;AAS3(A3[A2nf))(;S;SSA3[A2nf))(;S;;;;Thusweprovethat;S))and(;)arevariants.9Appendix:ProofofTheorem2.6Inthisappendix,wearegoingtoprovetheorem2.6,i.e.,theequivalencebetweenthealgorithmAsmentionedinsection2,thesetofpredicatesweuse,denotedby,is)whereisanyprogramvariable.Theinterpretationofis\^)=trueifandonlyif,assumingthatthetypeofisaclosedMLtypescheme."Theentailmentrelationonconstraintsetsisdenedas:``ifandonlyifissatisableand.First,weprovethefollowingseverallemmas.Theywillbelaterusedintheproofoftheorem2.6.Lemma9.1Givenasubstitutionandtwoconstrainedtypeschemes.If,thenProof)andletbetheinstantiationsubstitution=1;:::;n)=.Assumethat)and;:::;newtypevariableswhicharenotinReg().Let,thenmustbeoftheform)).Thereforedeningweget)))=))=)showingLemma9.2C;isavalidtyping,andisasolutionof,then;Sisalsovalid.ProofBystructuralinductionon.ThecasewhereisavariablefollowsfromLemma9.1.Oftheremainingcases,onlythecaseforletexpressionsisinteresting. ObviouslyC;mustbeinferredfromtheassumptionsthatbothC;f;g`arevalid,and``.Becauseisasolutionofmustbealsoasolutionof.Byinductions,both;S;Sf;g`)arealsovalidMLtypings.Let;:::;be).Assumethat)and;:::;newtypevariableswhicharenotinReg().Let;))=)=))).Noisfreein).Moreover,anytypevariablethatoccursfreein()))andisnotamustbefreein).Thereforewehave;))=;S)).Because``isasolutionof,so``Thusweprovethat;S:S()isvalid.Denition9.1Givenanconstrainedtypescheme,itsimageMLtypescheme,denotedbyforget,iswhereareallthosesthatarefreein.SimilarlyweuseforgettodenotetypeenvironmentTEforgetLemma9.3C;isavalidtyping,and;``,letTEforget,thenTEisaProofBystructuralinductionontheexpression.Onlythecaseforletexpressionsisinteresting.ObviouslyC;mustbeinferredfromtheassumptionsthatbothC;f;g`arevalid,and``.Because;``,thus;``.Byinductions,bothf;g`arevalid.Fromthedenitionofforget)holds,thus;;).Thereforef;Sg`)isalsoavalidMLtyping.So)isavalidMLtyping.Proofoftheorem2.6(Part1)Supposethat(S;)=;e)succeeds,wewanttoprovethat(;)=;e)alsosucceeds.WerstconstructanMLtypeenvironment7!8j;)whereDom()=.Obviously)=)=).Because(S;)=;esucceeds,fromthesoundnesstheoremofthealgorithm,weknowthatisavalidMLtyping.ThenthetypedeductiontreeofcanbeeasilytransformedintoaMLtypedeductiontree;S,thereforeweprovethat;SisalsovalidinML.Becauseforeach),andbytheorem2.4,(;)=;e)alsosucceeds.Moreoverthetyping;Sismoregeneralthan;S.Fromthedenition2.6,thereexistssomesuchthatj;;)).Thisalsomeansthattheremustexistasubstitutionsuchthat;``)).Thusisasolutionoftheconstraintset.Fromlemma2.5,thereexistsamostgeneralsolutionfor(Part2)Fortheotherdirection,supposethat(;)=;e)succeedsandisamostgen-eralsolutionfor,wewanttoprovethat(S;)=;e)alsosucceeds.Fromtheorem2.4,because;)=;e)succeeds,;SisavalidMLtyping.Bylemma9.2,weknowthat;S)isalsovalid.Weusethesamenotationasinpart1.Obviously)=)=).Wecaneasilyprovethat;S)isvalidbyconstructinganMLtypedeductiontreefromthetyping;S).Thenbylemma9.3,becauseforget)=,thus)isavalidMLtyping.Fromthecompletenesstheoremofthealgorithm,(S;)=;e)shouldalsosucceed. (Part3)Supposethatboth(;)=;e)and(S;)=;e)succeed,andisamostgeneralsolutionfor,wenowprovethat(;)and(;S)arevariants.(Part3.1)Fromthediscussioninpart1,weknowthatthetyping;Sismoregeneralthanthetyping;S.Thusthereexistsasubstitutionsuchthatthefollowingistrue:j;;))."Fromtheproofoflemma9.2,weknowthat;;S)).Thusthereexistsasubstitutionwithitsdomainbeingasubset)))suchthat))and;``)).Thisalsomeansthatisasolutionof.Assumethatisthemostgeneralsolutionof,thenthereexistsasubstitutionsuchthat.Thus))."Because)=,thus))shouldalsobetrue.Butthiscanonlybetrueif)=))Becauseisalwaysanidentityonwealsohave)=)))andthus)=Insummarywehaveprovedthatthereexistasubstitutionsuchthat;S))=;(Part3.2)Fromthediscussioninpart2,bythecompletenesstheoremofthealgorithm,weknowthatthetypingismoregeneralthan).Thisessentiallymeansthatthereexistsasubstitutionsuchthatthefollowingistrue:;))."Because;))=;S)),thus;S)).Thisalsomeansthatthereexistsasubstitutionwithitsdomainbeingasubsetof)))suchthat)=)).Nowlet,then)=))=))."Becauseisalwaysanidentityon))),wealsohave))=Insummarywehaveprovedthatthereexistasubstitutionsuchthat(;S))=;Fromthedenition8.3,weknowthat(;)and(;S)arevariants. 10Appendix:TypeDeductionRulesInthisappendix,welistthetypedeductionrulesforthemini-MLlanguageExp,thetypedeductionrulesforthelanguageML(i.e.,MLwithconstrainedtypes),andthestaticsemanticsoftheskeletalmodulelanguageModL10.1TypeDeductionin(VAR)fg`f;g`10.2TypeDeductionin(VAR)C;C;fg`C;C;C;C;C;f;g`C``C; 10.3StaticSemanticsofModLThegrammarofModLandthesemanticobjectsusedherearethosegiveningure3.Givenafunctor=()),afunctorinstance())isaninstanceof,writtenifthereexistsarealizationsuchthat))=())andDom(.Alsoweuse)todenotethesetofnamesoccurredfreeintodenote`)fgstrdecstrdecstrdecdec1strdecdec1)=decEm=((NamesetofofNames(E))aB`structdecendm;Estrexpm;E)=strexpstrexpSBfctid(Namesetofstrexpstrexpstrexp)f