Instant download Formal techniques for distributed objects components and systems 35th ifip wg 6 1 i

Page 1


Formal Techniques for Distributed Objects Components and Systems

35th

IFIP WG 6 1 International Conference FORTE 2015 Held as Part of the 10th International Federated Conference on Distributed Computing Techniques

DisCoTec 2015 Grenoble France Ju 1st Edition Susanne Graf

Visit to download the full and correct content document: https://textbookfull.com/product/formal-techniques-for-distributed-objects-components -and-systems-35th-ifip-wg-6-1-international-conference-forte-2015-held-as-part-of-the -10th-international-federated-conference-on-distributed-computi/

Formal Techniques for Distributed Objects, Components, and Systems

35th IFIP WG 6.1 International Conference, FORTE 2015 Held as Part of the 10th International Federated Conference on Distributed Computing Techniques, DisCoTec 2015 Grenoble, France, June 2–4, 2015, Proceedings

LectureNotesinComputerScience9039

CommencedPublicationin1973

FoundingandFormerSeriesEditors: GerhardGoos,JurisHartmanis,andJanvanLeeuwen

EditorialBoard

DavidHutchison

LancasterUniversity,Lancaster,UK

TakeoKanade

CarnegieMellonUniversity,Pittsburgh,PA,USA

JosefKittler UniversityofSurrey,Guildford,UK

JonM.Kleinberg CornellUniversity,Ithaca,NY,USA

FriedemannMattern

ETHZürich,Zürich,Switzerland

JohnC.Mitchell StanfordUniversity,Stanford,CA,USA

MoniNaor

WeizmannInstituteofScience,Rehovot,Israel

C.PanduRangan IndianInstituteofTechnology,Madras,India

BernhardSteffen

TUDortmundUniversity,Dortmund,Germany

DemetriTerzopoulos UniversityofCalifornia,LosAngeles,CA,USA

DougTygar UniversityofCalifornia,Berkeley,CA,USA

GerhardWeikum

MaxPlanckInstituteforInformatics,Saarbrücken,Germany

Moreinformationaboutthisseriesathttp://www.springer.com/series/7408

FormalTechniques forDistributedObjects, Components,andSystems

35thIFIPWG6.1InternationalConference,FORTE2015 HeldasPartofthe10thInternationalFederatedConference onDistributedComputingTechniques,DisCoTec2015 Grenoble,France,June2–4,2015

Proceedings

Editors

UniversitéGrenobleAlpes/VERIMAG

Grenoble France

MaheshViswanathan

UniversityofIllinoisatUrbana-Champaign Urbana,Illinois USA

ISSN0302-9743ISSN1611-3349(electronic)

LectureNotesinComputerScience

ISBN978-3-319-19194-2ISBN978-3-319-19195-9(eBook) DOI10.1007/978-3-319-19195-9

LibraryofCongressControlNumber:2015939161

LNCSSublibrary:SL2–ProgrammingandSoftwareEngineering SpringerChamHeidelbergNewYorkDordrechtLondon c IFIPInternationalFederationforInformationProcessing2015 Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpartofthe materialisconcerned,specificallytherightsoftranslation,reprinting,reuseofillustrations,recitation, broadcasting,reproductiononmicrofilmsorinanyother physicalway,andtransmissionorinformationstorageandretrieval,electronicadaptation,computer software,orbysimilarordissimilarmethodologynow knownorhereafterdeveloped.

Theuseofgeneraldescriptivenames,registerednames,trademarks,servicemarks,etc.inthispublication doesnotimply,evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfromtherelevant protectivelawsandregulationsandthereforefreeforgeneraluse.

Thepublisher,theauthorsandtheeditorsaresafetoassumethattheadviceandinformationinthisbook arebelievedtobetrueandaccurateatthedateofpublication.Neitherthepublishernortheauthorsorthe editorsgiveawarranty,expressorimplied,withrespecttothematerialcontainedhereinorforanyerrorsor omissionsthatmayhavebeenmade.

Printedonacid-freepaper

SpringerInternationalPublishingAGSwitzerlandispartofSpringerScience+BusinessMedia (www.springer.com)

Foreword

The10thInternationalFederatedConferenceonDistributedComputingTechniques (DisCoTec)tookplaceinMontbonnot,nearGrenoble,France,duringJune2–5,2015. ItwashostedandorganizedbyINRIA,theFrenchNationalResearchInstituteinComputerScienceandControl.TheDisCoTecseriesisoneofthemajoreventssponsored bytheInternationalFederationforInformationProcessing(IFIP).Itcomprisesthree conferences:

–COORDINATION,theIFIPWG6.1InternationalConferenceonCoordinationModelsandLanguages.

–DAIS,theIFIPWG6.1InternationalConferenceonDistributedApplicationsand InteroperableSystems.

–FORTE,theIFIPWG6.1InternationalConferenceonFormalTechniquesforDistributedObjects,ComponentsandSystems.

Together,theseconferencescoverabroadspectrumofdistributedcomputingsubjects,rangingfromtheoreticalfoundationsandformaldescriptiontechniquestosystems researchissues.

Eachdayofthefederatedeventbeganwithaplenarykeynotespeakernominatedby oneoftheconferences.ThethreeinvitedspeakerswereAloisFerscha(JohannesKeplerUniversität,Linz,Austria),LeslieLamport(MicrosoftResearch,USA),andWilly Zwaenepoel(EPFL,Lausanne,Switzerland).

Associatedwiththefederatedeventwerealsothreesatelliteworkshops,thattook placeonJune5,2015:

–The2ndInternationalWorkshoponFormalReasoninginDistributedAlgorithms (FRIDA),withakeynotespeechbyLeslieLamport(MicrosoftResearch,USA).

–The8thInternationalWorkshoponInteractionandConcurrencyExperience(ICE), withkeynotelecturesbyJadeAlglave(UniversityCollegeLondon,UK)andSteve Ross-Talbot(ZDLC,CognizantTechnologySolutions,London,UK).

–The2ndInternationalWorkshoponMeta ModelsforProcessLanguages(MeMo).

SincerethanksgotothechairsandmembersoftheProgramandSteeringCommitteesoftheinvolvedconferencesandworkshopsfortheirhighlyappreciatedefforts. OrganizingDisCoTecwasonlypossiblethankstothededicatedworkoftheOrganizingCommitteefromINRIAGrenoble-Rhône-Alpes,including SophieAzzaro,Vanessa Peregrin,MartineConsigney,AlainKersaudy,SophieQuinton,Jean-BernardStefani, andtheexcellentsupportfromCatherineNuelandthepeopleatInsightOutside.Finally,manythanksgotoIFIPWG6.1forsponsoringthisevent,andtoINRIAGrenobleRhône-AlpesanditsDirectorPatrickGrosfortheirsupportandsponsorship.

AlainGirault DisCoTec2015GeneralChair

DisCoTecSteeringCommittee

FarhadArbabCWI,Amsterdam,TheNetherlands RoccoDeNicolaIMTLucca,Italy

KurtGeihsUniversityofKassel,Germany

MicheleLoretiUniversityofFlorence,Italy

ElieNajmTelecomParisTech,France(Chair)

RuiOliveiraUniversityofMinho,Portugal

Jean-BernardStefaniInriaGrenoble-Rhône-Alpes,France

UweNestmannTechnicalUniversityofBerlin,Germany

Preface

ThisvolumecontainstheproceedingsofFORTE2015,the35thIFIPInternationalConferenceonFormalTechniquesforDistributedObjects,ComponentsandSystems.This conferencewasorganizedaspartofthe10thInternationalFederatedConferenceon DistributedComputingTechniques(DisCoTec)andwasheldinGrenoble,FrancebetweenJune2–4,2015.

