/
Finally,wecancreateactualrecordsby“adding”differencestotheem Finally,wecancreateactualrecordsby“adding”differencestotheem

Finally,wecancreateactualrecordsby“adding”differencestotheem - PDF document

marina-yarberry
marina-yarberry . @marina-yarberry
Follow
372 views
Uploaded On 2016-03-23

Finally,wecancreateactualrecordsby“adding”differencestotheem - PPT Presentation

afgvalabadd abfgvalbcadd bcfgWhentranslatedtothedualextensibilityofrecordsbecomesextensibilityofcodeHereisafunctionrepresentingthedifferencebetweentwocodefragmentsoneofwhichcanhandlecaseAwhile ID: 266854

afgvalab=add abfgvalbc=add bcfgWhentranslatedtothedual extensibilityofrecordsbecomesexten-sibilityofcode.Hereisafunctionrepresentingthedifferencebe-tweentwocodefragments oneofwhichcanhandlecase`Awhile

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "Finally,wecancreateactualrecordsby“..." 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

Finally,wecancreateactualrecordsby“adding”differencestotheemptyrecord:vala=add afgvalab=add abfgvalbc=add bcfgWhentranslatedtothedual,extensibilityofrecordsbecomesexten-sibilityofcode.Hereisafunctionrepresentingthedifferencebe-tweentwocodefragments,oneofwhichcanhandlecase`Awhiletheother,representedbytheargumentc,cannot:funadd Ac=cases`A()�=print"A"default:cNotethatfunctionadd Acorrespondstoadd aofthedual.Thetypeinferredforadd Ais:valadd A:( &#x]TJ/;༩ ;.96; Tf;&#x 23.;Զ ;� Td;&#x[000;,!())!(of(), &#x`A-5;─,!())Hereatypehi,!denotesthetypeofrst-classcaseswherehiisthesumtypethatisbeinghandledandistheresult.Onecanthinkof,!asanalternativefunctionarrowwhoseeliminationformwillbediscussedbelow.Examplesforfunctionsadd Bandadd C(correspondingtoadd bandadd cinthedual)are:funadd Bc=cases`B()�=print"B"default:cfunadd Cc=cases`C()�=print"C"default:cAsinthedual,wecannowcomposedifferencefunctionstoobtainlargerdifferences:funadd ABc=add A(add Bc)funadd BCc=add B(add Cc)Byapplyingadifferencetotheemptycasenocasesweobtaincasevalues:valcase A=add Anocasesvalcase AB=add ABnocasesvalcase BC=add BCnocasesThesevaluescanbeusedinamatchform.Thematchconstructistheeliminationformforthecasearrow,!.Thefollowingexpres-sionwillcause"B"tobeprinted:match`B()withcase BCThepreviousexamplesdemonstratehowfunctionalrecordexten-sionintheprimalcorrespondstocodeextensioninthedual.Thisformsthebasisforourproposedsolutiontotheexpressionprob-lem.Inthenon-recursivecase,codeextensionisasstraightforwardasshownabove.Section2discussesextensibleCPSconversionasarealisticexamplewherearecursivetypeisextendedinaninter-estingway.2.Casestudy:CPSconversionLetusconsiderarecursivesumtypewhosevaluesrepresentun-typed-terms.WeuseaScheme-likecalculus[21]withmulti-parameterfunctions.3Variables`Varxarerepresentedbysmallintegersx,applications`App(e,~e)byanoperatoreandalistofoperands4~e,and-abstractions`Lam(~x,e)byalistofboundvari-ables~xandabodye.Wealsoincludeconstants`Conc.Termswhoseoutermostconstructoris`Con,`Varor`Lamarecalledsyntacticvalues.Acommonlyconsideredrenementofthetermtyperestricts`Apptoonlytakesuchsyntacticvalues.ThisisknownastheCPS-restriction,sinceassumingaparticulareval-uationstrategy(e.g.,call-by-value,left-to-right)everyunrestrictedtermcanbeconvertedintoan“equivalent”CPS-termbymakinguseofC ontinuation-P assingS tyle. 3Aswewillseebelow,ourCPS-converterrequiresthisfeaturetoaccom-modatecontinuationarguments.4Weusethevector-arrownotationasin~atoindicatevariablesorsub-termsthatarelists. funkv2kbkv=v:`App(kv,[v])funkb2kvkb=withfresh(xr:`Lam([xr],kb(`Varxr)))funcvt app(e,~e,kv)=letfunlc([],kb)=kb([])|lc(e::~e,kb)=pc(e,~e,(v;~v):kb(v::~v))andpc(e,~e,kb)=cvt(e,v:lc(~e,~v:kb(v,~v)))inpc(e,~e,(v;~v):`App(v,kv::~v))endandcvt lam(~x,e)=withfresh(xk:`Lam(xk::~x,cvt(e,kv2kb(`Varxk))))andcvt(e,kb)=matchewithcases`Coni)kb(`Coni)|`Varx)kb(`Varx)|`Lam(~x,e))kb(cvt lam(~x,e))|`App(e,~e))cvt app(e,~e,kb2kv(kb))funconverte=cvt lam([],e) Figure1.AsimpleCPS-converter.Whenconverting`App,thecontin-uationbuilderkbmustbeturnedintoasyntacticvaluekvthatcanbepassedasanadditionalargument;thiskvisanew`Lamwithasingleparameterxrandabodyobtainedbyapplyingkbtoxr(seefunctionkb2kv).Conversely,toconverta`Lam,anextraformalargumentxkrepresentingthecontinu-ationisadded.Thecorrespondingkbsimplyconstructsan`Appofxktowhateverargumentvisgiventokb(seefunctionkv2kb).Forclarity,thecodefor`Appand`Lamhasbeenseparatedoutintofunctionscvt appandcvt lam;cvt appuseshelperfunctionslcandpctorecursivelyconverttheoperatoreandalloperands~e.FollowingAppel[1],theconversioncanbeperformedinessentiallylineartimeusinganapproachthatcouldbecalled“continuation-builderpassingstyle”wheretheconverterfunctioncvt(seeFigure1)receivestheexpressionetobeconvertedandkb,thecontinuationbuilder,whichrepresentsthecontextinwhicheappearedwithintheoriginalexpression.Oncetheconvertercomesupwithasyntacticvaluevfortheresultofe,kbisinvokedonthisvinordertoproducetheCPSexpressionrepresentinge'soriginalcontext.2.1Variants,polymorphism,subtyping,andrenementAsexplainedintheintroduction,ourlanguageMLPolyRhaspoly-morphicsumtypesinthestyleofOCaml.5ThetypesystemisbasedonR´emy-stylerowpolymorphism,handlesequi-recursivetypes,andcaninferprincipletypesforalllanguageconstructs.Forfunc-tionconvertinFigure1,thecompilercalculatesthefollowingtype:valconvert:8 :8:f`Appg;:f`Con,`Lam,`Varg:(asAppof(,[]),`Conof ,`Lamof([int],),`Varofint&#x`-10;)!(asConof ,`Lamof([int],Appof(,[]),&#x`-10;),`Varofint,&#x`-10;)Hereisarecursivesumtype,indicatedbykeywordasandatyperowenclosedin:::&#x]TJ/;༩ ;.96; Tf;&#x 9.4; 0;&#x Td[;;canclearlyberecognizedasthetypeoflambdaexpressions.6Similarly,typeisthetypeofsyntacticvalues.Functionconvertispolymorphicin ,thetypeofvaluescarriedby`Con.Finally,andarerowtypevariablesconstrainedtoaparticularkind.Thekindisasetoflabelsthatmustbeabsentinanyinstantiation.LikeinStandardML,thetypeprinterinourcompilerdoesnoteverprintuniversalquantiersforordinary 5Infact,evenoursyntaxforconstructorsisinspiredbyOCaml'schoice.6WeuseHaskellnotation[t]forMLPolyR'sbuilt-inlisttype. funcvti cother c(cvt,kb)=cases`If(ec,et,ee)):::asbefore:::default:other c(cvt,kb)funcvtc cother c(cvt,kb)=cases`LetCC(xc,e)):::asbefore:::default:other c(cvt,kb)funconvertie=mkConvert(cvti ccvt c,e)funconvertce=mkConvert(cvtc ccvt c,e)funconvertcie=mkConvert(cvtc c(cvti ccvt c),e) Figure5.Extensionsparameterizedbywhatisbeingextended.representingthecurrentcontinuation.7InCPS-convertedcode,thecurrentcontinuationisalwaysdirectlyavailableasavalue,mean-ingthat`LetCCcanbesupportedwithoutneedforanewlanguageconstructintheoutputlanguage.Asaresult,theextensionshowninFigure4extendstheinputlanguageonly.2.4LinearlycomposableextensionsOnemajorweaknessofthetwoextensions(`Ifand`LetCC)shownsofaristhattheyarenotorthogonalsinceeachofthemexplicitlyextendstheoriginalconverterratherthananother,poten-tiallyalreadyextendedversion.Butwiththemechanismsshown,thisdeciencycanbeovercomequiteeasilybyparameterizingtheextensionoverwhatisbeingextended.TheresultingpatternisshowninFigure5.Noticehowthetwoextensionshavebecomedifferencesinthesenseexplainedintheintroduction,sotheyarenowcomposable.Wecanthinkofthemaslayersoffunctionalitythatcanbe“stacked.”Onecantaketheideaofextensioncompositiontotheextremebyusingaprogrammingstyle(or“pattern”)whereeverycaseiswrittenindividuallyasasinglelayerintheabovesense.Givenksuchlayers,onecaneasilygenerateaconverterforanyofthe2kpossibleinputlanguagessimplybystackingthecorrespondingsub-setoflayers.Tosupportthisidea,MLPolyRprovidesthesyntacticformnocasesoftypehi,! forany .Thisformrepresents“nofunctionality”andcanbeusedasthe“base”uponwhichtostack.3.ThePolyRLanguageThissectiondescribesanidealizationofMLPolyR,calledPolyR,withpolymorphic,extensiblesums,records,andrst-classcases.TocompilePolyR,wersttranslateitintoaversionofSystemF,calledFR(Section3.2).FRhassupportforrecordsbutnotforsums.Forbrevity,wegivethestaticsemanticsforPolyRandthetranslationtoFRtogether(Section3.3).Section3.5describesthetranslationfromFRintoanuntyped-calculus.3.1AbstractSyntaxFigure6showstheabstractsyntaxforthelanguagePolyR.Themeta-variablexanditsvariantsrangeovervariables.Meta-variablelandvariantsrangeoveranunspeciedsetoflabels.Metavariables and (andvariants)rangeovertypeandrow-typevariablesre-spectively.Variables,labels,typevariables,androw-typevariablesaremutuallydisjointsets.Thetypesofthelanguageareseparatedinto(ordinary)types(denotedbyandvariants),row-types(denotedbyandvariants),andtypeschemas(denotedbyandvariants).Thetypesconsistoftypevariables ,thebasetypeint,functiontypes,recordtypes(fg),sumtypes(hi),recursivesumtypes( ashi),andcase 7`LetCC(x,e)isthesameasScheme's(call/cc(lambda(x)e))[21]. ::= jintj1!2jfgjhij ashijhi,!::= jjl:;::=fl1;:::;lkg::=8( 1;:::; m):8( 1:1;:::; n:n):v::=njfunfx=ejlvjfli=vigki=1jflixi)eigki=1e::=njfunfx=ejxjleje1e2jletx=e1ine2jfli=eigki=1je1 fl=e2gje ljflixi)eigki=1je1flx)e2gje lje:ljmatche1withe2 Figure6.TheabstractsyntaxofPolyR. ::= jintj1!2jfgj asj8( 1;:::; m):8( 1::1;:::; n::n):::= j jjl:;::=fl1;:::;lkgv::=njfunfx:=ejfli=vigki=1j( 1;:::; m):( 1::1;:::; n::n):ee::=xjnjfunfx:=ejletx:=e1ine2( 1;:::; m):( 1::1;:::; n::n):eje1e2je[1;:::;m][1;:::;n]jfli=eigki=1je:lje1 fl=e2gje l Figure7.TheabstractsyntaxofFR.types(hi,!).WedenotethesetoffreetypevariablesofatypebyFTV()andthatofatypingcontext�byFTV(�).Row-typesconsistofarow(-type)variables ,andpossiblyemptysequencesoflabelandtypematchings.ThesetoffreerowtypevariablesofatypeisdenotedbyFRV().Forthatofatypingcontext�wewriteFRV(�).Therecursivesum ashispeciesasumtypewherethetypevariable canrecursivelyoccurinthedenitionof.Typeschemasrelyonkinds,denotedbyandvariants,denedassetsoflabels.Kindsareassociatedwithrowvariablesandspec-ifythelabelsthatarowvariablemustnotcontain.Typeschemas,denotedby(andvariants),aredenedas::=8( 1;:::; m):8( 1::1;:::; n::n):Thequantiersbindoccurrencesoftypevariablesf 1;:::; mgandofrowvariablesf 1;:::; mgthatarefreein.Thekindsoftherowvariablesaregivenbyf1;:::;ng.Expressionsconsistofvalues,functions,variables,datatypeconstructors(le),applications,letbindings,recordexpressions,caseexpressions,andcases.Recordexpressionsconsistofrecordconstructorsfl1=e1;:::;lk=ekg(whichwewilloftenab-breviateasfli=eigki=1),recordextensionse1 fl=e2g,recordsubtractionse l,andrecordselectionse:l.Caseex-pressionsaresymmetrictorecordsandconsistofcaseconstructorsfl1x1)e1;:::;lkxk)ekg(abbreviatedasflixi)eigki=1),caseextensionse1flx)e2g,andcasesubtractionse l.Amatchexpressionmatche1withe2matchese1totheexpres-sionse2whosevaluemustbeacase.Valuesconsistofnumbers,namedfunctions,recordswhereeacheldisavalue,andcases.3.2SystemFPolyRexpressionscanbetranslatedintoexpressionsofavariantofSystemFwithrecordsandnamedfunctions.Wecallthislan-guageFR.Figure7showsthesyntaxoftheFRlanguage.(Fortherestofthepaperwewillusetheterms“SystemF”andFRin-terchangeably.)ThelanguagecanbederivedfromPolyRbyex- �(x)=8 1::: m:8 1::1::: n::n:08i:`iok8j:(`jok)^(`jnj)=0[i= i;j= j]i=1:::m;j=1:::niIiiIiI ;�`x:Ix[1;:::;m][1;:::;n]:(var);�`e:Ie:0 ;�`e:0Ie:(reorder) ;�`n:intIn:int(int);�;f:2!;x:2`e:Ie:`2ok2I2 ;�`funfx=e:2!Ifunfx=e:2!(fun);�`e:Ie:`(l:;)ok(l:;); I ;�`le:hl:;iI(letxv:=ein :fun xr=xr:lxv):8 :fg! (dataconst.);�`e1:2!Ie1:2!;�`e2:2Ie2:2 ;�`e1e2:Ie1e2:(app)~ = 1;:::; m=FTV(1)nFTV(�) 1;:::; n=FRV(1)nFRV(�)���! ::= 1::1;:::; n::n;���! ::;�`e1:1Ie1:1;�;x:8~ :8���! :::1`e2:2Ie2:2e1isasyntacticvalue ;�`letx=e1ine2:2Iletx:8~ :8���! :::1=~ :���! :::e1ine2:2(let/val);�`e1:1Ie1:1;�;x:1`e2:2Ie2:2e1isnotasyntacticvalue ;�`letx=e1ine2:2Iletx:1=e1ine2:2(let/non-val);�`e:h[ ashi= ]iIe:[ as= ] ;�`e: ashiIe: as(roll);�`e: ashiIe: as ;�`e:h[ ashi= ]iIe:[ as= ](unroll) 8i:;�`ei:iIei:i`l1;:::;lkok ;�`fli=eigki=1:fli:igki=1Ifli=eigki=1:fli:igki=1(r) 8i:(;�`iok)^(;�;xi:i`ei:Iei:)`l1;:::;lkok8i:(iIi) ;�`flixi)eigki=1:hli:iiki=1,!Ifli=fun xi:i=eigki=1:fli:i!gki=1(c) ;�`e1:fgIe1:fg`nflg;�`e2:2Ie2:2 ;�`e1 fl=e2g:fl:2;gIe1 fl=e2g:fl:2;g(r/ext) ;�`e1:hi,!Ie1:fg`nflg`1ok1I1;�;x:1`e2:Ie2: ;�`e1flx)e2g:hl:1;i,!Ie1 fl=fun x:1=e2g:fl:1!;g(c/ext) ;�`e:fl:;gIe:fl:;g ;�`e l:fgIe l:fg(r/sub) ;�`e:hl:1;i,!Ie:fl:1!;g ;�`e l:hi,!Ie l:fg(c/sub) ;�`e:fl:;gIe:fl:;g ;�`e:l:Ie:l:(select) ;�`e1:hiIe1:8 :(f g! );�`e2:hi,!Ie2:fg ;�`matche1withe2:Ie1[]e2:(match) Figure10.Thestaticsemanticsandtranslationforbasicterms(top),andrecordsandcases.motivationsbehinddifferentiatingbetweensyntacticvaluesandnon-values:1)itensuresthatthetransformationtoSystemFpre-servesnon-terminationsemanticsoftheprogram,and2)itmakesiteasiertoextendthelanguagewithsideeffects(e.g.,references).Whenused,avariablewithapolymorphictypeisinstantiatedtoanon-polymorphictypebyselectingtypesandrowtypesforitspolymorphicvariables(varrule).AninstantiationistranslatedintoSystemFasatypeapplication.ThebottomboxinFigure10showsthetypingrulesforrecords(left)andcases(right).Thejudgmentsarearrangedtobringoutthesymmetrybetweentheserules.Arecordconstructorisassignedtherecordtypethatmapsthelabelstothetypesofthecorrespondingeldsaslongasthelabelsaredistinct.Thetypeofarecordextensione1 fl=e2gisarecordtypethatextendsthetypefgoftherecorde1withthelabellundertheconditionthatlisnotincludedintherecordtype.Thetypeofarecordsubtractione lisarecordwherelabellisexcludedundertheconditionthatecontainsl.Thetypeofarecordselectionisthetypeoftheeldlbeingselected,undertheconditionthattherecordexpressioncontainstheeldwithlabell.SincetheFRlanguageincludestherecordexpressionsincludedinPolyR,allrecordexpressionsaretranslatedintotheFRlanguagedirectly.Acaseconstructorisassignedacasetypethatidentiestheresulttypeofthebodies(ei's)andmapseachlabellitoitsdomaintypei.Acaseistranslatedintoarecordoffunctions,oneforeachlabelli,whoseargumenttypeisequaltothedomaintypeiofliandwhosebodyisthebodyofthecaseei.Acaseextensionextendsthetypeofacasewithanewbranch.Acaseextensionistranslatedtoarecordextension.Acasesubtractiontakesoutthespeciedbranchfromacasetypeandtranslatesit `nBn(int) `xBx(var)`eBt `funfx:=eBfunfx=t(fun)`e1Bt1`e2Bt2 `e1e2Bt1t2(app)`e1Bt1`e2Bt2 `letx:=e1ine2Bletx=t1int2(let)`eBtt0=indexOf(;l;labels(typeOf(e))) `e:lBt:t0(select)8i;j:ij)l#(i)ll#(j)fl#(1);:::;l#(n)g=fl1;:::;lng8i:(`eiBti) `fli=eigni=1Bletx1=t1in:::letxn=tnin x#(i) ni=1(r)`e1Bt1`e2Bt2t0=indexOf(;l;labels(typeOf(e1))) `e1 fl=e2gBletx=t1inh(x;0;t0);t2;(x;t0;len(x))i(r/ext)`eBtt0=indexOf(;l;labels(typeOf(e))) `e lBletx=tinh(x;0;t0);(x;t0+1;len(x))i(r/sub);:::; i::f(l1i;x1i);:::;(lmii;xmii)g;:::`eBt8i:1in:i=fl1i;:::;lmiig `( 1; k):( 1::1;:::; n::n):eBx11:::xm11:::x1n:::xmnn:t(ty/abs)`eBttypeOf(e)=8( 1::1::: n::n):8i:1in:i=fl1i;:::;lmiig8i2f1;:::;ng8j2f1;:::;mig:tji=indexOf(;lji;(Li[i;0i))where(Li;0i)=labels(fig) `e[1;:::;k][1;:::;n]Btt11:::tm11:::t1n:::tmnn(ty/app) Figure13.ThetranslationfromtheFRintotheLReclanguage.Therecordextensione1 fl=e2gistranslatedbyrstndingtheindexoflinthetuplecorrespondingtoe1,thensplittingthetupleintotwoslicesatthatindex,andnallycreatingatuplethatconsistsofthethesetwoslicesalongwithasliceconsistingoftheneweld.Similarly,recordsubtractionsplitsthetuplefortherecordimmediatelybeforeandimmediatelyafterthelabelbeingsubtractedintotwoslicesandcreatesatuplefromtheseslices.Typeabstractionsaretranslatedintofunctionsbycreatinganargumentxjiforeachlabelljiinthekindiofthe i.Notethatabstractionsofordinarytypevariables( i's)aresimplydropped.Typeapplicationsaretransformedintofunctionapplicationsbygenerating“evidence”foreachsubstitutedrow-typevariable.Aswithtypeabstractions,substitutionsintoordinarytypevariablesaredropped.Evidencegenerationrequirescomputingtheindicesofeachlabellji2iinanyrecordtypethatextendsfigbyaddingeldsforeverysuchlji.4.ImplementationThecompilerforMLPolyRiswritteninStandardML.Itcompilestorelativelysimple,yetreasonablyefcientPowerPCassemblycodethatcanbeassembledandexecutedunderMacOSX.4.1BasiclanguagefeaturesAscurrentlyimplemented,theMLPolyRlanguagetakesasmallsubsetoftheStandardMLcorelanguageandextendsitwiththefollowingfeatures:Ohori-stylerecordpolymorphismpolymorphicfunctionalrecordextensionandpolymorphicfunctionalrecordtrimming(droppingofeldsvia“rowcap-ture”patterns)inferredrow-polymorphicsumtypesandequi-recursivetypesextensiblerst-classcasesmutablerecordelds4.2CompilerPhasesThecompilerisstructuredinafairlytraditionalwayandconsistsofthefollowingphases:lexerlexicalanalysis,tokenizationparserLALR(1)parser,generatingabstractsyntaxtrees(AST)elaboratorperformtypereconstructionandgenerationofanno-tatedabstractsyntax(Absyn)translategenerateindex-passingLReccodeanf-convertconvertLReccodeintoA-normalform[7]attenattenarguments,eliminatingmostrecord-andtupleargu-mentsbypassingeldsseparately(i.e.,inindividualregisters)uncurryeliminateofmostcurriedfunctionsanf-optimizeconstantfolding,simpleconstant-andvaluepropa-gation,eliminationofuselessbindings,short-circuitselectionfromknowntuples,inlinetinyfunctions,somearithmeticex-pressionsimplication;executionofthispassisrepeatedandinterleavedwithotherphases(e.g.,attenanduncurry)closureconverttorst-ordercodebyclosureconversionclustersseparateclosure-convertedblocksintoclustersofblocks;eachclusterroughlycorrespondstoasingleCfunctionbutmayhavemultipleentrypointstreeifyre-growlargerexpressiontreestomaketree-tilinginstruc-tionselectionmoreusefultraceschedulearrangebasicblockstominimizeunconditionaljumpscginstructionselectionbytree-tiling(maximum-munchalgo-rithm)regallocgraph-coloringregisterallocationemitgenerateassemblycode4.3Type-checkingandtranslationTypereconstructionisperformedbyavariantoftheclassicalgo-rithmW[19],augmentedtohandleR´emy-stylerowpolymorphismandequi-recursivetypes.Resemblingthecorrespondingpartsofothercompilers(e.g.,SML/NJ[2]),theprocessoftypecheckingandtranslationisdividedintotwophases:elaborationandtransla-tion.Theelaborationphasetakesanabstractsyntaxtreeandanno-tatesitwithtypeinformation,usinganimperative-styleunicationalgorithmasasubroutine.Itpermitsequi-recursivetypesaslongastype-levelrecursiongoesthoughatleastonesumtype8byselec- 8Thisisapragmaticimplementationdecisionbasedonexperiencewithfullygeneralequi-recursivetypesthatseemstoindicatethatmostofthetimewhensuchatypeisinferreditwasnotactuallyintendedbytheprogrammer[17]. expressionswhereitcaneasilybeinlined,thecodepointerdoesnotneedtoberepresentedatall.Thisleavesuswitharepresentationofthevariantasapairconsistingjustofilandv: Butthatispreciselythe“traditional”representationoftaggedunions,ilplayingtheroleofthetag.Spaceissavedbytheelimi-nationofthecodepointerandpossiblythesecondindirection.Thetimesavingsareduetotheinliningofthecode,sincegeneralfunc-tioncalloverhead,thememoryaccessforobtainingtheentryad-dress,andtheneedforanindirectjumpdominatethecostofthenaiveimplementation.Thisoptimizationisimplementedquiteconvenientlyaspartofourtranslationphase.Thefactthat,ashasbeennotedabove,weskipSystemFhaspracticalbenetshere.Normally,whengenerat-ingplainSystemFcode,wewouldloseinformationonwhichoftheclosurescorrespondtosumvalues,andwhichapplicationscor-respondtomatch.Thisinformationwouldeitherhavetoberecov-eredbysomeowanalysisorpreservedusingad-hocannotationonSystemFterms.4.6CoherenceIncoherencemanifestsitselfinthetranslationphaseasanon-generalizedanduninstantiatedtypevariable.Sincethetransforma-tiondiscardsordinarytypevariables,thelackofcoherenceonlymatterswhenitinvolvesrowtypes.Hereisaconcreteexampleforhowthismighthappen: funloop()=loop()valx=(loop()).a Thetypeofloopisinferredtobe8 :()! .Thetypingruleforeldselectioncanpickanarbitraryinstantiationfor aslongasitisarecordcontainingaelda.Buttheunderspeciedshapeoftheinstantiationdeterminestheindexforaccessinga!Notice,however,thatloop()doesnotproducearecordvalue.Infact,itwillneverreturnatall,sotheindexforadoesnotmatteratruntime.Intheelaboration/translationalgorithm,thissituationmanifestsitselfasanuninstantiated(unication-)rowtypevariable.Thephenomenonofcoherence(orrather:thelackthereof)iswell-knownandhasbeenstudiedinthecontextofthetranslationofMLintoanexplicitlytypedcalculus(avariantofSystemF)byOhori[23].ItwaslaterrediscoveredinthecontextofHaskell'stypeclassmechanism[14].LikeinSML#,wecantakeadvantageofwhatamountstoaparametricityresultforML,namelythatclosedprogramsare,infact,coherent.10Intuitively,wheneverincoherenceoccurs,theactualchoiceoftypewillnotmatteratruntimebecausethecodeinquestionwillnevergetexecuted.Ourcompiler(likeOhori's)picksarbitraryindexvaluesforlabelsthatbelongtounin-stantiated(unication-)rowtypevariables.4.7RuntimesystemTheruntimesystem,writteninC,implementsasimpletwo-spacecopyinggarbagecollector[13]andprovidesbasicfacilitiesforinputandoutput.Datarepresentationandmemorymanagement:Forthetracinggarbagecollectortobeabletoreliablydistinguishbetweenpoint-ersandintegers,weemploytheusualtaggingtrick.Integersare31-bit2's-complementnumbers.Anintegervalueiisrepresentedinternallyasa2's-complement32-bitquantityofvalue2i.Thismakesallintegerseven,withtheirleastsignicantbitscleared. 10ThesameargumentdoesnotworkforHaskell,becauseduetotypeclassesHaskell'spolymorphismisnotparametric.Heappointers,ontheotherhand,arerepresentedasodd32-bitval-ues.Ineffect,insteadofpointingtothebeginningofaword-alignedheapobject,theypointtotheobject'ssecondbyte.Generatedload-andstore-instructionsaccountforthisskewbyusinganaccord-inglyadjusteddisplacementvalue.Withthisrepresentationtrick,themostcommonarithmeticoperations(additionandsubtraction)canbeimplementedassingleinstructionsasusual;theydonotneedtomanipulatetagbits.Thesameistrueformostloadsandstores.Allocation-andlimitpointersarestoredinregisters,andtakingadvantageofthePowerPC'sstwuinstructionwecanallocateonememorywordinasingleinstruction.11Asmentionedbefore,thecodeforcopyingasliceoutofanexistingrecordintoanewlyallocatedoneusesaninnerloopofonlythreeinstructions(lwzu,stwu,bdnz),butthereisalsoafour-instructionpreamble(addi,srwi.,mtctr,beq)thatloadsthecountregisterandbypassestheloopwhenthecountisinitiallyzero.TheStringmodule:Ourlanguagedoesnotyethaveamodulesystem,butaslongasonlyvaluesbutnotypesareinvolved,onecanuserecordsasapoor-man'ssubstitute.TheruntimesystemexportsaspecialrecordboundtotheglobalvariableStringwhichcontainsroutinesformanipulatingstringvalues,forconvertingfromandtostrings,andforperformingverybasicinput-outputoperations.ThisrecordisallocatedusingCcodeanddoesnotresidewithintheMLPolyRheap.4.8MutablerecordeldsOurtypesystemsupportsmutableeldsinrecords.Typerecon-structionstillworkssincecorrespondingoperationsonmutableandimmutableeldsaresyntacticallydistinguishable.Recordswithmutableeldshaveidentity,andallocationofsuchrecordsisaside-effectingoperation.Inhindsightitappearsthatitwouldhavebeenbettertoinsteaddistinguishbetweentwokindsofrecords:thosethatareguaranteedtobeimmutable,andthosethatmaycontainmutableelds.Muta-bilityinteractsinsomeundesirablewayswithrowpolymorphism.Forexample,wecannotsaythattheright-handsideinthefollow-inglet-bindingisasyntacticvalueand,therefore,itstypecannotbegeneralized: letvalr=fa=foo,...=barg Whetherornottheallocationofthisrecordexpandsthestoredependsonthetypeofbar.Ignoringtheproblemwiththevaluerestriction,inthegeneralcasethecompilerisunabletoperformcertainoptimizationssuchas,e.g.,commonsubexpressionelimi-nationforcodelikethis: letvalr1=fa=foo,...=bargvalr2=fa=foo,...=barg Therefore,withourcurrentdesign,themereexistenceofthemutableeldsfeatureinthelanguageincurscertainpenalties,bothintermsofthestaticsemanticsandintermsofruntimeefciency,evenifthatfeatureisneverused.Sincewepreferapay-as-yougoschemewherefeaturesincurpenaltiesonlywhentheyareactuallybeingused,weplantogobacktoimmutablegeneralrecordsinthestyleofStandardMLandsupportmutableeldsseparately.5.RelatedworkRecordcalculiandthestudyofrecordpolymorphismhavealonghistory[31,32,26,5,25].Ohorishowsthatpolymorphicrecords 11Thecostoftheheaplimitcheckisamortizedovermultipleallocationswithinabasicblock. canbecompiledveryefciently,usinganindex-passingtransfor-mationbasedonakindedtypesystemforrecords[25].Healsopointsoutthedualitybetweenrecordsandsumsandsuggeststhatthesameindex-passingtechniquescanbeadoptedtoimplementpolymorphicsums.R´emygivesamoregeneraltypesystemcapableofexpressinglinearlyextensiblepolymorphicrecords.R´emy'scal-culusemploysrowpolymorphismandhasanefcienttyperecon-structionalgorithmthatinfersprincipaltypes[26].JonesandPey-tonJonesdescribeanimplementationofextensiblerecordsbasedonthesameideasforHaskell[15].GasterandJonesattemptadirectencodingofthedualconstruc-tionforsumtypeswithinHaskell'stypesystem[12].Theencodingrequirestypesystemfeaturesabsentfrommostlanguages,inpar-ticularhigher-orderpolymorphismandatypeconstructorwhichroughlycorrespondstotherowarrowinourSystemF.Typeinferenceinsuchasystemseemsdifcult,and,indeed,GasterandJonesreportthattheyhadtoimposeanad-hocrestrictiontoobtainmostgeneraluniers.Theirrestrictionistodisallowemptyrows,meaningthattheycouldnottypeournocasesconstruct.GarrigueimplementsaversionofpolymorphicsumtypesinOCaml.Hisapproachdoesnottakeadvantageofthedualitybe-tweensumsandrecordsbutinsteadprovidesaformofextensibil-itybasedonso-calledvariantdispatching[10,11].AsZengerandOderskypointout[33],variantdispatchingrequireswritingaddi-tionalfunctionstoforwardcontroltoexistingcode.Thisisacon-sequenceofthefactthatinGarrigue'ssystem,extensionsneedtoknowwhattheyareextending.Asaresult,extensionscannotbecomposeddirectly.ItshouldbenotedthatasuitablymodiedtypingruleforamatchexpressionwithadefaultcasecouldactuallybeusedtogiveGarrigue'simplementationthesamepowerofextensibilitythatweprovideinMLPolyR.Considerthefollowingexample:fungy=:::funfx=matchxwith`A())print"A"|y)gyHerethetypesofxandyshouldberelatedsumsthatshareacommonrow,theonlydifferencebeingthepresenceofthe`Aconstructorinx'stypeanditsabsenceiny'stype.Thetypingruleforthiscouldbe: �`e1:hl:l;i�;x:l`e2:�;y:hi`e3: �`matche1withlx)e2jy)e3: Thisapproachdoesnotrequirethealternativefunctionarrow,!forcasesbutusestheordinaryfunctionarrowinitsplace.Themainadvantageofhavingthecasearrow,!inthetypesystemandstaticallydistinguishingcasesfromotherfunctionsliesinthefactthatthismakesitveryeasytousedifferentruntimerepre-sentationsforthetwo.Inparticular,wecanrepresentMLPolyRcasesasrecordsoffunctions.Theserecordsrepresentjumptables.InGarrigue'simplementation,however,caseanalysisforpolymor-phicvariantsproceedsbydirectcomparisonsofconstructornames(signicantlyspedupviahashing).Thus,hisimplementationtech-niqueessentiallycorrespondstooursemanticsofPolyR.Inthissetting,extendingfunctionsbyextracasescanbeimplementedbysimplechainingofconditionals.6.ConclusionsWehavepresentedMLPolyR,alanguagewithrowpolymorphismforbothrecordsandsums.MLPolyRexplicitlyexposesthedualitybetweensumsandproductsbyprovidingatypeofrst-classcases.Valuesofcasetype(likerecords,theirdualcounterpart)canbefunctionallyextendedtohandlelargersums.Thissetuprestsrmlyonthewell-understoodtheoryofrowtypes.Itallowsforefcienttypereconstructionandshouldyieldfewsurprisesforprogrammers.Ontheotherhand,wendthatitenablesaveryexiblestyleofprogrammingwherethetreatmentofindividualvariantsofasumcanbecodedseparatelyandcombinedlaterwithminimalnotationaloverhead.Incombinationwithex-plicitlycodedopenrecursion(whichrequiresequi-recursivetypes),itprovidesanelegantapproachtosolvingtheexpressionproblem,i.e.,theproblemofaddingnewconstructorstoadatatypeandbe-ingabletore-useexistingcode.Sincewearestrivingforsimplicity,weconsciouslyleftoutfeaturessuchassubtypingorinferenceofintersections.WeimplementedourlanguageusingatechniquebasedonOhori'sindex-passingschemeforpolymorphicrecordsandtheexploitationofthesum-productdualityforrst-classcases.Inthispaperweexplainthistechniqueintermsofa2-stagetranslation,rstintoanexplicitly-typedpolymorphiclambdacalculus(Sys-temF)wheresumsandcasesareeliminatedusingdualitywithrecords,thenintoanuntyped-calculusLRecwhererecordsarerepresentedasvectorswithnumericindices.7.AcknowledgmentsWewouldliketothankAtsushiOhoriforhelpfuldiscussions.JacquesGarrigueaswellastheanonymousreviewersprovidedvaluablefeedback.References[1]A.W.Appel.Compilingwithcontinuations.CambridgeUniversityPress,NewYork,NY,USA,1992.[2]A.W.AppelandD.B.MacQueen.StandardMLofNewJersey.InM.Wirsing,editor,3rdInternationalSymp.onProg.Lang.ImplementationandLogicProgramming,pages1–13,NewYork,Aug.1991.Springer-Verlag.[3]F.BourdoncleandS.Merz.Type-checkinghigher-orderpolymorphicmulti-methods.InConferenceRecordofPOPL'97:The24thACMSIGPLAN-SIGACTSymposiumonPrinciplesofProgrammingLanguages,pages302–315,Paris,France,15–171997.[4]K.Bruce.Somechallengingtypingissuesinobject-orientedlanguages.InElectronicnotesinTheoreticalComputerScience,volume82(8),2003.[5]L.CardelliandJ.C.Mitchell.Operationsonrecords.InC.A.GunterandJ.C.Mitchell,editors,TheoreticalAspectsofObject-OrientedProgramming:Types,Semantics,andLanguageDesign,pages295–350.TheMITPress,Cambridge,MA,1994.[6]R.B.FindlerandM.Flatt.Modularobject-orientedprogrammingwithunitsandmixins.InICFP'99:ProceedingsofthefourthACMSIGPLANinternationalconferenceonFunctionalprogramming,volume34(1)ofSIGPLAN,pages94–104,NewYork,NY,June1999.ACM.[7]C.Flanagan,A.Sabry,B.F.Duba,andM.Felleisen.TheEssenceofCompilingwithContinuations.In1993ConferenceonProgrammingLanguageDesignandImplementation.,pages21–25,June1993.[8]M.Flatt.ProgrammingLanguagesforReusableSoftwareCompo-nents.PhDthesis,DepartmentofComputerScience,RiceUniversity,1999.[9]T.FreemanandF.Pfenning.RenementtypesforML.InPLDI'91:ProceedingsoftheACMSIGPLAN1991conferenceonProgramminglanguagedesignandimplementation,pages268–277,NewYork,NY,USA,1991.ACMPress.[10]J.Garrigue.Programmingwithpolymorphicvariants.InACMSIGPLANWorkshoponML,1998.[11]J.Garrigue.Codereusethroughpolymorphicvariants.InWorkshoponFoundationsofSoftwareEngineering,Nov.2000.