/
SmartestRecompilationZhongShaoAndrewW.Appelzsh@princeton.eduappel@prin SmartestRecompilationZhongShaoAndrewW.Appelzsh@princeton.eduappel@prin

SmartestRecompilationZhongShaoAndrewW.Appelzsh@princeton.eduappel@prin - PDF document

karlyn-bohler
karlyn-bohler . @karlyn-bohler
Follow
389 views
Uploaded On 2016-07-19

SmartestRecompilationZhongShaoAndrewW.Appelzsh@princeton.eduappel@prin - PPT Presentation

1IntroductionMosttraditionalseparatecompilationmethodsrelyonmanuallycreatedcontextsegModula3interfacesinclude lesinCandAdapackagespeci cationstoenforcetypecorrectnessacrossmoduleboundaries ID: 411668

1IntroductionMosttraditionalseparatecompilationmethodsrelyonmanuallycreatedcontexts(e.g. Modula-3interfaces \include- les"inC andAdapackagespeci cations)toenforcetypecorrectnessacrossmoduleboundaries.

Share:

Link:

Embed:

Download Presentation from below link

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.


Presentation Transcript

SmartestRecompilationZhongShaoAndrewW.Appelzsh@princeton.eduappel@princeton.eduCS-TR-395-92PrincetonUniversityOctober1992AbstractToseparatelycompileaprogrammoduleintraditionalstatically-typedlanguages,onehastomanuallywritedownanimportinterfacewhichexplicitlyspeci esalltheexternalsymbolsreferencedinthemodule.Wheneverthede nitionsoftheseexternalsymbolsarechanged,themodulehastoberecompiled.Inthispaper,wepresentanalgorithmwhichcanautomaticallyinferthe\minimum"importinterfaceforanymoduleinlanguagesbasedontheDamas-Milnertypediscipline(e.g.,ML).By\minimum",wemeanthattheinterfacespeci esasetofassumptions(forexternalsymbols)thatarejustenoughtomakethemoduletype-checkandcompile.Bycompilingeachmoduleusingits\minimum"importinterface,wegetaseparatecompilationmethodthatcanachievethefollowingoptimalproperty:Acompilationunitneverneedstoberecompiledunlessitsownimplementationchanges.AshortversionofthispaperwillappearintheTwentiethAnnualACMSIGPLAN-SIGACTSymposiumonPrinciplesofProgrammingLanguages,January,1993. 1IntroductionMosttraditionalseparatecompilationmethodsrelyonmanuallycreatedcontexts(e.g.,Modula-3interfaces,\include- les"inC,andAdapackagespeci cations)toenforcetypecorrectnessacrossmoduleboundaries.Usingthepropercontexts,thecompilercancheckthateachmoduleusesitsimportedinterfacesproperly,andimplementsitsexportedinterfaceasexpected.Thedisadvantageofusingthesemanuallycreatedcontextsisthattoguaranteeconsistency,allmodulesusingachangedcontextmustberecompiled,nomatterhowsmallthechangeis.Theconventionalrecompilationrule(asdescribedinTichy[30])isstatedasfollows:compilationunitmustberecompiledwheneveritsownimplementationchanges,oracontextchangesuponwhichthecompilationunitdepends."Thisisobviouslynotsatisfactorybecauseaddingacommentoraddinganewdeclarationtoapervasivecontextmaycausetheunnecessaryrecompilationoftheentiresystem.Tichy[30]presentsane ectivetechniquecalled\smartrecompilation"thateliminatesmostoftheredundantrecompilationstriggeredby(2).InTichy'sscheme,acompilationunitisrecompiledonlyifitsimplementationchanges,orifitreferencesasymbolde nedelsewherewhosede nitionhaschanged.SchwankeandKaiser[29]de ne\smarterrecompilation"whichcaneliminateevenmore(butnotall)redundantrecompilationscausedby(2).Soanaturalquestiontoaskis:Canweeliminateallredundantrecompilations?thatis,canweachievethefollowingsmartestrecompilationruleAcompilationunitneverneedstoberecompiledunlessitsownimplementation(sourcecode)changesStandardML(SML)[20]hasaratherelaboratemodulesystem,butSMLcompilershavenotsupportedseparatecompilationverywell.TheproblemisthatinSML,modulessuchasstructuresandfunctorscanliberallyreferenceexternallyde nedidenti erswithoutevenmentioningwhataretheirspeci cations.Forexample,byusing\quali ed"(dotted)identi ers,astructurecanuseBAR.QUX.ftoreferencethefunctionde nedinthesubstructureofthestructure,withoutevenknowingwhatthetypeofis.Becauseofthelackofexplicitimportinterfaces,structuresandfunctorswithfreevariables(let'scallthemopen-formedmodules)arenotconsideredasseparatelycompilableunits.Sohowcanweseparatelycompileopen-formedmodulesinSML?Thispaperpresentsanewseparatecompilationmethodwhichactuallyanswersbothoftheabovetwoquestions.Surprisingly,notonlycanweseparatelycompilearbitrarystructuresandfunctorsinSML,butwecanalsoaccomplishthe\smartestrecompilationrule."Ourideaissimple:inordertoseparatelycompileamodulewithreferencestoexternalidenti ers,wehavetoknowthespeci cations(e.g.,types)oftheseexternalidenti ers;sincetheyarenotexplicitlyspeci ed,weinferthembylookingathowtheseexternalidenti ersareusedinsidethemodule;thenwecompilethemodulebyusingthisinferredimportinterfaceasitscontext; nally,whenallthemodulesarelinkedtogether,cross-moduletypeerrorsarereportedbycheckingwhetherthesurroundingsmatch(orsatisfy)thespeci cationsineachinferredimportinterface.Thecatchhereisthatinordertoachievethe\smartestrecompilationrule",wehavetoinferthe\minimum"importinterface.Informallyspeaking,this\minimum"importinterfacespeci esasetofassumptions(onthoseexternalidenti ers)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.NowsupposethattherealstructureBARisde nedasfollows:structureBAR=structvalf=3valh=truevalg=fnz�=zendthenatlinktime,whentherealismatchedagainsttheimportinterfaceof,we ndthatthetypevariablesshouldbeshouldbebool,thusFOO.xwillhavetypewillhavetypebool.ThisisexactlywhatwewillgetifwecompileintheenvironmentthatwouldresultfromToachievethe\smartestrecompilationrule",thebackendofthecompilermustuseonlythetypeinforma-tionspeci edinthemodule'sinferredimportinterface.Thislimitationisnotabigproblem.ThebackendofthecurrentSML/NJcompiler[4]usesalmostnotypeinformationfromthefrontendbutitstillproducesquiteecientcode.Manyoptimizationtechniquesthatdousethetypeinformation,suchasLeroy'srepresentationanalysis[17],canstillbepartiallyincorporatedintoourseparatecompilationsystem.Thedetailswillbedescribedinsection4and5ofthispaper.Ourseparatecompilationmethodimmediatelyhasthefollowingadvantagesovertraditionalmethods:Becauseofthesmartestrecompilationrule,eachmoduleneverneedstoberecompiledunlessitsownimplementationchanges;somaximumreusabilityisachieved.Becauseallmodulesarecompiledindependentlyofeachother,theycanbecompiledinanyorder.Thisalsomeansthatprogrammersneednolongermaintaindependency les(e.g.,Makefile[9]).Open-formedmodulescanalsobeseparatelycompiled.Cross-moduletypeerrorsarenowsymmetric.Intraditionalmethods,ifmodulereferencesidenti ersde nedinmodule,typeinconsistenciesbetweenmoduleandmodulewillshowupwhencompiled.Iftheprogrammer xestheerrorbyediting,bothmustberecompiled.Butinourmethod,becausecross-moduletypeerrorsarereportedatlinktime,onlywillberecompiled.Thecompilerbasedonourmethodwillautomaticallybeastandalonecompiler.Asfarasweknow,noonehasyetbuiltastandalonecompilerforthecompleteSMLmodulesystem.1.1Closedvs.Open-formedModulesStandardMLallowsprogramminginopen-formedmodules.Theessentialdi erencebetweenclosedandopen-formedmodulescanbeseenfromrewritingtheaboveopen-formedstructureinclosedform,theSML functorFOO'(BAR:sigvalf:intvalg:'a�-'aend)=structvalx=BAR.fvaly=(BAR.g4,BAR.gtrue)Thisshowsthatprogrammershavetogiveassumptionsaboutthetypesofbasedonaproformaimplementationofthestructuredeclaration.Iflater,ischangedtohaveatypescheme,theabovedeclarationwillnolongerbeusefulandwillhavetobemodi edandrecompiled.Anopen-formedmodulesuchasstructuredoesnothavethisproblembecauseitdoesnotrequirethatthespeci cationsofimportedidenti ersbeexplicitlygiven.Peoplemaywanttowriteusingitsminimumimportinterfaceasitsargumentsignature,butthis\minimum"isnotexpressibleintheSMLtypesystem.Moreover,inferringtheminimumimportinterfacecannotbeeasilydonebyhand.Wedonotadvocatewritinglargeprogramsallinopen-formedmodules.SMLstronglyencouragesthateverystructuredeclarationshouldbewrittenwitharesultsignatureconstraint(asitsexportinterface).Programmerscanwritetheirprogramsallintheformofclosedfunctorssuchas.Ontheotherhand,inpractice,we nditextremelyconvenientand\rexibletowritepartsofourprogramsasopen-formedmodules.ForlanguagesbasedontheDamas-Milnertypediscipline[7]suchasSMLandHaskell[11],thereisanotherreasoninfavorofwritingcertainmodulesinopenedforms.OneofthemostimportantfeaturesoftheDamas-Milnertypedisciplineisthatthemostgeneraltypeforarbitraryexpressionscanbeautomaticallyinferredbycompilers.Itis,however,nontrivialtoinferthemostgeneraltypesimplybyhand,especiallywiththepresenceofpolymorphicreferencesinSMLortypeclassesinHaskell.Thismakesitalsonontrivialtowriteexplicitimportinterfacesformanymodules.TheSMLcommentary[19]alsosuggeststhatprogrammerswillprobablyneedtowritedownmanysharingequationsiftheywanttocloseeverymoduleandthatitwillbetoorestrictivetowriteeverythinginclosedfunctors.2AssumptionInferenceinCoreMLMLhasasophisticatedtypeinferencesystem.GivenanMLexpression+1),eventhoughthetypeofnewlyintroducedvariableisnotspeci ed,wecanstill ndthemostgeneraltypeofifweknowthetypeand+.Forexample,ifhastypeand+hastypewillhavetypeMilner'stypeinference(ortypereconstruction)algorithm(asinTofte[31])takestwoarguments,atypeenvironmentandanMLexpression;allthefreevariablesin(suchasand+)mustbespeci edwithatypein,and;e)willreturnthemostgeneraltypeforTosupport\smartestrecompilation,"wefacethechallengeofdoingtypeinferencewithoutevenknowingthetypeofexternalidenti ers.Forexample,canwe ndoutthemostgeneraltypeoftheaboveexpressionifwedonotknowthetypeofand+?Thisseemsimpossible.Butinthecaseofseparatecompilation,weassumethatthetypesofexternalidenti erswillbeknownatlinktime.Wecandividethetypeinferenceintotwophases: rst(atcompiletime),weinferatypeandasetofassumptionsforthefreevariablesin,whichessentiallymeansthatwillhavetypeifthefreevariablesinsatisfytheconstraintsin;then(atlinktime)whenthetypesofthosefreevariables(i.e.,)areknown,wematchthemagainstthoseinand\magically"recoverthemostgeneraltypeof.TodistinguishitfromusualMLtypeinference,wecalltheinferencedoneinthe rstphase\assumptioninference". Inthissectionandsection3wediscussthedetailsofourassumptioninferencealgorithmandshowhowthematchingdoneatlinktimecansuccessfullyrecoverthecorrecttypeforeachexpression.Tosimplifythepresentations,wedivideouralgorithmsintotwoparts:thissectionforCoreMLandthenextsectionfortheMLmodulelanguage.Weonlygivethedetailsofouralgorithmforthemini-MLlanguageExpandtheskeletalmodulelanguageModLusedbyTofte[31].HoweveritiseasytoextendouralgorithmtotherestofSML.Theexpressionsinthemini-MLlanguagearede nedbythefollowinggrammar:letHereisabriefreviewofthenotation.SupposeTyVarisanin nitesetoftypevariablesandTyConisasetofnullarytypeconstructors,thesetoftypes,Type,rangedoverbyandthesetoftypeschemes,TypeScheme,rangedoverbyarede nedbyj8.Atypeenvironmentisa nitemapfromprogramvariablestotypeschemes.)and)arethesetoftypevariablesthatoccurfreerespectively.Atypeisagenericinstanceofatypescheme;:::; writtenas,ifthereexistsasubstitutionwithitsdomainbeingasubsetof;:::; Atypeschemeismoregeneralthan,denotedas,ifallgenericinstancesofarealsogenericinstancesof.Thegeneralizationofatypeinatypeenvironmentisdenotedby;),itisthetypescheme;:::; ;:::; ).ThecoreMLtypesystem,intheformoftypedeductionrulesas,islistedintheappendixattheendofthispaper.ItisdirectlycopiedfromTofte'sthesis[31].2.1TheassumptioninferencealgorithmW*Wede neatypeassumptiontobeapair()whereisaprogramvariableandisatype.Anenvironment,rangedoverby,isasetoftypeassumptions;itisusuallyrepresentedbya nitemappingfromprogramvariablestolistsoftypes.Inthefollowing,weusetodenotethesetoftypeassumptionsinexceptthoseforvariable,and)todenotethesetoftypesassociatedwithvariable.WealsousetodenoteRobinson'soriginaluni cationalgorithmonclassicaltermalgebras[26].takesasetofpairsoftypesandreturnsasubstitution(themostgeneraluni er).Figure1givestheassumptioninferencealgorithmandthematchingalgorithmtakesanMLexpression,andreturnsatypeandanassumptionenvironment.takesanMLtypeenvironmentandanassumptionenvironment,andreturnsasubstitution.Theothertwoproceduresin gure1aretakesatypeandasetoftypes,andreturnsasubstitution.takestwoarguments:atripleofaTyVarsetandatypeandanassumptionenvironment,andasetoftypes;itreturnsasubstitutionandanassumptionenvironment.GivenanMLexpression)delaysthetype-checkingofallfreevariablesinbyrecordingtheirmonomorphictypeinstancesinanassumptionenvironment.Inthecaseoflambdaabstraction,thetypeistreatedasmonomorphic;theprocedurecheckswhetherthesetofassumptionscollectedforsatis esthisconstraint.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;thisisdonebythealgorithmin gure1.Theassumptionenvironmentreturnedfrommaybebig.Apossibleoptimizationistoinsertasimplifyingprocedureateachrecursivecalltointhealgorithm.Thissimplifyingprocedurewillidentifyall\isolated"typeassumptionsin.Given(;A)=),wede neanequivalencerelationontypevariables:\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\quali edtype"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 De nition2.1Letbea nite-indexedfamilyofpredicatesymbols.ThesetofpredicateconstraintsTypeisde nedas;Typewhere=1;:::;n.Aninterpretationofisafamilyoftotalcomputablefunctions(^,suchthatfor:(Type)De nition2.2Asetofconstraintsisifthereexistsasubstitutionsuchthatifistrue.Satis ablitywillbedenotedasDe nition2.3Asubstitutionisa,ifforallsubstitutions.Asolutioncalledthemostgeneralsolutionofaconstraintset,ifforanysolution,thereexistsasubstitution,suchthat.Inmostcases,themostgeneralsolutiondoesnotexist.relationonconstraintsets,written``,maybede nedonceaparticularpredicatesystemisgiven.Inthefollowing,weonlyconsiderthosepredicatesystemswhichsatisfythefollowingproperties:if``De nition2.4constrainedtypeisapair,consistingofatypeandasetofconstraints.Aconstrainedtypeschemeisoftheform.Aconstrainedtypeenvironmentisnowjusta nitemapfromvariablestoconstrainedtypeschemes.De nition2.5Aconstrainedtypeisagenericinstanceofaconstrainedtypeschemewrittenas,ifthereexistsasubstitutionwithdomainbeingasubsetofsuchthat``.Wealsodenoteifallgenericinstancesofaregenericinstancesof;andTypabilityofanexpressioninMLisexpressedasajudgementC;,whichcanbereadas\typeunder(constrained)typeenvironment,providedissatis able."Thegeneralizationofaconstrainedtypeinthecontextofatypeenvironmentisdenotedby;),itistheconstrainedtypescheme;:::; )andDe nition2.6AtypingC;moregeneral,ifthereexistsasubstitutionsuchthat(1)dom(2)gen;;Kaes[13]presentedthetypedeductionrules(alsolistedintheappendixattheendofthispaperforreference)andthetypeinferencealgorithm(asin gure2)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."Theentailmentrelationonconstraintsetsisde nedas:``ifandonlyifissatis ableand.Thisrelationisdecidableforourparticularpredicatesystembecauseofthefollowinglemma:Lemma2.5Foranyconstraintsetformedinthepredicatesystem,eitherthereisnosolutionorthereexistsamostgeneralsolutionProofIfweconsidereach)asanassumption(x;),alsoassumethatthetypeofisknown,thealgorithmin gure1canbeusedto ndthemostgeneralsolutionof.ThelemmathenfollowsfromRobinson'suni cationtheorem.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])in gure3.Noticethatsignatureexpressionsanddeclarationsareintentionallyleftoutbecausetheirelaborationscanbedelayedtolinktime,thusareirrelevanttoourassumptioninference.Functordeclarationsarenotconsideredinourlanguageeitherbecauseonlytheirbody,whichisastructureexpression,iselaboratedatcompiletime.However,functorapplicationsareconsideredinourlanguagebecausetheyarestructureexpressionswhichmustbeelaboratedatcompiletime.ThestaticsemanticsofModLisdiscussedindetailinthede nition[20]andTofte[31].Itsdeductionruleisintheformof\phrase"meaningthatphraseiselaboratedintoasemanticobjectinthebasis.Thesemanticobjectsarealsode nedin gure3.TheappendixattheendofthispaperliststhesetofstaticsemanticrulesforModL.Herewegiveaquickreviewonthemainconceptsusedinthestaticsemantics.De nition3.1structureSisapairm;E,whereisthenameofthestructureandisanenvironment,whichgivesthestaticinformationaboutthecomponentsofthestructure.Tomakethepresentationclear,fromnowon,weshalluse)todenoteastructure().Aisanobjectoftheform,whereisastructureandisa nitesetofnames.AfunctorsignatureisanobjectoftheformS;Nwhereistheprincipalsignaturefortheparametersignatureexpressionofthefunctorandisthebodystructureofthefunctor,thenamesboundinarethenamesinwhichhavetobegeneratedafreshuponeachfunctorapplication.De nition3.2structureenvironmentSEisa nitemapfromstructureidenti erstostructures,similarlysignatureenvironmentGEfunctorenvironmentFE De nition3.3(Names)isanin nitesetofnames:namesthatarespeci edinasignatureex-pressionandarenotsharedwithalreadydeclaredstructuresarecalled\rexiblenames,denotedasnamesofdeclaredstructuresarecalledrigidnames,denotedasDe nition3.4(Realization)realizationisa nitemappingfrom,andare-namingrealizationwhere=1;:::;kisarealizationwheresaredistinctrigidnames.De nition3.5(Enrichment)Astructure)enrichesastructureandthestructureenvironmentSEenrichestheSE.AstructureenvironmentSEenrichesastructureenvironmentSEDom(Dom(andforeachDom(,SEenrichesSEDe nition3.6(SignatureMatching)Astructurematchesasignature=ifthereexistsarealizationsuchthatBecausetheSMLmodulelanguageisexplicitlytyped,theelaborationofamoduleexpressionsimplyinvolvestype-checking.ThestaticsemanticsintheDe nition[20]canbeviewedasatypecheckingalgorithm.Givenastructureexpressionwithfreeidenti ers,wewanttoinfertheminimumconstraintsonthesefreeidenti erswithwhichtheexpressionwilljusttype-check.Againtheminimumconstraintsarenotexpressibleifweonlyusesemanticobjectsin gure3.Weintroduceanewkindofstructurevariablewhichissimilartorowvariablesusedintypingrecordcalculi.LetStrVarbeanin nitesetofstructurevariables;structuresandstructureenvironmentsarenowextendedasStr=(StrNameStrEnvvStrVarandStrEnv=StrId.Eachstructurevariablemusthaveakind.Kindsarede nedas(StrNameKindEnv)whereKindEnvisjusta nitemappingStrIdStrIdStrVar).Todistinguishitfromstructures,akind(isrepresentedas).Akindassignmentisa nitemappingfromstructurevariablestokinds.Am;SE)hasthekindunderthekindassignment,writtenas,ifitisderivablefromthefollowingsetofkindingrules:),if)=)::)ifDom()andDom()=Asubstitutionnowconsistsoftwoparts:onefromStrVartoStr,anotherfromFlexStrNametoStrName(i.e.,realization).Akindedsubstitutionisapairconsistingofakindassignmentandasubstitution.Akindedsubstitution()respectsakindassignmentif,forallindom()::))isaderivablekinding.Akindedsubstitution()ismoregeneralthan()ifforsomesuchthat()respects.Akindedsubstitution()isanuni erofakindedsetofequations)ifitrespects)=)forall(;t)inFigure4givesourinferencealgorithmsstrexponstructureexpressions,decondeclarations,fctidfunctoridenti ers,strdeconstructuredeclarationsandthematchingalgorithmModlMatch.Theargumentrecordsthosealready-usedstructurevariablesand\rexiblenames.Allfunctorapplicationsaredonebythematchingalgorithmatlinktime.The\thinninge ect"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:Kindeduni cationalgorithm 13 Figure5givestheuni cationalgorithms.Thekindeduni cationalgorithmpresentedthereextendstheoneinOhori[24]withconsiderationsonMLstructurenames.ThefollowingtheoremcanbeprovedinthesamewayasOhori[24].Theorem3.1Givenanykindedsetofequations,thealgorithmKindUnifycomputesamostgeneraluni erifoneexistsandreportsfailureotherwise.Thefollowinglemmashowshowthe\thinning"e ectisachievedinouralgorithm.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.Itcanalsobemodi edtotakeabasisitsargument(justasalgorithm)sothatitcanworkmoreecientlywhenwecompileastructureexpressioninthepervasivebasis.4CodeGenerationIssuesAcompilingprocessusuallycontainstwoparts:elaboration(i.e.,typeinferenceortype-checking)andcodegeneration(alsocodeoptimization).Theassumptioninferencealgorithmspresentedinthelasttwosectionssuccessfullysolvetheproblemintheelaborationphase.Inordertoachievethe\smartestrecompilationrule",ourcompilershouldgeneratecodethatwillbereusableaslongasthesurroundingssatisfythe\minimum"importinterface(i.e.,matchtheassumptionenvironment).Thisrequiresthatourcodegeneratorshouldusenomoretypeinformationthanisspeci edinthe\minimum"importinterface.FortunatelythereareveryfewdependenciesbetweenthestaticsemanticsandthedynamicsemanticsinSML.Moreover,althoughLeroy'srepresentationanalysis[17]showsthatthecompilercanbene talotbyusingtypeinformationinthefrontend,theSML/NJcompiler[4]usesalmostnotypeinformationinitsbackendbutitstillproducesquiteecientcode.InSML/NJ,theonlythingsthatthebackendneedstoknowfromthefrontendarethecorrespondingdynamicinterfaceforeachsignatureandtheidenti erstatusforeachidenti er.Bydelayingthesedependenciestoberesolvedatlinktime,aprogramcanbetranslatedintomachinecodeevenbeforeitiselaborated.Inthefollowing,weonlyinformallydiscussthesolutionstotheseissues.FunctorapplicationInSML,afunctorwithargumentsignaturecanbeappliedtoanystructurematchesSIG.Astructuredoesnothavetoagreeexactlywithasignatureinorderforittomatchthesignature,insteaditcancontainmorecomponentsthanrequired.Insuchcases,signaturematching willcoercethestructureagainstthesignature,producinga\thinned"structurethatexactlyagreeswiththesignatureintermsofnumberofcomponentsandtheirtypes.Supposethecorrespondingdynamiccodeforthefunctorandthestructure,thecodegeneratedforafunctionapplication)willbe))whereisathinningfunctionfrom.Inourseparatecompilationscheme,itispossiblethatwestilldonotknowtheargumentsignatureofortheexactspeci cationofwhenwehavetogeneratecodeforthefunctorapplication).Thisissimplysolvedbyaddinganabstractionon,andthecodebecomes).Thecorrectthinningfunctionis lledinatlinktimewhentherealspeci cationsofareknown.PatternmatchingIntheSML/NJcompiler,therepresentationofauserde neddatatypeisdeterminedbyitsde nition.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.Thesedetailsare lledinatlinktimewhenthede nitionofthedatatypeisknown.PolymorphicequalityfunctionsNothingneedstobedonetosupportourseparatecompilationschemeiftheequalityfunctionisimplementedasitcurrentlyisintheSML/NJcompiler.InSML/NJ(asinallMLcompilerstoourknowledge),thepolymorphicequalityfunctionisimplementedasaruntime\equalityinterpreter"whichchecksequalityoftwoobjectsbasedontheirruntimetags.Anotherwaytoimplementpolymorphicequality,whichisusedinHaskell[11],istopassanequalityfunctionforeachformalparameterthatisapolymorphicequalitytypevariable.Thecodeproducedbythisschemecloselydependsonthederivationtreeoftheelaborationphase.Inourseparatecompilationscheme,becausethetypesofsomeexternalidenti ersarenotknownatcompiletime,thederivationtreewegetatcompiletimeisnotaccurate.Forexample,funfx=S.g(3,x)fromassumptioninference,weknow'stypemustbeintheformof'sintheform.Becausemaywanttotesttheequalityonits2ndargument,thefunctionherehastobeimplementedwithanequalityfunctionfortypeasitsextraargument.Thiswillhavesomeruntimeoverheadinthecommoncasethatactuallyneverdoesequalitytestonits2ndargument.RepresentationanalysisLeroy[17]presentedaprogramtransformationthatallowspolymorphiclanguagestobeimplementedwithunboxed,multi-worddatarepresentation.Themainideaistointroducecoer-cionsbetweenvariousrepresentationsbasedonthetypingderivationtree.Inourseparatecompilationsystem,accuratetypeinformationforexternalidenti ersarenotavailableatcompiletime,sothetypingderivationtreeisnotveryspeci c.Howevertherepresentationanalysiscanstillbecarriedoutsincealltypeinstancesofexternalidenti ersarerecordedintheassumptionenvironment.Atlinktime,the matchingalgorithmwill ndouttheaccuratetypeinformationofallexternalidenti ersandco-ercethemintodi erenttypeinstancesintheassumptionenvironment.Forexample,theabovefunctionwillbeimplementedasapolymorphicfunction.Whenwe ndthathastypehastobecoercedtotypehastobecoercedfrom.Thecodeproducedinthiswaywillbelessecient,butitshouldbeacceptableifinpracticetherearenottoomanyexternalidenti ersinamodule(especiallywhenweusealgorithmOpendeclarationdeclarationinSMLcausesseveralnastyproblemsforourseparatecompilationscheme.Forexample,inthefollowingstructuredeclaration,thereisnowayto gureouttheidenti erstatusofwithoutlookingatthede nitionofstructurestructureS=structopenAfunredt(RED)=RED|redt_=BLUEcaneitherbeadataconstructorifitisde nedinadatatypedeclarationinstructure,orcouldsimplybeapatternvariableifitisnotde nedelsewhere(thisisoneoftheugliestfeaturesinML).Asolutiontothisproblemistointroduceabooleanstatusvariableforeach\ambiguous"identi er.Thisstatusvariablespeci eswhethertheidenti erisadataconstructororapatternvariable.Assumestatus-REDisthestatusvariableof,thentheabovefunctioncanberewrittenasfollows:valredt=ifstatus-REDthenfnx=�x(*REDisnotaconstructor*)else(fnRED�=RED(*REDisaconstructor*)|_�=BLUE)Howeverthissolutionmaycausecodeexplosionifnotcareful.Anothersolutionistointroduceapredicateforeachambiguousidenti er.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)canhavethesameidenti ernamesothatwecanuniquelydeterminewhichde nitioneachexternalidenti errefersto.Everytop-leveldeclarationisconsideredasacompilationunit.Becausesignaturesareusuallysmallandcompilingsignaturedeclarationsdoesnottakemuchtime,theirelaborationsaredelayedtobedoneatlinktime.Tocompileastructureorfunctordeclaration,weapplytheassumptioninferencealgorithmtoitsbody(whichisalwaysastructureexpression),generatethemachinecodeforthebody,andthenwriteboththeinferred interface(i.e.,theassumptionenvironment)andthemachinecodeintoitsbinary le.The nallinkingphaseisdoneincertainorderaccordingtothedependencyrelationamongdi erentmodules.Thisdependencyrelationhasbeenalreadyrecordedintheinferredinterfaceineachbinary le.Foreachmodule,thelinkersimplyreadsthebinary le,elaborateseverysignatureexpression,appliesthematchingalgorithm(i.e.,ModlMatch)torecoverthecorrectstaticenvironmentanddetectcross-moduletypeerrorsifthereareany,andthenconcatenatesthemachinecodewithcorrectthinningfunctions.6RelatedWorkMostdynamically-typedlanguagessuchasLispalsoallowindependentcompilationsandcanachievethesamekindof\smartestrecompilation"inthesensethatamoduleneverneedstoberecompiledunlessitsimplementationchanges.However,thisisbasedonabigsacri ce:cross-moduletypeerrorswillbedetectedonlyatruntime.Ourmethod,however,willdetectallcross-moduletypeerrorsatlinktime.Levy[18]presentsaseparatecompilationmethodverysimilartooursforPASCAL-likelanguages.Itscompileralsoautomaticallyinferstheimportinterfaceforeachcompilationunit.Cross-moduletypeerrorsarereportedatlinktime.Howeverhedoesnotmentionwhetherheachievesthesmartestrecompilationrule,andthetypesystemsofPASCAL-likelanguagesaremuchsimplerthanthatofSML.Traditionalseparatecompilationsystemsadoptedinmoststaticallytypedlanguagesallusemanuallycreatedinterface les.Eachcompilationunitcontainsanimplementationplusseveralinterface les.Ithastobefullycloseduptothepervasivebasissothatthespeci cationsofallexternalsymbolswillbefoundatcompiletime.Themakesystem[9]isthesimplestonealongthisline.Itwilltriggerrecompilationsiftheinterface leamoduledependsonchanges.Tichy[30]andSchwanke[29]eliminatedmostrecompilationsbyexamining ner-levelsofdependencyrelationsbetweeninterfacesandimplementations.Intheirmethods,iftheinterface leamoduledependsonchanges,butthesetofsymbolsthemoduleimportsdoesnotchange,thenthemoduledoesnotneedtoberecompiled.SRCModula-3[22,14]implementsexactlythesameidea:aversionstampwhichencodesthespeci cationofasymbolisproducedforeachexportedsymbolinaninterface;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;boththebinaryandthetimestamparethenwrittenouttothebinary le.Amodulehastoberecompiledwheneveritssourcechangesoranyofitspredecessors(inthedependencygraph)havebeenrecompiled.Gansnerisalsoplanningtoexportthestaticsemanticsofeachmoduleintothebinary lesothatredundantrecompilationscanbedetectedandavoidedifthestaticsemanticsofamodulehasnotbeenchanged. 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.Itisalsonotclearwhetherheralgorithmcanbemodi edtodoourassumptioninference.7ConcludingRemarksWehavepresentedaseparatecompilationmethodthatachievesthe\smartestrecompilationrule"foropen-formedmodulesinStandardML.Inourmethod,eachmoduleiscompiledindependentlywithoutknowingthespeci cationsofitsexternalidenti ers;itsimportinterface,instead,isinferredbylookingathoweachexternalidenti erisusedinsidethemodule.Cross-moduletypeinconsistenciesaredetectedatlinktimebysimplymatchingtherealspeci cationsagainsttheinferredimportinterface(thisprocessshouldbeveryfastbecauseitonlyinvolvesanuni cationofasetoftypes).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.Forapplicationswherereusabilityandrecon gurationaremoreimportantthaneciency,thesmartestrecompilationpropertyisstillverydesirable. AcknowledgementsWewouldliketothankWilliamAitken,CarlGunter,andQingMingMaformanyvaluablecommentsonanearlyversionofthispaper.WearealsogratefultoDavidMacQueenandPierreCregutforinterestingdiscussionsonrelatedsubjects.ThisresearchissupportedbytheNationalScienceFoundationGrantCCR-9002786andCCR-9200790,andbythe rstauthor'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'uni cationdanslestheoriesequationnelles.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.Gi ordetal.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.Atheoryofquali edtypes.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.TheDe nitionofStandardML.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,EnglewoodCli s,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.1isorganizedin veparts:the rstpartintroducessomenotationsandlemmasusedlaterintheproofs;therestfourpartsgivethedetailedproofs.8.1NotationsandLemmasBeforeweproceed,let'sintroducesomenewnotationsandlemmas:De nition8.1isa nitemapfromtypevariablestotypes.Theofasubstitution,denotedas),isthesetoftypevariablessuchthat.Theofasubstitutiondenotedas),istheunionofalltyvars()forallDom(.Asubstitutioniscalledavariable-substitutionifforallTyVarisatypevariable.Theoftwosubstitutionsdenotedas,is\se."Assumethatisasetoftypevariables,thesubstitutiondenotesthesubstitutionwithitsdomainrestrictedtoDom(Wede neanobjecttobeeitheratype,atypescheme,atypeenvironment,oratupleofotherobjects.Thesetoftypevariablesoccurredfreeinanobjectisdenotedas De nition8.2Givenanobject,arenamingsubstitutionforthisobjectisavariable-puresubstitution=1;:::;nsuchthat=1;:::;ng),thesaredistinctand(tyvars(=1;:::;n\f=1;:::;nDe nition8.3Twotypesarecalledvariantsifthereexistsubstitutionssuchthat,wecanalsode nevariantsrelationssimilarlyontypeschemes,typeenvironments,orobjectswithsameshapes.ThevariantrelationisdenotedasThevariantsrelationisobviouslyre\rexive,symmetricandtransitive,thusitisanequivalencerelation.\Vari-ants"isveryimportantincomparingtwoobjectsbecauseofthefollowinglemma:Lemma8.1Iftwoobjectsarevariants,thenthereexistarenamingsubstitutionandarenamingsubstitutionsuchthat=ID.Fromlemma8.1,toprovethesecondpartofthetheorem2.1,weonlyneedshowthat(TE;)and;S)arevariants.Herearesomeotherlemmaswearegoingtouseintheproof:Lemma8.2Givena nitesetofpairsoftypes,supposebotharethemostgeneraluni ersof,thenforanyobjectsarevariants.Lemma8.3Givena nitesetofpairsoftypes,thenthefollowingstatementsaretrue:IfUnifysucceeds,itwillreturnamguIfUnifysucceedsand,thenUnifyalsosucceeds;moreover,ififP2andS1isamguof,thenUnifyalsosucceeds.SupposeoseP2,Unifysucceedsandisamguof,andUnifysucceedsandamguof,thenUnifysucceedsandisamguofGivenarenamingsubstitution,supposeisaninversesubstitutionofinthesensethatID,thenUnifysucceedsifandonlyifUnifysucceeds.Moreover,ifisamguofPthen()isamguofInthe gure6wereviewTofte[31]'sversionoftheclassicalMLtypeinferencealgorithm.ThefollowinglemmacaneasilybeprovedbystructuralinductionontheexpressionLemma8.4GivenTEand,ifS;)=;esucceeds,and;issimplytheresultofanotherrunofthealgorithmonTEandbychoosingdi erentnewtypevariables,then;;arevariants.WeuseTyVartodenotethesetofnewtypevariablesusedinrunning;e)plusthosetypevariablesoccurredfreein.ThenweletonlyusenewtypevariablesfromTyVarTyVar.Fromlemma8.4,whicheversetofnewtypevariablesisusing,theresulting(;)isalwaysavariantofeachother.Thusitsucestoprovethattheorem2.1istruewhenareusingdi erentsetofnewtypevariables.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.Thecorrespondinguni cations)and;A)willsucceedtoo.Moreoverthereexistsfour(renaming)substitutionssuchthatthefollowingaretrue:,and!)and!!)and!!))and!!))and!Firstweprove))=).SupposeTTisthesetofpairsoftypestobeuni edinrunning;ATTwillcontaintypevariablesfromfromtyvars(A2)andsomenewtypevariables.Fromthede nitionofamgu,)shouldbetheidentityonalltypevariablesexceptthosein).BecausewearerunningRobinson'soriginaluni cationalgorithm,Reg()isasubset).Similarlyfromthede nitionofrenamingsubstitutions,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.Becauseweareusingdi erentnewtypevariablesin,andthecallof)and)areusingtotallydi erenttypevariables,thefollowingequationsareobviouslytrue:)=)and)=f;A[f)succeedsandisoneofitsmgu,bylemma8.3,f;AAA2[f)willalsosucceed.Moreover=(isoneofitsmgu.bethenewtypevariableusedin,let'sde ne.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!Firstwede nethefollowingnotations:letthetypeassumptionsforbe)==1;:::;ktyvars)be=1;:::;mtyvars)be=1;:::;ug[f=1;:::;v;weassumethatcontainssometypevariablesandsomenewtypevariables.Assumethat,where=1;:::;k=1;:::;m,arenewtypevariables,foreach=1;:::;k,wede nearenamingsubstitution=1;:::;m,anda=1;:::;m.Let.Assumethat,where=1;:::;k=1;:::;v,arenewtypevariables,foreach=1;:::;k,wede nearenamingsubstitution=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.Hereweinformallyusetomeanthedi erentinstancesof,correspondingtothoseWearegoingtoprovethatf=1;:::;k;AAC1A1[:::[CkA1[A2)succeedsinthefollowingtwosteps:Step1.1First,weprovethattheuni cation;AAC1A1[:::[CkA1)succeeds.Weshallconstructsuchmgu;AAssumethatwhendoing;A),thesetofnewtypevariablesintroducedbyinstantiatingboundvariablesin=1;:::;n.Let,where=1;:::;n=1;:::;k,benewtypevariables.Allthesetypevariablesvirtuallycorrespondstodi erentinstantiationsofboundvariablesinwhendoing;AAC1A1[:::[CkA1).Let'sde neasubstitutionforeach=1;:::;ksuchthat=1;:::;n.Wealsode nesubstitutions=1;:::;nforeach=1:::;k.Let'sdenotethesetoffreetypevariablestyvars)inby;:::;\r.Suppose;A)=Unify;y=1;:::;q).Thedomainofwillbe;:::; [f;:::; g[f;:::;\r.Theregionofwillbeasubsetof.Thereforeweknowforall)=.Wealsode ne[fij=1;:::;n=1;:::;kg[f=1;:::;m=1;:::;kBecauseDom()=,wede neasubstitutiontobetobeforeach=1;:::;k.Now;AAC1A1[:::[CkA1)isessentiallyequivalentto)where=(;y=1;:::;qg[[j=1f(Bjxi;C=1;:::;qThesubstitutionisconstructedasfollows,notethatthedomainofandtheregionofisasubsetofFirstwede neasubstitutionforeach=1;:::;ksuchthat )=then=1;:::;m)==1;:::;n)==1;:::;pWede neasubstitution)suchthat)==1;:::;m)==1;:::;n)==1;:::;pWealsode ne.ObviouslywehaveNowwecande nethesubstitution)=)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:isanuni erofProof)=)=)=)where=1;:::;qFromthede nitionof,weknowforeachtypevariable))=Thusforeach=1;:::;k,wehave)=))=))=)where=1;:::;qThesubstitution))isamostgeneraluni erof;C=1;:::;qProofWeknowforeachtypevariable))=)).ThusandthereforeGivenanuni er;C=1;:::;q,since)=)foreach=1;:::;qalsoanuni erof;y=1;:::;q.ThusthereexistsasubstitutionsuchthatThuswecanget=(Thisexactlymeansthatisamostgeneraluni er;C=1;:::;qisamostgeneraluni erofProofGivenanuni erwillbeanuni erfor;y=1;:::;qforeach=1;:::;k)isanuni erof;C=1;:::;q.Thusfromthede nitionofmgu,thereexists+1substitutions=0;:::;ksuchthatforeach=1;:::;k.Sincetheregionofisasubsetof,andforeach=1;:::;ktheregionofisasubsetof),wecanconstructasubstitution=0;:::;kfollows:Foreach),because)=,wede ne)= Forall=Reg(),wesimplyde ne)=Nowit'seasytoseeforall)=)),thatis,,thusisamostgeneraluni erofFromthede nitionof,weknowthatthefollowingaretrue:)=)=)=)=)=))=)))=(=1;:::;kStep1.2Weprovethattheuni cationf=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))=.Indoingtheuni cationf;;Athereareinstantiationsofthetype;).Suppose;),foreach=1;::;k,wede neasubstitution=1;:::;sarejustnewtypevariablesusedin.Andnowtheinstantiationsofthetype;)willbesimplyj;:::;kNoteDom())=andReg())=.Wealsode nesubstitutions=1;:::;sforeach=1;:::;kandasubstitution.Because isthesetoffreetypevariablesin),foreach=1;:::;k,thesetoftypevariablesinisessentiallyasubsetPV= [f.wecanconstructthefollowingrenamingsubstitutionfor=(PVWemakethefollowingtwoobservationsonNoticethatReg()==tyvars(S11)isasubsetofTV0.Foreachwillbemappedtosomefreetypevariablein)by.Thusdi erentboundtypevariables;)willbemappedbytodi erenttypevariablesin.Alsoforeach=1;:::;naccordingtothede nitionof,di erenttypevariablesinwillbemappedtodi erenttypevariablesinby().Thusisarenamingsubstitutionforbecauseitvirtuallymapsdi erenttypevariablestodi erenttypevariablesinForallfreetypevariables in)=).Thisisbecauseforidentitiesonalltypevariablesinandisanidentityonalltypevariablesin .Becauseallshaveconsistentde nitiononalltypevariablesin ,wecanalsode neSimilarlywelettodenotetheinversesubstitutionofsuchthatNowthatwehavealreadyknownthatf=1;:::;k;A)succeedsbyinductions,bylemma8.3,f=1;:::;k;Q))willalsosucceed, moreoverwillbeoneofitsmostgeneraluni er.Because))=))=)and)=1))=))and)=,wealsogetthatf=1;:::;k;S)succeedsandisoneofitsmostgeneraluni er.Thereforefromtheabovetwosteps,weprovethat=1;:::;k;AAC1A1[:::[CkA1[A2)succeeds,moreoverbylemma8.3,(isoneofitsmostgeneraluni er.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."Theentailmentrelationonconstraintsetsisde nedas:``ifandonlyifissatis ableand.First,weprovethefollowingseverallemmas.Theywillbelaterusedintheproofoftheorem2.6.Lemma9.1Givenasubstitutionandtwoconstrainedtypeschemes.If,thenProof)andletbetheinstantiationsubstitution=1;:::;n)=.Assumethat)and;:::; newtypevariableswhicharenotinReg().Let,thenmustbeoftheform)).Thereforede ningweget)))=))=)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.De nition9.1Givenanconstrainedtypescheme,itsimageMLtypescheme,denotedbyforget,iswhereareallthosesthatarefreein.SimilarlyweuseforgettodenotetypeenvironmentTEforgetLemma9.3C;isavalidtyping,and;``,letTEforget,thenTEisaProofBystructuralinductionontheexpression.Onlythecaseforletexpressionsisinteresting.ObviouslyC;mustbeinferredfromtheassumptionsthatbothC;f;g`arevalid,and``.Because;``,thus;``.Byinductions,bothf;g`arevalid.Fromthede nitionofforget)holds,thus;;).Thereforef;Sg`)isalsoavalidMLtyping.So)isavalidMLtyping.Proofoftheorem2.6(Part1)Supposethat(S;)=;e)succeeds,wewanttoprovethat(;)=;e)alsosucceeds.We rstconstructanMLtypeenvironment7!8j;)whereDom()=.Obviously)=)=).Because(S;)=;esucceeds,fromthesoundnesstheoremofthealgorithm,weknowthatisavalidMLtyping.ThenthetypedeductiontreeofcanbeeasilytransformedintoaMLtypedeductiontree;S,thereforeweprovethat;SisalsovalidinML.Becauseforeach),andbytheorem2.4,(;)=;e)alsosucceeds.Moreoverthetyping;Sismoregeneralthan;S.Fromthede nition2.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))=;Fromthede nition8.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.3StaticSemanticsofModLThegrammarofModLandthesemanticobjectsusedherearethosegivenin gure3.Givenafunctor=()),afunctorinstance())isaninstanceof,writtenifthereexistsarealizationsuchthat))=())andDom(.Alsoweuse)todenotethesetofnamesoccurredfreeintodenote`)fgstrdecstrdecstrdecdec1strdecdec1)=decEm=((NamesetofofNames(E))aB`structdecendm;Estrexpm;E)=strexpstrexpSBfctid(Namesetofstrexpstrexpstrexp)f