TheFORTEconferenceseriesrepresentsaforumforfundamentalresearchontheory,models,tools,andapplicationsfordistributedsystems.Theconferenceencourages contributionsthatcombinetheoryandpractice,andthatexploitformalmethodsand theoreticalfoundationstopresentnovelsolutionstoproblemsarisingfromthedevelopmentofdistributedsystems.FORTEcoversdistributedcomputingmodelsandformalspecification,testing,andverificationmethods.Theapplicationdomainsinclude allkindsofapplication-leveldistributedsystems,telecommunicationservices,Internet, embeddedandreal-timesystems,aswellasnetworkingandcommunicationsecurity andreliability.

Wereceivedatotalof53fullpapersubmissionsforreview.Eachsubmissionwas reviewedbyatleastthreemembersoftheProgramCommittee.Basedonhigh-quality reviews,andathorough(electronic)discussionbytheProgramCommittee,weselected 15papersforpresentationattheconferenceandforpublicationinthisvolume.

LeslieLamport(MicrosoftResearch)waskeynotespeakerofFORTE2015.Leslie receivedtheTuringAwardin2013.Heisknownforhisseminalcontributionsindistributedsystems.Hehasdevelopedalgorithms,formalmodels,andverificationmethods fordistributedsystems.Leslie’skeynotelecturewasonTemporalLogicofActions.

WewouldliketothankallthosewhocontributedtothesuccessofFORTE2015: theauthors,forsubmittinghigh-qualityworktoFORTE2015;theProgramCommittee andtheexternalreviewers,forprovidingconstructive,high-qualityreviews,anefficient discussion,andafairselectionofpapers;theinvitedspeakerforaninspiringtalk;and, ofcourse,alltheattendeesofFORTE2015.WearealsogratefultotheDisCoTecGeneralChair,AlainGirault,OrganizationChair,Jean-BernardStefani,andallmembersof theirlocalorganizationteam.TheEasyChairconferencemanagementsystemfacilitated PCdiscussions,andthepreparationoftheseproceedings.ThankYou.

June2015SusanneGraf MaheshViswanathan

Organization

ProgramCommitteeChairs

SusanneGrafVERIMAG&CNRS,Grenoble,France

MaheshViswanathanUniversityofIllinoisatUrbana-Champaign,USA

ProgramCommitteeMembers

ErikaAbrahamRWTHAachenUniversity,Germany

LucaAcetoReykjavikUniversity,Iceland

S.AkshayIITBombay,India

PaulAttieAmericanUniversityofBeirut,Lebanon

RohitChadhaUniversityofMissouri,USA

RanceCleavelandUniversityofMaryland,USA

FrankdeBoerCWI,Amsterdam,TheNetherlands

BorzooBonakdarpourMcMasterUniversity,Ontario,Canada MicheleBorealeUniversitàdegliStudidiFirenze,Italy

StephanieDelauneCNRS&ENSCachan,France

WanFokkinkVrijeUniversiteitAmsterdam,TheNetherlands

GregorGoesslerInriaGrenoble,France

GerardHolzmannJetPropulsionLaboratory,Pasadena,CA,USA

AlanJeffreyAlcatel-LucentBellLabs,USA

PetrKuznetsovTelecomParisTech,France

IvanLaneseUniversityofBologna/INRIA,Italy

KimLarsenUniversityofAalborg,Denmark

AntoniaLopesUniversityofLisbon,Portugal

StephanMerzLORIA&INRIANancy,France

CatusciaPalamidessiINRIASaclay,France

AlanSchmittIRISA&INRIARennes,France

SteeringCommittee

ErikaAbrahamRWTHAachen,Germany

DirkBeyerUniversityofPassau,Germany

MicheleBorealeUniversitàdegliStudidiFirenze,Italy

EinarBrochJohnsenUniversityofOslo,Norway FrankdeBoerCWI,Amsterdam,TheNetherlands

HolgerGieseUniversityofPotsdam,Germany

CatusciaPalamidessiINRIA,Saclay,France

GrigoreRosuUniversityofIllinoisatUrbana-Champaign,USA Jean-BernardStefaniINRIA,Grenoble,France(Chair)

HeikeWehrheimUniversityofPaderborn,Germany

AdditionalReviewers

Agrawal,Shreya Astefanoaei,Lacramioara Azadbakht,Keyvan Bauer,Matthew Bettini,Lorenzo Bezirgiannis,Nikolaos Bracciali,Andrea Bresolin,Davide Castellani,Ilaria Corzilius,Florian Dalsgaard,AndreasEngelbredt Dang,Thao DellaMonica,Dario Demangeon,Romain Denielou,Pierre-Malo DiGiusto,Cinzia Dokter,Kasper Enea,Constantin Fehnker,Ansgar Foshammer,Louise Francalanza,Adrian Franco,Juliana Griffith,Dennis Guha,Shibashis Henrio,Ludovic Herbreteau,Frédéric Hirsch,Martin Höfner,Peter Jongmans,Sung-ShikT.Q. Kemper,Stephanie Kini,Dileep Laurent,Mounier

Lenglet,Sergueï Loreti,Michele Mandel,Louis Marques,EduardoR.B. Martins,Francisco Massink,Mieke Mateescu,Radu Mezzina,ClaudioAntares Najm,Elie Ober,Iulian Padovani,Luca Peressotti,Marco Pessaux,François Phawade,Ramchandra Poulsen,DannyBøgsted Prisacariu,Cristian Pérez,JorgeA. Quinton,Sophie Ravi,Srivatsan Reniers,Michel Rezine,Ahmed S.Krishna Sangnier,Arnaud Serbanescu,VladNicolae Sirjani,Marjan TapiaTarifa,SilviaLizeth Tiezzi,Francesco Trivedi,Ashutosh Valencia,Frank Wognsen,ErikRamsgaard Xue,Bingtian

EnsuringPropertiesofDistributedSystems TypesforDeadlock-FreeHigher-OrderPrograms

LucaPadovaniandLucaNovara

OnPartialOrderSemanticsforSAT/SMT-BasedSymbolicEncodings ofWeakMemoryConcurrency .....................................

AlexHornandDanielKroening

AStrategyforAutomaticVerificationofStabilizationofDistributed

RitwikaGhoshandSayanMitra

VanChanNgo,Jean-PierreTalpin,andThierryGautier

FormalModelsofConcurrentandDistributed Systems

YoussefArbach,DavidKarcher,KirstinPeters,andUweNestmann

KedarS.NamjoshiandRichardJ.Trefler

CodeMobilityMeetsSelf-organisation:AHigher-OrderCalculusof ComputationalFields .............................................

FerruccioDamiani,MirkoViroli,DaniloPianini,andJacobBeal

Mart´ınAbadiandMichaelIsard

DifferenceBoundConstraintAbstractionforTimedAutomata

WeifengWangandLiJiao

ComplianceandSubtypinginTimedSessionTypes 161 MassimoBartoletti,TizianaCimoli,MaurizioMurgia, AlessandroSebastianPodda,andLivioPompianu

Security

TypeCheckingPrivacyPoliciesinthe π -calculus ..................... 181 DimitriosKouzapasandAnnaPhilippou

ExtendingTestingAutomatatoAllLTL

AlaEddineBenSalem

EfficientVerificationTechniques

SimpleIsolationforanActorAbstractMachine ...................... 213 BenoitClaudel,QuentinSabah,andJean-BernardStefani

SlicedPathPrefixes:AnEffectiveMethodtoEnable RefinementSelection .............................................

DirkBeyer,StefanL¨owe,andPhilippWendler

Ensuring Properties of Distributed Systems

TypesforDeadlock-FreeHigher-OrderPrograms

