• Aucun résultat trouvé

Static analysis of communications for Erlang

N/A
N/A
Protected

Academic year: 2021

Partager "Static analysis of communications for Erlang"

Copied!
13
0
0

Texte intégral

(1)

HAL Id: hal-02132880

https://hal.archives-ouvertes.fr/hal-02132880

Submitted on 17 May 2019

HAL is a multi-disciplinary open access

archive for the deposit and dissemination of

sci-entific research documents, whether they are

pub-lished or not. The documents may come from

teaching and research institutions in France or

abroad, or from public or private research centers.

L’archive ouverte pluridisciplinaire HAL, est

destinée au dépôt et à la diffusion de documents

scientifiques de niveau recherche, publiés ou non,

émanant des établissements d’enseignement et de

recherche français ou étrangers, des laboratoires

publics ou privés.

Static analysis of communications for Erlang

Fabien Dagnat, Marc Pantel

To cite this version:

Fabien Dagnat, Marc Pantel. Static analysis of communications for Erlang. EUC 2002 (8th

interna-tional Erlang User Conference), Stockholm, November 19, Nov 2002, Stockholm, Suède. �hal-02132880�

(2)

Static analysis of communications for Erlang

Fabien Dagnat

LaboratoireInformatiquedesTele ommuni ation ENSTdeBretagne,Te hnop^oleBrestIroise,BP832

29285Brest,Fran e

Fabien.Dagnat@enst-bretagne.fr

Marc Pantel

InstitutdeRe her heenInformatiquedeToulouse LIMA/ENSEEIHT,2rueCami hel

31071Toulouse,Fran e

Marc.Pantel@enseeiht.fr

ABSTRACT

Inthispaper,wepresentaninsightofthetwomajor ontri-butionsofworksmadetobuildastati analyzerofErlang programs. First, we introdu ea general framework based onapro ess al ulus(the on gurations). This formalism des ribes on urrentaspe tsand abstra tsfun tionalones. Obtainingthe Erlangsemanti sisthenjustinstantiating this framework with an adequate fun tional setting. The se ond ontributionis asophisti ated typesystemfor Er-lang. This type system infers types and subtyping on-straintsfor aprogram and ensuresthat the olle ted on-straintshaveatleastonesolution. Thissystemdete tsusual fun tionalerrorsbutalsosomeofthe ommuni ationerrors. More pre isely, for ea h pro ess, it umulates all re eived messagesandallhandledmessagesandensuresthatthe rst isin ludedinthese ond.Todothis,itborrows on eptsto theobje t(orre ord)usual typinginML.

1.

INTRODUCTION

The development of tele ommuni ations industry and the generalization ofnetworkusebring on urrent,distributed and mobile omputinginto the limelight. Inthat ontext, programming is a hard task and, generally, the resulting appli ations ontainmanymorebugs thanusualsequential entralized software. Indeed, the indeterminism resulting fromthe unreliability ofnetworksand thesize of the ode of su happli ations makesit diÆ ult to validateany dis-tributedfun tionalityusinginformalapproa hes. Ourwork fo usesonusingstati analysis,akindofformalmethodsto easedevelopment.

