FranoisPottier
INRIARoquenourt,BP105,78153LeChesnayCedex,Frane.
Franois.Pottierinria.fr
Abstrat. Extendingasubtyping-onstraint-basedtypeinfereneframe-
workwithonditionalonstraints androws yieldsapowerfultypeinfer-
ene engine. We illustrate this laim by proposing solutions to three
deliatetypeinferene problems:\aurate"patternmathings, reord
onatenation,and\dynami"messages.Untilnow,knownsolutionsre-
quiredsigniantlydierent tehniques;our theoretialontributionis
inusingonly asingle (and simple)set of tools. Onthe pratial side,
thisallowsallthreeproblemstobenetfromaommonsetofonstraint
simpliationtehniques,leadingtoeÆientsolutions.
1 Introdution
Typeinfereneisthetaskofexaminingaprogramwhihlakssome(orevenall)
typeannotations,andreoveringenoughtypeinformationtomakeitaeptable
by a type heker. Its original, and most obvious, appliation is to free the
programmer from the burden of manually providing these annotations, thus
making statityping alessdreary disipline. However,type inferenehas also
seenheavyuseasasimple,modularwayofformulatingprogramanalyses.
Thispaperpresentsaommonsolutiontoseveralseeminglyunrelatedtype
infereneproblems, byunifying inasingletypeinferene systemseveralprevi-
ouslyproposedtehniques,namely:asimpleframeworkforsubtyping-onstraint-
based type inferene [15℄, onditional onstraints inspired by Aiken, Wimmers
andLakshman[2℄,androws alaRemy[18℄.
Constraint-Based Type Inferene
Subtypingisapartialorderontypes,denedsothatanobjetofasubtypemay
safelybesuppliedwhereveranobjetofasupertypeisexpeted.Typeinferene
in the presene of subtyping reets this basi priniple. Every time a piee
of data is passed from a produer to a onsumer, the former's output type is
requiredtobeasubtypeofthelatter'sinputtype.Thisrequirementisexpliitly
reordedbyreatingasymbolisubtypingonstraintbetweenthesetypes.Thus,
eah potentialdata owdisoveredin the programyields one onstraint. This
fatallowsviewingaonstraintsetasadiretedapproximationoftheprogram's
dataowgraph{regardlessofourpartiulardenitionofsubtyping.
Various type inferene systems based on subtyping onstraints exist. One
and Smith [22℄, as well as an abstrat framework by Odersky, Sulzmann and
Wehr [12℄.Related systemsinlude set-basedanalysis [8,6℄and typeinferene
systemsbasedonfeatureonstraints[9,10℄.
Conditional Constraints
Inmostonstraint-basedsystems,theexpressionif e
0
then e
1
else e
2 may,
atbest,bedesribedby
1
^
2
where
i
stands for e
i
's type, and stands for the whole expression's type.
This amounts to stating that \e
1
's (resp. e
2
's) value may beome the whole
expression'svalue",regardlessofthetest'soutome.Amorepreisedesription
{ \if e
0
may evaluate to true (resp. false),then e
1
's (resp e
2
's) value may
beomethewholeexpression's value"{maybegivenusingnaturalonditional
onstraints:
true
0
?
1
^ false
0
?
2
Introduingtests intoonstraintsallowskeepingtrakofthe program'sontrol
ow{that is, mirroringthe way evaluation is aeted byatest's outome, at
theleveloftypes.
Conditional set expressions were introdued by Reynolds [21℄ as a means
of solving set onstraints involving strit type onstrutors and destrutors.
Heintze [8℄ usesthem to formulate an analysis whih ignores \dead ode".He
also introduesase onstraints,whih allowignoringtheeet of abranh,in
aaseonstrut,unless it isatually liableto be taken.Aiken, Wimmersand
Lakshman [2℄ use onditional types, together with intersetion types, for this
purpose.
In the present paper, we suggest a single notion of onditional onstraint,
whihisomparableinexpressivepowertotheaboveonstruts,andlendsitself
to asimpleand eÆientimplementation. (A similarhoie wasmade indepen-
dentlybyFahndrih[5℄.)Weemphasizeitsuseasawaynotonlyofintroduing
ontrolintotypes,butalsoofdelayingtypeomputations,thusintroduingsome
\laziness"intotypeinferene.
Rows
Designingatype systemforaprogramminglanguagewithreords, orobjets,
requires some way of expressing labelled produts of types, where labels are
eld ormethodnames.Dually,ifaprogramminglanguageallowsmanipulating
strutureddata, then itstype systemshall likely requirelabelled sums, where
labelsarenamesofdataonstrutors.
Remy[18℄elegantlydealswithbothproblemsatonebyintroduingnotation
toexpress denumerable,indexed familiesoftypes,alledrows:
(Here, rangesovertypes, and a;b;::: range over indies.) An unknown row
mayberepresentedbyarow variable, exatlyasin theaseof types.(Bylak
ofsymbols,weshallnotsyntatiallydistinguishregulartypevariablesandrow
variables.) The term a: ; representsa row whose element at index ais ,
and whoseother elementsaregivenby.Theterm standsforarowwhose
elementat anyindexis.Theseinformalexplanationsaremadepreise viaan
equationaltheory:
a:
a
; (b:
b
; )=b:
b
; (a:
a
; )
=a:;
Formoredetails,wereferthereaderto[18℄.
Rowsoerapartiularlystraightforwardwayofdesribingoperationswhih
treatalllabels(exeptpossiblyanitenumberthereof)uniformly.Beauseevery
failityavailableattheleveloftypes(e.g.onstrutors,onstraints)analsobe
made available at thelevelof rows, adesriptionofwhat happens atthe level
ofasinglelabel{writtenusingtypes{analsobereadasadesriptionofthe
whole operation {written using rows.This interestingpoint will bedeveloped
further inthepaper.
Putting ItAll Together
Ourpointistoshowthattheombinationofthethreeoneptsdisussedabove
yields a very expressive system, whih allows type inferene for a number of
advaned language features. Among these, \aurate" pattern mathing on-
struts,reordonatenation,and\dynami"messageswillbedisussedinthis
paper.Oursystemallowsperformingtype infereneforall ofthese features at
one. Furthermore,eÆieny issuesonerning onstraint-basedtypeinferene
systemshavealreadybeenstudied [5, 15℄.Thisexisting knowledgebenetsour
system,whih maythus beusedto eÆiently perform typeinferenefor allof
theabovefeatures.
Inthispaper,wefousonappliations ofourtypesystem,i.e.weshowhow
it allowssolvingeah ofthe problemsmentioned above.Theoretialaspets of
onstraint solving are disussed in [15, 17℄. Furthermore, a robust prototype
implementationispublilyavailable [14℄.Wedonotprovethatthetypesgiven
to the three problemati operations disussed in this paperare sound, but we
believethis isastraightforwardtask.
Thepaperisorganizedasfollows.Setion 2givesabrieftehnialoverview
of the type system, fousing on the notion of onstrained type sheme, whih
should be enoughto gain an understanding ofthe paper.Setions 3, 4,and 5
disuss typeinferene for\aurate" pattern mathings, reordonatenation,
and \dynami" messages, respetively, within our system. Setion 6 sums up
ourontribution,thenbrieydisussesfutureresearhtopis.AppendixAgives
somemoretehnialdetails,inludingthesystem'stypeinferenerules.Lastly,
AppendixBgivesseveralexamples,whihshowwhatinferredtypeslooklikein
2 System's Overview
Theprogramminglanguageonsidered throughout thepaperis aall-by-value
-aluluswithlet-polymorphism,i.e.essentiallyoreML.
e::=x;y;:::jx:ej(ee)jX;Y;:::jlet X=e in e
The typealgebra needed to dealwith suh aore languageis simple. The set
ofgroundtermsontainsallregulartreesbuiltover?,>(witharity0) and!
(witharity2). Itisequippedwithastraightforwardsubtyping relationship[15℄,
denoted ,whihmakesit alattie. Itisthe logialmodelin whih subtyping
onstraintsareinterpreted.
Symbols,type variables,types andonstraintsaredened asfollows:
s::=?j!j> v::=;;:::
::=vj?j ! j> ::=
j sv?
A groundsubstitution isamapfrom typevariablesto groundterms.A on-
straintoftheform
1
2
,whihreads\
1
mustbeasubtypeof
2
",issatised
by if and only if (
1
) (
2
). A onstraint of the form s ?
1
2 ,
whihreads\ifexeedss,then
1
mustbeasubtypeof
2
",issatisedbyif
and onlyifs
S
head(()) implies(
1 )(
2
),where headmapsaground
termto itsheadonstrutor,and
S
istheexpeted orderingoversymbols.A
onstraintset Cis satisedbyifandonlyifallofitselementsare.
Atypesheme isoftheform
::=8C :
where isatypeandCisaonstraintset,whihrestritsthesetof'sground
instanes.Indeed,thelatter,whihweall'sdenotation,isdenedas
f 0
;9 satisesC^() 0
g
Beauseallofatypesheme'svariablesareuniversallyquantied,wewillusually
omitthe8quantierandsimplywrite\ whereC".
Of ourse, the type algebra given above is very muh simplied. In gen-
eral,thesystemallowsdeningmoretypeonstrutors,separatingsymbols(and
terms)intokinds,andmakinguseofrows.(Afulldenition{withoutrows{ap-
pearsin[17℄.)However,forpresentation'ssake,wewillintroduethesefeatures
onlystepbystep.
Theoreprogramminglanguagedesribedaboveisalsolimited.Toextendit,
wewilldenenewprimitiveoperations,equippedwithanoperationalsemantis
and an appropriate type sheme. However, no extension to the type system {
e.g. in the form of new typing rules { will bemade. This explainswhy we do
notfurther desribethesystemitself. (Somedetailsare givenin Appendix A.)
3 Aurate Analysis of Pattern Mathings
When faed with a pattern mathing onstrut, most existing type inferene
systemsadoptasimple,onservativeapproah:assumingthateahbranhmay
betaken,theyletitontributetothewhole expression'stype.Amoreaurate
system should use types to prove that ertain branhes annot be taken, and
preventthemfromontributing.
Inthissetion, wedesribesuh asystem.Theessentialidea{introduing
a onditional onstrut at the level of types { is due to [8, 2℄. Some novelty
residesin ourtwo-steppresentation,whihwebelievehelpsisolateindependent
onepts. First, we onsider the ase where only one data onstrutor exists.
Then, we easily move to the general ase, by enrihing the type algebra with
rows.
3.1 The Basi Case
Weassumethelanguageallowsbuildingandaessingtaggedvalues.
e::=:::jPrejPre 1
Asingledataonstrutor,Pre,allowsbuildingtaggedvalues,whilethedestru-
tor Pre 1
allowsaessing theirontents.This relationshipis expressedbythe
followingredutionrule:
Pre 1
v
1 (Prev
2
) redues to (v
1 v
2 )
TherulestatesthatPre 1
rsttakesthetagothevaluev
2
,thenpassesit to
thefuntionv
1 .
At the levelof types,we introdue a (unary) varianttype onstrutor [℄.
Also,weestablishadistintionbetweenso-alled\regulartypes,"written,and
\eldtypes,"written.
::=;;;:::j?j>j ! j[℄
::='; ;:::jAbsjPre jAny
A subtypeorderingovereldtypesisdened straightforwardly:Absisitsleast
element,Anyisitsgreatest,andPreisaovarianttypeonstrutor.
ThedataonstrutorPreisgiventhefollowingtypesheme:
Pre:![Pre℄
Notie that there is no way of building a valueof type [Abs℄. Thus, if anex-
pressionhasthis type,thenitmustdiverge.Thisexplainsourhoieofnames.
Ifanexpression hastype [Abs℄, thenitsvaluemustbe\absent";ifithastype
ThedatadestrutorPre 1
isdesribedasfollows:
Pre 1
:(!)!['℄!
where 'Pre
Pre'?
The onditional onstraintallows (Pre 1
e
1 e
2
)to reeive type ? when e
2 has
type[Abs℄, reetingthefat that Pre 1
isn't invokeduntile
2
produes some
value. Indeed,aslongas'equals Abs, theonstraintis vauouslysatised, so
is unonstrainedand assumesitsmost preisevalue, namely?. However,as
soon as Pre ' holds, must be satised as well. Then, Pre 1
's type
beomesequivalentto(!)![Pre℄!,whihisitsusualMLtype.
3.2 The General Case
Wenowmovetoalanguagewithadenumerablesetofdataonstrutors.
e::=:::jKjK 1
jlose
(We letK,L; ::: stand for data onstrutors.)An expression maybe tagged,
as before, by applying a data onstrutor to it. Aessing tagged values be-
omesslightlymoreomplex,beausemultiple tagsexist.Thesemantisofthe
elementarydatadestrutor,K 1
,isgivenbythefollowingredutionrules:
K 1
v
1 v
2 (Kv
3
) reduesto (v
1 v
3 )
K 1
v
1 v
2 (L v
3
) reduesto (v
2 (Lv
3
)) whenK6=L
Aordingtotheserules,ifthevaluev
3
arriestheexpetedtag,thenitispassed
tothefuntionv
1
.Otherwise,thevalue{stillarryingitstag{ispassedtothe
funtion v
2
. Lastly, a speial value, lose, is added to the language, but no
additionalredutionruleisdened forit.
Howdowemodifyourtypealgebratoaommodatemultipledataonstru-
tors? InSetion 3.1, weused eld typesto enode informationaboutatagged
value's presene or absene. Here, we need exatlythe same information, but
this time about every tag. So, we need to manipulate a family of eld types,
indexed by tags.Todo so,weadd onelayerto the typealgebra:rows of eld
types.
::=;;;:::j?j>j ! j[℄
::='; ;:::jK:; j
::='; ;:::jAbsjPre jAny
Weannowextendtheprevioussetion'sproposal, asfollows:
K:![K:Pre; Abs℄
K 1
:(!)!([K:Abs; ℄!)![K:'; ℄!
where 'Pre
Pre'?
K 1
's typesheme involvesthesameonstraintsasin thebasiase. Usinga
singlerowvariable,namely ,intwodistintpositionsallowsexpressingthefat
thatvaluesarryinganytagotherthanKshallbepassedunmodiedtoK 1
's
seondargument.
lose'sargumenttypeis[Abs℄,whihpreventsitfromeverbeinginvoked.
This aords with the fat that losedoes not have an assoiated redution
rule.Itplaystherole ofafuntiondened byzeroases.
Thissystemoers extensible patternmathings: k-ary ase onstruts may
be written using k nested destrutor appliations and lose, and reeive the
desired, aurate type. Thus, no spei languageonstrut or type inferene
ruleisneededtodealwiththem.
4 Reord Conatenation
Stati typing for reord operations is a widely studied problem [4, 13℄. Com-
monoperationsinludeseletion,extension,restrition,andonatenation.The
latteromesintwoavors:symmetriandasymmetri.Theformerrequiresits
argumentsto havedisjointsetsof elds,whereasthelattergivespreedeneto
theseondonewhen aonitours.
Of these operations, onatenation is probably the most diÆult to deal
with, beause itsbehaviorvaries aordingto thepresene orabsene of eah
eldin itstwoarguments.Thishasledmanyauthorstorestrittheirattention
totypeheking,andtonotaddresstheissueoftypeinferene[7℄.Aninferene
algorithm for asymmetri onatenation was suggestedby Wand [23℄. He uses
disjuntions of onstraints, however,whih giveshis system exponentialom-
plexity.Remy[19℄suggestsanenodingofonatenationinto-abstrationand
reordextension,wheneaninferenealgorithmmaybederived.Unfortunately,
itspowerissomewhatdereasedbysubtleinterationswithML'srestritedpoly-
morphism;furthermore,theenodingisexposedto theuser.Inlaterwork [20℄,
Remy suggests a diret, onstraint-based algorithm, whih involves a speial
formofonstraints.Ourapproahisinspiredfromthiswork,butre-formulated
in terms of onditional onstraints, thus showing that no ad ho onstrut is
neessary.
Again,ourpresentationis in twosteps.Thebasi ase,where reordsonly
haveoneeld,istakledusingsubtypingandonditionalonstraints.Then,rows
allowustoeasilytransferourresultstotheaseofmultipleelds.
4.1 The Basi Case
Weassumealanguageequipped withone-eldreords,whoseuniqueeld may
beeither\absent"or\present".Morepreisely,weassumeaonstantdataon-
strutorAbs,andaunarydataonstrutorPre;a\reord"isavaluebuiltwith
oneoftheseonstrutors.Adatadestrutor,Pre 1
,allowsaessingtheontents
onatenationprimitives,writtenand,respetively.
e::=:::jAbsjPrejPre 1
jj
The relationship between reord reation and reord aess is expressed by a
simpleredutionrule:
Pre 1
(Prev) reduesto v
Thesemantisofasymmetrireordonatenationisgivenasfollows:
v
1
Abs redues to v
1
v
1
(Prev
2
) redues to Prev
2
(Ineahoftheserules,thevaluev
1
isrequiredtobeareord.)Lastly,symmetri
onatenationisdenedby
Absv
2
reduesto v
2
v
1
Abs reduesto v
1
(In thesetworules,v
1 andv
2
arerequiredtobereords.)
TheonstrutionofourtypealgebraissimilartotheoneperformedinSe-
tion3.1.Weintroduea(unary)reordtypeonstrutor,aswellasadistintion
betweenregulartypesandeldtypes:
::=;;;:::j?j>j ! jfg
::='; ;:::jBotjAbsjPre jEither jAny
Letusexplain,stepbystep,ourdenitionofeldtypes.Ourrst,naturalstep
is to introdue type onstrutors Abs and Pre, whih allow desribing values
built with the data onstrutors Abs and Pre. The former is a onstant type
onstrutor,whilethelatterisunaryandovariant.
Many type systems for reord languages dene Pre to be a subtype of
Abs. This allows a reord whose eld is present to pretend it is not, leading
to a lassi theory of reords whose elds may be \forgotten" via subtyping.
However,whenthelanguageoersreordonatenation,suhadenition isn't
appropriate.Why?Conatenation{asymmetriorsymmetri{involvesahoie
betweentworedutionrules,whihisperformedbymathingone,orboth,ofthe
argumentsagainstthe dataonstrutors AbsandPre. If,at theleveloftypes,
weallowanon-empty reordtomasquerade asan empty one,thenitbeomes
impossible, basedonthe arguments'types, tond outwhih ruleapplies, and
to determinethetypeoftheoperation'sresult.Insummary,in thepreseneof
reord onatenation,nosubtyping relationshipmust exist betweenPre and
Abs.(Thisproblemiswelldesribed{althoughnotsolved{in[4℄.)
ThisleadsustomakingAbsandPreinomparable.Onethishoiehasbeen
made,ompletingthedenitionofeldtypesisratherstraightforward.Beause
Bot, and agreatest element Any. Lastly, weintrodue aunary, ovarianttype
onstrutor,Either, whih wedeneastheleastupperboundofAbsandPre,
sothatAbst(Pre)equalsEither.Thisoptionalrenementallowsustokeep
trakofaeld's type,evenwhen itspreseneisnotasertained.Thelattieof
eld typesisshownin gure1.
Any
Either
OO
Abs
99 t
t t t t t t t t
Pre
ee LL
LL LL LL LL
Bot
ee JJ
JJ JJ JJ J
99 r
r r r r r r r r r
Fig.1.Thelattieofreordeldtypes
Letusnowassigntypestotheprimitiveoperationsoeredbythelanguage.
Reordreationandaess reeivetheirusualtypes:
Abs:fAbsg
Pre:!fPreg
Pre 1
:fPreg!
There remainstoomeupwithorret,preise typesforbothavorsofreord
onatenation. Thekeyidea issimple. As shown by its operationalsemantis,
(eitheravorof)reordonatenationisreallyafuntion dened byasesover
thedataonstrutorsAbsandPre{andSetion3hasshownhowtoaurately
desribesuh afuntion.Letusbegin,then,withasymmetri onatenation:
:f'
1 g!f'
2 g!f'
3 g
where '
2
Either
2
Abs'
2
?'
1 '
3
Pre'
2
?Pre
2 '
3
Clearly, eah onditional onstraint mirrors one of the redution rules. In the
seond onditional onstraint,we assume
2
isthe typeof theseond reord's
eld {if ithas one.The rstsubtyping onstraint representsthis assumption.
Notiethat weusePre
2
, ratherthan'
2
,astheseond branh's resulttype;
thisisstritly morepreise,beause' maybeoftheform Either .
Lastly,weturnto symmetrionatenation:
:f'
1 g!f'
2 g!f'
3 g
where Abs'
1
?'
2 '
3
Abs'
2
?'
1 '
3
Pre'
1
?'
2 Abs
Pre'
2
?'
1 Abs
Again, eah of the rst two onstraints mirrorsaredution rule. The last two
onstraintsdisallowtheasewherebothargumentsarenon-emptyreords.(The
areful reader will notie that any one of these two onstraints would in fat
suÆe;botharekeptforsymmetry.)
Inbothases,theoperation'sdesriptionin termsof onstraintsloselyre-
sembles its operationaldenition. Automatially derivingthe former from the
latterseemspossible;thisisanareaforfutureresearh.
4.2 The General Case
We now move to a languagewith adenumerable set of reord labels, written
l, m, et. The languageallows reatingthe empty reord, aswell asany one-
eldreord;italsooersseletionandonatenationoperations.Extensionand
restritionanbeeasily added,ifdesired;weshalldispensewiththem.
e::=?jfl=egje:ljj
Wedonotgivethelanguage'ssemantis,whihshouldhopefullybelearenough.
At thelevelof types,we againintroduerows ofeld types, denoted by.
Furthermore,we introdue rowsof regular types,denoted by%. Lastly, welift
theveeld typeonstrutorstothelevelofrows.
::=;;;:::j?j>j ! jfg
::='; ;:::jBotjAbsjPre jEither jAny
%::=;;;:::jl:; %j
::='; ;:::jl:; jjBotjAbsjPre%jEither%jAny
Thisallowswritingomplexonstraintsbetweenrows,suhas'Pre,where
'andarerowvariables.Aonstraintbetweenrowsstandsforaninnitefamily
ofonstraintsbetweentypes,obtainedomponent-wise.That is,
(l:' 0
; ' 00
)Pre(l: 0
; 00
) standsfor (' 0
Pre 0
)^(' 0 0
Pre 00
)
We may now give types to the primitive reord operations. Creation and
seletionareeasilydealtwith:
?:fAbsg
fl=g:!fl:Pre; Absg
Interestingly,thetypesofbothonatenationoperationsareunhangedfromthe
previoussetion { at least, syntatially. (For spaereasons, we donot repeat
them here.) Asubtle dierene liesin thefat that allvariables involvedmust
nowbereadasrowvariables,ratherthanastypevariables.Inshort,theprevious
setionexhibitedonstraintswhihdesribeonatenation,atthelevelofasingle
reordeld;here,therowmahineryallowsustorepliatetheseonstraintsover
aninnitesetoflabels.Thisinreaseinpoweromesalmostforfree:itdoesnot
addanyomplexityto ournotionofsubtyping.
5 Dynami Messages
So-alled\dynami"messageshavereentlyreeivednewattentioninthestati
typing ommunity. Bugliesi and Crafa [3℄ propose a higher-order type system
whihaountsforrst-lassmessages.Nishimura[11℄taklestheissueoftype
infereneandsuggestsaseond-ordersystemalaOhori[13℄.MullerandNishi-
mura[10℄proposeasimpliedapproah,basedonanextendedfeature logi.
Theproblemonsistsinperformingtypeinfereneforanobjet-orientedlan-
guagewheremessagesarerst-lassvalues,madeupofalabel andaparameter.
Here, we view objets asreords of funtions, and messagesas tagged values.
(Betterwaysofmodelingobjetsexist,butthatisanindependentissue.)Thus,
weonsideralanguagewithreordsanddataonstrutors,asdesribedinSe-
tions3.2and4.2.Furthermore,weletreordlabelsanddataonstrutorsrange
overasinglenamespae,thatofmessagelabels.(Tosavespae,wehoosetodeal
diretlywith thease ofmultiple messagelabels; however,ourusual, two-step
presentationwouldstillbepossible.)Lastly,wedeneaprimitivemessage-send
operation,written#,whosesemantisisasfollows:
#fm=v
1
;:::g(mv
2
) reduesto (v
1 v
2 )
Inplain words,# examinesitsseondargument,whih mustbesomemessage
m with parameter v
2
. It then looks up the method named m in the reeiver
objet,and appliesthemethod's ode,v
1
,to themessageparameter.
In a languagewith \stati" messages, a message-send operation may only
involveaonstantmessagelabel.So,insteadofasinglemessage-sendoperation,
afamily thereof,indexedby messagelabels, isprovided. Infat,in oursimple
model, these operationsare denablewithin the language.Theoperation#m,
whihallowssendingthemessagemtosomeobjetowithparameterp,maybe
dened aso:p:(o:mp). Then,typeinfereneyields
#m:fm:Pre(!); Anyg!!
Beausethemessagelabel,m,isstatiallyknown,itmaybeexpliitlymentioned
in the type sheme, making it easy to require the reeiver objetto arry an
appropriatemethod.Inalanguagewith\dynami"messages,ontheotherhand,
misnolongerknown.Theproblemthusappearsmoreomplex;ithas,infat,
sparked thedevelopment ofspeial-purpose onstraintlanguages[10℄. Yet,the
Considerthe partial appliation of the message send primitive # to some
reordr.Itisafuntionwhihaeptssometaggedvalue(mv),theninvokesan
appropriatepieeofode,seletedaordingtothelabelm.Thisshould ringa
bell{itismerelyaform ofpattern mathing,whihthispaperhasextensively
disussedalready.Therefore,wepropose
#:f'g![ ℄!
where Pre
Pre ?'Pre(!)
(Here,allvariablesexept arerowvariables.)Theoperation'srst(resp.se-
ond) argument is required to be an objet (resp. a message), whose ontents
(resp. possiblevalues) aredesribedby therow variable '(resp. ).The rst
onstraintmerelyletsstandforthemessageparameter'stype.Theonditional
onstraint,whihinvolvestworowterms,shouldagainbeunderstoodasafamily,
indexedbymessagelabels,ofonditionalonstraintsbetweenreordeldtypes.
Theonditionalonstraintassoiatedwithsomelabelmshallbetriggeredonly
if 'selementatindexmisoftheformPre ,i.e.onlyifthemessage'slabelmay
bem.Whenitistriggered,itsright-handsidebeomesative,withathree-fold
eet. First,''s element at index m mustbe ofthe form Pre( ! ),i.e. the
reeiverobjetmustarryamethodlabeledm.Seond,themethod'sargument
typemustbe(asupertypeof)'selementat labelm,i.e. themethodmust be
able to aeptthe message'sparameter.Third, themethod's resulttype must
be(asubtypeof),i.e.thewholeoperation'sresulttypemustbe(atleast)the
join ofallpotentiallyinvokedmethods'returntypes.
Our proposal shows that type inferene for \dynami" messages requires
nodediated theoretialmahinery.Italso showsthat\dynami"messagesare
naturallyompatible with alloperationsonreords, inludingonatenation{
aquestionwhih wasleftunansweredbyNishimura[11℄.
6 Conlusion
In this paper, we have advoated enrihing an existing onstraint-based type
inferene framework [15℄ with rows [18℄ and onditional onstraints [2℄. This
providesasingle (andsimple) solution to several diÆulttypeinferene prob-
lems, eah of whih seemed to require,until now,speial forms ofonstraints.
Fromapratialpointofview,itallowsthemtobenetfromknownonstraint
simpliationtehniques[17℄,leadingto aneÆientinferenealgorithm[14℄.
We believe our system subsumes Remy's proposal for reord onatena-
tion [20℄, as well asMuller and Nishimura's viewof \dynami" messages [10℄.
Aiken, Wimmers and Lakshman's \soft" type system [2℄ is more preise than
ours, beauseit interprets onstraintsin a riher logialmodel, but otherwise
oerssimilarfeatures.Infat,theideasdevelopedinthispaperouldhavebeen
presentedin the setting of Bane [5℄, or, more generally, of any systemwhih
Referenes
[1℄ AlexanderS. Aiken and Edward L. Wimmers. Type inlusion onstraints and
typeinferene. InFuntionalProgramming&Computer Arhiteture,pages31{
41. ACMPress, June1993. URL: http://http.s.berkeley.edu/~ aike n/ftp /
fpa93.ps.
[2℄ Alexander S. Aiken, Edward L. Wimmers, and T. K. Lakshman. Soft typing
withonditionaltypes. InPriniples ofProgrammingLanguages,pages163{173,
January1994. URL:http://http.s.berkeley.edu/ ~aik en/ft p/po pl94 .ps.
[3℄ Mihele Bugliesi and Silvia Crafa. Objet aluli for dynami messages. In
TheSixthInternationalWorkshoponFoundationsofObjet-OrientedLanguages,
FOOL 6, San Antonio, Texas, January 1999. URL: ftp://ftp.s.williams.
edu/pub/kim/FOOL6/bugliesi.ps.
[4℄ LuaCardelliandJohnMithell.Operationsonreords.MathematialStrutures
inComputerSiene,1:3{48,1991. AlsoinCarlA.GunterandJohnC.Mithell,
editors, Theoretial Aspets of Objet-Oriented Programming: Types, Semantis,
andLanguageDesign,MITPress,1994.URL:http://researh.mirosoft.om /
Users/lua/Papers/Reords.ps.
[5℄ Manuel Fahndrih. Bane: A Library for Salable Constraint-Based Program
Analysis. PhDthesis, University of California at Berkeley, 1999. URL: http:
//researh.mirosoft.om/~maf/ diss. ps.
[6℄ CormaFlanagan andMatthias Felleisen. Componentialset-based analysis. In
Proeedings of the ACM SIGPLAN '97 Conferene on Programming Language
DesignandImplementation,pages235{248,LasVegas,Nevada,June1997. URL:
http://www.s.rie.edu/CS/PLT/ Publi ati ons/p ldi9 7-ff .ps. gz.
[7℄ Robert Harper and Benjamin Piere. A reord alulus based on symmet-
ri onatenation. In Conferene Reord of the 18th Annual ACM Sympo-
siumonPriniples of ProgrammingLanguages (POPL'91),pages131{142,Or-
lando, Florida, January 1991. ACM Press. URL: http://www.is.upenn.edu/
~bpiere/papers/merge.ps.gz.
[8℄ NevinHeintze. SetbasedanalysisofMLprograms. TehnialReportCMU-CS-
93-193,CarnegieMellonUniversity,ShoolofComputerSiene,July1993.URL:
ftp://reports.adm.s.mu.edu/u sr/an on/1 993/C MU-CS-9 3-19 3.ps .
[9℄ Martin Muller, Joahim Niehren, and Andreas Podelski. Ordering onstraints
over feature trees. Constraints, an International Journal, Speial Issue on
CP'97, Linz, Austria, 1999. URL: ftp://ftp.ps.uni-sb.de/pub/p apers /
ProgrammingSysLab/ftsub-onstr aint s-99 .ps. gz.
[10℄ MartinMullerandSusumuNishimura.Typeinfereneforrst-lassmessageswith
featureonstraints. InJiehHsiangand AtsushiOhori, editors,Asian Computer
Siene Conferene(ASIAN 98), volume1538of LNCS,pages169{187,Manila,
ThePhilippines,Deember1998.Springer-Verlag. URL:ftp://ftp.ps.uni-sb.
de/pub/papers/ProgrammingSysLa b/Fir stCl ass98 .ps. gz.
[11℄ SusumuNishimura. Statityping for dynami messages. InConferene Reord
of POPL '98: The 25th ACM SIGPLAN-SIGACT Symposium on Priniples
of Programming Languages, pages 266{278, San Diego, California, January
1998. URL: ftp://ftp.kurims.kyoto-u.a.j p/pub /pap er/m ember /nis imura /
dmesg-popl98.ps.gz.
[12℄ Martin Odersky, Martin Sulzmann, and Martin Wehr. Type inferene with
onstrained types. Theory and Pratie of Objet Systems, 5(1), 1999. URL:
[13℄ AtsushiOhori. Apolymorphireordalulusanditsompilation. ACMTrans-
ationsonProgrammingLanguagesandSystems,17(6):844{895,November1995.
[14℄ Franois Pottier. Wallae: an eÆient implementation of type inferene with
subtyping. URL:http://pauilla.inria.fr/~fpo ttie r/wal lae /.
[15℄ FranoisPottier.Simplifyingsubtypingonstraints:atheory.Submittedforpub-
liation,Deember1998. URL:http://pauilla.inria.fr/~f potti er/p ublis /
fpottier-journal-98.ps.gz.
[16℄ Franois Pottier. Type inferene inthe presene of subtyping: from theory to
pratie. Tehnial Report 3483, INRIA, September 1998. URL: ftp://ftp.
inria.fr/INRIA/publiation/RR/ RR-3 483.p s.gz .
[17℄ FranoisPottier.Subtyping-onstraint-basedtypeinferenewithonditionalon-
straints: algorithms and proofs. Unpublished draft, July 1999. URL: http:
//pauilla.inria.fr/~fpottier/ publi s/fp ottie r- ondit iona l.ps. gz.
[18℄ Didier Remy. Projetive ML. In 1992 ACM Conferene on Lisp and Fun-
tional Programming, pages 66{75, New-York, 1992. ACM Press. URL: ftp:
//ftp.inria.fr/INRIA/Projets/ rist al/D idier .Rem y/lf p92.p s.gz .
[19℄ DidierRemy.Typingreordonatenationforfree.InCarlA.GunterandJohnC.
Mithell, editors, Theoretial Aspets Of Objet-Oriented Programming. Types,
SemantisandLanguage Design.MITPress,1993. URL:ftp://ftp.inria.fr/
INRIA/Projets/ristal/Didier. Remy/ taoo p2.ps .gz.
[20℄ DidierRemy.Aasestudyoftypehekingwithonstrainedtypes:Typingreord
onatenation. Presented at theworkshop onAdvanes inTypesfor Computer
Siene at the Newton Institute, Cambridge, UK, August 1995. URL: http:
//ristal.inria.fr/~remy/work/ sub-ona t.dv i.gz .
[21℄ John C.Reynolds. Automatiomputation of datasetdenitions. InA. J. H.
Morrell,editor,InformationProessing68,volume1,pages456{461,Amsterdam,
1969.North-Holland.
[22℄ ValeryTrifonov andSottSmith. Subtypingonstrained types. InProeedings
of the Third International Stati Analysis Symposium, volume 1145 of LNCS,
pages349{365.SV,September1996. URL:http://www.s.jhu.edu/~trifonov /
papers/subon.ps.gz.
[23℄ MithellWand.Typeinfereneforreordonatenationandmultipleinheritane.
InformationandComputation,pages1{15,1993.Apreliminaryversionappeared
inPro.4thIEEE SymposiumonLogiin Computer Siene (1989),pp. 92{97.
URL:ftp://ftp.s.neu.edu/pub/peop le/wa nd/p aper s/i-91.d vi.
A Rules
This appendix gives a short desription of the system's type inferene rules
(Figure2).Eventhoughonlytheorelanguageisexpliitlytreated,theserules
are suÆient to deal with a full-featured programminglanguage. Indeed, any
extralanguageonstrutmaybeviewedeither assyntatisugar,orasanew
primitiveoperation, whih anbe bound in an initial typing environment
0 .
Also,notethatthesetypeinferenerulesuseneitheronditionalonstraints,nor
rows;thesewillome onlyfrom
0 .
Forsimpliity, wedistinguish identiersbound by ,denoted x;y;::: from
those bound bylet, denoted X;Y;::: Furthermore,we expet -identiers to
fresh
`
I
x:8?:hx:i)
(Vari)
`
I
e:8C :A) 0
A(x)=
`Ix:e:8C :(Anx))! 0
(Abs
i )
`Ie1:8C1:A1)1 `Ie2:8C2:A2)2
fresh C=C
1 [C
2 [f
1
2
!g
`Ie1e2:8C :(A1uA2))
(App
i )
(X)= freshrenamingof
`
I
X :()
(LetVari)
`
I e
1 :
1
+[X7!
1
℄`
I e
2 :
2
`Ilet X=e1 in e2:2
(Let
i )
Fig.2.Typeinferenerules
program.Lastly,in everyexpressionoftheformlet X =e
1 in e
2
,werequire
X to appearfreewithin e
2
.It would beeasytooveromethese restritions,at
theexpenseofheaviernotation.
Therules are fairly straightforward. Themain point of interest is the way
eahappliation node produesasubtypingonstraint. Theonlypeuliarityis
inthewaytypeenvironmentsaredealtwith.Theenvironment ,whihappears
ontheleftoftheturnstile,isalistofbindingsoftheformX :.Typeshemes
are slightlymoreomplex thaninitially shownin Setion 2.Theyare, in fat,
of the form ::= 8C :A ), where the ontext A is a set of bindings of the
formx:.Thepointofsuhaformulationistoobtainasystemwherenotype
sheme hasfreetype variables.This allowsasimplertheoretial desriptionof
onstraintsimpliation.
Asfar asnotation isonerned, hx:i representsaontextonsisting ofa
singleentry,whihbindsx to .Anx istheontext obtainedbyremovingx's
bindingfromA,ifitexists.Forthesakeofreadability,wehaveabusednotation
slightly. In rule (Abs
i
), A(x) stands for thetype assoiatedwith x in A, if A
ontains a binding for x; it stands for > otherwise. In rule (App
i ), A
1 uA
2
represents the point-wise intersetion of A
1 and A
2
. That is, whenever x has
a binding in A
1 or A
2
, its binding in A
1 uA
2 is A
1
(x)uA
2
(x). Beause we
donothaveintersetion types,this expressionshould in fat beunderstood as
afreshtypevariable,aompaniedbyanappropriateonjuntion ofsubtyping
onstraints.
Therulesimpliitlyrequireeveryonstraintsettoadmitatleastonesolution.
B Examples
Example 1. Wedeneafuntionwhihreadseldloutofareordr,returninga
defaultvaluedifrhasnosuheld,bysettingextrat=d:r:(fl=dgr):l.
Inoursystem,extrat'sinferredtypeis
extrat:!fl:'; g!
where 'Either Either
Abs'? Abs ?AbsAny
Pre'? Pre ?PreAny
Therstonstraintretrievesr:l'stypeand namesit, regardlessoftheeld's
presene.(Iftheeldturnsouttobeabsent, willbeunonstrained.)Theleft-
hand onditionalonstraintslearlyspeify thedependenybetweentheeld's
preseneandthefuntion'sresult.
Theright-handonditionalonstraintshavetautologousonlusions{there-
fore,theyaresuperuous.Theyremainonlybeauseoururrentonstraintsim-
pliation algorithms are \lazy" and ignore any onditional onstraints whose
onditionhasnotyetbeenfullled.Thisproblemouldbexedbyimplementing
slightlymoreaggressivesimpliationalgorithms.
Thetypeinferredforextrat0fl=1gandextrat0fm=1gisint.Thus,
inmanyases,oneneednotbeawareoftheomplexityhiddeninextrat'stype.
Example 2. Weassumegivenanobjeto,ofthefollowingtype:
o:f getText:Pre(unit!string); setText:Pre(string!unit);
selet:Pre(intint!unit); Abs g
o mayrepresent, forinstane, an editable text eld in agraphi userinterfae
system.Itsmethodsallowprogrammatiallygettingandsettingitsontents,as
wellas seletingaportionoftext.
Next,weassumealistdatastruture, equippedwithasimpleiterator:
iter:(!unit)! list!unit
Thefollowingexpressionreatesalistofmessages,andusesitertosendeahof
themin turntoo:
iter(#o)[setText\Hello!"; selet(0;5)℄
This expression is well-typed,beause o ontainsappropriate methods to deal
witheahofthesemessages,andbeausethesemethodsreturnunit,asexpeted
byiter.Theexpression's typeisofourseunit,iter'sreturntype.
Hereisasimilarexpression, whihinvolvesagetTextmessage:
iter(#o)[setText\Hello!"; getText()℄
This time, it is ill-typed. Indeed, sending a setText messageto o produesa
resultoftypeunit,whilesendingitagetTextmessageproduesaresultoftype
string.Thus,(#o)'sresulttypemustbe>,thejoinofthesetypes.Thismakes
(#o) an unaeptable argument for iter, sine the latter expets a funtion
whosereturntypeisunit.