DipartimentodiInformatica,Universit`adiTorino,Torino,Italy luca.padovani@di.unito.it

Abstract. Typesystemsforcommunicatingprocessesaretypicallystudiedusing abstractmodels– e.g., processalgebras –thatdistillthecommunicationbehavior ofprogramsbutoverlooktheirstructureintermsoffunctions,methods,objects, modules.Itisnotalwaysobvioushowtoapplythesetypesystemstostructured programminglanguages.Inthisworkweportarecentlydevelopedtypesystem thatensures deadlockfreedom inthe π-calculustoahigher-orderlanguage.

1Introduction

Inthisarticlewedevelopatypesystemthatguaranteeswell-typedprogramsthatcommunicateoverchannelstobefreefromdeadlocks.Typesystemsensuringthisproperty alreadyexist[7,8,10],buttheyallusethe π-calculusasthereferencelanguage.This choiceoverlookssomeaspectsofconcreteprogramminglanguages,likethefactthat programsarestructuredinto compartmentalizedblocks(e.g.,functions)withinwhich onlythelocalstructureoftheprogram(thebodyofafunction)isvisibletothetype system,andlittleifanythingisknowabouttheexterioroftheblock(thecallersof thefunction).Thestructureofprogramsmayhindersomekindsofanalysis:forexample,thetypesystemsin[7,8,10]enforceanorderingofcommunicationeventsandto dosotheytakeadvantageofthenatureof π-calculusprocesses,whereprogramsare flatsequencesofcommunicationactions.Howdowereasononsuchorderingwhen theexecutionorderisdictatedbythereductionstrategyofthelanguageratherthanby thesyntaxofprograms,orwheneventsoccurwithinafunction,andnothingisknown abouttheeventsthataresupposedtooccurafterthefunctionterminates?Weanswer thesequestionsbyportingthetypesystemin[10]toahigher-orderfunctionallanguage. Toillustratethekeyideasoftheapproach,letusconsidertheprogram

send a (recv b ) | send b (recv a ) (1.1) consistingoftwoparallelthreads.Thethreadontheleftistryingtosendthemessage receivedfromchannel b onchannel a;thethreadontherightistryingtodotheopposite.Thecommunicationson a and b aremutuallydependent,andtheprogramisa deadlock.Thebasicideausedin[10]andderivedfrom[7,8]fordetectingdeadlocks istoassigneachchannelanumber–whichwecall level –andtoverifythatchannels areusedinorderaccordingtotheirlevels.In( 1.1)thismechanismrequires b tohave smallerlevelthan a intheleftmostthread,and a tohaveasmallerlevelthan b inthe rightmostthread.Nolevelassignmentcansimultaneouslysatisfybothconstraints.In ordertoperformthesecheckswithatypesystem,thefirststepistoattachlevelsto

c IFIPInternationalFederationforInformationProcessing2015 S.GrafandM.Viswanathan(Eds.):FORTE2015,LNCS9039,pp.3–18,2015. DOI:10.1007/978-3-319-19195-9 1

channeltypes.Wethereforeassignthetypes![int]m and?[int]n respectivelyto a and b intheleftmostthreadof(1.1),and?[int]m and![int]n tothesamechannelsintherightmostthreadof(1.1).Crucially,distinctoccurrencesofthesamechannelhavetypes withoppositepolarities(input?andoutput!) andequallevel.Wecanalsothinkof theassignments send : ∀ı ![int]ı → int → unit and recv : ∀ı ?[int]ı → int forthecommunicationprimitives,whereweallowpolymorphismonchannellevels.Inthiscase, theapplication send a (recv b ) consistsoftwosubexpressions,thepartialapplication send a havingtype int → unit anditsargument recv b havingtype int.Neitherofthese typeshintsattheI/Ooperationsperformedintheseexpressions,letaloneatthelevels ofthechannelsinvolved.Torecoverthisinformationwepairtypeswith effects [1]:the effectofanexpressionisanabstractdescriptionoftheoperationsperformedduringits evaluation.Inourcase,wetakeaseffectthelevelofchannelsusedforI/Ooperations, or ⊥ inthecaseofpureexpressionsthatperformnoI/O.So,thejudgment

b :?[int]n recv b : int & n

statesthat recv b isanexpressionoftype int whoseevaluationperformsanI/Ooperationonachannelwithlevel n.Asusual,functiontypesaredecoratedwitha latenteffect sayingwhathappenswhenthefunctionisappliedtoitsargument.So,

a :![int]m send a : int →m unit & ⊥

statesthat send a isafunctionthat,appliedtoanargumentoftype int,producesa resultoftype unit and,indoingso,performsanI/Ooperationonachannelwithlevel m.Byitself, send a isapureexpressionwhoseevaluationperformsnoI/Ooperations, hencetheeffect ⊥.Effectshelpusdetectingdangerousexpressions:ina call-by-value languageanapplication e1 e2 evaluates e1 first,then e2 ,andfinallythebodyofthe functionresultingfrom e1 .Therefore,thechannelsusedin e1 musthavesmallerlevel thanthoseoccurringin e2 andthechannelsusedin e2 musthavesmallerlevelthanthose occurringinthebodyof e1 .Inthespecificcaseof send a (recv b ) wehave ⊥ < n for thefirstcondition,whichistriviallysatisfied,and n < m forthesecondone.Sincethe samereasoningon send b (recv a ) alsorequiresthesymmetriccondition(m < n),we detectthattheparallelcompositionofthetwothreadsin(1.1)isilltyped,asdesired. Itturnsoutthattheinformationgivenbylatenteffectsinfunctiontypesisnotsufficientforspottingsomedeadlocks.Toseewhy,considerthefunction

f def = λx.(send ax; send bx)

whichsendsitsargument x onboth a and b andwhere ; denotessequentialcomposition. Thelevelof a (say m)shouldbesmallerthanthelevelof b (say n),for a isusedbefore b (weassumethatcommunicationissynchronousandthat send isapotentiallyblocking operation).Thequestionis,whatisthelatenteffectthatdecoratesthetypeof f ,ofthe form int →h unit?Considerthetwoobviouspossibilities:ifwetake h = m,then

recv a | f 3 ; recv b (1.2) iswelltypedbecausetheeffect m of f 3issmallerthanthelevelof b in recv b,which agreeswiththefactthat f 3isevaluated before recv b;ifwetake h = n,then

recv a ; f 3 | recv b (1.3)

iswelltypedforsimilarreasons.Thisisunfortunatebecauseboth(1.3)and(1.2)reduce toadeadlock.Toflagbothofthemasilltyped,wemustrefinethetypeof f to int →m,n unit wherewedistinguishthesmallestlevelofthechannelsthat occur inthebodyof f (thatis m)fromthegreatestlevelofthechannelsthat areused by f when f isapplied toanargument(thatis n).Thefirstannotationgivesinformationonthechannelsinthe function’sclosure,whilethesecondannotationisthefunction’slatenteffect,asbefore. So(1.2)isilltypedbecausetheeffectof f 3isthesameasthelevelof b in recv b and (1.3)isilltypedbecausetheeffectof recv a isthesameasthelevelof f in f 3.

Inthefollowing,wedefineacoremultithreadedfunctionallanguagewithcommunicationprimitives(Section 2),wepresentabasictypeandeffectsystem,extendit toaddressrecursiveprograms,andstateitsproperties(Section 3).Finally,webriefly discusscloselyrelatedworkandafewextensions(Section 4). Proofsandadditional materialcanbefoundinlongversionofthepaper,onthefirstauthor’shomepage.

2LanguageSyntaxandSemantics

Indefiningourlanguage,weassumeasynchronouscommunicationmodelbasedonlinearchannels.Thisassumptionlimitstherangeofsystemsthatwecanmodel.However, asynchronousandstructuredcommunicationscanbeencodedusinglinearchannels: thishasbeenshowntobethecaseforbinarysessions[5]andformultipartysessionsto alargeextent[10,technicalreport].

Weuseacountablesetof variablesx, y, ... ,acountablesetof channelsa, b, ... , andasetofconstants k. Namesu, ... areeithervariablesorchannels.Weconsidera languageof expressions and processes asdefinedbelow:

::= k u λx.e eeP, Q ::= e (νa)P P | Q

Expressionscompriseconstants k,names u,abstractions λx e,andapplications e1 e2 Wewrite forunused/freshvariables.Constantsincludetheunitaryvalue (),theintegernumbers m, n, ,aswellastheprimitives fix, fork, new, send, recv whose semanticswillbeexplainedshortly.Processesareeitherthreads e ,ortherestriction (νa)P ofachannel a withscope P,ortheparallelcomposition P | Q ofprocesses.

Thenotionsoffreeandboundnamesareasexpected,giventhattheonlybindersare λ’sand ν’s.Weidentifytermsmodulorenamingofboundnamesandwewrite fn(e) (respectively, fn (P))forthesetofnamesoccurringfreein e (respectively,in P).

Thereductionsemanticsofthelanguageisgivenbytworelations,oneforexpressions,anotherforprocesses.Weadopta call-by-value reductionstrategy,forwhichwe needtodefine reductioncontexts E , ... and values v, w , ... respectivelyas:

E ::=[] E e vE v, w ::= k a λx.e send v

Thereductionrelation −→ forexpressionsisdefinedbystandardrules (λx.e)v −→ e{v/x} fix λx.e −→ e{ fix λx.e/x}

andclosedunderreductioncontexts.Asusual, e{e /x} denotesthecapture-avoiding substitutionof e forthefreeoccurrencesof x in e

Table1. Reductionsemanticsofexpressionsandprocesses

Thereductionrelationofprocesses(Table 1)has labels , ... thatareeitherachannelname a,signallingthatacommunicationhasoccurredon a,orthespecialsymbol τ denotinganyotherreduction.Therearefourbasereductionsforprocesses:acommunicationoccursbetweentwothreadswhenoneiswillingtosendamessage v ona channel a andtheotheriswaitingforamessagefromthesamechannel;athreadthat containsasubexpression fork v spawnsanewthreadthatevaluates v ();athreadthat containsasubexpression new() createsanewchannel;thereductionofanexpression causesacorresponding τ-labeledreductionofthethreadinwhichitoccurs.Reductionforprocessesisthenclosedunderparallelcompositions,restrictions,andstructural congruence.Therestrictionof a disappearsassoonasacommunicationon a occurs:in ourmodelchannelsare linear andcanbeusedforonecommunicationonly;structured formsofcommunicationcanbeencodedontopofthissimplemodel(seeExample 2 and[5]).Structuralcongruenceisdefinedbythestandardrulesrearrangingparallel compositionsandchannelrestrictions,where () playstheroleoftheinertprocess.

Weconcludethissectionwithtwoprogramswrittenusingaslightlyricherlanguage equippedwith let bindings,conditionals,andafewadditionaloperators.Allthese constructseitherhavewell-knownencodingsorcanbeeasilyaccommodated.

Example1(parallelFibonaccifunction). The fibo functionbelowcomputesthe n-th numberintheFibonaccisequenceand sendstheresultonachannel c:

1 fix λfibo.λn.λc.if n ≤ 1 then send cn

2 elselet a= new() and b= new() in

3 (fork λ_.fibo(n-1)a);

4 (fork λ_.fibo(n-2)b);

5 send c(recv a+ recv b)

Thefreshchannels a and b areusedtocollecttheresults fromtherecursive,parallel invocationsof fibo.NotethatexpressionsareintertwinedwithI/Ooperations.Itis relevanttoaskwhetherthisversionof fibo isdeadlockfree,namelyifitisableto reduceuntilaresultiscomputedwithoutblockingindefinitelyonanI/Ooperation.

Example2(signalpipe). Inthisexampleweimplementafunction pipe thatforwards signalsreceivedfromaninputstream x toanoutputstream y:

1 let cont= λx.let c= new() in (fork λ_.send xc);c in

2 let pipe= fix λpipe.λx.λy.pipe(recv x)(conty)

Notethatthispipeisonlycapableofforwardinghandshakingsignals.Amoreinterestingpipetransmittingactualdatacanberealizedbyconsideringdatatypessuchas recordsandsums[5].Thesimplifiedrealizationweconsiderheresufficestoillustratea relevantfamilyofrecursivefunctionsthatinterleaveactionsondifferentchannels.

Sincelinearchannelsareconsumedaftercommunication,eachsignalincludesa continuationchannel onwhichthesubsequentsignalsinthestreamwillbesent/received. Inparticular, contx sendsafreshcontinuation c on x andreturns c,sothat c can beusedforsubsequentcommunications,while pipexy sendsafreshcontinuation on y afterithasreceivedacontinuationfrom x,andthenrepeatsthisbehavioronthe continuations.Theprogrambelowconnectstwopipes:

3 let a= new() and b= new() in

4 (fork λ_.pipeab);(fork λ_.pipeb(conta))

Evenifthetwopipesrealizeacyclicnetwork,wewillseeinSection 3 thatthis programiswelltypedandthereforedeadlockfree.Forgetting cont online4ornot forkingthe send online1,however,producesadeadlock.

3TypeandEffectSystem

Wepresentthefeaturesofthetypesystemgradually,inthreesteps:westartwitha monomorphicsystem(Section 3.1),thenweintroducelevelpolymorphismrequiredby Examples 1 and 2 (Section 3.2),andfinallyrecursivetypesrequiredbyExample 2 (Section 3.3).Weendthesectionstudyingthepropertiesofthetypesystem(Section 3.4).

3.1CoreTypes

Let L def = Z ∪{⊥, } bethesetof channellevels orderedintheobviousway(⊥ < n < forevery n ∈ Z);weuse ρ, σ , ... torangeover L andwewrite ρ σ (respectively, ρ σ )forthe minimum (respectively,the maximum)of ρ and σ Polaritiesp, q, ... are non-emptysubsetsof {?, !};weabbreviate {?} and {!} with?and!respectively,and {?, !} with#. Typest , s, ... aredefinedby

where basictypes B, ... include unit and int.Thetype p[t ]n denotesachannelwith polarity p andlevel n.Thepolaritydescribestheoperationsallowedonthechannel:? meansinput,!meansoutput,and#meansbothinputandoutput.Channelsarelinear resources:theycanbeusedonceaccordingtoeachelementintheirpolarity.Thetype t →ρ,σ s denotesafunctionwithdomain t andrange s.Thefunctionhaslevel ρ (its closurecontainschannelswithlevel ρ orgreater)and,whenapplied,ituseschannels withlevel σ orsmaller.If ρ = ,thefunctionhasnochannelsinitsclosure;if σ = ⊥, thefunctionusesnochannelswhenapplied.Wewrite → asanabbreviationfor → ,⊥ , so → denotespurefunctionsnotcontainingandnotusinganychannel.

RecallfromSection 1 thatlevelsaremeanttoimposeanorderontheuseofchannels: roughly,thelowerthelevelofachannel,thesoonerthechannelmustbeused.Weextendthenotionoflevelfromchanneltypestoarbitrarytypes:basictypeshavelevel becausethereisnoneedtousethemasfaras deadlockfreedomisconcerned;thelevel offunctionsiswrittenintheirtype.Formally,thelevelof t ,written |t |,isdefinedas:

Levelscanbeusedtodistinguish lineartypes,denotingvalues(suchaschannels)that must beusedtoguaranteedeadlockfreedom,from unlimitedtypes,denotingvaluesthat havenoeffectondeadlockfreedomand may bedisregarded.Wesaythat t is linear if |t |∈ Z;wesaythat t is unlimited ,written un(t ),if |t | =

Belowarethetypeschemesoftheconstantsthatweconsider.Someconstantshave manytypes(constraintsareontheright);wewrite types(k) forthe setof typesof k.

Thetypeof (),ofthenumbers,andof fix areordinary.Theprimitive new createsa freshchannelwiththefullset#ofpolaritiesandarbitrarylevel n.Theprimitive recv takesachanneloftype?[t ]n ,blocksuntilamessageisreceived,andreturnsthemessage. Theprimitiveitselfcontainsnofreechannelsinitsclosure(hencethelevel )because theonlychannelitmanipulatesisitsargument.Thelatenteffectisthelevelofthe channel,asexpected.Theprimitive send takesachanneloftype![t ]n ,amessageoftype t ,andsendsthemessageonthechannel.Notethatthepartialapplication send a isa functionwhoselevelandlatenteffectareboththelevelof a.Notealsothatin new, recv, and send thelevelofthemessagemustbegreaterthanthelevelofthechannel:since levelsareusedtoenforceanorderontheuseofchannels,thisconditionfollowsfrom theobservationthatamessagecannotbeuseduntil after ithasbeenreceived,namely afterthechannelonwhichittravelshasbeenused.Finally, fork acceptsathunkwith arbitrarylevel ρ andlatenteffect σ andspawnsthethunkintoanindependentthread (seeTable 1).Notethat fork isapurefunctionwithnolatenteffect,regardlessof thelevelandlatenteffectofthethunk.Thisphenomenoniscalled effectmasking [1], wherebytheeffectofevaluatinganexpressionbecomesunobservable:inourcase, fork dischargeseffectsbecausethethunkrunsinparallelwiththecodeexecutingthe fork. Wenowturntothetypingrules.A typeenvironment Γ isafinitemap u1 : t1 ,..., un : tn fromnamestotypes.Wewrite/0fortheemptytypeenvironment, dom(Γ ) forthe domainof Γ ,and Γ (u) forthetypeassociatedwith u in Γ ;wewrite Γ1 , Γ2 fortheunionof Γ1 and Γ2 when dom(Γ1 ) ∩ dom(Γ2 )= / 0.Wealsoneedamoreflexiblewayofcombining typeenvironments.Inparticular,wemakesurethateverychannelisusedlinearlyby distributingdifferentpolaritiesofachanneltodifferentpartsoftheprogram.Tothis aim,following[9],wedefineapartial combination operator + betweentypes:

thatweextendtotypeenvironments,thus:

Forexample,wehave (x : int, a :![int]n )+(a :?[int]n )= x : int, a :#[int]n ,sowe mighthavesomepartoftheprogramthat(possibly)usesavariable x oftype int along

withchannel a forsendinganintegerandanotherpartoftheprogramthatusesthesame channel a butthistimeforreceivinganinteger.Thefirstpartoftheprogramwould betypedintheenvironment x : int, a :![int]n andthesecondoneintheenvironment a :?[int]n .Overall,thetwopartswouldbetypedintheenvironment x : int, a :#[int]n indicatingthat a isusedforbothsending and receivinganinteger. Weextendthefunction |·| totypeenvironmentssothat |Γ | def = u∈dom(Γ ) |Γ (u)| with theconventionthat | / 0| = ;wewrite un(Γ ) if |Γ | =

Table2. Coretypingrulesforexpressionsandprocesses

Typingofexpressions

Typingofprocesses

Wearenowreadytodiscussthecoretypingrules,showninTable 2.Judgments oftheform Γ e : t & ρ denotethat e iswelltypedin Γ ,ithastype t andeffect ρ; judgmentsoftheform Γ P simplydenotethat P iswelltypedin Γ .

Axioms [T- NAME ] and [T- CONST ] areunremarkable:asinallsubstructuraltypesystems theunusedpartofthetypeenvironmentmustbeunlimited.Namesandconstantshave noeffect(⊥);theyareevaluatedexpressionsthatdonotuse(butmaycontain)channels.

Inrule [T- FUN ] ,theeffect ρ causedbyevaluatingthebodyofthefunctionbecomesthe latenteffectinthearrowtypeofthefunctionandthefunctionitselfhasnoeffect.The levelofthefunctionisdeterminedbythatoftheenvironment Γ inwhichthefunction istyped.Intuitively,thenamesin Γ arestoredinthe closure ofthefunction;ifany ofthesenamesisachannel,thenwemustbesurethatthefunctioniseventuallyused (i.e.,applied)toguaranteedeadlockfreedom.Infact, |Γ | givesaslightlymoreprecise information,sinceitrecordsthesmallestlevelofallchannelsthatoccurinthebodyof thefunction.WehaveseeninSection 1 whythisinformationisuseful.Afewexamples:

– theidentityfunction λx.x hastype int → ,⊥ int inanyunlimitedenvironment;

– thefunction λ .a hastype unit →n,⊥ ![int]n intheenvironment a :![int]n ;itcontains channel a withlevel n initsclosure(whencethelevel n inthearrow),butitdoes notuse a forinput/output(whencethelatenteffect ⊥);itisnonethelesswelltyped because a,whichisalinearvalue,isreturnedasresult;

– thefunction λx.send x 3hastype![int]n → ,n unit;ithasnochannelsinitsclosure butitperformsanoutputonthechannelitreceivesasargument;

– thefunction λx.(recv a + x) hastype int →n,n int intheenvironment a :?[int]n ; notethatneitherthedomainnorthecodomainofthefunctionmentionanychannel, sothefactthatthefunctionhasachannelinitsclosure(andthatitperformssome I/O)canonlybeinferredfromtheannotationsonthearrow;

– thefunction λx.send x (recv a ) hastype![int]n+1 →n,n+1 unit intheenvironment a :![int]n ;itcontainschannel a withlevel n initsclosureandperformsinput/output operationsonchannelswithlevel n + 1(orsmaller)whenapplied.

Rule [T- APP ] dealswithapplications e1 e2 .Thefirstthingtonoticeisthetypeenvironmentsinthepremisesfor e1 and e2 .Normally,theseareexactlythesameasthe typeenvironmentusedforthewholeapplication.Inoursetting,however,wewantto distributepolaritiesinsuchawaythateachchannelisusedforexactlyonecommunication.Forthisreason,thetypeenvironment Γ1 + Γ2 intheconclusionisthecombination ofthetypeenvironmentsinthepremises.Regardingeffects, τi istheeffectcausedby theevaluationof ei .Asexpected, e1 mustresultinafunctionoftype t →ρ,σ s and e2 in avalueoftype t .Theevaluationof e1 and e2 mayhoweverinvolveblockingI/Ooperationsonchannels,andthetwosideconditionsmakesurethatnodeadlockcanarise. Tobetterunderstandthem,recallthatreductionis call-by-value andapplications e1 e2 areevaluated sequentiallyfromlefttoright.Now,thecondition τ1 < |Γ2 | makessure thatanyI/Ooperationperformedduringtheevaluationof e1 involvesonlychannels whoselevelissmallerthanthatofthechannelsoccurringfreein e2 (thefreechannels of e2 mustnecessarilybein Γ2 ).Thisisenoughtoguaranteethatthefunctionalpart oftheapplicationcanbefullyevaluatedwithoutblockingonoperationsconcerning channelsthatoccur later intheprogram.Inprinciple,thisconditionshouldbepaired withthesymmetricone τ2 < |Γ1 | makingsurethatanyI/Ooperationperformedduring theevaluationoftheargumentdoesnotinvolvechannelsthatoccurinthefunctional part.However,whentheargumentisbeingevaluated,weknowthatthefunctionalpart hasalreadybeenreducedavalue(seethedefinitionofreductioncontextsinSection 2). Therefore,theonlyreallycriticalconditiontocheckisthatnochannelsinvolvedinI/O operationsduringtheevaluationof e2 occurinthe value of e1 .Thisisexpressedbythe condition τ2 < ρ,where ρ isthelevelofthefunctionalpart.Notethat,when e1 isan abstraction,byrule [T- FUN ] ρ coincideswith |Γ1 |,butingeneral ρ maybegreaterthan |Γ1 |,sothecondition τ2 < ρ givesbetteraccuracy.Theeffectofthewholeapplication e1 e2 is,asexpected,thecombinationoftheeffectsofevaluating e1 , e2 ,andthelatent effectofthefunctionbeingapplied.Inourcasethe“combination”isthegreatestlevel ofanychannelinvolvedintheapplication.Belowaresomeexamples:

– (λx.x) a iswelltyped,becauseboth λx.x and a arepureexpressionswhoseeffect is ⊥,hencethetwosideconditionsof [T- APP ] aretriviallysatisfied;

– (λx.x)(recv a) iswelltypedintheenvironment a :?[int]n :theeffectof recv a is n (thelevelof a)whichissmallerthanthelevel ofthefunction;

– send a (recv a) isilltypedintheenvironment a :#[int]n becausetheeffectof evaluating recv a,namely n,isthesameasthelevelof send a;

– (recv a)(recv b) iswelltypedintheenvironment a :?[int → int]0 , b :?[int]1 .The effectoftheargumentis1,whichis not smallerthantheleveloftheenvironment a :?[int → int]0 usedfortypingthefunction.However,1issmallerthan ,which

isthelevelofthe result oftheevaluationofthefunctionalpartoftheapplication. Thisapplicationwouldbeillegalhadweusedthesidecondition τ2 < |Γ1 | in [T- APP ] .

Thetypingrulesforprocessesarestandard: [T- PAR ] splitscontextsfortypingtheprocessesinparallel, [T- NEW ] introducesanewchannelintheenvironment,and [T- THREAD ] typesthreads.Theeffectofthreadsisignored:effectsareusedtopreventcirculardependenciesbetweenchannelsusedwithinthe sequential partsoftheprogram(i.e.,within expressions);circulardependenciesthatarisebetween parallel threadsareindirectly detectedbythefactthateachoccurrenceofa channelistypedwiththesamelevel(see thediscussionof(1.1)inSection 1).

3.2LevelPolymorphism

LookingbackatExample 1,wenoticethat fibonc maygeneratetworecursive callswithtwocorrespondingfreshchannels a and b.Sincethe send operationon c is blockedby recv operationson a and b (line5),thelevelof a and b mustbesmallerthan thatof c.Also,sinceexpressionsareevaluatedleft-to-rightand recv a+ recv b is syntacticsugarfortheapplication (+)(recv a)(recv b),thelevelof a mustbe smallerthanthatof b.Thus,todeclare fibo welltyped,wemustallowdifferentoccurrencesof fibo tobeappliedtochannelswithdifferentlevels.Evenmorecritically,this formoflevelpolymorphismof fibo isnecessary within thedefinitionof fibo itself, soitisaninstanceof polymorphicrecursion [1].

ThecoretypingrulesinTable 2 donotsupportlevelpolymorphism.Followingthe previousdiscussionon fibo,theideaistorealizelevelpolymorphismby shifting levels intypes.Wedefinelevelshiftingasatypeoperator ⇑n ,thus:

where + isextendedfromintegerstolevelssothat n + = and n + ⊥ = ⊥.Theeffect of ⇑n t istoshiftallthefinitelevelannotationsin t by n,leaving and ⊥ unchanged.

Now,wehavetounderstandinwhichcaseswecanuseavalueoftype ⇑n t where oneoftype t isexpected.Morespecifically,whenavalueoftype ⇑n t canbepassedtoa functionexpectinganargumentoftype t .Thisispossibleifthefunctionhaslevel .We expressthisformoflevelpolymorphismwithanadditionaltypingruleforapplications:

[ T- APP - POLY ]

Thisruleadmitsanarbitrarymismatch n betweentheleveltheargumentexpected bythefunctionandthatoftheargumentsuppliedtothefunction.Thetypeoftheapplicationandthelatenteffectareconsequentlyshiftedbythesameamount n

Soundnessof [T- APP - POLY ] canbeintuitivelyexplainedasfollows:afunctionwithlevel hasnochannelsinitsclosure.Therefore,theonlychannelspossiblymanipulatedby thefunctionarethosecontainedintheargumenttowhichthefunctionisappliedor channelscreatedwithinthefunctionitself. Then,thefactthattheargumenthaslevel

n + k ratherthanlevel k iscompletelyirrelevant.Conversely,ifthefunctionhaschannelsinitsclosure,thentheabsoluteleveloftheargumentmighthavetosatisfyspecificorderingconstraintswithrespectto thesechannels(recallthetwosideconditions in [T- APP ] ).Sincelevelpolymorphismisakeydistinguishingfeatureofourtypesystem, andonethataccountsformuchofitsexpressiveness,weelaboratemoreonthisintuition usinganexample.Considertheterm

fwd def = λx.λy.send y (recv x)

whichforwardson y themessagereceivedfrom x.Thederivation . . .

[T- APP ] y :![int]1 send y : int →1,1 unit & ⊥ . . .

[T- APP ] x :?[int]0 recv x : int &0

[T- APP ] x :?[int]0 , y :![int]1 send y (recv x) : unit &1

[T- FUN ] x :?[int]0 λy.send y (recv x) :![int]1 →0,1 unit & ⊥

does not dependontheabsolutevalues0and1,butonlyonthelevelof x beingsmaller thanthatof y,asrequiredbythefactthatthe send operationon y isblockedbythe recv operationon x.Now,consideranapplication fwd a,where a hastype?[int]2 .The mismatchbetweenthelevelof x (0)andthatof a (2)isnotcritical,becauseallthelevels inthederivationabovecanbe uniformlyshiftedup by2,yieldingaderivationfor fwd :?[int]2 → ![int]3 →2,3 unit & ⊥

Thisshiftingispossiblebecause fwd hasnofreechannelsinitsbody(indeed,itistyped intheemptyenvironment).Therefore,using [T- APP - POLY ] ,wecanderive a :?[int]2 fwd a :![int]3 →2,3 unit & ⊥

Notethat (fwd a) isafunctionhavinglevel2.Thismeansthat (fwd a) is not level polymorphicandcanonlybeapplied,through [T- APP ] ,tochannelswithlevel3.Ifwe allowed (fwd a) tobeappliedtoachannelwithlevel2using [T- APP - POLY ] wecouldderive a :#[int]2 fwd aa : unit &2 whichreducestoadeadlock.

Example3. ToshowthattheterminExample 1 iswelltyped,considertheenvironment Γ def = fibo : int → ![int]0 → ,0 unit, n : int, c :![int]0

Intheproofderivationforthebodyof fibo,thisenvironmentiseventuallyenriched withtheassignments a :#[int] 2 and b :#[int] 1 .Nowwecanderive . . .

Γ fibo(n-2) :![int]0 → ,0 unit & ⊥

[T- APP ]

[T- NAME ] a :![int] 2 a :![int] 2 & ⊥

[T- APP - POLY ] Γ , a :![int] 2 fibo(n-2)a : unit & 2

wheretheapplication fibo(n-2)a iswelltypeddespitethefactthat fibo(n-2) expectsanargumentoftype![int]0 ,while a hastype![int] 2 .Asimilar derivationcanbeobtainedfor fibo(n-1)b,andtheproofderivationcannowbe completed.

3.3RecursiveTypes

LookingbackatExample 2,weseethatinacall pipexy thechannel recv x isused inthesamepositionas x.Therefore,accordingto [T- APP - POLY ] , recv x musthavethe sametypeas x,uptosomeshiftingofitslevel.Similarly,channel c isbothsenton y andthenusedinthesamepositionas y,suggestingthat c musthavethesametypeas y, againuptosomeshiftingofitslevel.This meansthatweneedrecursivetypesinorder toproperlydescribe x and y

Insteadofaddingexplicitsyntaxforrecursivetypes,wejustconsiderthepossibly infinitetreesgeneratedbytheproductionsfor t shownearlier.Inlightofthisbroader notionoftypes,theinductivedefinitionoftypelevel(3.1)isstillwellfounded,buttype shift(3.4)mustbereinterpretedcoinductively,becauseithastooperateonpossibly infinitetrees.Theformalities,nonetheless,arewellunderstood.

Itisfolklorethat,wheneverinfinitetypesare regular (thatis,whentheyaremade offinitelymanydistinctsubtrees),theyadmitfiniterepresentationseitherusingtype variablesandthefamiliar μ notation,orusingsystemsoftypeequations[4].Unfortunately,acarefulanalysisofExample 2 suggeststhat–atleastinprinciple–wealso need non-regular types.Toseewhy,let a and c bethechannelstowhich (recv x) and (conty) respectivelyevaluateonline2oftheexample.Now:

– x musthavesmallerlevelthan a since a isreceivedfrom x (cf. thetypesof recv). – y musthavesmallerlevelthan c since c issenton y (cf. thetypesof send).

– x musthavesmallerlevelthan y since x isusedinthefunctionalpartofanapplicationinwhich y occursintheargument(cf. line2and [T- APP - POLY ] ).

Overall,inordertotype pipe inExample 2 weshouldassign x and y thetypes t n and sn thatrespectivelysatisfytheequations

Unfortunately,theseequationsdonotadmitregulartypesassolutions.Werecover typeabilityof pipe withregulartypesbyintroducinganewtypeconstructor

::= ··· t n thatwrapstypeswithapendingshift:intuitively t n and ⇑n t denotethesametype,exceptthatin t n theshift ⇑n on t ispending.Forexample, ?[int]0 1 and ?[int]2 1 arebothpossiblewrappingsof?[int]1 ,while int →0,⊥ ![int]0 istheunwrappingof int →1,⊥ ![int]1 1 .Toexcludemeaninglessinfinitetypessuchas ··· n n n we imposea contractivenesscondition requiringeveryinfinitebranchofatypetocontain infiniteoccurrencesofchannelorarrowconstructors.Toseewhywrapshelpfinding regularrepresentationsforotherwisenon-regulartypes,observethattheequations

denote–uptopendingshifts–thesametypesastheonesin(3.5),withthekeydifferencethat(3.6)admitregularsolutionsandthereforefiniterepresentations.Forexample, t n couldbefinitelyrepresentedasafamiliar-looking μα.?[ α 2 ]n term.

Weshouldremarkthat t n and ⇑n t are different types,eventhoughtheformeris morallyequivalenttothelatter:wrappingisatype constructor,whereasshiftisatype operator.Havingintroducedanewconstructor,wemustsuitablyextendthenotionsof typelevel(3.1)andtypeshift(3.4)wehavedefinedearlier.Wepostulate

inaccordancewiththefactthat · n denotesapendingshiftby n (notethat |·| extended towrappingsiswelldefinedthankstothecontractivenesscondition).

Wealsohavetodefineintroductionandeliminationrulesforwrappings.Tothisaim, weconceivetwoconstants, wrap and unwrap,havingthefollowingtypeschemes:

Weadd wrap v tothevalueforms.Operationally,wewant wrap and unwrap toannihilateeachother.Thisisdonebyenrichin greductionforexpressionswiththeaxiom

unwrap (wrap v) −→ v

Example4. WesuitablydressthecodeinExample 2 using wrap and unwrap: 1 let cont= λx.let c= new() in (fork λ_.send x(wrap c));c in 2 let pipe= fix λpipe.λx.λy.pipe(unwrap (recv x))(conty) andwearenowabletofindatypingderivationforitthatusesregulartypes.Inparticular,weassign cont thetype sn → sn+2 and pipe thetype t n → sn →n, unit where t n and sn arethetypesdefinedin(3.6).Notethat cont isapurefunctionbecauseits effectsaremaskedby fork andthat pipe haslatenteffect sinceitloopsperforming recv operationsonchannelswithincreasinglevel.Becauseofthesideconditionsin [T- APP ] and [T- APP - POLY ] ,thismeansthat pipe canonlybeusedintailposition,whichis preciselywhathappensaboveandinExample 2

3.4Properties

Toformulatesubjectreduction,wemusttakeintoaccountthatlinearchannelsare consumed aftercommunication(lastbutonereductioninTable 1).Thismeansthatwhena process P communicatesonsomechannel a, a mustberemovedfromthetypeenvironmentusedfortypingtheresidualof P.Tothisaim,wedefineapartialoperation Γ thatremoves from Γ ,when isachannel.Formally:

Theorem1(SubjectReduction). If Γ PandP −→ Q,then Γ Qwhere Γ τ def = Γ and (Γ , a :#[t ]n ) a def = Γ .

Notethat Γ a isundefinedif a ∈ dom(Γ ).Thismeansthatwell-typedprograms neverattemptatusingthesamechanneltwice,namelythatchannelsinwell-typedprogramsareindeed linearchannels.Thispropertyhasimportantpracticalconsequences, sinceitallowstheefficientimplementation(anddeallocation)ofchannels[9].

Deadlockfreedommeansthat if theprogramhalts,thentheremustbenopending I/Ooperations.Inourlanguage,theonlyhaltedprogramwithoutpendingoperationsis (structurallyequivalentto) () .Wecanthereforedefinedeadlockfreedomthus:

Definition1. WesaythatPis deadlockfree ifP τ −→ ∗ Q −→ impliesQ ≡ () .

Asusual, τ −→ ∗ isthereflexive,transitiveclosureof τ −→ and Q −→ meansthat Q is unabletoreducefurther.Now,everywell-typed,closedprocessisfreefromdeadlocks: Theorem2(Soundness). If / 0 P,thenPisdeadlockfree.

Theorem 2 maylookweakerthandesirable,consideringthateveryprocess P (even anill-typedone)canbe“fixed”andbecomepartofadeadlock-freesystemifcomposedinparallelwiththedivergingthread fix λx x .Itisnoteasytostateaninterestingpropertyofwell-typed partialprograms –programsthatarewelltypedinunevenenvironments–orof partialcomputations –computationsthathavenotreached astable(i.e.,irreducible)state.Onemightthinkthatwell-typedprogramseventually usealloftheirchannels.Thispropertyisfalseingeneral,fortworeasons.First,our typesystemdoesnotensureterminationofwell-typedexpressions,soathreadlike send a (fix λx.x) neveruseschannel a,becausetheevaluationofthemessagediverges.Second,therearethreadsthatcontinuouslygenerate(orreceive)newchannels, sothatthesetofchannelstheyownisneverempty;thishappensinExample 2.What wecanproveisthat, assuming thatawell-typedprogramdoesnotinternallydiverge, then each channelitownsiseventuallyusedforacommunicationorissenttotheenvironmentinamessage.Toformalizethisproperty,weneedalabeledtransitionsystem describingtheinteractionofprogramswiththeirenvironment. Labels π, ... oftransitionsaredefinedby

andthetransitionrelation π −→ extendsreductionwiththerules

where C rangesover processcontexts C ::= E | (C | P) | (P | C ) | (νa)C .Messages ofinputtransitionshavetheform a?e where e isanarbitraryexpressioninsteadofa value.ThisisjusttoallowatechnicallyconvenientformulationofDefinition 2 below. Weformalizetheassumptionconcerningtheabsenceofinternaldivergencesasapropertythatwecall interactivity.Interactivityisapropertyof typedprocesses,whichwe writeaspairs Γ P,sincethemessagesexchangedbetweenaprocessandtheenvironmentinwhichitexecutesarenotarbitraryingeneral.

Definition2(Interactivity). Interactivityisthelargestpredicateonwell-typedprocessessuchthat Γ P interactive implies Γ Pand:

1.PhasnoinfinitereductionP 1 −→ P1 2 −→ P2 3 −→··· ,and 2.ifP −→ Q,then Γ Qisinteractive,and

3.ifP a!v −→ Qand Γ = Γ , a :![t ]n ,then Γ Qisinteractiveforsome Γ ⊆ Γ ,and

4.ifP a?x −→ Qand Γ = Γ , a :?[t ]n ,then Γ Q{v/x} isinteractiveforsome v and Γ ⊇ Γ suchthatn < |Γ \ Γ |.

Clause(1)saysthataninteractiveprocess doesnotinternallydiverge:itwilleventuallyhalteitherbecauseit terminatesorbecauseitneedsinteractionwiththeenvironmentinwhichitexecutes.Clause(2)statesthatinternalreductionspreserveinteractivity.Clause(3)statesthataprocesswithapendingoutputonachannel amust reduce toaninteractiveprocessaftertheoutputisperformed.Finally,clause(4)statesthata processwithapendinginputonachannel amay reducetoaninteractiveprocessafter theinputofaparticularmessage v isperformed.Thedefinitionlooksdemanding,but manyconditionsaredirectconsequencesofTheorem 1.Thereallynewrequirements besideswelltypednessare convergence of P (1)andthe existence of v (4).Itisnow possibletoprovethatwell-typed,interactiveprocesseseventuallyusetheirchannels.

Theorem3(Interactivity). Let Γ Pbeaninteractiveprocesssuchthata

4ConcludingRemarks

Wehavedemonstratedtheportabilityofatypesystemfordeadlockfreedomof πcalculusprocesses[10]toahigher-orderlanguageusingan effectsystem [1].Wehave shownthat effectmasking and polymorphicrecursion arekeyingredientsofthetype system(Examples 1 and 2),andalsothatlatenteffectsmustbepairedwithonemore annotation–thefunctionlevel.Theapproachmayseemtohinderprogrammodularity, sinceitrequiresstoringlevelsintypesandlevelshaveglobalscope.Inthisrespect, levelpolymorphism(Section 3.2)alleviatesthisshortcomingoflevelsbygrantingthem arelative–ratherthanabsolute–meaningatleastfornon-linearfunctions.

Othertypesystemsforhigher-orderlanguageswithsession-basedcommunication primitiveshavebeenrecentlyinvestigated[6,14,2].Inadditiontosafety,typesareused forestimatingboundsinthesizeofmessagequeues[6]andfordetectingmemory leaks[2].Sincebinarysessionscanbeencodedusinglinearchannels[5],ourtype systemcanaddressthesamefamilyofprogramsconsideredintheseworkswiththe advantagethat,inourcase,well-typedprogramsareguaranteedtobedeadlockfree alsoinpresenceofsessioninterleaving.Forinstance,the pipe functioninExample 2 interleavescommunicationsontwodifferentchannels.Thetypesystemdescribedby Wadler[14]isinterestingbecauseitguaranteesdeadlockfreedomwithoutresortingto anytypeannotationdedicatedtothispurpose.Inhiscasethesyntaxof(well-typed) programspreventsthemodelingofcyclic networktopologies,whichisanecessary conditionfordeadlocks.However,thisalsomeansthatsomeusefulprogrampatterns cannotbemodeled.Forinstance,theprograminExample 2 isilltypedin[14].

Thetypesystemdiscussedinthispaperlackscompellingfeatures. Structureddata types (records,sums)havebeenomittedforlackofspace;anextendedtechnicalreport[13]andpreviousworks[11,10]showthattheycanbeaddedwithoutissues.The samegoesfor non-linearchannels [10],possiblywiththehelpofdedicated accept

and request primitivesasin[6]. Truepolymorphism (withlevelandtypevariables) hasalsobeenstudiedinthetechnicalreport[13].Itsimpactontheoveralltypesystemissignificant,especiallybecauselevelandtypeconstraints(thoseappearingasside conditionsinthetypeschemesofconstants,Section 3.1)mustbepromotedfromthe metatheorytothetypesystem.Therealizationoflevelpolymorphismastypeshiftingthatwehaveadoptedinthispaperisaninterestingcompromisebetweenimpact andflexibility.Ourtypesystemcanalsoberelaxedwith subtyping:arrowtypesare contravariantinthelevelandcovariantinthelatenteffect,whereaschanneltypesare invariantinthelevel.Invarianceofchannellevelscanberelaxedrefininglevelsto pairs ofnumbersasdonein[7,8].Thiscanalsoimprovetheaccuracyofthetypesystemin somecases,asdiscussedin[10]and[3].Itwouldbeinterestingtoinvestigatewhich ofthesefeaturesareactuallynecessaryfortypingconcretefunctionalprogramsusing threadsandcommunication/synchronizationprimitives.

Typereconstruction algorithmsforsimilartypesystemshavebeendefined[11,12]. Weareconfidenttosaythattheyscaletotypesystemswitharrowtypesandeffects.

Acknowledgments. Theauthorsaregratefultothereviewersfortheirdetailedcommentsand usefulsuggestions.ThefirstauthorhasbeensupportedbyAteneo/CSPprojectSALT,ICTCOST ActionIC1201BETTY,and MIURprojectCINA.

References

1.Amtoft,T.,Nielson,F.,Nielson,H.:TypeandEffectSystems:BehavioursforConcurrency. ImperialCollegePress(1999)

2.Bono,V.,Padovani,L.,Tosatto,A.:PolymorphicTypesforLeakDetectioninaSessionOrientedFunctionalLanguage.In:Beyer,D.,Boreale,M.(eds.)FMOODS/FORTE2013. LNCS,vol.7892,pp.83–98.Springer,Heidelberg(2013)

3.Carbone,M.,Dardha,O.,Montesi,F.:Progressascompositionallock-freedom.In:K¨uhn, E.,Pugliese,R.(eds.)COORDINATION2014.LNCS,vol.8459,pp.49–64.Springer,Heidelberg(2014)

4.Courcelle,B.:Fundamentalpropertiesofinfinitetrees.Theor.Comp.Sci.25,95–169(1983)

5.Dardha,O.,Giachino,E.,Sangiorgi,D.:Sessiontypesrevisited.In:PPDP2012,pp.139–150.ACM(2012)

6.Gay,S.J.,Vasconcelos,V.T.:Lineartypetheoryforasynchronoussessiontypes.J.Funct. Program.20(1),19–50(2010)

7.Kobayashi,N.:Atypesystemforlock-freeprocesses.Inf.andComp.177(2),122–159 (2002)

8.Kobayashi,N.:Anewtypesystemfordeadlock-freeprocesses.In:Baier,C.,Hermanns,H. (eds.)CONCUR2006.LNCS,vol.4137,pp.233–247.Springer,Heidelberg(2006)

9.Kobayashi,N.,Pierce,B.C.,Turner,D.N.:Linearityandthepi-calculus.ACMTrans.Program.Lang.Syst.21(5),914–947(1999)

10.Padovani,L.:DeadlockandLockFreedomintheLinear π-Calculus.In:CSL-LICS2014, pp.72:1–72:10.ACM(2014), http://hal.archives- ouvertes.fr/hal-00932356v2/

11.Padovani,L.:TypeReconstructionfortheLinear π-CalculuswithCompositeandEquiRecursiveTypes.In:Muscholl,A.(ed.)FOSSACS2014.LNCS,vol.8412,pp.88–102. Springer,Heidelberg(2014)

12.Padovani,L.,Chen,T.-C.,Tosatto,A.:TypeReconstructionAlgorithmsforDeadlock-Free andLock-FreeLinear π-Calculi.In:Holvoet,T.,Viroli,M.(eds.)COORDINATION2015. LNCS,vol.9037,pp.85–100.Springer,Heidelberg(2015)

13.Padovani,L.,Novara,L.:TypesforDeadlock-FreeHigher-OrderConcurrentPrograms. Technicalreport,Universit`adiTorino(2014), http://hal.inria.fr/hal-00954364

14.Wadler,P.:Propositionsassessions.In:ICFP2012,pp.273–286.ACM(2012)

Another random document with no related content on Scribd:

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.