AsErlang software are mainly used intele ommuni ation equipment that do not tolerate failure, their development mustbe erti ed. Morepre iselyeverysteptowardthe nal appli ationmustbe validated (ideallyautomati ally). Our aim is to parti ipate to this hard task, by building stati analysisof ommuni ationsusingtypeinferen ete hniques. Togiveanabstra tmodeltoErlangprograms,weusethe a tormodeldevelopedbyAghain[1℄. Itisbasedona net-work ofautonomous and ooperative agents( alled a tors andsimilarto Erlang pro esses),whi hen apsulate data and programs. They ommuni ateusing an asyn hronous pointto point proto ol andstore ea hre eived message in amailbox. When idle, ana tor handles the rst message it aninitsmailbox. Besidesthose onventions(whi hare alsotruefor on urrentobje ts), ana tor andynami ally

modifytheset ofmessagesana tor anhandle,yieldinga morea urateandwidelyusableprogrammingmodel. For example, it angiveanabstra t modeltoapplets and dy-nami odeloading.

Ina rstapproa h,wede nedtypesystemsfortheCap al- ulusdes ribedin[8℄,aprimitivea tor al ulusderivedfrom asyn hronous - al ulus and Cardelli's Cal ulus of Primi-tive Obje ts. Twotypesystemsweredeveloped. The rst one[9℄,basedonusualobje ttypeabstra tions, at hesall usual fun tional and ommuni ation errors (erroneous pa-rameters) but only a subset of messages whi h will never be handled. The se ond [7℄, dete ts all (safety) messages notunderstoodbutrequiresamu hmore omplextype ab-stra tionandanewprogrammingdis ipline. Thesesystems wereprovedtobe orre t. Inordertovalidatetheir pra ti- aluse,theneedfor aprogramminglanguage implementa-tionarose. Ina rstapproa h,wedevelopedalablanguage ML-A tintegratingalaMLprogrammingwitha tor prim-itivesand in ludinga sophisti ated typesystem extending thepreviousworkonCap(see[11℄). Then,westudied Er-lang,asitappearsthat,thoughtitsfun tionalaspe tshave a strongly di erent semanti s (and typing)than ML-A t one's, their on urrent semanti s and typing weresimilar. Therefore,wedevelopedaframeworkabstra tingtheparts ofbothlanguageshavingsemanti s(andtyping)di eren es (for example, fun tionalaspe tsor mailbox semanti s). It be amepossibleto buildsystemati ally thesemanti s, the typingandsomepropertiesaboutthetyping,on eprovided thefun tionalsetting. Furthermore,thisfun tionalsetting anuseawellknown lassi al one. Forexample, ML-A t usetheMLfun tionalsemanti sandtyping.

Thisarti legivesanintrodu tiontothisabstra tionandits appli ationtoErlang. The rstse tionprovidesabetter insight oftheformof ommuni ationerrorswewishto de-te tandtheonesoursystem aptures.Then,weintrodu ea simpli edversionofErlanganditsformalsemanti sbased on on gurations, an asyn hronous- al ulus like pro ess algebra. Then,wede neourtypesystemand illustrateits use onexamples. Finally,wedis usss alingthissystem to thefulllanguageandsomepossibleextensionstoourwork.

2.

COMMUNICATION ERRORS

In anusual on urrent setting, a pro ess P may re eive a message m (P ! m, inErlang). Supposing Pis idle, there aretwopossibilities,eitherP anhandlemorit annot. Our

(3)

the method not understood errors of obje t oriented pro-gramming.Inthea tor ontext,amessagethatmaynotbe understoodbyitsre eiveris alledanorphan.

Typedobje torientedlanguagesdeterminethesetof meth-odsanobje tP understands(typeof(P))and ensuresthat ea h method invo ation P.m is orre t by verifying that m is part ofthe type of P (m 2 typeof(P)). Furthermore,as thetypeofanobje tdoesnot hange,the veri ation an bedonewhenthemethodisinvoked. Adaptingthiste hni toErlang (P be ominga pro ess andP.m be oming P!m) raises two problemsleading to amu hmore omplex typ-ing: a)the omputationofthesetofmessagesapro ess an handle is dynami and more omplexand b) as the time between sending a message and itsre eption by itstarget may be important (the message may travel through large networks),theveri ationmustbedoneuponre eption. Theusualapproa hfora torlanguagesistodynami ally he k for message not understood errors. A pro essknows themessagesit an(immediately)handleandifare eived messagedoesnot onformtothisinterfa e,itraisesa mes-sagenotunderstooderror(seetheinitiala tormodel[1℄or theVas on elos andTokoroobje t al ulus[26℄). Butthis approa hredu es onsequentlythesetofprogramsthatone may build. Infa t, theprogrammer mustadopt asort of syn hronous programming dis ipline to be sure that mes-sagesarrive inright states. Wethinkthat this strategyis toorestri tive. Forexample, onsideraprinterdevi ethat hastwostates: working(it a eptsprintingrequests) and stopped(itwaitsforinitialization). A lientmustwaitthat aninitializationmessagehasbeensenttotheprinterbefore printing. Itwouldbemu hmore exibletoenqueueall re-questsre eivedwhentheprinterisstoppedand topro ess allpendingrequestswhenitisinitialized(possibly indepen-dentlyby another pro ess) whi his the usualbehavior of uni esprintspoolers.

These ondandoppositeapproa hneverreje tsamessage. Whenapro essre eivesamessagethatit annothandle,it silentlyenqueuesit. Noti ethat,inthis ontext,amessage maystayinde nitely inamailbox(their size isunbound). Thissemanti shasbeen hosenbytheblue al ulus[4℄,the join al ulus[14℄andErlang.

Webelievethat a ombinationof bothapproa hes maybe mu h more appropriate. Su h asystem would reje t pro-gramsthat ontains message never understood and would a eptallothermessageswarningtheprogrammerthatthey mayneverbehandled. Toa hievethisgoal,weusea power-fulbehavioral

1

typesystemtoenfor ethereje tionofsu h messages. Our type system dete ts all messages that are not in the set of messages the re eiver may handle dur-ing its exe ution. This means that typeof(P) umulates all the re eive that P ould exe ute. To dothis the sys-temmustfollowthe owoffun tions alledbyP.Itis lear that,ingeneral,ouranalysiswillanswer>(top)toexpress thefa tthatapro essmayassumeanexternallyde ned re- eiveand therefore understandsvirtually everything. But, we thinkthatthe resultsare generallyalready helpfuland 1

Byoppositionwith amoreusual lassname typesystem

programsaswillbedis ussedlater.

Forexample,apro essPexe utingthe rstfun tionofthe programbelow(ping) hasa type ontaining ping, hange andall messagesa eptedbyall possiblebehaviorsF.This means that sending a message { hange, pong} to P adds pongtothetypeof P.

ping() -> re eive ping -> ping();

{ hange, F} -> apply(F,[℄) end.

pong() -> re eive pong -> pong() end.

3.

A SIMPLIFIED VERSION OF ERLANG

Following a ommonuseinthe de nitionofstati and dy-nami semanti s,wesimplifytheErlanglanguageby sup-pressingsynta ti sugarandignoring onstru tionsthatare typed orthogonally to our work (for example, ex eptions, listsorre ords). Furthermore,wedonotaddressthe seman-ti softhe realtimepartof thelanguagewhi his omplex butdonotaddanyspe i problemtothetypesystem. An e orthasbeenmadetode nepre iselyasmall(butstilltoo big)languagenamedCoreErlang([5℄or[6℄). Therefore, weuseasmallerversionofthelanguagenamedErlang:

prg ::= ;:::; . j ; :::; .prg ::=s(p,:::, p)->e

p ::= j V j s j i j { p,:::,p}

e ::=V j s j i j {e,:::, e} j ( e) j e,e j e!e j e(e,:::, e) j aseeoffend j re eivefend f ::=p->e j p->e;f

A Erlang programis a setof fun tionde nitions in lud-ingafun tionnamedmain. Thismainfun tionislaun hed tostart theexe utionofthe program. Therest ofthe lan-guage isvery losetoErlang. Ea hfun tionis omposed of lauses separated by semi- olons and terminated by a dot. All lauses (s(p,:::, p) -> e) mustrefer to the same fun tionnames andhave thesamearity. Noti ethatthis languagedoesin ludeguardstosimplifythesemanti sand the type system for this paper. A patternmay be ajoker (always su eeding), a variable V (always su eeding and binding the variable

2

), an atoms, aninteger ior atuple. An expressionmay be any of thosevalues and add paren-theses, sequen ing (,), message sending (!), fun tion all, hoi e ( ase) and message handling operation (re eive). The hoi e (resp. the re eive operation) mat hes an ex-pression (resp. themailboxof the urrentpro ess)usinga setof lters omposedofapatternandanexpression(f is namedinterfa e). Finally,someatoms representsbuilt-in fun tions,asforexample,spawnandself.

Noti ethat as Core Erlang,weadoptlexi al s oping of variablestoease thepresentation. Ourprototypeuses Er-langstrategymixingdynami andlexi als oping. There-fore, the real system uses systemati ally an input and an outputenvironmentfor ea hexpression. Againfor sake of simpli ity,Erlangdoesnotin lude liststhatare repla ed inappli ationandspawningbytuples.

2

(4)

4.

FORMAL SEMANTICS OF ERLANG

Ourworkfo uses onstati analysis and morepre isely on typing. Inordertoprovethe orre tnessofourtypesystem, weneedaformalsemanti sof Erlang. Toourknowledge, fewworkshaveaddressedsu hahardtask. Indeed,as Er-langisafull edgefun tional, on urrent,distributedand mobilelanguage,itssemanti sis omplex. Somee ortshave beenmadetogiveaninformal,but learandsystemati de-s riptionofitssemanti s([3℄and[6℄). But,thisisnot suÆ- ientto buildandprovesomestati veri ationsystem. It seemsthatonlytwopapers([12℄and[15℄)trytobuildsu h a formal semanti s. These two papers de ne two Labeled TransitionSystem thatdoesnotsuitourneed(provingthe orre tnessofatypesystem). Inspiredbythoseapproa hes andourpreviousworksonsemanti sfora tors,webuiltour ownformalsemanti sbyinstan iatingageneralframework alled on gurations previouslybuildonalablanguage ex-tending ML to a tors (ML-A t). Thisframework de nes a general syntax for on urrent a tions and abstra ts (in thesenseoftakingasparameter)thefun tionalpartofthe studiedlanguage. Withthis approa h,we anreuse exist-ing semanti sand typing from the fun tional world. The Erlang semanti sis obtained by instantiating this frame-workwithanadequatefun tionalsemanti s.

Wearenotgoingtogivealltheformalde nitionsand jus-ti ationsofthismodelthatmaybefoundin[10℄. Weare onlygoingto giveinsightson on gurations to dedu ethe Erlangsemanti s. Mostrulesaregiveninappendixforthe interestedreader.

Configuration

A on gurationisatermthatrepresentsa on urrent sys-tematagiventime. Itsde nitionisparameterizedbythree sets: the nameseta2A, themessagesetm2Mess and theexpressionset e2Exp withA Exp andMess Exp. Thesetof on gurationsnotedW isbuiltfromthefollowing grammar:

w ::= jErrja:wjwkwja/mj .e ::= ?jhajmie

A on guration looks like a - al ulus term with a send operation,noteda/m(aisthere eiverandmthemessage), and a pro ess, noted .e ( is the identity and e is the exe uted expression). The identity of a pro ess is either unspe i ed?tomodeltoplevel omputations

3

or,hajm ie a pair omposed ofaname(pid inErlangtradition) anda mailbox(thetildenotationdenotessequen e).Asitisusual inpro ess al uli,weuse aname binder tosimulatethe name reationandsupposethatthe orrespondingnotionof freenamesandsubstitutionarede ned.

Inthe ontextofErlang, Exp representsthesyntax intro-du edinthepreviousse tion, addressesarebuilt automat-i allywhenthebuilt-infun tionspawnis alledanda mes-sage anbeanyvalue(atom,integerortuple).

A ongruen e is de ned to state whi h on gurations are equivalents:

 (W;k;)is a ommutative monoid, the orderof sub- on gurations is not important and we ansuppress 3

allo urren eof.

 wkErrErrand .ErrErr ,errorsarepropagated untiltheprogramevaluationstops.

 a:wwifaisnotfreeinw,a:wb:[b=a℄wifbis notfreeinwanda1:a2:wa2:a1:w;thosethree usualpropertiesallowtoforgetthebindingsofunused names,torenameaboundednameandtomodifythe orderofrestri tions.

 the restri tion rule, a:w1 k w2 a:(w1 kw2) if a is not free inw

2

, allows to enlarge the s oping of a name. Combined with the previous rule, it enables (upto arenaming of a inw1) to extendthe s oping andtosimulatenamepropagationinthemedium.  ?.vanda:(haj?i.v)ifvisavalue(it annot

be redu ed) ; therefore, a global omputation (or a pro ess) whi hredu etoavalue anbedestroyedby agarbage olle tor. Noti ethatthepro essmusthave anemptymailbox and beina essible to the outside world.

Noti ethat it is possible to adda rule toexpressthe fa t that a stoppedpro esswaiting for a message, that donot understandanyofitsmailboxmessagesandisnomore a - essible from outside isan error. But,as our type system annot aptureallsu hmessages(forexampleinadeadlo k ase),we annotproveits orre tnesswiththisrule. Theappendix ontainsallthe on gurationredu tionrules. Letusdis ussonlyoriginalrules.

Asintrodu edinthese ondse tionofthispaper,wetryto dete t ommuni ationerrors. To de ne thoseerrors more pre isely,theyareintrodu edinthesemanti sof on gura-tions. Therefore,whenapro essre eivesamessage,it an a ept it (andput itinitsmailbox)or reje tit by raising anerror:

hajmie .eka/m ! 

hajmmie .e ifP(m;e) Err else

To abstra t the hoi eof rea tion, a ( ommuni ation) po-tential P(m;e) is de ned. This predi ate approximatese to determine whether m may be understoodor not. This allowsthesemanti sofourframeworktobehavedi erently towardsu hmessages. Itis possible, for example, to ode usualErlang semanti swith apredi ate alwaystrue. In thenextse tionontyping,wewilldis ussmoredeeplythis subje t.

Ourgeneralsemanti sin ludesaruletospe ifythe intera -tionbetweenfun tionaland on urrentredu tion:

a2=FN( .e) a` ; e w !e 0 ; e 0 .e !a:( 0 .e 0 kw)

Where, we supposethat the fun tional redu tionhave the given shape with a being a fresh name (a 2= FN( .e)) that maybeused during the expression evaluation and w beinga on gurationdes ribingthe on urrente e tofthe fun tional redu tion step. Inthe rest of the paper, if the labelof su haredu tion is, it is omitted. Noti ethat if a is unused, the third ongruen e rule enable to forgetits

(5)

Functional reduction

A Erlang programis a setof fun tionde nitions and its exe ution orrespondsto the redu tion of thebodyof the mainfun tionina ontextwherealltheotherfun tionsare de ned. By onsequen e,the rststepofthefun tional se-manti sbuilds the fun tion environment (noted F). This pro esswill notbe des ribedhere, itsresultisan environ-mentasso iatinganatomandanaritytothebody(allthe patternmat hing onvertedtoatuplemat hing)ofthe or-respondingfun tion. Forexample:

 f( p1,p2)->e1; f( p3,p4)->e2. produ es (f;2)7!  {p1,p2}->e1; {p3,p4}->e2. 

Tosimplifyourpresentationthissetisabstra tedand sup-posed tobea essible inall rules. This ould be done by taggingea hexpression withthis environment: e

F and by propagatingitduringredu tion.

Fun tional redu tion uses the lassi notion of evaluation ontext. A ontextnoted C[℄ is anexpression witha hole markingthesub-expressionsubje tofthe urrentredu tion step. Theredu tionC[e1℄ !eC[e2℄redu etheexpression e

1

and repla eit by the resulte 2

. The evaluation ontext grammarisalsogivenintheappendix,itexpressesthefa t that the order of evaluation is unde nedwhenevaluating atuple,amessage sendingor anappli ation. Onthe on-trary,evaluationof asequen e(resp. a hoi e)starts with the rst expression (resp. the tested value). In addition we suppose that anerror ause the end of the evaluation pro ess: C[Err ℄,Err.

Variables on e de ned have their values propagated by a substitution noted  that we will not des ribe here. The mat hing operator =uses a fun tionmat hto omparea patternand avalueand buildthe substitutionof the vari-ables in the pattern by their orresponding values. This fun tion either returns a substitution or fails. It tries to mat hthe rst lterp!e. Ifmat h(p;v) returns,= re-turns(e). Else,ifitdidnotmat hed,thepro ess ontinue withtheremaining lters. Atthe end,if noneofthe lter havemat hed,wegetanerror.

Purely fun tional evaluation is lassi . The most original rules on ernsappli ation:

a` ;C[v(v1;:::;vn)℄ !e ; 

Err if(v;n)62dom(F) C[fv1;:::;vng=F(v;n)℄ The alled fun tion mustbe in the urrent fun tion envi-ronment(F). Theresult orrespondstothemat hingofits bodywiththetupleofa tualarguments. Thisrulesuppose thatthe expressiondes ribingthefun tionmustredu eto avalidatomandtherefore, itextends slightlyErlang se-manti s.

Thefun tionala tions that are onne tedwith on urrent behaviorhaveanoriginalformandmustbeexplained:

 Sending amessage impose that the rstargument is a name, returns thesent value and is labeled by the on gurationsendingterm:

a` ;C[v 1 !v 2 ℄ v 1 /v 2 ! e ;  Err ifv 1 62A C[v2℄

 Spawningimposethatitsse ondargumentisatuple, returnsthe name (guaranteed to be freshby on ur-rent redu tion) of the future pro ess and is labeled bythe on gurationdes ribingthenewly reated pro- ess.Thisisonlyruleswherethefreshnameisused. a` ;C[spawn(v;v 1 ;:::;v n )℄ haj?i.v(v1;:::;vn) ! e ;C[a℄  A allto the built-infun tionself mustbedone in apro ess and isrepla edbythe name ofthe urrent pro ess: a`ha 0 jmi;e C[self()℄ !eha 0 jmi;e C[a 0 ℄  A essingthe mailboxis similarto the hoi eex ept

thattheorderofmat hingisdi erent. Thepro esstry rsttomat hea hmessagewiththe rstpatternand trynextpatternsonlyifnoneofthemailboxmessages su essfullymat hedthe rstpattern. Forthisweuse afun tionmat hmailboxthat returnsthe resulting mailboxandthe rea tion. Noti ethatif themailbox is empty no redu tion an take pla e and by onse-quen ethepro essisstopped(untilamessagerea hes itsmailbox).

a`ha 0

jmi;e C[re eivefend ℄ !eha 0 jme 0 i;C[e℄ wheremat hmailbox(f;m)e =me 0 ; e

5.

TYPING



Erlang

Whenbuilding atypesystem to stati allydete terrorsin programs. The rstthingtodoistode ne pre iselywhat kindof errors, we want to avoid. In a on urrent setting, twofamiliesoferrorsarise: fun tionalerrorsand on urrent errors. Theformer familyis usualinthe sequentialworld and orrespondtotheerroneoususeofavalue(forexample, usinganunde nedvariableorusing1as afun tion). The latterisratherunusualandhasbeendes ribedindetailsin these tion2.

A typesystem anprovideseverallevel of pre ision. Two prototypeshavealreadybeenbuiltforErlang(see[17℄and [16℄)that on entratesontyping purelyfun tional ompu-tationbysimplifyingthelanguagesemanti s. Ourambition istobuildamoreusefulsystemforErlangprogramsthat also analyzes on urrent parts. As we use similarte hni s for olle tingandsolving onstraints,ourworkmaybe on-sideredasanextensionofthosesystems.

Type inference and Constraints

Oursystem allows the synthesisof thetypesof every pro-gramentitywithoutrequiringanytypeannotationfromthe programmer. Todothis,afreshtypevariableisasso iated withea hnodeofthesynta ti treeoftheprogramand on-straintsbetweenthosevariablesare olle ted. Attheendof this olle tphase,aresolutiontooldetermineswhetherthe onstraintsethassolutions. Ifthisisthe ase,theprogram isde laredwell-typed.Thes hemaof gure1des ribesthis pro ess.

To type fun tionsand give themwidely usabletypes, ML uses parametri polymorphism. For example, map has the type 8 ; ( ! ) ! list ! list meaning that it

(6)

types + contraints

safety error(s)

<< readable >> types

Program

types + solved contraints

Solver

Printer

Analyser

Figure 1: The analyzers hema

the on urrent ontext,thisformofpolymorphismbe omes toorestri ting. Oursystemadoptsin lusionpolymorphism thatintuitivelymeansthatthesystemensuresthe orre t-nessonlyforallvaluesusedintheprogramasrealarguments (thatis niteinterse tionsratherthanin niteones). There-fore, inour ontext,we usethesubtyping relation. A type t1 being asubtype ofatypet2 (t1 vt2) ifavalue oftype t

1

maybeused(safely)whereavalueoftypet 2

isrequired. ForErlang,themainuseofsubtypingisonpro esstype: apro ess thatunderstands moremessagesand sendsitself less messages than another pro ess, an repla e this one. TypinganexpressioneunderassumptionsAwillprodu ea typetandasubtyping onstraint setC: A`e:t; C,this dedu tionbeing validonlyifC hasatleastonesolution. Noti ethat usualMLtypesystem su has SMLor O aml anbeviewedasfollowingthesamepro ess olle ting equal-ity onstraints. But,whensubtypingisneeded(asfor Er-lang),the onstraintsbe ome omplexandtheirresolution mustuse sophisti atedand powerful graphalgorithm. We refer the interested reader to the works of Pottier [19℄ or Fanhdri h[13℄. Indeed,a onstraintsetisviewedasagraph wheretypevariablesarenodes(withtheirupperandlower bounds)andsubtypingrelationde nestheedges.

Thetypeof map be omes ( ! ) ! list ! list and ea h appli ationwithanargument of type t1 and another oftypet

2

produ esthe onstraint set ft 1

v ! ; t 2

v list; listvtrgwheretristheresultingtype. This strat-egy olle ts all possible argument types and ensures that they anallbeusedsafely:

f G i t i 1 v ! ; G i t i 2 v list; listv l i t i r g

Potential and Errors

Beforegoingon,letuslookattheexamplebelowtopre ise somevo abulary: state1(V) -> re eive {add,V1} -> state1(V1 + V); { hange,V1} -> state2(V,V1) end. state2(V1,V2) -> re eive {add,V3,V4} -> state2(V1 + V3, V2 + V4); {mute,F} -> F() end. re eive kill -> true end. main() -> ase (spawn(state1,1)) of P -> P ! {add,1,3}, P ! kill, P ! { hange,11}, P ! {mute,state3} end.

A fun tionmay ontaintwo formsof interfa es(the lters fofare eivef end). One alledimmediate thatispresent inthebodyofthefun tionorinthebodyofanother alled fun tion ignoring re eived datas (in messages). And the se ond ategory orrespondstointerfa esre eivedvia mes-sages. This notionis extendedto pro esses, thesetof im-mediateinterfa es of apro ess being the setof immediate interfa esofitsinitializingfun tion. Intheexample,state1 allsstate2anditselfandstate2only allsitself. By on-sequen es,theimmediateinterfa essetof Pis:

f{add,V1}{ hange,V1}{add,V3,V4}{mute,F}g The immediateinterfa es may be viewedas the stati au-tomatondes ribingourpro essand theothersassome dy-nami part(intheexemple,kill).

Ourtypesystem apturesallorphansthatleadstoerror(in the semanti s)usingthepotentialintrodu ed inthe previ-ous se tion. It is possible togive apredi ate that olle ts all immediate interfa es (we refer the interested reader to [10℄). Su hapotentialwouldapproximatesthepreviousset (keepingonlylabels)andwouldbede nedby:

P(m;e),(label (m)2fadd hangemute g) () Furthermore,aswedonotwanttoraiseanerrorandforbid thesendingofthemessagekill,thepotentialofapro esse alling are eivedfun tion a eptsanything. Thereal po-tentialof P is thenanopen potential: P(m;e),true. In fa t, the potential de ned in() would orrespond to the samepro essifwe hangestate2's se ond lterbody(the muterea tion)toany odenot allingF.

Buildingtherulesforsu hasystemisalready omplexand does not apture all errors that our type system dete ts. Indeed,ifintheexample,wesendamessagesubtoP,itis notreje tedbe ausethepotentialofPisopened.Buildinga morepre isepredi ate(withrespe ttothe apturederrors) is hardand infa t orrespondstoaslight simpli ationof

(7)

simpli ationofthetype. Ea hatomsentinmutemessage is olle tedand itspotentialisaddedto thepotentialof P whi hbe omes:

P(m;e),(label (m)2fadd hangemutekillg) Themessage killis notde lared orphanbutthe message sub auses a type error (it raises a dynami error if not reje ted).

Weare urrentlydevisinganewde nitionoferrorsbasedon adedi atedarbores enttemporallogi (see[25℄). However, thisapproa h urrentlyonlyhandleimmediateinterfa es.

Message and Process Types

An automati analysis of the Erlang ompiler ode, its standardlibrariesandprogramsfreelyavailableoninternet

4 revealedthatsentmessagesandre eiveinterfa esaremainly tupleswhere oneelementisanatom. Thisatomplaysthe roleofalabelformessages. Furthermorerule5.7from[27℄ states that all messages should be tagged. Following the pioneerworkof[17℄,weimposetoallprogramsthispre ept. Noti e that the only (less rare) ex eptions are the use of jokersorvariablestodelegatethetreatmentofthemessage to a hoi e instru tion or to another pro ess. These two usesdonot goagainstourpre eptsin etheyjustserveas forwarder. Finally, a programnot following this prin iple mayeasilybeadaptedmanually.

Thoselabelsplayarolesimilartothoseofre ordlabelinML or of methodnamesin obje ts (for example). We borrow the row te hnology, used to type re ords, to approximate interfa es. Rows are now frequently used for stati anal-ysisin MLworld (see for example, ex eption analysis [18℄ orobje ttyping inO aml [20℄). Inour ontext,a pro ess typeisarow,whi hisapartialfun tionfromlabelstopair of types des ribing arguments the message ontains. The rstonedes ribesre eivedmessages ontentandthese ond handled messages ontent. Indeed, the originality of our typesis thefa tthat they ontain bothre eivedand han-dledmessagesinthetypeofapro ess. Apro essre eiving messageslabeledm

1

ontaining datasof typeT 1

and han-dlingitwithvaluesoftypeT2 will havethefollowing type: fm1:(T1;T2); ig. The(row)variableiexpressesthefa t that the type of the pro ess is onlypartially known. The onversion from atupletype T to amessage type

b T (if it issent)orT (ifitis handled)isdone inalazyway andis de nedintheappendix. Eitherthesystemknowstheform ofthetypeand onvertsit,oritsstru tureisunknownand thesystemwaits. Amessage redu edtoanatomshasthe type sand orrespond tothe messagetypefs:(unit;>)g ortofs:(?;unit)g. Meaningrespe tivelythatitisasent message (the handling part is meaningless

5

) or a handled message(there eivedpartismeaningless). The onversion of tuplemessage is similar. Inthe paper[17℄, the onver-sion was done for all tuples but we think that this is not reallyne essary.Ba ktoourexample,thepro essPhasthe 4

Thisrepresent200000 odelines. 5

Thesensofthe>or?will be ome lear whensubtyping

TP,fadd : (13;intt(intint)); hange :(11;int); mute : (state3 ;T); kill : (unit; ); ig

WhereT is thetypeof thefun tionFtakenas parameter. Noti ethattheunknownpartiisrelatedtothetypeT. The orre tness ofthe systemis ensuredbygeneratingfor ea hspawnpro essafreshinterfa etypeiverifyingi. This predi ateistrueifea hre eivedmessageisunderstoodand ismathemati allyde nedby:

fmi:(Ti;T 0 i )gi2I ,8i2I TivT 0 i AppliedonprevioustypeT

P

,weget:

f13vintt(intint); 11vint; state3vT;unit v g Wehavenotyetde nedsubtypingbutintuitively,one an seethatthe two rst onstraintsare trivial. The omplete is dis ussed resolution after the presentation of types and subtyping.

Types and Subtyping

InErlang,oneofthediÆ ulties,isthatbeinguntyped,an expression mayevaluate tovaluesof really di erent stru -tures (for example, a boolean and a fun tion). Therefore, the type language must in lude a notion of union t

1 tt

2 meaningthat avalueof thistypemaybeof type t1 or t2. Moreoverto get suÆ ient pre ision, ea h onstant has its owntype(forexample,1isoftype1subtypeoftheinteger int).

InErlang,anyexpression anexe uteare eive(i.e, a - essthemailboxofthe urrentpro ess). Therefore,the sys-temuseanindire te e t al ulusinspiredby[24℄to olle t, inthetypeofself,allinterfa esmat hedagainstthe mail-box. This e e tisthenin ludedinthe typeofafun tion. Whenapro essisspawnedthee e tofitsinitialfun tionis addedtothepro esstype. Inourexample,state3hasthe followingfun tiontypewherethee e tisthesupers riptof thearrow:

unit

fkill:(?;unit)g !true

The language of typesneeded for Erlang is built by the following grammar:

T ::= ?j>jtjTtT jTuT

j ijint integers j sjatom atoms j unitjT:::T jtuple tuples j T

I

!T fun tions

j I pro esses

I ::= fgj>Ijijfm:(T;T); Ig interfa estype Subtyping is de ned in the formula appendix, only three rulesareunusual:

 Pro esstypesare ontravariantbe auseapro essmay repla eanotheroneonlyifitsinterfa eislarger,Iv I

0

isequivalenttoI 0

vI.

 Fun tiontypesare ontravariantonargumentsasusual and ovariantone e tandonresult. Indeed,ifa

(8)

fun - on urrent e e t: T1 I ! T2 v T 0 1 I !T 0 2 () T 0 1 v T1^IvI 0 ^T2vT 0 2

 Interfa esubtypingis ovariantonre eivedtype, on-travariant onhandledtypeand ompose ovariantly.

fm:(T1;T2); Igvfm:(T 0 1 ;T 0 2 ); I 0 g () T 1 vT 0 1 ^T 0 2 vT 2 ^IvI 0 Theintuitionbehindthisruleisthatthesystemmust keepthelargesttypeT

r

ofre eivedmessagesandthe lowesttypeTu ofhandledmessages. The orre tness predi ate  leads to T

r v T

u

and any re eived on-tentoftypeT isguaranteedtobeunderstoodbyany re eiverstateT

0

be auseT vTrvTuvT 0

.

Attentive readers may have remarked that the subtyping oninterfa esisde nedonlyforrowsbeginningbythesame messagelabel. A ompletealgebrai theoryexistsandproves thatit istheonlyneededrule. Ifonelabelofthe leftside rowis absent from right side row, thesubtyping is learly false and on e all left side labels are treated, the system redu estofgvI whi hisanaxiom.

Another example

Before going into further dis ussion on this type system, onsiderafun tionthatrealizesatimerwaitingfor a mes-sage an elortheendofatimespe i edatits reationto throwanalarm:

timer({Pid, Time, Alarm}) -> re eive { an el,Pid} -> true after Time -> Pid ! Alarm end.

Atimeout fun tionspawnssu hatimer pro essusingthe pid ofthe urrentpro essandreturnsthepidofthetimer. Thesamepro essmay an elthistimerusingthereturned pid:

timeout({Time, Alarm}) ->

spawn(timer, {self(),Time,Alarm}). an el(Timer) ->

Timer ! { an el,self()}.

Supposingargumentsof after(Time)areintegers,our sys-teminfers: timer: intb  f an el:(?; )gb !truet timeout: int b !f an el:(?;b )g an el: f an el:(;>)g  ! an el meaningthat:

 Thetimerfun tiontakesthreearguments:anaddress (re eivingthethirdargument),anintegerandavalue (amessage). Theresultiseithertrueorthisvalueand the urrentpro essre eivesa an elmessage ontain-ing (an addressof) apro ess that re eivesthe third argument.

 Alarm (oftype )mustbealegal message(tuple be-ginningbyanatom).

 Thepro ess allingtimeoutre eivesthealarm(it

ap- The result of this fun tion is the name of a pro ess understanding an elmessages ontaininganaddress thatre eivesthealarmmessage.

 A allto an el mustin ludes anargumentthat re- eivesa an ellationmessage ontainingtheaddressof the urrentpro essandreturnsthis an ellation mes-sage.

Those types are omplex but very informative about the behavior of these fun tions. For example, the system an ensurethatthepid returnedby a alltotimeoutdoesnot re eivemessagesotherthan an ellation. It analsoensure that thepro ess alling this fun tionisable to re eive the alarmmessage.

Functional Typing

Pattern mat hing annotbetreated inthe usualML way: ( 1 ! 1 )t( 2 ! 2 ) annot be equal to ( 1 u 2 ) ! ( 1 t 2

). In fa t, the type system mustin lude pattern mat hing,todothis[2℄introdu edthenotionof onditional typet

1 ?t

2

. Thistypemeanst 1

(ift 2

isdi erentfrom?)or ?. Forexample,ife:te, aseeoftrue->1;false->foo is of type (int?(teutrue ))t(foo?(teufalse )). Our sys-tem does notuse this onditionaltype whi h enjoys good algebrai properties butis notreallyreadableandleads to theloss ofthepatternmat hingstru ture. Instead,weuse a onditional onstraint 1 ) 2 meaningthatif 1 is veri- edthenthe system mustalso ensure

2

. This onstraint, generatedtoapproximatepatternmat hing,allowstokeep ahighlevelofpre isiononthelinkbetweenmat hedvalues andresults. Typingprevious hoi eleadtothefollowingset of onstraints: C =fte vtrue)intvtr; te vfalse) foo vtr; te v truetfalse g where tr is the result type. Eitherthe system knows the stru tureoft

e

andC anbe simpli ed,oritisde omposedintwosub-systems(be ause themat hingis omposedoftwobran hes):

 One,inwhi h,teissubtypeoftrueandthereforeC= ftevtrue ; intvtrg

 Otherwise(duetothird onstraint),te isasubtypeof falseandC=ft

e

vfalse; foovt r

g

As,ingeneral,wedonotknowpre iselythemat hedvalue, all those de omposed sub-systems must have a solution. Thismeansthatanbran hpatternmat hing resthe res-olutionofnsub-systems. However,thepra ti ehaveshown that this is not a real problem. Indeed, whenapplying a patternmat hingtoavalue,weoftenknowmoreorlessits stru tureandmanyofthesub-systemsaretrivial.

Thetypingjudgmentshavethefollowing shape: Environment ` Expression : Type; ConstraintSet As,manytypingrulesare lassi ,welimitourexplainations tosends, hoi es,re eivesand alls:

 Typing e1!e2 returns the se ondsub-expression type and the onstraint set ontaining all onstraints pro-du ed by the typing of e

1 and e

2

, plus a onstraint spe ifyingthat e1 mustevaluatetoapro ess that re- eivesthevalueofe2:

E`e 1 :t 1 ;C 1 E `e 2 :t 2 ;C 2 E`e 1 !e 2 :t 2 ;C 1 [C 2 [ft 1 v b t 2 g

(9)

allpatternsandasso iatedexpressionsofthe lter. A rea tionexpressionmustbetypedafteraddingtothe urrent environment the environment resulting from typingofthe orrespondingpattern:

E`e:t e ;C e E `p i :t p i ;E i E[E i `e i :t i ;C i E` aseeofp1!e1; ::::t; Ce[ [ i Ci[C

where the resulting onstraints umulate all already al ulated onstraintsandthoseduetothe hoi e(C). C spe i es that the tested value mustbe taken into a ountbyoneofthepatternsandaddallalready ex-plained onditional onstraints(oneforea hbran h):

C=ft e v G i t p i g[ [ i (ft e vt p i )t i vtg)

Thismeansthattheresulttypetwillbetheunion of the type of ea h patternthat may mat hthe tested value.

 Typingthemessagehandlingmayresultinany possi-blebran htype(hen etheunion)andaddsallpattern typestothe urrentselftype:

E`pi:t p i ;Ei E[Ei`ei:ti;Ci C 0 i =fE(self)vt p i g E `re eivep 1 !e 1 ; :::: G i t i ; [ i (C i [C 0 i )

 Typing anappli ation ismu hmore omplex. First, onemusttypethefun tionexpressionandea h argu-mentexpression. E`e:te;Ce E`ei:ti;Ci E `e(e 1 ;:::;e n ):t;C e [ [ i C i [C

whereCis omposedoftevdom(TF),E(self)vI, Fun(TF;te;n)v(t1:::tn)

I

!tmeaningthat: { Thefun tionmustbede ned.

{ Itse e tIisaddedtothe urrentpro esse e t. { All possible fun tions are subtype of a fun tion

typea eptingthena tualargumentst i

,having ane e tIandresultingint(itistheresultofthe appli ation). Togetthesetofpossiblefun tions, weuseafun tionFunwhi happliedto(T

F ;t

e ;n) returnstheunionofallfun tiontypesasso iated toanatom(andthearityn)ofteinTF. Likethe transformationfromtupletypetomessage type, thisfun tionislazyandwaitstoknowthevalue oftetoperformitsa tion.

For ea hpossible fun tions of type I

0

! , the last on-straint ensures that all appli ations are legals be ause by substyping it leads to ft1:::tn v ; I

0

v I; v tg. Furthermore,alle e ts(resp. results)are umulatedinthe globale e tI (resp. resultt).

Thefun tiontyping environment TF results fromthe typ-ingofall fun tionsinF. Amapping(s;n)7!f inF adds a mapping (s;n) 7! t

f

if the typing of f by the rule be-low results int . And,Wesuppose that all onstraints it

resolution. E`pi:ti;Ei E[Ei`ei:t 0 i ;Ci E `p1!e1; :::: G i (ti!t 0 i ); [ i Ci

Goingba ktoourexample,theappli ationof Fleadsto: 

state3vT; unitv ; T vfstate1 ;state2 ;state3 g; TP vI; Fun(TF;T;0)vunit

I !t



The rst onstraint ombinedwiththe fthleadsto: unit

fkill:(?;unit)g

!truevunit I !t

This imply that TP v I v fkill : (?;unit)g and true v t. The rst onstraint simulates (in the type sys-tem)the re eption of unit message: (?;unit) v(unit; ) equivalenttof?vunit; vunitg. Addingthistothe ini-tial onstraint setleadsto asolvable onstraint set(where =unit). Thisallowsthesystemtoguaranteethe orre t-ness.

6.

SCALING TO ERLANG TYPING

Thesimpli edsystempresentedheredoesnot orrespondto therealprototypeimplementation.Tos aletothissystem, wehaveto:

 extend the types by lists, hara ters, oating point numbers and all otherbasi types( orresponding to Erlangbasi values). Thisextensionandthe de ni-tionofbuilt-infun tionisstraightforwardbutneedto addalotofrules.

 hanges opingrulepoli y. Oursystemneedstohave aninput andanoutputenvironmentfor ea h expres-sion. Thisisalsoboringroutine.

 addguardstothepatternmat hing(againroutine ex-tension). Noti ethatintheprototype,itisoneofthe onstru tionsthat ontainsalotoftypeinformations.  take are ofdynami patterns. Indeed,inErlang,a variablein a pattern is a de nition only if the vari-ableisnotalreadyde ned. Thissmallmodi ationof the semanti sand morepre isely ofthe semanti s of patternsneedsimportant hangesinthetypesystem summarizedjustbelow.

Oneofthebiggestproblemthatwefa edwhentyping Er-langisdynami patternmat hing.Indeed,inthepatterns, avariableisnotalwaysabindingo urren e,thatis,ifthe variableisalreadybound,itsvaluerepla esthevariable be-fore pattern mat hing is realized. For example, onsider:

g(X) -> ase 1 of X -> ok; _ -> no end. Theterm{g(1),g(2)}redu esto:

{ ase 1 of 1 -> ... , ase 1 of 2 -> ...}

and then to {ok,no}. Usual typing of this fun tion gives !twiththe onstraints:

(10)

ausethetwoappli ationsgives1t2v meaningthatboth bran hes may beused. Theproblem omes fromthe fa t, that the usual fun tiontyping impose to all possible real argumenttypestobesimultaneously ompatibleswithall their potential use inthe body of the fun tion. For this, when typing the body of thefun tion, the system olle ts onstraintsoftheform vtwhere isthetypeofan argu-ment. Andea h alltothefun tionprodu es onstraintsof theformt

0

v whi henableby transitivity toensurethat t

0

vt. But,inthebodyofafun tion,ifapatternin ludes anargument,thesystemgeneratesa onstrainttv in om-parablewitht

0

v . Thismeansthatwe annotguarantee that the argument respe t one of the onstraints required bythefun tion.

Thetypeobtainedfor{g(1),g(2)}isnotverypre ise(using usualstrategy)butaboveall,ifthejokerbran hisnotinthe hoi e, theprogram auseanerrorthat annotbedete ted by the type system. To solve this problem, the system is going to type ea h appli ation of a fun tionusing afresh instan eofitstype. Withthisstrategynoharmful ow(of information)mayhappenbetweentwoappli ationsites as before. Indeed, the intuition behind this problem is that whenafun tionuseoneofitsargumentsinapattern,ea h appli ation produ es a new (and di erent) version of the body(ofthefun tion). Therefore,the onstraintsitimposes arenotthesameandthereturntypearedi erenttoo. Thetyping ofafun tionleadstoatype ! anda on-straintsetC. Its allingonanargumentoftypetwill use typet!

0

(where 0

isfresh)andadd[t= ; 0

= ℄C tothe global onstraintset. Therefore,typing:

g(X) -> ase 1 of X -> ok end.

gives !twith f1v ; ok vtg. Therefore, thetypeof {g(1),g(2)}is t 1 t 2 withf1v1; okvt 1 ; 1v2; okv t 2

g where the boxed onstraint is false. The error is now dete ted!

Thedrawba k of this strategyis that the numberof type variables and onstraints grow morerapidly. Tosolve this problem,inpra ti e,thesystemapplythisstrategyonlyto asubsetoffun tions. Morepre isely,thisstrategyisapplied totheargumentsoffun tionsusingoneoftheir arguments inapattern. Asthissituationisnotthemostusual,the ost topay(forthisstrategy)isnottooexpensive(ingeneral).

7.

DISCUSSION

Inthispaper,wehaveproposedaformalizationofthe Er-langsemanti susingatwolevelredu tionsystem. A rst level on entrateson on urrentaspe tsofthelanguage us-ing a formalism inspiredby the - al ulus, the on gura-tions. And a se ond expressing the fun tional semanti s (andits potential on urrent e e ts) using a more lassi setting. Finally,wehaveintrodu edatypesystem for Er-langinsisting intheoriginal partsof our works: message typingandthefa tthatthesystemtrytostay losetothe language. The versionspresented inthis arti le represent onlyinsightofthe omplexsystemdevelopedandthe pro-totypeofstati analyzer realized.

Formal semantics of Erlang

rea hagoodformalizationofthesemanti sofErlang. A ompleteformalizationofthewholelanguagewouldrequire alotofworkbe auseonewouldhaveto:

 addthenode(site)notion. Forthis, on gurations must be extended by a set of node names and by a onstru tionhnjwin meaningthatw isexe utedon noden. A on gurationdes ribingatwonodes ould thenben 1 ;n 2 :(hn 1 jw 1 ikhn 2 jw 2 i).

 implementdynami oderepla ement. Ea hsite mustin ludetheenvironmentofde nedfun tionsand thevaluesofthosefun tions ould hange: hnjE jwi.  allowsending messagebetweensites. Thetarget ofthemessagemaybelo alkeepingthesamesyntax orremoteonnodenandthetransitmessage ouldbe an/m.

 integratethetimenotion.InErlang,themessage handlingoperation hasa lauseafter that allows to stoptheexe utionofthisinstru tionafteraspe i ed delay. Onesolution ouldbetoaddanotionof ounter toea hnode.

 add a notion of symboli names and a di tio-nary. A servi e anbe abstra ted by asso iating it withaname. Thisde larednamerepresentapro ess (that an hange). Ea hnodeneeds tomaintain di -tionary: hnjEf jEnjwi.

 addsignals. Erlangusesignalstopropagate ex ep-tionsamong pro esses. For example, we ouldadd a agtothemessage makingitpossibleforthere eiver todistinguishasignal fromamessage.

Somere entworkondistributedpro ess al ulilikeD(see [21℄) orthe join al ulus(see [14℄) an alsohelp insu ha proje tofformalizationofthesemanti sofErlang. Noti e that thosepoints are not all the problemsthat needed to besolved,werefer theinterestedreaderto the hapter10, 11 and 12of [3℄. Those three hapters does notin lude a formalsemanti sbuttheir informal systemati des ription of Erlangsemanti senable toviewall possibilities.

Complete Erlang Typing

To be ome a ompleteand widely usabletool our system needssomeextensions.

First, the Erlang messagesdoes not ontainlabel so the typeofpro essmustbe retailored. TheworksonXM (a typedfun tional language usedto manipulateXML do u-ments) of [23℄ an be a good basis. Indeed, to type or-re tly the hoi es of XML, they build a typed - al ulus in luding a notion of re ord without label. For example, (1)+("test") +(x:if x then 1 else 0) is typed by fint; string; bool!intg. Thisadaptation does not seem tobestraightforwardbe ause thetypesystemof XMuse equality onstraints and is based upon a notion of on-straintimpli ation. Therefore,itsintegrationwiththe sub-typing needed for Erlang needs studies about subtyping onstraint impli ation and to our knowledge, none of the workmadeinthisareahavereallya hievedthatgoalyet.

(11)

veryimportant to rea h a ertain level of quality for pro-grams. Indeed,the reliability of su happli ations needsa pre isetreatmentofeverypossibleex eptions. Atype sys-tem helping the programmer inthis task would be a real aid. It ouldestimatethesetofpotentialex eption aused by every expressions ofthe program and ensurethat they aretreated. Anextensionof[18℄maybeagoodstartpoint towardsu hastati analyzer.

Finally, the most diÆ ult point with Erlang is that the approximationmadebythisidealtypesystemshouldhave to be ompatible with hot ode swapping. Indeed, in Er-lang,amoduleisusedbyhundredsorthousandsofnodes that annotbe stoppedor restarted. Anevolutionof su h amoduleusedynami oderepla ementandtherefore,the old version and the newone haveto be exe uted simulta-neouslyandmust ooperatesafely(atleastforatemporary period). Su hataskistotallyoutofrea hatthemoment, buta rststeptoitsresolution ouldstartfrom[22℄.

8.

REFERENCES

[1℄ G.Agha.A tors: AModelofCon urrentComputation inDistributedSystems.SeriesinArti ialIntelligen e. TheMITPress,Cambridge,MA,USA,1986.

[2℄ A.Aiken,E.Wimmers,andT.Lakshman.Softtyping with onditionaltypes.InPro .ofPOPL,pages 163{173,Portland,USA,Jan.1994.ACMPress. [3℄ J.BarklundandR.Virding.Erlang4.7.3Referen e

Manual,February1999.downloadablefrom www.erlang.org.

[4℄ G.Boudol.The- al ulusindire tstyle.InPro .of POPL,pages228{241.ACM,Jan.1997.

[5℄ R.Carlsson.Anintrodu tionto ore erlang.Erlang Workshop.Prin iples,Logi s,andImplementationsof High-levelProgrammingLanguages.Floren e,2001. [6℄ R.Carlsson,B.Gustavsson,E.Johansson,

T.Lindgren,S.-O.Nystrom,M.Pettersson,and R.Virding.CoreErlang1.0.2,languagespe i ation, O t.2001.

[7℄ J.-L.Cola o,M.Pantel,F.Dagnat,andP.Salle. Stati safetyanalysisfor non-uniformservi e availability ina tors.InPro .ofFMOODS,pages 371{386,Floren e,Italy,Feb.1999.Kluwer.

[8℄ J.-L.Cola o,M.Pantel,andP.Salle.Cap: Ana tor dedi atedpro ess al ulus.InPro .ofProofTheoryof Con urrentObje t-Oriented Programming,May1996. [9℄ J.-L.Cola o,M.Pantel,andP.Salle.Aset- onstraint

basedanalysisofa tors.InPro .of FMOODS, Canterbury,UK,July1997.Chapman&Hall. [10℄ F.Dagnat.Aframeworkfortypinga torsand

on urrentobje ts.Ongoingreport,availablefrom perso-info.enst-bretagne.fr/ ~fdag nat, 2002. [11℄ F.Dagnat,M.Pantel,M.Colin,andP.Salle.Typing

on urrentobje tsanda tors.L'Objet{Methodes formellespourles objets,Volume6(1/2000):pages

distributedsystems.InPro .oftheACMSymposium onAppliedComputing,volume28,pages532{540. ACM,June1998.

[13℄ M. Fahndri h.BANE:A libraryforS alable Constraint-BasedProgram Analysis.PhDthesis, UniversityofCaliforniaatBerkley,1999.

[14℄ C.Fournet,G.Gonthier,J.-J.Levy,L. Maranget,and D. Remy.A al ulusofmobileagents.InPro .of CONCUR,Pisa,Italy,volume1119ofLNCS,pages 406{421.Springer-Verlag,1996.

[15℄ F.Hu h.Veri ationofErlangprogramsusing abstra tinterpretationandmodel he king. Pro eedingsofICFP'99,34(9):261{272,Sept.1999. [16℄ A.Lindgren.Aprototypeofasofttypesystemfor

erlang.Master'sthesis,ComputingS ien e Departement,UppsalaUniversity,1996.

[17℄ S.MarlowandP.Wadler.Apra ti alsubtyping systemforErlang.InPro .ofInternational Conferen e onFun tionnalProgramming,June1997. [18℄ F.PessauxandX.Leroy.Type-basedanalysisof

un aughtex eptions.ACMTransa tionson

ProgrammingLanguagesandSystems, 22(2):340{377, 2000.

[19℄ F.Pottier.Simplifyingsubtyping onstraints: a theory.Information&Computation,170(2):153{183, Nov.2001.

[20℄ D. RemyandJ.Vouillon.Obje tiveML:Ane e tive obje t-orientedextensiontoML.Theory AndPra ti e of Obje tSystems, 4(1):27{50,1998.

[21℄ P.Sewell.Global/lo alsubtypingand apability inferen efor adistributed- al ulus.InPro .of ICALP'98.LNCS1443,pages695{706.

Spinger-Verlag,July1998.

[22℄ P.Sewell.Modules,abstra ttypes,anddistributed versioning. InPro .of POPL,pages236{247,London, UK,Jan.2001.

[23℄ M. ShieldsandE.Meijer.Type-indexedrows.InPro . of POPL,pages261{275,London,UK,Jan. 2001. [24℄ J.-P.TalpinandP.Jouvelot.Thetypeande e t

dis ipline.InformationandComputation, 111(2):245{296,June1994.

[25℄ X.Thirioux,M.Pantel,andM.Colin.Multi-set abstra tionofnon-uniformbehavior on urrent obje ts.Workinprogress,Nov.2002.

[26℄ V.T.Vas on elosandM.Tokoro.Atypingsystemfor a al ulusofobje ts.InPro .ofOTAS, Kanazawa, Japan,volume742ofLNCS,pages460{474,New York,USA,1993.Springer-Verlag.

[27℄ M. WilliamsandJ.Armstrong.ProgramDevelopment Using Erlang-Programming RulesandConventions. ERICSSON,mar1996.Do .EPK/NP95:035.

(12)

APPENDIX

Con gurationsredu tionrules: Congruen e: w1w 0 1 w 0 1 !w 0 2 w 0 2 w2 w1 !w2 Parallel: w1 !w2 wjjw1 !wjjw2 Restri tion: w1 !w2 a:w1 !a:w2 A ept: P(m;e) hajmie .eka/m !hajmmie .e Reje t: not(P(m;e)) hajmie .eka/m !Err Expression: a2=FN( .e) a` ; e w !e 0 ; e 0 .e !a:( 0 .e 0 kw)

Evaluation ontext grammar:

C::=[℄j(C)j{A}jC,ejC!eje!CjC( e,:::, e)je(A)j aseCoffend A::=[℄je,AjA,e Mat hing semanti s: 8 < : v=[℄,Err v=(pwheng!e)::f,  v=f ifmat h(p;v)=fail (e) ifmat h(p;v)=

Fun tional redu tionrules: VariableError: a` ;C[x℄ !e ; Err Sequen e: a` ;C[v;e℄ !e ; C[e℄ Appli ationError: (v;n)62dom(F) a` ; C[v(v 1 ;:::;v n )℄ ! e ; Err Appli ation: a` ; C[v(v 1 ;:::;v n )℄ ! e ; C[fv 1 ;:::;v n g=F(v;n)℄ Case: a` ; C[ asevoffend ℄ ! e ; C[v=f℄ SendError: v 1 62A a` ;C[v1!v2℄ !e ; Err Send: v 1 2A a` ; C[v1!v2℄ v 1 /v 2 !e ; C[v2℄ Spawn Error: v 0 isnotatuple a` ; C[spawn(v;v 0 )℄ ! e ;Err Spawn: a` ; C[spawn(v;v1;:::;vn)℄ haj?i.v(v 1 ;:::;v n ) !e ; C[a℄ SelfError: a`?; C[self()℄ !e?; Err Self: a`ha 0 jmi;e C[self()℄ ! e ha 0 jmi;e C[a 0 ℄ Re eiveError:

a`?; C[re eivefend ℄ !e?; Err Re eive: mat hmailbox (f;m)e =me 0 ;e a`ha 0

jmi;e C[re eivefend℄ !eha 0 jme 0 i; C[e℄ Mailbox semanti s: 9j (8i<j m i =f 1 =Err) m j =f 1 =e mat hmailbox (f1:: ;(mi)i2J)=(mi)

i2Jnfjg ;e (8i2J m i =f 1 =Err )

mat hmailbox(f1:: ;(mi)i2J)=mat hmailbox ( ;(mi)i2J)

Type Conversion: 8 > > > > > > > > > < > > > > > > > > > : b s,fs:(unit;>)g \ sT1:::Tn,fs:(T1:::Tn;>)g b >,>I [ F i Ti, F i b Ti [ d i T i , d i b T i b , b if isatypevariable b 8 > > > > > > > > > < > > > > > > > > > : s,fs:(?;unit)g sT1:::Tn,fs:(?;T1:::Tn)g >,>I F i Ti, F i Ti d i T i , d i T i , if isatypevariable T ,Err otherwise

(13)

?vT T v> fgvI Iv>I T vT1 T vT2 T vT 1 uT 2 T vT1 T vT 1 tT 2 T vT2 T vT 1 tT 2 i2N ivint s2At svatom T 1 :::T n vtuple 8i TivT 0 i T 1 :::T n vT 0 1 :::T 0 n I 0 vI IvI 0 T 0 1 vT1 IvI 0 T2vT 0 2 T1 I !T2vT 0 1 I 0 !T 0 2 T1vT 0 1 T 0 2 vT2 IvI 0 fm:(T1;T2); Igvfm:(T 0 1 ;T 0 2 ); I 0 g

Typing Dedu tion System: Var V 2dom(E) E `V :E(V);fg Constant E` : ;fg Tuple E `ei:ti;Ci E`fe1;:::;eng:t1:::tn; [ i Ci Paren E `e:t;C E`(e):t;C Sequen e E `e1:t1;C1 E`e2:t2;C2 E `e 1 ;e 2 :t 2 ;C 1 [C 2 Send E`e 1 :t 1 ;C 1 E `e 2 :t 2 ;C 2 E`e 1 !e 2 :t 2 ;C 1 [C 2 [ft 1 v b t 2 g Case E `e:t e ;C e E`p i :t p i ;E i E[E i `e i :t i ;C i E ` aseeofp 1 !e 1 ; ::::t; C e [ [ i C i [ft e v G i t p i g[ [ i (ft e vt p i )t i vtg) Appli ation E`e:t e ;C e E`e i :t i ;C i E`e(e 1 ;:::;e n ):t;C e [ [ i C i [ft e vdom(T F

); E(self)vI; Fun(T F ;t e ;n)v(t 1 :::t n ) I !tg Re eive E`pi:t p i ;Ei E[Ei`ei:ti;Ci E `re eivep1!e1; :::: G i ti; [ i (Ci[fE(self)vt p i g)

Références

Documents relatifs

Since it has been understood that the Curry-Howard isomorphism relating proofs and programs can be extended to classical logic, various systems have been introduced: the λ c

L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des

bibliography of which can be found in the articles of Tang and Than [21], Mac Cormack, Harris, Hurwitz, and Spagon [11], or Ding [6]. The literature related to the processes limited

Notice that the part containing derivatives is due to the variation of the point in which the field is evaluated (while keeping fixed the label x), so it is simply due to the fact

We bring positive answers to both questions for the diverse usual computation models C (Turing machines, stack automata, RAMs, Sch¨ onhage Machines, Chomsky type 0 gram- mars,

[r]

• La création d’une période de lecture guidée à l’échelon du cycle primaire pour permettre aux enseignants- ressources de donner du soutien aux élèves à risque

Des guetteurs derrière leur créneau avec, dans la main le fusil ou la grenade à main, assurent des millions d'hommes barricadés, enterrés comme s'ils étaient morts et