EXTENDINGRESOURCE-BOUNDEDFUNCTIONAL PROGRAMMINGLANGUAGES
WITHMUTABLE STATE ANDCONCURRENCY
STEPHEN GILMORE, KENNETH MACKENZIE AND NICHOLAS WOLVERSON
∗
Abstrat. Camelotisaresoure-boundedfuntionalprogramminglanguage whihompilestoJavabyteodetorunonthe
Java VirtualMahine. WeextendCamelotto inludelanguage support forCamelot-level threadswhihareompiledto native
Javathreads. WeextendtheexistingCamelotresoure-boundedtypesystemtoprovidesafetyguaranteesabouttheheapusageof
Camelotthreads. Wedemonstratetheusefulnessofouronurrenyextensionstothelanguagebyimplementingamulti-threaded
graphialnetworkhatappliationwhihouldnothavebeenexpressedasnaturallyinthesequential,objet-freesublanguageof
Camelotwhihwaspreviouslyavailable.
1. Introdution. Funtionalprogramminglanguagesallowprogrammerstoexpress algorithmsonisely
usinghigh-levellanguageonstrutsoperatingoverstrutured data,seuredbystrongtype-systems. Together
thesepropertiessupporttheprodutionofhigh-qualitysoftwareforomplexappliationproblems. Funtional
programsinstrongly-typedlanguagestypiallyhaverelativelyfewprogrammingerrorswhenomparedtosimilar
appliationsimplementedin languageswithoutthese beneial features.
These desirable languageproperties mean that developersshed theburdens of expliit memory
manage-ment,butthishastheassoiatedostthattheytypiallyloseallontroloverthealloationanddealloationof
memory. TheCamelotlanguageprovidesanintermediatewaybetweenompletelyautomatimemory
manage-mentandunassistedalloationanddealloationinthatitprovidestype-safestoragemanagementbyre-binding
ofaddresses. Theaddressofadatum anbeobtainedinapatternmathandusedinanexpression(tostorea
dierentdatavalueat thataddress),overwritingtheurrently-heldvalue.
The Camelot ompiler targets the Java Virtual Mahine but the JVM does not provide an instrution
to free memory, onsigning this to the garbageolletor, agenerational olletor with three generations and
implementationsofstop-and-opyandmark-sweepolletions. Camelotallowsmorepreiseontrolofmemory
alloation,allowingin-plaemodiationofuser-deneddatastrutures. TheCamelotompilersupportsvarious
resoure-awaretypesystemswhihensurethatmemoryre-usetakesplaeinasafemannerandalsoallowstati
preditionof heap-spae usage. Camelot usesa uniform representationfor types whih are generated by the
ompiler, allowing data types to exhange storage ells. This uniform representation is alled the diamond
type [10, 12℄, implemented by aDiamond lass in the Camelot run-time. The Camelot languageimplements
atypesystem whih assigns types to funtions whih reord the number of parameterswhih they onsume,
andtheirtypes; thetypeof theresult;and thenumberofdiamonds onsumed orfreed. Theoutome isthat
the storage onsumption requirements of afuntion are statially omputed at ompile-time along with the
traditionalHindley-Milnertypeinfereneproedure.
Thenovelontributionof thepresentpaperis toexplain howsuhanunusually rih programmingmodel
anbeextendedto inorporate objet-orientedand onurrentprogrammingidioms. This ontribution isnot
justadesign: ithasbeenrealisedin thelatestreleaseoftheCamelotompiler.
Strutureofthis paper. InSetion2wepresenttheCamelotlanguagein orderthatthereadermay
under-standtheoperationalontextofthework. WefollowthisinSetion 3withadisussionofourobjet-oriented
extensionstoCamelot. ThisleadsontoapresentationoftheuseofthreadsinSetion4followedbyananalysis
ofthemanagementofthreadsbytherun-timesysteminSetion5. Setion6explainstherelationshipbetween
threadsinCamelotandthreadsastraditionallyimplementedinonurrentfuntionallanguagesusingrst-lass
ontinuations. Setion7detailstheimpliationsforveriationofCamelotprograms. Relatedworkissurveyed
inSetion 8andonlusionsfollowafter that.
2. TheCamelotlanguage. TheoreofCamelotisastandardpolymorphiML-likefuntionallanguage
whosesyntaxisbaseduponthatofO'Caml;themainnoveltyliesinextensionswhihallowtheprogrammerto
performin-plaemodiationstoheap-alloateddata-strutures. Thesefeaturesaresimilartothosedesribed
inbyHofmannin[11℄,butinludesomeextraextensionsforfreelistmanagement. Toretainapurelyfuntional
semantis forthe languagein the preseneof these extensions alinear typesystem anbe employed: in the
present implementation, linearityan be enforedvia aompilerswith. Weare in theproess of enhaning
∗
theompilerbytheadditionofother,lessrestritivetypesystemswhih stillallowsafein-plaemodiations:
moredetails willbegivenbelow.
Cruialdesign hoiesfor theompilationare transparenyand anexatspeiationof the ompilation
proess. Theformerensuresthattheompilationdoesnotmodifytheresoureonsumptioninanunpreditable
way. The latterprovidesaformal basis forusing resoureinformation inferred for thehigh-levellanguagein
proofsontheintermediatelanguage.
Inthefollowingsetionswewillgiveabriefdesriptionofthestrutureofthelanguage. Wewillthenoutline
howthelanguageisompiled,andin partiularhowthememory-managementextensionsareimplemented.
2.1. The strutureofCamelot. WewillgivesomeexamplestoindiatethebasistrutureofCamelot;
fulldetails anbefoundin [20℄.
Datatypesaredenedinthenormalway:
type intlist = Nil | Cons of int * intlist
type 'a polylist = NIL | CONS of 'a * 'a polylist
type ('a, 'b) pair = Pair of 'a *'b
Valuesbelonging to user-dened types are reatedby applying onstrutors and are deonstrutedusing the
mathstatement:
let re length l = math l with
Nil -> 0
| Cons (h,t) -> 1+length t
let test () = let l = Cons(2, Cons(7,Nil))
in length l
As an be seen from this example, onstrutor arguments are enlosed in parentheses and are separated by
ommas. Inontrast, funtion denitions and appliationswhih requiremultiple argumentsarewritten in a
urried style:
let add a b = a+b
let f x y z = add x (add y z)
Despitethis notation, thepresent versionofCamelot doesnot support higher-orderfuntions; any
appli-ationofafuntionmustinvolveexatlythesamenumberofargumentsasarespeiedinthedenitionofthe
funtion.
2.2. Diamonds and Resoure Control. TheCamelotompilertargetstheJavaVirtual Mahine,and
valuesfromuser-deneddatatypesarerepresentedbyheap-alloatedobjetsfromaertainJVMlass. Details
ofthisrepresentationwillbegivenin Setion2.4.
Considerthefollowingfuntion whih usesanaumulator to reverse alistof integers(as dened bythe
intlisttypeabove).
let re rev l a = math l with
Nil -> a
| Cons (h,t) -> rev t (Cons (h,a))
let reverse l = rev l Nil
Thisfuntionalloatesanamountofmemoryequaltotheamountoupiedbytheinputlist. Ifnofurther
refereneis madeto the inputlist thentheheap spaewhihit oupiesmayeventuallyberelaimed bythe
JVMgarbageolletor.
Inorder to allowmorepreiseontrol of heapusage,Camelot inludes onstrutsallowingre-useofheap
ells. Thereisaspeialtypeknownasthediamond type(denotedby<>)whosevaluesrepresentbloksof
heap-alloatedmemory,andCamelotallowsexpliitmanipulationofdiamondobjets. Thisisahievedbyequipping
onstrutorsandmathruleswithspeialannotationsreferringtodiamondvalues. Hereisthereversefuntion
rewrittenusingdiamondssothatitperformsin-plaereversal:
let re rev l a = math l with
Nil -> a
| Cons (h,t)d -> rev t (Cons (h,a)d)
let reverse l = rev l Nil
thatthelistellCons(h,a)shouldbeonstrutedinthediamondobjetreferredtobyd,andnonewspae
shouldbealloatedontheheap.
Onemightnot always wish to re-use adiamond valueimmediately. This an sometimes ause diulty
sinesuh diamonds mightthen havetobereturnedaspartofafuntion resultso that theyanbereyled
byother partsof theprogram. Forexample, thealertreadermayhavenotied that thelist reversalfuntion
abovedoesnotin fat reverselists entirelyin plae. Whenthe useralls reverse,theinvoationof theNil
onstrutorin the allto revwillause anewlist ellto bealloated. Also, theNilvalueat theend of the
inputlistoupiesadiamond,and thisissimply disardedin theseondline oftherevfuntion (andwillbe
subjettogarbageolletioniftherearenootherreferenesto it).
Theoveralleetisthatwereateanewdiamondbeforeallingtherevfuntionandareleftwithanextra
diamondafter theallhad ompleted. Weould reovertheextradiamondby makingthereverse funtion
return apair onsisting of the reversed list and the spare diamond, but this is rather lumsy and programs
quiklybeomeveryomplexwhenusingthiskindoftehnique.
Toavoidthiskindof problem,unwanteddiamonds anbestoredonafree list forlateruse. This isdone
byusingtheannotation_asinthefollowingexamplewhihreturnsthesumoftheentriesinanintegerlist,
destroyingthelistintheproess:
let re sum l a = math l with
Nil_ -> a
| Cons (h,t)_ -> sum t (a+h)
Thequestionnowishowtheuserretrievesadiamondfromthefreelist. Infat,thishappensautomatially
duringonstrutorinvoation. IfaprogramusesanundeoratedonstrutorsuhasNilorCons(4,Nil)then
ifthefreelistis empty theJVMnewinstrutionis usedto alloatememoryfor anewdiamondobjetonthe
heap; otherwise, adiamond is removed from the head of the free list and is used to onstrutthe value. It
mayoasionallybeusefultoexpliitlyreturnadiamondtothefreelistandanoperatorfree: <> -> unitis
providedforthispurpose.
There is one nal notational renement. The in-plae list reversal funtion above is still not entirely
satisfatorysinetheNilvaluearriesnodatabutisnonethelessalloatedontheheap. Weanoveromethis
byredeningtheintlisttypeas
type intlist = !Nil | Cons of int * intlist
TheexlamationmarkdiretstheompilertorepresenttheNilonstrutorbytheJVMnullreferene. With
thenewdenition of intlisttheoriginallist-reversalfuntion performstruein-plaereversal: noheapspae
isonsumedordestroyedwhenthereversefuntionisapplied. The! annotationanbeusedforasingle
zero-argumentonstrutorin anydatatypedenition. Inaddition,ifeveryonstrutorforapartiular datatypeis
nullarythentheymayallbepreededby !,in whihasetheywillberepresentedbyintegervaluesatruntime.
We have deliberately hosento expose this hoie to the programmer (rather than allowingthe ompiler to
automatiallyhoosethemosteientrepresentation)inkeepingwithourpoliyofnotallowingtheompiler
toperformoptimisationswhih haveunexpetedresultsonresoureonsumption.
Thefeaturesdesribedaboveareverypowerfulandanleadtomanykindsofprogramerror. Forexample,
ifoneappliedthereversefuntiontoasublistofsomelargerlistthenthesmalllistwouldbereversedproperly,
butthelargerlistouldbeomepartiallyreversed. Perhapsworse,adiamondobjetmightbeused inseveral
dierentdatastruturesofdierenttypessimultaneously. Thusalistellmightalsobeusedasatreenode,and
anymodiationofonestruturemightleadtomodiationsoftheother. Thesimplestwayofpreventingthis
kindofproblem istorequirelinearusageofheap-alloatedobjets,whihmeansthatvariables bound tosuh
objets may beused at mostone after theyarebound. Detailsof this approahanbefound in Hofmann's
paper[11℄. Stritlinearitywouldrequireonetowritethelistlengthfuntion assomethinglike
let re length l = math l with
Nil -> Pair (0, Nil)
| Cons(h,t)d ->
let p = length t
in math p with
Pair(n, t1)d1 -> Pair(n+1, Cons(h,t1)d)d1
Itisneessarytoreturnanewopyofthelistsineitis illegaltorefertolafter allinglength l.
of linear typing an lead to unneessary ompliations. Aspinall and Hofmann [1℄ give a typesystem whih
relaxesthe linearity ondition while still allowingsafein-plae updates, and Mihal Kone£ný generalises this
still furtherin [15,16℄. Aspartofthe MRGprojet,Kone£nýhasimplementedatypehekerforavariantof
thetypesystemof[15℄adaptedto Camelot.
A dierentapproah to providing heap-usageguaranteesis given byHofmannand Jost in [13℄, where an
algorithm is presented whih anbe used to statiallyinfer heap-usagebounds for funtional programs of a
suitableform. InollaborationwiththeMRGprojet,SteenJosthasimplementedavariantofthisinferene
algorithm forCamelot: the implementationis desribed in [14℄. Both of these implementationsare urrently
stand-aloneprograms,butweareintheproessofintegratingthemwiththeCamelotompiler.
Oneof ourgoalsin the designof Camelotwasto dene alanguagewhih ould beused asatestbed for
dierentheap-usageanalysismethods. Theinlusionofexpliitdiamondststhetypesystemsof[1,15,16℄,and
theinlusion of thefreelist failitatestheHofmann-Jost inferenealgorithm,whih requires that allmemory
managementtakesplaeviaafreelist.
2.3. Compilation of expressions. Camelot is initially ompiled into the Grail intermediate language
[5,19℄whihisessentiallyafuntionalformofJavabyteode. This proessisfailitatedbyaninitial phasein
whihseveraltransformationsareapplied totheabstratsyntaxtree.
2.3.1. Monomorphisation. Firstly, all polymorphismis removed from the program. For polymorphi
types
(α
n
, . . . , α
1
)
t
suh asα
listweexaminetheentire programto determineallinstantiationsofthetypevariables, andompile aseparatedatatypeforeahdistint instantiation. Similarly, whenevera polymorphi
funtionisdened theprogramisexaminedtondallusesofthefuntionandamonomorphifuntionofthe
appropriatetypeisgeneratedforeahdistintinstantiationof types.
2.3.2. Normalisation. Aftermonomorphisationthereisaphasereferredtoasnormalisationwhih
trans-formstheCamelotprogramintoaform whihloselyresemblesGrail.
Firstlytheompilerensuresthat allvariableshaveuniquenames. Anydupliationsareresolvedby
gener-atingnewnames. Thisallowsusto mapCamelotvariablenamesdiretlyontoGrail variablenames(whihin
turnmapontoJVMloalvariableloations)withnodangeroflashesarising.
Next,wegivenamestointermediateresultsinmanyontextsbyreplaingomplexexpressionswith
vari-ables. For example, the expression
f
(a
+
b
+
c)
would be replaed by an expression of the form lett
1
=
a
+
b
in lett
2
=
t
1
+
c
inf
(t
2
)
. The introdutionof names for intermediate resultsan produe alargenumberofGrail (andheneJVM)variables. After thesoureode hasbeenompiled toGrail thenumberof
loalvariablesisminimised byapplyingastandardregisteralloationalgorithm(see[30℄).
A naltransformation ensuresthat let-expressionsarein astraight-line form. After allof these
trans-formations have been performed expressions have been redued to a form whih we refer to as normalised
Camelot
Thestruture ofnormalisedCamelot(whih isin fat in atypeofA-normal form[9℄)is suientlylose
to that ofGrail that itis fairlystraightforwardto translatefromthe formerto thelatter. Anotherbenetof
normalisation isthat itis easierto write andimplementtypesystemsfor normalisedCamelot. Thefat that
the omponentsof many expressions are atoms rather than omplex subexpressions means that typing rules
anhaveverysimplepremisses.
2.4. Compilation of values. Camelot has various primitive types (int, float, et.) whih an be
translated diretly into orresponding JVM types. The ompilation of user-dened datatypes, however, is
rather moreompliated. Objets belonging to datatypes are representedby members ofa singleJVM lass
whih wewill refer to as thediamond lass. Objetsof thediamond lassontainenoughelds to represent
anymemberofany datatypedenedintheprogram. Eahinstane
X
ofthediamondlassontainsanintegertageldwhihidentiestheonstrutorwith whih
X
isassoiated. Thediamondlass alsoontainsastatieldpointingtothefreelist. Thefreelistismanagedviathestatimethodsallo(whihreturnsthediamond
at theheadof thefreelist,orreatesanewdiamondbyalling newifthefreelistisempty),and freewhih
plaes a diamondobjet onthe free list. The diamondlass also hasoverloaded stati methods alled make
andfill,oneinstaneofeahforeverysequeneof typesappearingin aonstrutor. Themakemethods are
to ll in the appropriate elds with the tag and the arguments. The fillmethods are also used when the
programmerreuses anexisting diamondtoonstrutadatatypevalue.
ItanbearguedthatthisrepresentationisineientinthatdatatypevaluesareoftenrepresentedbyJVM
objetswhiharelargerthantheyneedtobe. Thisistrue,butisdiulttoavoidduetothetype-safenature
ofJVMmemorymanagementwhihpreventsonefromre-usingtheheapspaeoupiedbyavalueofonetype
tostoreavalueofadierenttype. Wewishtobeabletoreuseheapspae,butthisanbeimpossibleifobjets
anontain only onetype of data. With the urrent sheme onean easily write aheapsort program whih
operatesentirelyin-plae. List ellsare largeenoughto bereusedasheapnodesand thisallowsaheaptobe
builtusingellsobtainedbydestroyingtheinputlist. Onetheheaphasbeenbuiltitaninturnbedestroyed
and the spae reusedto build the output list. Inthis ase, theamount of memory oupied bya list ell is
largerthanit needsto be,but the overall amountof storerequiredis lessthan would be theaseif separate
lasseswereusedtoontainlistellsandheapnodes.
Intheurrentontextitanbelaimedthatitisbettertohaveanineientrepresentationaboutwhihwe
angiveonreteguaranteesthananeientonewhihaboutweansaynothing. Mostoftheprogramswhih
we havewritten sofar usea limitednumber ofdatatypes sothat theoverhead introdued bythe monolithi
representationfordiamonds isnottoosevere. However,itis likelythat forverylargeprogramsthis overhead
wouldbeomeunaeptablylarge. Onepossibilitywhih wehavenotyetexploredis thatitmightbepossible
to ahievemoreeientheapusage byusing dataow tehniques to followtheowof diamonds throughthe
programand detetdatatypeswhih are neverused in an overlappingway. Oneould then equip aprogram
withseveralsmallerdiamondlasseswhihwouldrepresentsuhnon-overlappingtypes.
These problems ould be avoided by ompiling to some platform other than the JVM (for example to
C orto a speialised virtual mahine) where ompation of heap regions would be possible. The
Hofmann-Jostalgorithm isstill appliablein this situation,soitwouldstill be feasibleto produeresoureguarantees.
However,itwasafundamentaldeisionoftheMRGprojettousetheJVM,basedonthefatsthattheJVM
iswidelydeployedandverywell-known,andthat resoureusageis agenuine onerninmanyontextswhere
theJVMisused. Ourpresentapproahallowsustoprodueonreteguaranteesattheostofsomeoverhead;
wehopethat atalaterstageamoresophistiatedapproah(suhastheonesuggestedabove)mightallowus
toreduetheoverheadswhilestillobtainingguaranteedresourebounds.
2.5. Remarks. There are various ways in whih Camelot ould be extended. The lak of higher-order
funtionsis inonvenient,but theresoure-awaretypesystemswhihweuse arepresentlyunableto dealwith
higher-order funtions, partly beause of the fat that these are normally implemented using heap-alloated
losureswhosesizemaybediulttopredit. Apossiblestrategyfordealingwiththiswhihweareurrently
investigating is Reynolds' tehnique of defuntionalization [24℄ whih transforms higher-order programs into
rst-order ones, essentially by performing a transformation of the soure ode whih replaes losures with
membersof datatypes. Thishasthe advantagethatextraspae requiredbylosuresis exposed at thesoure
level,whereitisamenabletoanalysisbytheheap-usageinferenetehniquesmentionedearlier.
3. Objet-orientedextensions. TheoreCamelotlanguageasdesribedinSetion2aboveenablesthe
programmertowriteaprogramwithapreditableresoureusage;however,onlyprimitiveinterationwiththe
outsideworldis possible,throughommandline arguments,leinputand printedoutput. Tobeabletowrite
afullinterfaeforagameorutilitytoberunonamobile devie,Camelotprogramsmustbeabletointerfae
withexternal Javalibraries. Similarly, theprogrammermaywish to utilise devie-spei libraries,orJava's
extensivelasslibrary.
Thissetiondesribesourobjet-orientedextensiontoCamelot. ThisisprimarilyintendedtoallowCamelot
programsto aessJavalibraries. It wouldalso bepossibletowrite resoure-ertiedlibrariesin Camelotfor
onsumptionbystandardJavaprograms,orindeedusetheobjetsystemforOOprogrammingforitsownsake,
butgivingCamelotprogramsaesstotheoutsideworldisthemainobjetive.
IndesigninganobjetsystemforCamelot, manyhoies aremade forus, orat leasttightly onstrained.
We wish to reate asystem allowing inter-operation with Java,and we wish to ompile anobjet systemto
JVML. SowearealmostforedintodrawingtheobjetsystemoftheJVMuptotheCamelotlevel,andannot
seriouslyonsiderafundamentallydierentsystem.
undesirablefromaprogrammer'spointofview. Wealsodonotwanttointerferewithtypesystemsforresoures
asmentionedabove.
Weshall rstattempt to maketheessentialfeatures of Javaobjetsvisible in Camelotin asimpleform,
withtheviewthat asimpleabbreviationormodule systemanbeaddedatalaterdate tomakethingsmore
palatableifdesired.
3.1. Basi Features. We shall view objetsasreords of possibly mutableelds together with related
methods, although Camelot hasno existing reord system. We dene the usual operations onthese objets,
namelyobjetreation,method invoation,eld aess andupdate, andastingand mathing. Asonemight
expet we hoose a lass-based systemlosely modelling the Javaobjet system. Consequentlywe must
a-knowledgeJava'susesoflassesforenapsulation,andassoiatestatimethodsand eldswithlassesalso.
We now onsider these features. Theexamples below illustrate the newlasses of expressions weadd to
Camelot.
Statimethodalls Thereisnooneptualdierenebetweenstatimethodsandfuntions,ignoringtheuse
oflassesforenapsulation,soweantreatstatimethodallsjust likefuntion alls.
java.lang.Math.max a b
Statield aess Some librariesrequirethe useof stati elds. Weshould onlyneed to provide aess to
onstantstatields,sotheyorrespondto simplevalues.
java.math.BigInteger.ONE
Objet reation We learly need a way to reate objets, and there is no need to deviate from the new
operator. ByanalogywithstandardCamelotfuntionappliationsyntax(i.e. urriedform)wehave:
new java.math.BigInteger "101010" 2
Instane eldaess Toretrievethevalueofaninstanevariable,wewrite
objet#field
whereastoupdatethat valueweusethesyntax
objet#field <- value
assumingthatfieldisdelaredto beamutable eld.
Itouldbearguedthat allowingunfetteredexternalaesstoanobjet'svariablesisagainstthespirit
ofOO,andmoretothepointinappropriateforoursmalllanguageextension,butwewishtoalloweasy
interoperabilitywith anyexternalJavaode.
Methodinvoation Drawinginspirationfrom the O'Camlsyntax,and again usingaurried form,wehave
instanemethod invoation:
myMap#put key value
Nullvalues InJava,anymethodwithobjetreturntypemayreturnthenullobjet. Forthisreasonweadd
aonstrut
isnull
e
whihtestsiftheexpression
e
isanullvalue.Casts and typease It maybeoasionallybeneessaryto ast objetsupto superlasses, forexample to
fore theintended hoie betweenoverloadedmethods. Wewill also wantto reoversublasses,suh
aswhenremovinganobjetfromaolletion. Hereweproposeasimplenotationforup-asting:
obj :> Class
Thisnotationisthat ofO'Caml,alsoborrowedbyMLj(desribedin [3℄). Tohandledown-astingwe
shallextendpatternsinthemannerof typease(againlikeMLj)asfollows:
math obj with o :> C1 -> o.a()
| o :> C2 -> o.b()
| _ -> obj.()
Hereoisboundin theappropriatesubexpressionstotheobjetobjviewedasanobjetoftypeC1or
C2respetively. Asindatatypematheswerequirethateverypossibleaseisovered;herethismeans
thatthedefaultaseismandatory. Wealsorequirethateahlassisasublassofthetypeof obj,and
suggestthat aompilerwarningshouldbegivenforanyredundantmathes.
Unlike MLjwehoose notto allow downastingoutside of thenew form of math statement, partly
beauseat presentCamelothasnoexeptionsupporttohandleinvaliddown-asts.
Thefollowingexampledemonstratessomeoftheabovefeatures,andillustratestheeaseofinteroperability.
Note that the type of the parameter
l
is speied by a onstrainthere. Type inferene does not ross lassboundariesinCamelot.
let onvert (l: string list) =
math l with [℄ -> new java.util.LinkedList ()
| h::t ->
let ll = onvert t
in let _ = ll#addFirst h
in ll
3.2. Dening lasses. Onewehavetheabilitytowriteandompileprogramsusingobjets,wemayas
wellstartwritinglassesin Camelot. Wemustbeabletoreatelassestoimplementallbaks,suhasin the
SwingGUIsystemwhih requiresusto writestatefuladaptorlasses. Otherwise,asmentionedpreviously,we
may wish to write Camelotodeto bealled from Java, forexampleto reate aresoure-ertiedlibrary for
usein aJavaprogram, and dening alass is anaturalwayto do this. Implementation of these lasseswill
obviouslybetiedtotheJVM,buttheformthesetakeinCamelothasmoresopeforvariation.
Weallowthe programmerto dene alass whih mayexpliitlysublass anotherlass, and implementa
numberofinterfaes. We alsoallow theprogrammerto dene (possibly mutable) elds andmethods, aswell
asstatimethodsand eldsforthepurposeofreatingaspeilassforinterfaingwithJava. Wenaturally
allowreferenetothis.
Theformofalassdelarationisgivenbelow. Itemswithinangularbrakets
h. . .i
areoptional.classdecl
::=
lasscname
=hscname
withi
body
endbody
::=
hinterf acesi hf ieldsi hmethodsi
interf aces
::=
implementiname
hinterf acesi
f ields
::=
f ield
hf ieldsi
methods
::=
method
hmethodsi
Thisdenesalassalled
cname
,implementingthespeiedinterfaes. Theoptionalscname
givesthenameofthediretsuperlass;ifitisnotpresent,thesuperlassistakentobetherootofthelasshierarhy,namely
java.lang.Objet.Thelass
cname
inheritsthemethodsandvaluespresentin itssuperlass,andthesemaybereferredto initsdenition.
As well asasuperlass, alass andelare that it implements oneormore interfaes. These orrespond
diretlyto theJavanotionofan interfae. Javalibrariesoftenrequirethereationof alassimplementinga
partiularinterfaeforexample,to useaSwingGUI onemustreate lassesimplementingvariousinterfaes
to be usedasallbaks. Note that at theurrent timeit is notpossibleto dene interfaesin Camelot, they
areprovidedpurelyforthepurposeofinteroperability.
Nowwedesribeelddelarations.
f ield
::=
fieldx
:τ
|
fieldmutablex
:τ
|
valx
:τ
Instaneeldsaredenedusingthekeywordfield,andanoptionallybedelaredtobemutable. Statields
aredened using val,and arenon-mutable. Inasense these mutableelds arethe rstintrodutionof
side-eetsintoCamelot. WhiletheCamelotlanguageisdenedtohaveanarraytype,thishaslargelybeenignored
in our moreformal treatments asit is notfundamental to the language. Mutable elds, on the other hand,
are fundamental to our notionof objet orientation, so we expet any extension of Camelot resoure-ontrol
featurestoobjet-orientedCamelottohavetodealwiththis properly.
Methodsaredened asfollows,where
1
≤
i
1
, . . . , i
m
≤
n
.method
::=
maker(x
1
:τ
1
). . .
(x
n
:τ
n
)h
:superx
i
1
. . . x
i
m
i
=exp
|
methodm
(x
1
:τ
1
). . .
(x
n
:τ
n
):τ
=exp
|
methodm
():τ
=exp
|
letm
(x
1
:τ
1
). . .
(x
n
:τ
n
):τ
=exp
Again,weusetheusualletsyntaxtodelarewhatJavawouldallstatimethods. Statimethodsaresimply
monomorphi Camelot funtions whihhappen to bedened within a lass, although theyare invoked using
thesyntaxdesribedearlier. Instanemethods, ontheotherhand,areatuallyafundamentallynewaddition
to thelanguage. Weonsider the instanemethodsof alass to be aset ofmutually reursivemonomorphi
funtions,inwhihthespeialvariablethisisbound totheurrentobjetofthatlass.
We an onsider the methods as mutually reursive without using any additional syntax (suh as and
bloks)sine they are monomorphi. ML uses and bloks to group mutually reursive funtions beause its
let-polymorphismpreventsanyofthesefuntionsbeingusedpolymorphiallyinthebodyoftheothers,butthis
isnotanissuehere. Inanyasethisimpliitmutualreursion feelsappropriatewhenweare ompilingtothe
JavaVirtualMahine,andhaveto ometotermswithopenreursion.
Inadditiontostatiandinstanemethods, wealsoallowaspeialkindofmethod alledamaker. Thisis
justwhatwouldbealledaonstrutorintheJavaworld,butasin[8℄weusethetermmakerinordertoavoid
onfusionbetweenobjetanddatatypeonstrutors. Themakertermabovedenesamakeroftheontaining
lass
C
suh that if newC
is invoked with arguments of typeτ
1
. . . τ
n
, an objet of lassC
is reated, thesuperlassmakerisexeuted(thisis thezero-argumentmakerof thesuperlassifnoneis expliitlyspeied),
expression
exp
(of unittype)isexeuted,andtheobjetisreturnedastheresultofthenewexpression. Everylasshasatleastonemaker;alasswithnoexpliitmakeristakentohavethemakerwithnoargumentswhih
invokesthesuperlasszero-argumentmakeranddoesnothing. Thisimpliitmakerisinsertedbytheompiler.
3.3. Polymorphism. WeremarkedearlierthatstatimethodsarebasiallymonomorphiCamelot
fun-tionstogetherwithaformofenapsulation,but itisworthonsideringpolymorphismmoreexpliitly.
objet-orientedCamelotmethods,whetherstatiorinstanemethods,arenotpolymorphi. Thatis,theyhavesubtype
polymorphismbutnotparametripolymorphism(generiity),unlikeCamelotfuntionswhihhaveparametri
but not subtype polymorphism. This isnot generallya problem, asmost polymorphifuntions will involve
manipulation of polymorphi datatypes,and anbeplaed in themain program, whereasmost methods will
beinterfaingwiththeJavaworldandthusshould onformto Java'ssubtypingpolymorphism.
3.4. Translation. As mentioned earlier, the present Camelot ompiler targets the JVM, via the
inter-mediate languageGrail. Translatingthe objet-orientedfeatures whih havejust been desribed is relatively
straightforward,astheJVM(andGrail)providewhatweneed. Adetailedformaldesriptionofthetranslation
proessanbefoundin[31℄
3.5. Objets and Resoure Types. Asdesribed earlier, theuseof diamondannotationsonCamelot
programs in ombination with ertain resoure-awaretype systems allows the heapusage of those programs
to beinferred, as well asallowingsomein-plae update to our. Clearly thepresene of mutableobjetsin
objet-orientedCamelot alsoprovidesfor in-plae update. Howeverbyallowing arbitraryobjet reationwe
alsorepliatetheunboundedheap-usageproblemsolvedfordatatypes. Perhapsmoreseriously,weareallowing
Camelotprogramsto invokearbitraryJavaode,whihmayuseanunlimitedamountofheapspae.
Firstlyonsidertheseondproblem. Evenifwehavesomewaytoplaeaboundontheheapspaeusedby
ournewOOfeatureswithinaCamelotprogram,externalJavaodemayusearbitraryamountsofheap. There
seem to bea few possible approahes to this problem, noneof whih are partiularly satisfatory. We ould
deidetoonlyallowtheuseofexternallassesiftheyamewithaproofofboundedheapusage. Construting
aresoure-bounded Javalass libraryorinferring resourebounds for anexisting library would be amassive
undertaking,althoughperhapslessproblematiwiththesmallerlasslibrariesusedwithmobile devies. This
suggestionseemssomewhatunrealisti.
Alternatively,weouldsimplyallowtheresoureusageofexternalmethodstobestatedbytheprogrammer
or library reator. This extends the trusted omputing base in the sense of resoures, but seems a more
reasonablesolution. The other alternativeonsideringresoure-bound proofs to only referto the resoures
diretlyonsumed by theCamelot odeseemsunrealisti, asone ould easily (and even aidentally) heat
byusingJavalibrariestodosomememory-onsumingdirtywork.
Theissueof heap-usageinternal to objet-orientedCamelot programsseemsmoretratable, although we
donotproposeasolutionhere. Arstattemptmightmimithetehniquesusedearlierfordatatypes;perhaps
weanadapttheuseofdiamondsandlineartypesystems? Theuseofdiamondsforin-plaeupdateisirrelevant
here,andindeed relies ontheuniformrepresentationof datatypesby objetsofapartiularJavalass. Sine
However,weould imaginean abstrat diamondwhih representsthe heapstorage used byan arbitrary
objet, and require any instane of new to supply one of these diamonds, in order that the total number of
objets reatedis limited. Unfortunatelyrelamationof suh anabstrat diamondwould onlyorrespondto
makinganobjetavailable togarbageolletion,ratherthandenitely beingabletore-usethestorage. Even
so,suh asystem mightbeable to give ameasure of the totalnumberof objetsreatedand the maximum
numberin ativeusesimultaneously.
4. Using threads in Camelot. Previously the JVM had been used simply as a onvenient run-time
forthe Camelotlanguagebut theobjet-orientedextensionsdesribed aboveallowtheJavanamespaeto be
aessedfromaCamelotappliation. ThusaCamelotappliationannowreateJavaobjetsandinvokeJava
methods. Figure 4.1 shows the implementation of a remote input reader in RoundTable, a networked hat
appliationwrittenin Camelot. Thisexamplelassstreamsinputfromanetworkonnetionandrendersitin
adisplayareain thegraphialuserinterfaeoftheappliation.
(*Threadto readfromthenetwork,passingdatato adisplayobjet*)
lass
remote
=
java
.
lang
.
Thread
with
eld
input
:
java
.
io
.
BufferedReader
eld
disp
:
display
maker
(
i
:
java
.
io
.
BufferedReader
)(
d
:
display
) =
let_
=
input
←
i
indisp
←
d
method
run
() :
unit
=
let
line
=
this#
input
#
readLine
()
inif
isnullobj line
then()
elselet_
=
this#
disp
#
append line
inthis
#
run
()
end
Fig.4.1. AnextratfromtheRoundTablehatappliationshowingtheOOextensionstoCamelot
ThisexampleshowstheCamelotsyntaxformethodinvoation(obj#meth()),eldaess(obj#field)and
mutableeld update(f <- exp). Bothofthese arefamiliarfromObjetiveCaml.
Thisexamplealsoshowsthatevenintheobjet-orientedfragmentoftheCamelotlanguagethatthenatural
denitionstyleforunboundedrepetitionistowritereursivemethodalls. TheCamelotompileronverts
tail-alls of instane methods(suh asthis#
run
)into while-loopssothat methods implementedasin Figure 4.1runin onstantspaeanddonotoverowtheJavarun-timestak. Inontrastreursivemethodalls inJava
arenotoptimisedin thiswayandwouldleadto theprogramoverowingthestak.
Asreenshotofawindowfrom theRoundTableappliationis shownin Figure 4.2. Thisshows
date-and-time-stamped messages arriving spontaneously in the window. The appliation oers the ability to thread
messages by ontent or to sort them by time. The sorting routine is guaranteed by typeheking to run in
onstantspaebeauseaddressesofonsellsinthelistofmessagesarere-yledusingthefreelistasdesribed
TheextensionoftheCamelotompilertosupport interoperationwithJavafailitatestheimplementation
of graphial appliations suh as these. TheJava APIsused by this appliation inlude the Swing graphial
userinterfaeomponents,networking,threads andpluggablelook-and-feelomponentssuhastheSkin
look-and-feelshownabove.
5. Management of threads. Indesigning athread managementsystemfor Camelot ourstrongest
re-quirement was to have asystem whih works harmoniouslywith the storage management systemalready in
plae forCamelot. Oneaspetof thisisthat theresoureonsumption ofasingle-threadedCamelotprogram
anbeomputedinlinewiththereasoningexplainedin Setion1.
Inmovingfrom onetomultiplethreads themostimportantquestionwith respettomemoryusageisthe
following. Shouldthefreelistofstoragewhihanbereusedbeasinglestatiinstanesharedarossallthreads;
orshould eahthread separatelymaintainitsownloalinstaneofthefreelist?
Intheformerasetheaessormethodsforthefreelistmustbesynhronisedinorder fordatastrutures
notto beome disorderedbyonurrentwrite operations. Synhronisation inursan overheadof loking and
unlokingtheparentoftheeldwhen enteringandleavingaritialregion. Thisimposesarun-timepenalty.
Inthelatterasethere isnorequirementforaessto thefreelistto besynhronised;eah threadhasits
ownfreelist. Inthisase,though,thefreememoryoneahfreelistisprivate,andnotshared. Thismeansthat
therewillbetimeswhenonethread alloatesmemory(withaJavanewinstrution)whileanotherthreadhas
unused memoryonitsloal freelist. Thisimposes apenaltyonthe programmemoryusage,and thisform of
threadmanagementwould leadtoprogramstypiallyusingmorememoryoverall.
Wehavehosentheformersheme;wehaveasinglestatiinstaneofafreelistsharedarossallthreads. Our
programswilltakelongerthantheiroptimumrun-timebut memoryperformanewillbeimproved. Cruially,
preditabilityofmemoryonsumptionisretained.
Thereareseveralpossiblevariantsonthisseondshemewhihweonsidered. Theywerenotrightforour
purposesbut mightbe rightforothers. Oneinterestingalternativeisahybridofthetwoapproahesis where
eahthread had abounded (small)loal freelist and ushes thisto the globalfree listwhen itbeomesfull.
Thiswouldreduetheoverheadofallstoaessthesynhronisedglobalfreelist,whilepreventingthreadsfrom
keepingtoomanyunusedmemoryellsloally. Thisouldbeasuitableompromisebetweenthetwoextremes
but theanalysis ofthis approahwouldinevitably bemoreompliated thantheapproahwhih weadopted
(asinglestatifreelist).
Aseondalternativewouldbetoimplementweakloalfreelists. Inthisonstrutioneahthreadwouldhave
itsownprivatefreelistimplementedusing weak referenes whiharereferenesthatarenotstrongenoughby
themselvestokeepanobjetaliveifnogenuinereferenestoitareretained. Weakreferenesaretypiallyused
to implementahesand seondaryindexes fordata strutures. Other high-levelgarbage-olletedlanguages
suh as O'Caml implement weak referenes also. This sheme was not usable by us beause the Camelot
ompiler also targets small JVMs on handheld devies and the J2ME does not provide the neessary lass
(java.lang.ref.WeakReferene).
TheanalysisofmemoryonsumptionofCamelotprogramsisbasedontheonsumptionofmemoryby
heap-alloateddatastrutures. ThepresentanalysisofCamelotprogramsisbasedonasingle-threadedarhiteture.
Toassist with the development of an analysis method for multi-threadedCamelot programs we require that
data strutures in a multi-threaded Camelot program are not sharedaross threads. Forexample, it is not
possibleto hold partof alist in onethread andthe remainderin another. This requirementmeans that the
spaeonsumptionofamulti-threadedCamelotprogramisobtainedasthesumofper-threadspaealloation
plusthespaerequirementsofthethreadsthemselves.
Atpresentourtype systemtakesaountof heapalloationsbut doesnot takeaountof stakgrowth.
ThusCamelotprogramsanpotentially(andsometimesdoinpratie) failatruntimewitha
java.lang.StakOverflowErrorexeption iftheprogrammer overuses theidiomof working with familiesof
mutually-reursivefuntions andmethodswhihomputewithdeeply-nestedreursion.
Even sophistiated funtional language ompilers for the JVM suer from this problem and some, suh
asMLj[4, 3℄, do noteven implement tail-all eliminationin ases where theCamelotompiler does. Several
authorsonsidertheabseneofsupportfortailalleliminationtobeafailingoftheJVM[2,22℄. Anapproah
to eliminatingtailalls suhasthat usedby Funnel[25℄ would beausefulnextimprovementto theCamelot
requireinspetionof thestakto ensure thata partiularmethod has suientprivileges to exeuteanother
method;eliminatingtail-allswouldleadtothedisardingofstakframeswhihontaintheneessaryseurity
information. However, Clements and Felleisen have reently proposed another seurity model whih allows
safe tail-all optimisation[7℄; they laim that this requires only aminor hange to the mehanism urrently
used by the JVM (and other platforms), so there may be somehope that future JVM implementations will
support propertail-all optimisationand thus simplify the proess of implementing funtional languages for
theJVM.
6. Asimplethreadmodel forCamelot. ToretainpreditabilityofmemorybehaviourinCamelotwe
restrittheprogrammingmodeloeredbyJava'sthreads.
Firstly,wedisallowuse ofthestopandsuspendmethodsfrom Java'sthreads API. Thesearedepreated
methods whih have been shown to havepoorprogramming propertiesin any ase. Use of thestopmethod
allowsobjetsto be exposed in adamaged state, part-waythrough anupdate by a thread. Use of suspend
freezes threads but these do not release the objets whih they are holding loks on, thereby often leading
todeadloks. Dispensingwithpre-emptivethread interruptionmeansthat there isaorrespondene between
Camelotthreads andlightweight threads implemented using rst-lass ontinuations,all/ and throw,as
areusuallytobefoundin multi-threadedfuntional programminglanguages[6,18℄.
Seondly,werequirethatallthreadsarerun,againforthepurposesofsupportingpreditabilityofmemory
usage. IntheJavalanguagethreadalloation(usingnew )isseparatedfromthreadinitiation(usingthestart
method in thejava.lang.Threadlass)and there is noguarantee that alloated threads will everberun at
all. In multi-threadedCamelot programswerequirethat all threads are started at thepoint where they are
onstruted.
Finally, we have a single onstrutor for lasses in Camelot beause our type system does not support
overloading. This must bepassed initial valuesfor allthe elds of the lass(beausethe thread will initiate
automatially). AllCamelotthreadsexeptthemain threadofontrolaredaemonthreads,whihmeansthat
theJavaVirtualMahinewill notkeeprunningifthemain threadexits.
letre
threadname
(
args
) =
let
locals
=
subexps
inthreadname
(
args
)
let
threadInstance
=
new
threadname
(
actuals
)
in. . .
lass
threadnameHolder
(
args
) =
java
.
lang
.
Thread
withletre
threadname
() =
let
locals
=
subexps
inthreadname
()
method
run
() :
unit
=
let _
=
this#
setDaemon
(
true)
in
threadname
()
end
let
threadInstance
=
new
threadnameHolder
(
actuals
)
inlet_
=
threadInstance
#
start
()
in. . .
Fig.6.1.Derived formsforthreadreationanduseinCamelot
ThissimpliedidiomofthreaduseinCamelotallowsustodenederivedformsforCamelotthreadswhih
abbreviate the use of threads in the language. These derived forms an be implemented by lass hoisting,
movingageneratedlassdenitiontothetopleveloftheprogram. ThistranslationisoutlinedinFigure 6.1.
7. Threads and (non-)termination. The Camelotprogramminglanguageis supported notonly bya
strong,expressivetypesystembutalsobyaprogramlogiwhihsupportsreasoningaboutthetimeandspae
bepossibleto onvert thislogiinto alogi oftotalorretnesswhih wouldguaranteeterminationinsteadof
assumingitbutproofsinsuhalogiwouldbemorediulttoproduethanproofsinthepartialorretness
logi.
It mightseemnonsensial to havealogiof partial orretnessto guarantee exeutiontimes ofprograms
(thisprogrameitherterminatesin20seondsoritneverdoes)buteventheseproofsaboutexeutiontimeshave
theiruse. Theyareusedtoprovideaboundontherunningtimeofaprogramsothatifthistimeisexeededthe
programmaybeterminatedforiblybytheuserortheoperatingsystembeauseafterthispointitseemsthat
theprogramwillnotterminate. Suhapriori informationaboutexeutiontimeswouldbeusefulforsheduling
purposes. InGrid-basedomputingenvironmentsGridservieproviderssheduleinomingjobsonthebasisof
estimatedexeution timessuppliedbyGrid users. Theseestimatesare sometimes signiantlywrong,leading
thesheduler eitherto foriblyterminate anover-runningjobdue to anunder-estimatedexeution timeorto
sheduleotherjobs poorlyonthebasisofanover-estimatedexeutiontime.
Beauseofthepreseneofthreadsinthelanguagewenowhavemeaningful(impure,side-eeting)funtions
whihdo notterminatesoastrong funtionalprogrammingapproah[27℄ requiringproofs oftermination for
everyfuntion wouldbeinappropriateforourpurposes.
8. Related work. The ore of the Camelot programminglanguage is a strit, all-by-value rst-order
funtionalprogramminglanguageintheMLfamilyextendedwithexpliitmemorydealloationommandsand
an extended type system whih expresses the ost of funtion appliation in terms of an inreasein thesize
ofthealloatedmemoryonthe heap. Other authorshaveaddressedasimilar programmingmodelwithsome
variations. Lee, Yang and Yi [17℄ presenta statianalysis approah whih is used in applying asoure-level
transformationto insert expliitfree ommandsinto the programtext. Theiranalysis allowsuses ofexpliit
memory dealloation whih are not expressible in Camelot due to the linearity requirement of the Camelot
type system. Vasonelos and Hammond[28℄ presenta typesystem whih is superior to oursin applying to
higher-orderfuntional programs. Ourprimary ostomputationis memoryalloationwhereastheirprimary
fous is on run-time abstrated as the number of beta-redutions in the abstrat semanti interpretation of
the funtion term againstthe operational semantis of the language. Our work diers from bothof these in
onsideringmulti-threaded,notonlysingle-threadedprograms.
WehavemadereferenetoMLj,theaspets ofwhih relatedtoJavainteroperabilityaredesribedin [3℄.
MLjisafullyformedimplementationofStandardML, andassuhisamuhlargerlanguagethanweonsider
here. Inpartiular,MLjandrawuponfeaturesfromSMLsuhasmodulesandfuntors,forexample,allowing
the reation of lasses parameterised on types. Suh exibility omes with a prie, and we hope that the
restritionsofoursystemwillmaketheertiationoftheresoureusageofobjet-orientedCamelotprograms
morefeasible.
ByvirtueofompilinganML-likelanguagetotheJVM,wehavemademanyofthesamehoiesthathave
beenmadewithMLj. Inmanyasesthereisoneobvioustranslationfromhighlevelonepttoimplementation,
andinotherstheappropriatelanguageonstrutissuggestedbytheJavaobjetsystem. Howeverwehavealso
made dierent hoies moreappropriate to ourpurpose, in terms of transparenyof resoure usage and the
desireforasmallerlanguage. Forexample,werepresentobjetsasreordsofmutableeldswhereasMLjuses
immutableelds holdingreferenes.
There have been various other attempts to add objet oriented features to ML and ML-like languages.
O'Camlprovidesalean,exibleobjetsystemwithmanyfeaturesandimpressivetypeinfereneaformalised
subsetisdesribedin[23℄. Asinobjet-orientedCamelot,objetsaremodelledasreordsofmutableeldsplus
aolletionofmethods. ManyoftheadditionalfeaturesofO'Camlouldbeaddedtoobjet-orientedCamelot
ifdesired, but there are someompliations ausedwhen weonsider Javaompatibility. Forexample, there
are various waysto ompile parameterisedlasses and polymorphimethods for the JVM, but making these
featuresinteratleanly withtheJavaworldismoresubtle.
Thepowerofthe O'Camlobjetsystemseemsto ome morefrom thedistintivetype systememployed.
O'Camlusesthenotionofarow variable, atypevariablestandingforthetypesofanumberofmethods. This
makesitpossibletoexpressalasswith thesemethods,and possiblymore asatype. Wherewewouldhave
amethod parametertakingapartiularobjettypeandby subsumptionanysubtype, in O'Camlthetypeof
thatparameterwouldinludearowvariable,sothatanyobjetwiththeappropriatemethodsandeldsould
AlassmehanismforMobyisdenedin[8℄withthepriniplethatlassesandmodulesshouldbeorthogonal
onepts. Lakingamodulesystem,Camelotisunableto takesuh anapproah,but bothMobyandO'Caml
havebeenaguide toonreterepresentation. Manyotherrelevantissuesare disussedin [21℄, but againlak
ofamodule systemandourdesireto avoidthis to keepthelanguagesmallgivesusadierent perspetive
ontheissues.
9. Conlusions and further work. Our ongoing programme of researh on the Camelot funtional
programminglanguagehasbeeninvestigatingresoureonsumptionandprovidingstatiguaranteesofresoure
onsumptionatthetimeofprogramompilation. Ourthreadmanagementsystemprovidesalayerofabstration
over Javathreads. This ould allow us to modify the present implementation to multi-task several Camelot
threadsontoasingleJavathread. Thereasontodothiswouldbetoirumventtheungenerousthreadlimiton
someJVMs. Thisextensionremainsasfutureworkbutourpresentdesignstronglysupportssuhanextension.
Wehavedisussedaverysimplethread pakageforCamelot. Amoresophistiatedone,perhapsbasedon
Thimble[26℄, wouldprovideamuh morepowerfulprogrammingmodel.
A possibly protable extension of Camelot would be to use defuntionalization [24℄ to eliminate mutual
tail-reursion. Givenasetof mutuallyreursivefuntions
F
whose resultsareof typet,wedeneadatatypes whih has for eah of the funtions in
F
a onstrutor with arguments orresponding to the funtion'sarguments. The olletion of funtions
F
is then replaed by a single funtion f: s -> t whose body is amathstatement whih arriesout the omputations required by theindividual funtions in
F
. In this waythe mutually reursive funtions an be replaed by asingle tail-reursivefuntion, and we already have an
optimisation whih eliminates reursion for suh funtions. This tehnique is somewhat lumsy, and are is
required in reyling the diamonds whih are required to ontain members of the datatypes required by s.
Anotherpotentialproblemisthatseveralsmallfuntionsareeetivelyombinedintoonelargeone,andthere
is thus adanger that that 64k limit forJVM methods might be exeeded. Nevertheless, this tehnique does
overometheproblemsrelatedtomutualreursionwithoutaetingthetransparenyoftheompilationproess
unduly, and it mightbe possiblefor the ompiler to perform the appropriate transformationsautomatially.
Weintendtoinvestigatethisin moredetail.
Aknowledgements. TheauthorsaresupportedbytheMobile ResoureGuaranteesprojet(MRG,projet
IST-2001-33149). TheMRGprojetis fundedunder theGlobalComputing pro-ativeinitiativeoftheFuture
andEmergingTehnologiespartoftheInformationSoietyTehnologiesprogrammeoftheEuropean
Commis-sion'sFifthFrameworkProgramme. TheothermembersoftheMRGprojetprovidedhelpfulommentsonan
earlierpresentationofthiswork. JavaisatrademarkofSUNMirosystems.
REFERENCES
[1℄ D.AspinallandM.Hofmann,Anothertypesystemforin-plaeupdate,inPro.11thEuropeanSymposiumon
Program-ming,Grenoble,vol.2305ofLetureNotesinComputerSiene,Springer,2002.
[2℄ N.Benton,Someshortomings of,and possibleimprovements to,theJavaVirtualMahine. Thisisanunpublishednote
whihisavailableon-lineathttp://researh.mirosof t. om/
∼
n ik/ jvm rit ique .pd f,June1999.[3℄ N. Bentonand A.Kennedy,Interlanguageworking withouttears: BlendingSMLwith Java,inProeedingsof the4th
ACMSIGPLANConfereneonFuntionalProgramming,Paris,Sept.1999,ACMPress.
[4℄ N. Benton,A. Kennedy, andG. Russell,CompilingStandard MLtoJavabyteodes,inProeedingsofthe3rd ACM
SIGPLANConfereneonFuntionalProgramming,Baltimore,sep1998,ACMPress.
[5℄ L. Beringer,K. MaKenzie,andI. Stark,Grail: a funtionalformforimperativemobileode,inEletroniNotesin
TheoretialComputerSiene,V.Sassone,ed.,vol.85,Elsevier,2003.
[6℄ E. Biagioni,K. Cline,P.Lee,C.Okasaki, andC. Stone,Safe-for-spaethreadsinStandard ML,Higher-Orderand
SymboliComputation,11(1998),pp.209225.
[7℄ J. Clements and M. Felleisen, A tail-reursive mahine with stak inspetion, ACM Transations on Programming
LanguagesandSystems. Toappear.
[8℄ K.FisherandJ.Reppy,Mobyobjetsandlasses,1998. Unpublishedmanusript.
[9℄ C. Flanagan,A.Sabry,B.F. Duba,andM.Felleisen,Theesseneofompilingwith ontinuations,inProeedings
ACMSIGPLAN1993Conf.onProgrammingLanguageDesignandImplementation,PLDI'93,Albuquerque,NM,USA,
2325June1993,vol.28(6),ACMPress,NewYork,1993,pp.237247.
[10℄ M. Hofmann,A type system for bounded spae and funtional in-plae update, NordiJournal ofComputing, 7 (2000),
pp.258289.
[11℄ ,Atypesystemforboundedspaeandfuntionalin-plaeupdate,NordiJournalofComputing,7(2000),pp.258289.
[13℄ ,Statipredition ofheapspaeusage forrst-orderfuntionalprograms,inPro.30thACMSymp.onPriniplesof
ProgrammingLanguages,NewOrleans,2003.
[14℄ S. Jost, lfd_infer: animplementation of a stati infereneon heap-spae usage.,inProeedings ofSPACE'04,Venie,
2004.Toappear.
[15℄ M. Kone£ný, Funtional in-plae update with layered datatype sharing, in TLCA 2003, Valenia, Spain, Proeedings,
Springer-Verlag,2003,pp.195210.LetureNotesinComputerSiene2701.
[16℄ ,Typingwithonditionsandguaranteesforfuntionalin-plaeupdate,inTYPES2002Workshop,Nijmegen,
Proeed-ings,Springer-Verlag,2003,pp.182199. LetureNotesinComputerSiene2646.
[17℄ O.Lee,H.Yang,andK.Yi,InsertingsafememoryreuseommandsintoML-likeprograms,inProeedingsofthe10th
AnnualInternationalStatiAnalysisSymposium,vol.2694ofLetureNotesinComputerSiene,Springer-Verlag,2003,
pp.171188.
[18℄ P.Lee,ImplementingthreadsinStandardML,inAdvanedFuntionalProgramming,SeondInternationalShool,Olympia,
WA,USA,August26-30,1996,TutorialText,J.Launhbury,E.Meijer,andT.Sheard,eds.,vol.1129ofLetureNotes
inComputerSiene,Springer,1996,pp.115130.
[19℄ K.MaKenzie,Grail: afuntionalintermediatelanguageforresoure-boundedomputation.LFCS,UniversityofEdinburgh,
2002.Availableathttp://groups.inf.ed.a .uk /mrg /pu bli atio ns/ .
[20℄ K.MaKenzieandN.Wolverson,CamelotandGrail: Resoure-awarefuntionalprogrammingfortheJVM,inTrends
inFuntionalProgramming,Intellet,2004,pp.2946.
[21℄ D.MaQueen,ShouldMLbeobjet-oriented?,FormalAspetsofComputing,13(2002).
[22℄ E.MeijerandJ.Miller,TehnialOverview oftheCommon LanguageRuntime(orwhy theJVMis notmyfavourite
exeutionenvironment). URL:http://dos.msdnaa.net/a rk/W ebf iles /whi tep aper s.ht m, 2001.
[23℄ D.Remy andJ. Vouillon,ObjetiveML:Aneetive objet-oriented extensiontoML, TheoryandPratie ofObjet
Systems,4(1998),pp.2750.
[24℄ J.C.Reynolds,Denitionalinterpretersforhigher-orderprogramminglanguages,Higher-OrderandSymboliComputation,
11(1998),pp.363397.
[25℄ M. Shinz andM. Odersky,Tailallelimination on theJavaVirtual Mahine,inProeedings ofBabel'01, vol.59of
EletroniNotesinTheoretialComputerSiene,2001.
[26℄ I.Stark,ThimbleThreadsforMLj,inProeedingsoftheFirstSottishFuntionalProgrammingWorkshop,no.RM/99/9
inDepartmentofComputingandEletrialEngineering,Heriot-WattUniversity,TehnialReport,1999,pp.337346.
[27℄ D.Turner,Elementarystrongfuntionalprogramming,inProeedingsoftheFirstInternationalSymposiumonFuntional
ProgrammingLanguagesinEduation,R.PlasmeijerandP.Hartel,eds.,vol.LNCS1022,Nijmegen,Netherlands,De.
1995,Springer.
[28℄ P.B. Vasonelos andK. Hammond,Inferringosts forreursive, polymorphi and higher-orderfuntionalprograms,
inProeedingsofthe15thInternational WorkshopontheImplementationofFuntionalLanguages,G.Mihaelsonand
P.Trinder,eds.,LNCS,Springer-Verlag,2003. Toappear.
[29℄ D. Wakeling, Compilinglazy funtional programs for theJava VirtualMahine, Journalof Funtional Programming,9
(1999),pp.579603.
[30℄ N.Wolverson,Optimisationandresourebounds inCamelotompilation. Final-yearprojetreport,Universityof
Edin-burgh,2003.Availableathttp://groups.inf.ed.a. uk/ mrg/ publ ia tion s/w olve rson .ps .
[31℄ N.WolversonandK.MaKenzie,O'Camelot:addingobjetstoaresoure-awarefuntionallanguage,inProeedingsof
TFP2003,Intellet,2004,pp.4762.
Editedby: FrédériLoulergue
Reeived: June15,2004