arxiv.org · zu064-05-fpr main 15 september 2018 13:52 2 igarashi et al. crosoft’s typescript and...

48
ZU064-05-FPR main 15 September 2018 13:52 Under consideration for publication in J. Functional Programming 1 Gradual Session Types ATSUSHI IGARASHI Kyoto University, Japan PETER THIEMANN University of Freiburg, Germany YUYA TSUDA Kyoto University, Japan VASCO T. VASCONCELOS LaSIGE, Faculty of Sciences, University of Lisbon, Portugal PHILIP WADLER University of Edinburgh, Scotland (e-mail: [email protected], [email protected], [email protected], [email protected], [email protected]) Abstract Session types are a rich type discipline, based on linear types, that lifts the sort of safety claims that come with type systems to communications. However, web-based applications and microservices are often written in a mix of languages, with type disciplines in a spectrum between static and dynamic typing. Gradual session types address this mixed setting by providing a framework which grants seamless transition between statically typed handling of sessions and any required degree of dynamic typing. We propose Gradual GV as a gradually typed extension of the functional session type system GV. Following a standard framework of gradual typing, Gradual GV consists of an external language, which relaxes the type system of GV using dynamic types, and an internal language with casts, for which operational semantics is given, and a cast-insertion translation from the former to the latter. We demonstrate type and communication safety as well as blame safety, thus extending previous results to functional languages with session-based communication. The interplay of linearity and dynamic types requires a novel approach to specifying the dynamics of the language. 1 Introduction It was the best of types, it was the worst of types. Type systems are retreating from areas they used to dominate, with statically-typed lan- guages such as Java seen as old hat while dynamically-typed languages such as Javascript, Python, and R are on the rise. Simultaneously, type systems are expanding into new do- mains, such as dependent types in Agda, Coq, and Idris, effect types in Eff, Frank, and Koka, and session types in Links, Scribble, and Singularity OS. Gradually-typed languages reconcile these two trends. They permit one to assemble programs with some components written in a statically-typed language and some in a dynamically-typed language. Gradually-typed languages have been widely explored in both theory and practice, beginning with contracts in Racket and continuing with Mi-

Upload: others

Post on 18-Oct-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

  • ZU064-05-FPR main 15 September 2018 13:52

    Under consideration for publication in J. Functional Programming 1

    Gradual Session Types

    ATSUSHI IGARASHIKyoto University, JapanPETER THIEMANN

    University of Freiburg, GermanyYUYA TSUDA

    Kyoto University, JapanVASCO T. VASCONCELOS

    LaSIGE, Faculty of Sciences, University of Lisbon, PortugalPHILIP WADLER

    University of Edinburgh, Scotland(e-mail: [email protected], [email protected],

    [email protected], [email protected], [email protected])

    Abstract

    Session types are a rich type discipline, based on linear types, that lifts the sort of safety claims thatcome with type systems to communications. However, web-based applications and microservices areoften written in a mix of languages, with type disciplines in a spectrum between static and dynamictyping. Gradual session types address this mixed setting by providing a framework which grantsseamless transition between statically typed handling of sessions and any required degree of dynamictyping.

    We propose Gradual GV as a gradually typed extension of the functional session type system GV.Following a standard framework of gradual typing, Gradual GV consists of an external language,which relaxes the type system of GV using dynamic types, and an internal language with casts, forwhich operational semantics is given, and a cast-insertion translation from the former to the latter. Wedemonstrate type and communication safety as well as blame safety, thus extending previous resultsto functional languages with session-based communication. The interplay of linearity and dynamictypes requires a novel approach to specifying the dynamics of the language.

    1 Introduction

    It was the best of types, it was the worst of types.Type systems are retreating from areas they used to dominate, with statically-typed lan-

    guages such as Java seen as old hat while dynamically-typed languages such as Javascript,Python, and R are on the rise. Simultaneously, type systems are expanding into new do-mains, such as dependent types in Agda, Coq, and Idris, effect types in Eff, Frank, andKoka, and session types in Links, Scribble, and Singularity OS.

    Gradually-typed languages reconcile these two trends. They permit one to assembleprograms with some components written in a statically-typed language and some in adynamically-typed language. Gradually-typed languages have been widely explored inboth theory and practice, beginning with contracts in Racket and continuing with Mi-

  • ZU064-05-FPR main 15 September 2018 13:52

    2 Igarashi et al.

    crosoft’s TypeScript and Facebook’s Hack and Flow. Many systems, such as Racket andTypeScript TPD, rely on contracts or similar constructs to ensure that dynamically-typedvalues adhere to statically-typed constraints when values pass from one world to the other.

    At first blush, one might consider gradual types as largely a response to the former trend:they provide a way for developers using dynamically-typed languages to evolve their codetoward statically-typed languages that are easier to maintain. But on second thought, onemight consider gradual types as even more helpful in light of the latter trend. When it comesto dependent types, effect types, or session types the fraction of programmers working inlanguages that offer static checking for such types is essentially zero. In this sense, all ofus can benefit from a way to evolve toward languages with more precise type systems.

    In consequence, an important line of research is to extend gradual typing so that itnot only relates statically-typed and dynamically-typed languages, but also relates less-precisely-typed and more-precisely-typed languages. There is a small body of research ondoing so for dependent types and effect types, which we review in the section on relatedwork. This paper presents the first system that extends gradual typing to session types.

    Session types were introduced by Honda (1993), drawing on Milner’s π-calculus (Mil-ner et al., 1992) and Girard’s linear logic (Girard, 1987), and further developed by manyothers (Honda et al., 1998; Yoshida & Vasconcelos, 2007). Gay and Hole (2005) introducedsubtyping for session types, and session types were embedded into a functional languagewith linear types, similar to the one used in this paper, by Gay and Vasconcelos (2010).Caires, Pfenning, Toninho, and Wadler introduced propositions-as-types interpretations ofsession types in linear logic (Caires & Pfenning, 2010; Caires et al., 2014; Wadler, 2012;Wadler, 2014). One important line of research is multiparty session types (Honda et al.,2008; Honda et al., 2016) but we confine our attention here to dyadic session types.

    Session types have been adapted to a variety of languages, either statically or dynam-ically checked, and using either libraries or additions to the toolchain; implementationsinclude C, Erlang, Go, Haskell, Java, Python, Rust, and Scala. New languages incorporat-ing session types include C0, Links, SePi, SILL, and Singularity. Industrial uses of sessiontypes include: Red Hat’s support of the Scribble specification language, which has beenused as a common interface for several systems based on session types; Thoughtworks’suse of session types to manage microservices; and the Ocean Observatories Initiative’s useof dynamically-checked session types in Python. Session types inspired an entire line ofresearch on what has come to be called behavioural types, the subject of EU COST actionBETTY, a recent Shonan meeting, and a recent Dagstuhl seminar.

    Here is a simple session type encoding of a protocol to purchase an online video:

    Svideo = !string.?int. ⊕{buy : !CC.?URL.end?,quit : end!}.

    It describes a channel endpoint along which a client sends the name of a video as a string,receives its cost as an integer, and then selects either to buy the video, in which case onesends a credit card number, receives a URL from which the video may be downloaded,and waits for an indication that the channel has been closed, or selects to quit and closesthe channel. There is a dual session type for server at the other end of the channel, where! (write) is swapped with ? (read), ⊕ (select from a choice) is swapped with & (offer achoice), and end! (close a channel) is swapped with end? (wait for a channel to close).

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 3

    Session types are necessarily linear. Let x be bound to a string and let c be bound to achannel endpoint of type Svideo. Performing

    let d = sendxc in . . .

    binds d to a channel endpoint of type R, where Svideo = !string.R. To avoid sending a stringto the same channel twice, it is essential that c must be bound to the only reference tothe channel endpoint before the operation, and for similar reasons d must be bound to theonly reference to the channel endpoint after. Such restrictions can easily be enforced in astatically-typed language with an affine type discipline. Linearity is required to guaranteethat channels are not abandoned before they are closed.

    But how is one to ensure linearity in a dynamically-typed language? Following (Tov &Pucella, 2010), we require that each dynamically-typed reference to a channel endpoint isequipped with a lock, and after the channel is used once the reference is locked to ensure itcannot be used again. To ensure that each channel is appropriately terminated, with either await or a close operation, garbage collection flags an error if a dynamically-typed referenceto a channel becomes inaccessible.

    Our system is the first to integrate static and dynamic session types. It preserves thesafety properties of statically-typed sessions, namely progress, preservation, and absenceof run-time errors. The latter includes session fidelity: every send is matched with a receive,every select is matched with an offer, and every wait is matched with close. Many, butnot all, systems with session types support recursive session types, and many, but notall, systems with session types ensure deadlock freedom; we leave such developments forfuture work.

    We give our system a compact formulation along the lines of the blame calculus (Wadler& Findler, 2009), based on the notion of a cast to mediate interactions between more-precisely typed (e.g., statically typed) and less-precisely typed (e.g., dynamically typed)components of a program. We define the usual four subtyping relations, ordinary, positive,negative, and naive, and show the usual results, including a tangram theorem relating thefour forms of subtyping and blame safety. A corollary of our results is that in any interac-tion between more-precisely typed and less-precisely typed components of a program, anycast error is due to the less-precisely typed component.

    Our paper makes the following contributions.

    • Section 2 provides an overview of the novel techniques in our work, and how wedynamically enforce linearity and session types.

    • Section 3 describes a complete formal calculus, including syntax, reduction rules,typing rules of both external and internal languages, cast-insertion translation fromthe external to the internal language, and embedding of a dynamically typed lan-guage with channel-based communication into our calculus.

    • Section 4 presents standard results for our calculus, including progress and preser-vation, session fidelity, the tangram theorem, blame safety, conservativity of theexternal language typing over the GV typing, and type preservation of the castinsertion translation.

    Section 5 describes related work and Section 6 concludes.

  • ZU064-05-FPR main 15 September 2018 13:52

    4 Igarashi et al.

    Compared to the previous paper (Igarashi et al., 2017), we extend the development withthe external language, the cast-insertion translation, a type checker, and proofs of theirproperties as well as more detailed proofs for the earlier results. These extensions makegradual session types accessible for the programmer, who works in the external language.

    2 Motivation

    Sy and Rob are programmers, who work together on a project that relies on microservices.Sy is a strong advocate of static typing and relies on an implementation language thatsupports session types out of the box. Rob, on the other hand, is a strong advocate ofdynamically typed languages. One of the credos of microservices architectures is thatthe implementation of a service endpoint is language-agnostic, which means it can beimplemented in any programming language whatsoever as long as it adheres to its protocol.However, Sy does not want to compromise the strong guarantees (e.g., type safety, sessionfidelity) of the statically typed code by communicating with Rob’s client. Rob is also keenon having strong guarantees, but does not mind if they are enforced at run time. Here isthe story how they can collaborate safely using Gradual GV, our proposal for a graduallytyped functional language with synchronous binary session types.

    2.1 A Compute Service

    The compute service is one of the “hello world” programs of the session-type communityand it is a simplified version of one of the protocols in Sy and Rob’s project. This serviceinvolves two peers, a server and a client, connected via a communication link. The serverruns a protocol that first offers a choice of two arithmetic operations, negation or addition,then reads one or two numbers depending on the operation, outputs the result of apply-ing the selected operation to its operand(s), and finally closes the connection. The clientchooses an operation by sending the server a label, which is either neg or add indicatingthe choice of negation or addition, respectively. In session-type notation, the server’s viewof the compute protocol reads as follows.

    Compute = &{neg : ?int.!int.end!,add : ?int.?int.!int.end!}

    Sy chooses to implement the server in the language GV that is inspired by previous work(Gay & Vasconcelos, 2010) and that we will describe formally in Section 3.

    computeServer : Compute → un i tcomputeServer c =

    case c o f {neg : c . l e t v1 , c = r e c e i v e c i n

    l e t c = send (−v1 ) c i nc l o s e c ;

    add : c . l e t v1 , c = r e c e i v e c i nl e t v2 , c = r e c e i v e c i nl e t c = send ( v1+v2 ) c i nc l o s e c

    }

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 5

    The parameter c of type Compute is the server’s endpoint of the communication link tothe client (when unambiguous, we often just say endpoint or channel). The case c of ...expression receives the client’s choice on channel c in the form of a label neg or add andbranches accordingly. The notation “c. ” in each branch (re-)binds the variable c to thechannel in the state after the transmission has happened. The type of c is updated to thesession type corresponding to the respective branch in the Compute type. The receive coperation receives a value on channel c and returns a pair of the received value and thedepleted channel with a correspondingly depleted session type. Analogously, the send v coperation sends value v on channel c and returns the depleted channel. The final close cdisconnects the communication link by closing the channel.

    2.2 The View from the Client Side

    A client of the Compute protocol communicates on a channel with the protocol ComputeDdefined below. This protocol is the dual of Compute which (roughly) swaps all sending andreceiving operations.

    ComputeD =⊕{neg : !int.?int.end?,add : !int.!int.?int.end?}

    Clients of the compute service may always select the same operation and then proceedlinearly according the corresponding branch. Such clients can use a simpler supertypeof ComputeD with a unary internal choice. For example, a client that only ever asks fornegation can implement ComputeDneg.

    ComputeDneg =⊕{neg : !int.?int.end?}

    Here is Sy’s implementation of a typed client for ComputeDneg.

    n e g a t i o nC l i e n t : i n t → ComputeDneg → i n tn e g a t i o nC l i e n t v c =

    l e t c = s e l e c t neg c i nl e t c = send v c i nl e t y , c = r e c e i v e c i nl e t _ = wai t c i ny

    There are two new operations in the client code. The select neg c operation selects the negbranch in the protocol by sending the neg label to the server. It returns a channel to run theselected branch of the protocol with type !int.?int.end?. The wait c operation matches theclose operation on the server and disconnects the client.

    2.3 A Unityped Server

    To test some new features, Rob also implements the Compute protocol, but does so in theunityped language Uni GV, which is strongly typed like Racket or Python but does notimpose a static typing discipline. Here is Rob’s implementation of the server.

    −− un i t yp eddynSe r v e r c =

    case c o f {

  • ZU064-05-FPR main 15 September 2018 13:52

    6 Igarashi et al.

    neg : c . serveOp 1 (λ x .−x ) c ;add : c . serveOp 2 (λ x .λ y . x+y ) c

    }

    serveOp n op c =i f n==0 then

    c l o s e ( send op c )e l s e

    l e t v , c = r e c e i v e c i nserveOp (n−1) ( op v ) c

    The main function dynServer takes a channel c on which it receives the client’s selection.It delegates to an auxiliary function serveOp that takes the arity of a function, the functionitself, and the channel end on which to receive the arguments and to send the result. TheserveOp function counts down the number of remaining function applications in the first ar-gument, accumulates partial function applications in the second argument, and propagatesthe channel end in the third argument.

    It is easy to see that the dynServer function implements the Compute protocol. Robchose this style of implementation because it is amenable to experimentation with protocolextensions: the function dynServer is trivially extensible to new operations and types byadding new lines to the case dispatch.

    2.4 The Gradual Way

    How can we embed Rob’s server with other program fragments in the typed language (e.g.,Sy’s client) while retaining as many typing guarantees as possible?

    One answer would be to use a dependently typed system that can describe the type ofthe serveOp function adequately. In an extension of a recently proposed system (Toninho& Yoshida, 2018) with iteration on natural numbers and large elimination, we might writethat code as follows.

    Op : nat → TypeOp 0 = i n tOp (n+1) = i n t → Op n

    Ch : nat → Se s s i o nCh 0 = ! i n t . end!Ch (n+1) = ? i n t . Ch n

    serveOpDep : ( n : nat ) ( op : Op n ) ( c : Ch n ) → un i tserveOpDep 0 op c = c l o s e ( send op c )serveOpDep ( n+1) op c = l e t v , c = r e c e i v e c i n

    serveOpDep n ( op v ) c

    However, we are not aware of a fully developed theory of a session-type system that wouldbe able to process this definition.

    An alternative that is immediately available is to resort to gradual typing. For this par-ticular program it will insert casts to make the program type check, but all those castsare semantically guaranteed to succeed because it would have a dependent type. To thisend, we rewrite the function dynServer in a gradually type external language analogous to

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 7

    the gradually typed lambda calculus GTLC (Siek et al., 2015b), but extended with GV’scommunication operations.

    In our example, the rewrite to the external language boils down to providing suitabletype signatures for dynServer and serveOp:

    dynSe r v e r : Compute → un i tserveOp : i n t → ? → ?© → un i t

    The first argument n of dynServe is consistently handled as an integer, so its type is int . Thesecond argument op is invoked with values of type int → int → int , int → int , and int :these types are subsumed to the dynamic type ?. Similarly to other gradual type systems,an expression of type ? can be used in any context, e.g., addition, function application, oreven communication, and any value can be passed where ? is expected. The third argumentc is invoked with channels of different types: ? int .? int .! int .end!, ? int .! int .end!, and ! int.end!. These types are subsumed to a type that is novel to this work, the dynamic sessiontype, ?©, a linear type which subsumes all session types. It is important to see that thechannel c is handled linearly in functions dynServer and serveOp. For that reason, the roleand handling of the linear dynamic session type with respect to the set of session types isanalogous to the role and handling of ? with respect to general types, as shown in earlierwork (Fennell & Thiemann, 2012; Thiemann, 2014). Aside from the type annotation, thecode remains exactly the same as in the unityped case.

    The external language comes with a translation into a blame calculus with explicit casts.This translation inserts just the casts that are necessary to make typing of the code gothrough. Here is the output of this translation (suffix Cast is appended to the names of thefunctions to distinguish different versions):

    dynSe r v e rCa s t : Compute → un i tdynSe r v e rCa s t c =

    case c o f {neg : c . se rveOpCast 1 ( (λ x .−x ) : i n t → i n t ⇒ ? )

    ( c : ? i n t . ! i n t . end! ⇒ ?©) ;add : c . se rveOpCast 2 ( (λ x .λ y . x+y ) : i n t → i n t → i n t ⇒ ? )

    ( c : ? i n t . ? i n t . ! i n t . end! ⇒ ?©)}

    se rveOpCast : i n t → ? → ?© → un i tse rveOpCast n op c =

    i f n==0 thenc l o s e ( send op ( c : ?© ⇒ ! ? . end! ) )

    e l s el e t v , c = r e c e i v e ( c : ?© ⇒ ?? . ?©) i nse rveOpCast (n−1) ( ( op : ? ⇒ ? → ? ) v ) c

    Casts are inserted where values are converted from/to ? or ?©, similarly to the translationfrom GTLC. The resulting casts in dynServerCast and serveOpCast look fairly involved, butwe should keep in mind that the programmer does not have to write them as they resultfrom the translation.

  • ZU064-05-FPR main 15 September 2018 13:52

    8 Igarashi et al.

    2.5 Dynamic Linearity

    The refined criteria for gradual typing (Siek et al., 2015b) postulate that a gradual typesystem should come with a full embedding of a unityped calculus. This embedding (whichwe indicate by ceiling brackets d. . .e) extends the embedding given for the simply-typedlambda calculus (Wadler & Findler, 2009) to handle the operations on sessions (see Fig-ure 14 for its definition).

    For example, (the unityped version of) the dynServer as written by Rob is compiled andembedded into the gradually typed language as a value dynServer : ?. To directly incorpo-rate Rob’s code, the gradual type checker enables Sy to write a function callDynServer thataccepts a channel of type Compute and returns a value of type unit, but internally just callsdynServer.

    c a l lD y nS e r v e r : Compute → un i tc a l lD y nS e r v e r c =

    dynSe rve r c

    The gradual type checker translates the definition of callDynServer by inserting the appro-priate casts: it casts the embedded dynServer (of type ?) to the function type ? → ?, it caststhe channel argument to this function to ?, and it casts the result to unit.

    c a l lD y nS e r v e r : Compute → un i tc a l lD y nS e r v e r c =

    ( dynSe r v e r : ? ⇒ ? → ? ) ( c : Compute ⇒ ? ) : ? ⇒ un i t

    The casts inserted in this code make Sy’s expectations completely obvious: dynServer mustbe a function and it is expected to use c as a channel of type Compute. Any misuse willallocate blame to the respective cast in dynServer. (We omit blame labels in the examplesfor simplicity.)

    One kind of misuse that we have not discussed, yet, is compromising linearity: Sy hasno guarantee that Rob’s code does not accidentally duplicate or drop the communicationchannel. Both actions can lead to protocol violations, which should be detected at runtime. Gradual GV takes care of linearity by factoring the cast (c : Compute ⇒?) throughthe dynamic session type ?©:

    ( ( c : Compute ⇒ ?©) : ?© ⇒ ? )

    The first part is a cast among linear (session) types and it can be handled as outlined inSection 2.4. The second part is a cast from a linear type (which could be a session type, alinear function type, or a linear product) to the unrestricted dynamic type ?.

    A cast from a linear type to unrestricted ? is a novelty of Gradual GV. Operationally,the cast introduces an indirection through a store: it takes a linear value as an argument,allocates a new cell in the store, moves the linear value along with a representation ofits type into the cell, and returns a handle a to the cell as an unrestricted value of type?. Gradual GV represents the cell by a process and creates handles by introducing anappropriate binder so that a process of the form E[v : ?©⇒ ?] reduces to (νa 7→ v : ?©⇒?)E[a]. Linear use of this cell is controlled at run time using ideas for run-time monitoringof affine types (Tov & Pucella, 2010; Padovani, 2017).

    Any access to a cell comes in the guise of a cast a : ?⇒ T from ? to another type appliedto a handle a. If the first access to the cell is a cast from ? to a linear type consistent with the

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 9

    type representation stored in the cell, then the cast returns the linear value and empties thecell. Any subsequent access to the same cell results in a linearity violation which allocatesblame to the label on the cast from ?. If the first cast attempts to convert to an inconsistenttype, then blame is allocated to that cast. In addition, there is a garbage collection rule thatfires when the handle of a full cell is no longer reachable from any process. It allocatesblame to the context of the cast to ? because that cast violated the linearity protocol bydismissing the handle.

    2.6 End-to-end Dynamicity

    The examples so far tacitly assume that channels are created with a fully specified sessiontype that provides a “ground truth” for the protocol on this channel. Later on, channels maybe cast to ?© and on to ?, but essentially they adhere to the ground truth established at theircreation.

    Unfortunately, this view cannot be upheld in a calculus that is able to embed a unitypedlanguage like Uni GV. When writing new in a unityped program to create a channel, Rob(hopefully) has some session type in mind, but it is not manifest in the code.

    In the typed setting, new returns a linear pair of session endpoints of type S×lin S whereS is the server session type and S its dual client counterpart (cf. the Compute and ComputeDtypes in Sections 2.1 and 2.2). When embedding the unityped new, the session type S isunknown. Hence, the embedding needs to create a channel without an inherent groundtruth session type. It does so by assigning both channel ends type ?© and casting it to ?as in new : ?©×lin ?©⇒ ?. To make this work, the dynamic session type ?© is consideredself-dual, that is ?©= ?©. Gradual GV offers no static guarantees for either end of such achannel.

    To see what run-time guarantees Gradual GV can offer for a channel of unknown sessiontype, let’s consider the embedding of the dynamic send and receive operations that may beapplied to it. The embedded send operation takes two arguments of type ?, for the valueand the channel, and returns the updated channel wrapped in type ?. The embedded receiveoperation takes a wrapped channel of type ? and returns a (?-wrapped) pair of the receivedvalue and the updated channel.

    dsende f e = (senddee(d f e : ? p⇒ !?. ?©)) : ?©⇒ ?dreceiveee = (receive(dee : ? q⇒ ??. ?©)) : ?×lin ?©⇒ ?

    Now consider running the following unityped program with entry point main.

    1 c l i e n t cc =2 l e t v , cc = r e c e i v e cc i n wa i t cc3 s e r v e r c s =4 l e t c s = send 42 cs i n c l o s e c s5 main =6 l e t cs , cc = new i n7 l e t _ = f o r k ( c l i e n t cc ) i n8 s e r v e r c s

  • ZU064-05-FPR main 15 September 2018 13:52

    10 Igarashi et al.

    After a few computation steps, it reaches a configuration where the client and the serverhave reduced to (νcs, cs)( client | server ) where

    client = 〈E[(receive(cc : ?© q⇒ ??. ?©)) : ?×lin ?©⇒ ?]〉

    server = 〈F [(send(42 : int⇒ ?)(cs : ?© p⇒ !?. ?©)) : ?©⇒ ?]〉

    for some contexts E and F . The channel ends cc : ?© and cs : ?© are the two ends of thechannel created in line 6. Fortunately, the two processes use the channel consistently as thecast target ??. ?© on one end is dual to the cast target !?. ?© at the other end. Hence, GradualGV has a reduction that drops the casts at both ends in this situation, and retypes the endsto cc : ??. ?© and cs : !?. ?©, respectively.

    〈E[(receivecc) : ?×lin ?©⇒ ?]〉 | 〈F [(send(42 : int⇒ ?)cs) : ?©⇒ ?]〉

    Implementing this reduction requires communication between the two processes to checkthe cast targets for consistency. While our formal presentation abstracts over this imple-mentation issue, we observe that a single asynchronous message exchange is sufficient:Each cast first sends its target type and then receives the target type of the cast at the otherend. Then both processes check locally whether the target types are duals of one another.If they are, then both processes continue; otherwise they allocate blame. As both endsperform the same comparison, the outcome is the same in both processes.

    3 GV and Gradual GV

    3.1 GV

    We begin by discussing a language GV with session types but without gradual types. GVis inspired by both the Gay and Vasconcelos’ functional session type calculus (Gay &Vasconcelos, 2010) and Wadler’s ‘good variant’ of the language (Wadler, 2012; Wadler,2014). Unlike the latter, we do not guarantee deadlock freedom.

    3.1.1 Types and subtyping

    Figure 1 summarises types of GV. Let m,n range over multiplicities for types whose use iseither unrestricted, un, or must be linear, lin.

    Let T,U range over types, which include: unit type, unit; unrestricted and linear functiontypes, T →m U ; unrestricted and linear product types, T ×m U ; and session types. Onemight also wish to include booleans or base types, but we omit these as they can be dealtwith analogously to unit.

    Let l range over labels used for selection and case choices. Let S,R range over sessiontypes that describe communication protocols for channel endpoints, which include: send!T.S, to send a value of type T and then behave as S; receive ?T.S, to receive a value oftype T and then behave as S, select⊕{li : Si}i∈I , to send one of the labels li and then behaveas Si; case &{li : Si}i∈I to receive any of the labels li and then behave as Si; close end!, toclose a channel endpoint; and wait end?, to wait for the other end of the channel to close.In ⊕{li : Si}i∈I and &{li : Si}i∈I , the label set must be non-empty. We will call the sessiontype that describes the behaviour after send, receive, select, or case the residual.

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 11

    Multiplicities m,n ::= lin | unTypes T,U ::= unit | S | T →m U | T ×m USession types S,R ::= !T.S | ?T.S | ⊕{li : Si}i∈I | &{li : Si}i∈I | end! | end?

    Duality S = R

    !T.S = ?T.S ⊕{li : Si}i∈I = &{li : Si}i∈I end! = end??T.S = !T.S &{li : Si}i∈I =⊕{li : Si}i∈I end? = end!

    Multiplicity ordering m

  • ZU064-05-FPR main 15 September 2018 13:52

    12 Igarashi et al.

    Names z ::= x | cExpressions e, f ::= z | () | λmx.e | e f | (e, f )m | letx,y = e in f | forke

    |new | sende f | receivee | select l e | caseeof {li : xi.ei}i∈I| closee | waite

    Processes P,Q ::= 〈e〉 | (P | Q) | (νc,d)PType environments Γ,∆ ::= · | Γ,z : T

    Environment splitting Γ = Γ1 ◦Γ2

    ·= · ◦ · Γ = Γ1 ◦Γ2 un(T )Γ,z : T = (Γ1,z : T )◦ (Γ2,z : T )

    Γ = Γ1 ◦Γ2 lin(T )Γ,z : T = (Γ1,z : T )◦Γ2

    Γ = Γ1 ◦Γ2 lin(T )Γ,z : T = Γ1 ◦ (Γ2,z : T )

    Typing expressions Γ ` e : T

    un(Γ)Γ,z : T ` z : T

    un(Γ)Γ ` () : unit

    Γ,x : T ` e : U m:>(Γ)Γ ` λmx.e : T →m U

    Γ ` e : T →m U ∆ ` f : TΓ◦∆ ` e f : U

    Γ ` e : T ∆ ` f : U m:>(T ) m:>(U)Γ◦∆ ` (e, f )m : T ×m U

    Γ ` e : T1×m T2 ∆,x : T1,y : T2 ` f : UΓ◦∆ ` letx,y = e in f : U

    Γ ` e : unitΓ ` forke : unit

    un(Γ)Γ ` new : S×lin S

    Γ ` e : T ∆ ` f : !T.SΓ◦∆ ` sende f : S

    Γ ` e : ?T.SΓ ` receivee : T ×lin S

    Γ ` e :⊕{li : Si}i∈I j ∈ IΓ ` select l j e : S j

    Γ ` e : &{li : Si}i∈I (∆,xi : Si ` ei : T )i∈IΓ◦∆ ` caseeof {li : xi.ei}i∈I : T

    Γ ` e : end!Γ ` closee : unit

    Γ ` e : end?Γ ` waite : unit

    Γ ` e : T T

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 13

    Values v,w ::= () | λmx.e | (v,w)m | cEval contexts E,F ::= [] | E e | vE | (E,e)m | (v,E)m | letx,y = E ine | sendE e | sendvE

    | receiveE | select l E | caseE of {li : xi.ei}i∈I | closeE | waitE

    Expression reduction e−→ f

    (λmx.e)v−→ e[v/x]letx,y = (v,w)m ine−→ e[v/x][w/y]

    Structural congruence P≡ Q

    P | Q≡ Q | P P | (Q | P′)≡ (P | Q) | P′ P | 〈()〉 ≡ P((νc,d)P) | Q≡ (νc,d)(P | Q) (νc,d)P≡ (νd,c)P (νc,d)(νc′,d′)P≡ (νc′,d′)(νc,d)P

    Process reduction P−→ Q

    〈E[forke]〉 −→ 〈E[()]〉 | 〈e〉〈E[new]〉 −→ (νc,d)〈E[(c,d)lin]〉

    (νc,d)(〈E[sendvc]〉 | 〈F [received]〉)−→ (νc,d)(〈E[c]〉 | 〈F [(v,d)lin]〉)(νc,d)(〈E[select l j c]〉 | 〈F [cased of {li : xi.ei}i∈I ]〉)−→ (νc,d)(〈E[c]〉 | 〈F [e j[d/x j]]〉) if j ∈ I

    (νc,d)(〈E[closec]〉 | 〈F [waitd]〉)−→ 〈E[()]〉 | 〈F [()]〉

    P−→ P′

    P | Q−→ P′ | QP−→ Q

    (νc,d)P−→ (νc,d)QP′ ≡ P P−→ Q Q≡ Q′

    P′ −→ Q′e−→ f

    〈E[e]〉 −→ 〈E[ f ]〉Fig. 3. Reduction in GV.

    expressions of the form (λlinx.e) f to letx = e in f , as usual. A GV program is always givenas an expression, but as it executes it may fork new processes.

    We let P,Q range over processes, which include expressions, parallel composition, anda binder that introduces a pair of channel endpoints. The initial process will consist of asingle expression, corresponding to a given GV program.

    The bindings in the language are as follows: variable x is bound in subexpression e ofλmx.e, variables x,y are bound in subexpression f of letx,y = e in f , variables xi are arebound in subexpressions ei of caseeof {li : xi.ei}i∈I , channel endpoints c,d are bound insubprocess P of (νc,d)P. The notions of free and bound variables as well that substitutionare defined accordingly. We follow Barendregt’s variable convention, whereby all namesin binding occurrences in any mathematical context are pairwise distinct and distinct fromthe free names (Barendregt, 1984).

    We let Γ,∆ range over environments, which are used for typing. An environment consistsof zero or more associations of names with types. Environment splitting Γ = Γ1 ◦Γ2 isstandard. It breaks an environment Γ for an expression or process into environments Γ1and Γ2 for its components; a name of unrestricted type may be used in both environments,while a name of linear type must be used in one environment or the other but not both. Wewrite m(Γ) if m(T ) holds for each T in Γ, and similarly for m:>(Γ).

  • ZU064-05-FPR main 15 September 2018 13:52

    14 Igarashi et al.

    Write Γ ` e : T if under environment Γ expression e has type T . The typing rules forexpressions are standard. In the rules for names, unit, and new the remaining environmentmust be unrestricted, to enforce the invariant that linear variables are used exactly once. Afunction abstraction that is unrestricted must have only unrestricted variables bound in itsclosure, and a pair that is unrestricted may only contain components that are unrestricted.The rules for send, receive, select, case, close, and wait match the corresponding sessiontypes. The typing system supports subsumption: if e has type T and T is a subtype of Uthen e also has type U .

    Write Γ ` P if under environment Γ process P is well typed. The typing rules forprocesses are also standard. If expression e has unrestricted type T then process 〈e〉 is well-typed. If processes P and Q are well-typed, then so is process P |Q, where the environmentof the latter can be split to yield the environments for the former. And if process P is well-typed under an environment that includes channel endpoints c and d with session types Sand S, then process (νc,d)P is well-typed under the same environment without c and d.

    3.1.3 Reduction

    Values, evaluation contexts, reduction for expressions, structural congruence, and reduc-tion for processes for Gradual GV are summarised in Figure 3.

    Let v,w range over values, which include unit, function abstractions, pairs of values, andchannel endpoints. Let E,F range over evaluation contexts, which are standard.

    Write e −→ f to indicate that expression e reduces to expression f . Reduction is stan-dard, consisting of beta reduction for functions and pairs.

    Write P ≡ Q for structural congruence of processes. It is standard, with compositionbeing commutative and associative. A process returning the unit is the identity of parallelcomposition, so P | 〈()〉 ≡ P. The order in which the endpoints are written in a ν-binderis irrelevant. Distinct prefixes commute, and satisfy scope extrusion. The Barendregt con-vention ensures that c,d are not free in Q in the rule for scope extrusion.

    Write P −→ Q if process P reduces to process Q. Evaluating forke returns () andcreates a new process 〈e〉. Evaluating new introduces a new binder (νc,d) and returnsa the pair (c,d)lin of channel endpoints. Evaluating sendvc on one endpoint of a channeland received on the other, causes the send to return c and the receive to return (v,d)lin.Similarly for select on one endpoint of a channel and case on the other, or close on oneendpoint of a channel and wait on the other.

    Process reduction is a congruence with regard to parallel composition and binding forchannel endpoints, it is closed under structural congruence, and supports expression reduc-tion under evaluation contexts.

    3.2 Gradual GV

    We now introduce Gradual GV. Following standard frameworks of gradual typing (Siek& Taha, 2006; Siek et al., 2015b), Gradual GV consists of two sublanguages: an externallanguage GGVe, in which source programs are written, and an internal language GGVi,to which GGVe is elaborated by cast-inserting translation to make necessary run-timechecks explicit. The operational semantics of a program is given as reduction of processes

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 15

    Types T,U ::= unit | S | T →m U | T ×m U | ?Session types S,R ::= !T.S | ?T.S | ⊕{li : Si}i∈I | &{li : Si}i∈I | end! | end? | ?©Ground types T,U ::= unit | ?© | ?→m ? | ?×m ?Ground session types S,R ::= !?. ?© | ??. ?© | ⊕{li : ?©}i∈I | &{li : ?©}i∈I | end! | end?

    Duality S = R

    ?©= ?©

    Multiplicity of a type m(T )

    un(?) lin( ?©)Subtyping T

  • ZU064-05-FPR main 15 September 2018 13:52

    16 Igarashi et al.

    Blame labels p,q

    Names z ::= · · · | a

    Expressions e, f ::= · · · | e : T p⇒U

    Store contents ω ::= w : T p⇒ ? | locked pProcesses P,Q ::= · · · | (νa 7→ ω)P | blame p q X | blame p X

    Typing expressions Γ ` e : T

    Γ ` e : T T .UΓ ` (e : T p⇒U) : U

    Typing processes Γ ` P

    Γ ` w : T lin(T) ∆,a : ? ` PΓ◦∆ ` (νa 7→ w : T p⇒ ?)P

    Γ,a : ? ` PΓ ` (νa 7→ locked p)P

    flv(Γ) = XΓ ` blame p q X

    flv(Γ) = XΓ ` blame p X

    Fig. 5. Expressions, processes, and typing in GGVi.

    we will need to take special care when handling values of type ? that correspond to valuesof a linear type. Subtyping is extended trivially by adding reflexivity rules for ? and ?©.

    Consistent subtyping is defined over types of Gradual GV also in Figure 4. It is identicalto the definition of subtyping from Figure 1, with each occurrence of

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 17

    3.2.2 Expressions, processes, and typing of GGVi

    Expressions, processes, and type rules of GGVi are summarised in Figure 5. The expres-sions of GGVi are those of GV, plus an additional form for casts. A cast is written

    e : Tp⇒U (1)

    where e is an expression of type T and p,q range over blame labels. Blame labels carry apolarity, which is either positive or negative. The polarity of the blame label of a primarycast in the program before evaluation is positive. A cast redex of the form v : T

    p⇒ Uthat arises during evaluation can be the result of a sequence of cast reductions appliedto a primary cast expression. If the cast raises positive blame, it means that the subjectexpression surrounded by the primary cast is at fault because it does not return a valueof the form requested by its context. Negative blame indicates that the context of theprimary cast provided an unsuitable value, e.g., as an argument to the subject. Blame labelsswitch polarity when traversing the argument position of a function or a send type duringreduction. Contravariance accounts for the switch. The complement operation p performsthis switch. Complement is an involution on blame labels, so that p = p.

    In a valid cast, the type T must be a consistent subtype of U (T .U), the type of theentire expression. If a cast in a program fails, it evaluates to blame p q X or blame p X(which, as we see later, are treated as processes) where the blame label p and q indicate theroot cause of the failure (we will explain X shortly). If the cast in (1) fails, it means thatthe value returned by e has type T , but not type U . For example, let e = 4711 : int

    q⇒ ?,T = ?, and U = bool. As ? . bool, the resulting expression (4711 : int

    q⇒ ?) : ? p⇒ boolis well-typed. However, at run time it raises blame by reducing to blame q p /0, which flagsthe error that int is not a subtype of bool: that is, int 6

  • ZU064-05-FPR main 15 September 2018 13:52

    18 Igarashi et al.

    Values v,w ::= · · · | v : T p⇒ ? | v : S p⇒ ?© | v : T →m Up⇒ T ′→n U ′ | v : S

    p⇒ R | awhere un(T),S 6= ?©,R 6= ?©

    Eval contexts E,F ::= · · · | E : T p⇒U

    Expression reduction e−→ f

    v : ?p⇒ ? −→ v

    v : ?© p⇒ ?© −→ vv : unit

    p⇒ unit −→ v(v : T →m U

    p⇒ T ′→n U ′)w −→ (v(w : T ′p⇒ T )) : U p⇒U ′

    (v,w)m : T ×m Up⇒ T ′×n U ′ −→ (v : T

    p⇒ T ′,w : U p⇒U ′)nsendv(w : !T.S

    p⇒ !T ′.S′) −→ (send(v : T ′ p⇒ T )w) : S p⇒ S′

    receive(w : ?T.Sp⇒ ?T ′.S′) −→ (receivew) : T ×lin S

    p⇒ T ′×lin S′

    select lk (w : ⊕{li : Ri}i∈Ip⇒⊕{l j : S j} j∈J)−→ (select lk w) : Rk

    p⇒ Sk if k ∈ J, J ⊆ Icase(w : &{li : Ri}i∈I

    p⇒&{li : Si}i∈J)of {l j : x j.e j} j∈J−→ casewof {li : xi.letxi = (xi : Ri

    p⇒ Si) inei}i∈I if I ⊆ Jclose(v : end!

    p⇒ end!) −→ closevwait(v : end?

    p⇒ end?) −→ waitvv : T

    p⇒ ? −→ (v : T p⇒ T) : T p⇒ ? if T 6= ?, T 6= T, T ∼ Tv : ?

    p⇒ T −→ (v : ? p⇒ T) : T p⇒ T if T 6= ?, T 6= T, T ∼ Tv : S

    p⇒ ?© −→ (v : S p⇒ S) : S p⇒ ?© if S 6= ?©, S 6= S, S∼ Sv : ?© p⇒ S −→ (v : ?© p⇒ S) : S p⇒ S if S 6= ?©, S 6= S, S∼ S

    Fig. 6. Reduction in GGVi, expressions.

    linear reference is of type ?, and contains a value w of ground type T, where T is linear(either ?→lin ? or ?×lin ? or the dynamic session type ?©). Linear references are governedby two binding forms

    (νa 7→ w : T p⇒ ?)P or (νa 7→ locked p)P

    where w is a value of type T, p is a blame label, and P is a process which may refer to a.Bindings for linear references initially take the first form, but change to the second formafter the linear reference has been accessed once; any subsequent attempt to access thereference a second time will cause an error.

    3.2.3 Reduction

    Values, evaluation contexts, reductions for expressions, structural congruence, and reduc-tions for processes for GGVi are summarised in Figures 6 and 7.

    The values of GGVi are those of GV, plus five additional forms. Values of dynamic typeeither have the form v : T p⇒ ? as in other blame calculi, if T is unrestricted, or a linearreference a, if the dynamic type wraps a linear value. Additionally, there are values ofdynamic session type which take the form v : S p⇒ ?©.

    Following standard practice for blame calculus, we take a cast of a value betweenfunction types to be a value, and for similar reasons a cast from a session type to a session

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 19

    Structural congruence P≡ Q

    ((νa 7→ ω)P) | Q≡ (νa 7→ ω)(P | Q) (νa 7→ ω)(νb 7→ ω ′)P≡ (νb 7→ ω ′)(νa 7→ ω)P(νc,d)(νa 7→ ω)P≡ (νa 7→ ω)(νc,d)P (νa 7→ locked p)〈()〉 ≡ 〈()〉

    Process reduction P−→ Q

    〈E[w : T p⇒ ?]〉 −→ (νa 7→ w : T p⇒ ?)〈E[a]〉if lin(T) and E 6= F [[ ] : ? q⇒ U]

    (νa 7→ w : T p⇒ ?)(〈E[a : ? q⇒ U]〉 | Q)−→ (νa 7→ locked p)(〈E[(w : T p⇒ ?) : ? q⇒ U]〉 | Q)(νa 7→ locked p)(〈E[a : ? q⇒ U]〉 | Q)−→ (νa 7→ locked p)(blame p q (flv(E)) | Q)

    (νa 7→ w : T p⇒ ?)〈()〉 −→ blame p (flv(w))〈E[(v : T p⇒ ?) : ? q⇒ U]〉 −→ 〈E[v]〉 if T

  • ZU064-05-FPR main 15 September 2018 13:52

    20 Igarashi et al.

    p unchanged. The casts for the remaining session types follow a similar pattern, thoughcovariant on all components.

    Also typical of blame calculus, casts to the dynamic type factor through a ground type,

    v : Tp⇒ ?−→ (v : T p⇒ T) : T p⇒ ?

    when T 6= ?, T 6= T, and T ∼T. This factoring is unique because for every type T such thatT 6= ? there is a unique ground type T such that T ∼ T. The additional condition T 6= Tensures that the factoring is non-trivial and that reduction does not enter a loop. Casts fromthe dynamic type, and casts to and from the dynamic session type are handled analogously.

    Additional structural congruences and reductions for expressions appear in Figure 7.Like bindings for channel endpoints, bindings for linear references satisfy scope extrusionand reduction is a congruence with respect to them. Note that it is not possible to commute(νa 7→ w : T p⇒ ?) with other ν-binders if an outer ν binds free variables in w.

    The first four reduction rules for processes deal with linear references, ensuring that avalue cast from a linear type to a dynamic type is accessed exactly once. As the only valuesof the dynamic type are casts from a ground type, expressions of interest take the form

    w : T p⇒ ?

    where w is a value and T is a linear ground type. The first rule introduces a linear reference,represented as a binding of the form (νa 7→ w : T p⇒ ?)P where P contains all uses ofa, a freshly introduced name. The context restriction ensures that a linear reference isonly introduced if the value is not immediately accessed. Any attempt to access the linearreference a must take the form

    E[a : ?q⇒ U]

    where E is an evaluation context and U is a ground type that may or may not be linear. Thesecond rule implements the first access to a linear value by copying the value v in placeof the linear reference a, and updating the binding to (νa 7→ locked p), indicating that thelinear reference has been accessed once. The third rule implements any subsequent attemptto access a linear value, which allocates blame to both of the casts involved, negative blamep for the inner cast and positive blame q for the outer cast, indicating that in both casesblame is allocated to the side of the cast of type ?. The blame term also contains flv(E),the set of free linear variables that appear in the context E, which as mentioned earlieris required to maintain the invariant on linear variables; all occurrences of blame containcorresponding sets of linear variables, which we will not mention further. The final ruleindicates what happens when all processes containing the unlocked linear reference finishexecution. If the reference is not locked then it was never accessed, and blame should beallocated to the context of the original cast, which discarded the value rather than usingit linearly. The case where the reference is locked is represented in the last structuralcongruence rule, which expresses deallocation of the reference. In practice, these ruleswould be implemented as part of garbage collection.

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 21

    The remaining six rules come in three pairs. Typical of blame calculus is the first pair,often called the collapse and collide rules:

    〈E[(v : T p⇒ ?) : ? q⇒ U]〉 −→ 〈E[v]〉 if T

  • ZU064-05-FPR main 15 September 2018 13:52

    22 Igarashi et al.

    Expressions e,f ::= z | () | λmx:T.e | ef | (e, f)m | letx,y = e inf | forke|new S | sendef | receivee | select le | caseeof {li : xi.ei}i∈I| closee | waite

    Fig. 8. Expressions in GGVe.

    Matching T .U

    T→m U . T→m U ? . ?→lin ?T×m U . T×m U ? . ?×lin ?!T.S . !T.S ? . !?. ?© ?© . !?. ?©?T.S . ?T.S ? . ??. ?© ?© . ??. ?©

    ⊕{li : Si}i∈I .⊕{lj : Sj} ? .⊕{lj : ?©} ?© .⊕{lj : ?©}( j ∈ I)

    &{li : Si}i∈I . &{li : Si}i∈I ∪{lj : Sj}j∈J ? . &{lj : ?©}j∈J ?© . &{lj : ?©}j∈J(J∩ I = /0)

    Fig. 9. Matching.

    The type system of GGVe adheres to standard practice for gradually typed languages(Siek et al., 2015b; Cimini & Siek, 2016), but requires a few adaptations to cater forfeatures not covered in previous work. We first introduce a few auxiliary definitions used intyping rules. Figure 9 defines the matching relation T .U (Cimini & Siek, 2016). Roughlyspeaking, T .U means that T can be used, after run-time checking, as U . The second andthird columns declare that, if T is ? or ?©, then it can be used as any type or session type,respectively. Otherwise, the matching relation extracts substructure, i.e., the domain type,the codomain type, the first-element type, and so on, from T . So, we have neither ?.unitnor ?©. end! or ?©. end?.

    Matching for the internal and external choice types is slightly involved as it has to caterfor subtyping. Matching for internal choice is invoked in the type rule for an expressionselect l e. Thanks to subtyping, the type of e can be any internal choice with a branch forlabel l. Hence, matching only asks for the presence of this single label and extracts itscontinuation type.

    Dually, matching for external choice is invoked in the rule for a caseeof . . . expression.Again due to subtyping, the case expression can check more labels than provided by thetype of e. Hence, matching allows for extra branches to be check with arbitrary continua-tion types (l j : S j in the definition) while extracting the continuation types for all branchesprovided by e.

    Obtaining the result type of a case expression from the types of its branches requires ajoin operation T ∨U that ensures that its result is (in a certain sense) a supertype of both Tand U . Figure 10 contains the definitions of join and its companion meet, which is neededin contravariant positions of the type. Both operations are partial: join or meet is undefinedfor cases other than those listed in Figure 10.

    Join of two ⊕-types can be obtained by taking the joins of the types associated withcommon labels. Note that labels where the joins Si ∨Ri do not exist will be dropped. Onthe other hand, the label set of the join of two &-types is the union of the two label sets

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 23

    Multiplicity join and meet m∨n m∧n

    un∨un = un un∨ lin = lin lin∨un = lin lin∨ lin = linun∧un = un un∧ lin = un lin∧un = un lin∧ lin = lin

    Type join T ∨U

    unit∨unit = unit(T→m U)∨ (T ′→n U′) = (T ∧T ′)→m∨n (U∨U′)(T×m U)∨ (T ′×n U′) = (T ∨T ′)×m∨n (U∨U′)

    !T.S∨!T ′.S′ = !(T ∧T ′).(S∨S′)?T.S∨?T ′.S′ = ?(T ∨T ′).(S∨S′)

    ⊕{li : Si}i∈I ∨⊕{lj : Rj}j∈J =⊕{li : S′i | S′i = Si∨Ri is defined and i ∈ I∩ J}&{li : Si}i∈I ∨&{lj : Rj}j∈J = &{li : Si}i∈I\J ∪{lk : Sk ∨Rk}k∈I∩J ∪{lj : Rj}j∈J\I

    end!∨ end! = end!end?∨ end? = end?

    ?∨T = TT ∨?= T?©∨S = S

    S∨ ?©= S

    Type meet T ∧U

    unit∧unit = unit(T→m U)∧ (T ′→n U′) = (T ∨T ′)→m∧n (U∧U′)(T×m U)∧ (T ′×n U′) = (T ∧T ′)×m∧n (U∧U′)

    !T.S∧!T ′.S′ = !(T ∨T ′).(S∧S′)?T.S∧?T ′.S′ = ?(T ∧T ′).(S∧S′)

    ⊕{li : Si}i∈I ∧⊕{lj : Rj}j∈J =⊕{li : Si}i∈I\J ∪{lk : Sk ∧Rk}k∈I∩J ∪{lj : Rj}j∈J\I&{li : Si}i∈I ∧&{lj : Rj}j∈J = &{li : S′i | S′i = Si∧Ri is defined and i ∈ I∩ J}

    end!∧ end! = end!end?∧ end? = end?

    ?∧T = TT ∧?= T?©∧S = S

    S∧ ?©= S

    Fig. 10. Join and meet of types.

    from the input. For the common labels in I ∩ J, the joins Sk ∨Rk must exist. Join or meetis undefined if the resulting type is ⊕{} or &{} (with the empty set of labels) as they areill-formed types.

    Moreover, in Figure 11, we define the corresponding ordering relation, which we callpolarised consistent subtyping. This relation is a partial order that lies properly between

  • ZU064-05-FPR main 15 September 2018 13:52

    24 Igarashi et al.

    Polarised consistent subtyping T .⊕ U T . U

    Polarities u range over ⊕,; complemented by the flip operation: ⊕= and =⊕

    ?.⊕ U T . ? unit.u unit

    T .u T ′ U .u U′ m (T) m:>(U)Γ◦∆ ` (e, f)m : T×m U

    Γ ` e : T T . T1×m T2 ∆,x : T1,y : T2 ` f : UΓ◦∆ ` letx,y = e inf : U

    Γ ` e : T T ∼ unitΓ ` forke : unit

    un(Γ)Γ ` new S : S×lin S

    Γ ` e1 : T1 ∆ ` e2 : T2 T2 . !T3.S T1 . T3Γ◦∆ ` sende1 e2 : S

    Γ ` e : T1 T1 . ?T2.SΓ ` receivee : T2×lin S

    Γ ` e : T T .⊕{lj : Sj}Γ ` select lj e : Sj

    Γ ` e : T T . &{lj : Rj}j∈J (∆,xj : Rj ` ej : Uj)j∈J U =∨{U j} j∈J

    Γ◦∆ ` caseeof {lj : xj.ej}j∈J : UΓ ` e : T T ∼ end?

    Γ ` closee : unitΓ ` e : T T ∼ end!

    Γ ` waite : unit

    Typing programs eprog

    ` e : T un(T)eprog

    Fig. 12. Expression typing in GGVe.

    subtyping and consistent subtyping. It is defined such that the lifted join is the join opera-tion for (positive) polarised consistent subtyping.

    Two examples demonstrate that neither subtyping nor consistent subtyping are suitablefor defining a join operation. Consider a case expression where one branch has type ? andthe other has type int. The resulting join type should be int. Standard subtyping for GGVi

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 25

    cannot be used since ? 6

  • ZU064-05-FPR main 15 September 2018 13:52

    26 Igarashi et al.

    Cast insertion Γ ` e f : Tun(Γ)

    Γ,z : T ` z z : Tun(Γ)

    Γ ` () () : unitΓ,x : T ` e f : U m:>(Γ)Γ ` λmx:T.e λmx. f : T→m U

    Γ ` e e : T1 ∆ ` f f : T2 T1 . T11→m T12 T2 . T11Γ◦∆ ` ef (e : T1

    p⇒? T11→m T12)(f : T2p⇒? T11) : T12

    Γ ` e e : T ∆ ` f f : U m:>(T) m:>(U)Γ◦∆ ` (e, f)m (e, f )m : T×m U

    Γ ` e e : T T . T1×m T2 ∆,x : T1,y : T2 ` f f : UΓ◦∆ ` letx,y = e inf letx,y = (e : T p⇒? T1×m T2) in f : U

    Γ ` e e : T T ∼ unitΓ ` forke fork(e : T p⇒? unit) : unit

    un(Γ)Γ ` new S new : S×lin S

    Γ ` e e : T1 ∆ ` f f : T2 T2 . !T3.S T1 . T3Γ◦∆ ` sendef send(e : T1

    p⇒? T3)(f : T2p⇒? !T3.S) : S

    Γ ` e e : T1 T1 . ?T2.SΓ ` receivee receive(e : T1

    p⇒? ?T2.S) : T2×lin S

    Γ ` e e : T T .⊕{lj : Sj}Γ ` select lj e select lj (e : T

    p⇒? ⊕{lj : Sj}) : SjΓ ` e e : T T . &{lj : Rj}j∈J (∆,xj : Rj ` ej fj : Uj)j∈J U =

    ∨{U j} j∈J

    Γ◦∆ ` caseeof {lj : xj.ej}j∈J case(e : Tp⇒? &{lj : Rj}j∈J)of {lj : xj. fj : Uj

    p⇒? U}j∈J : U

    Γ ` e e : T T ∼ end!Γ ` closee close(e : T p⇒? end!) : unit

    Γ ` e e : T T ∼ end?Γ ` waite wait(e : T p⇒? end?) : unit

    Fig. 13. Cast insertion.

    4 Results

    Proofs in this section are for Gradual GV described in Section 3.2. Proofs for GV ofSection 3.1 are similar to those for GGVi except that they do not mention casts and blame,which are specific to GGVi.

    4.1 Preservation and Progress for GGVi

    We show preservation and absence of run-time errors for GGVi. The basic structure of theproof follows Gay and Vasconcelos (2010).

    Lemma 1 (Weakening)If Γ ` e : T and un(U), then Γ,x : U ` e : T .

    ProofBy induction on Γ ` e : T .

    Lemma 2 (Strengthening)If Γ,x : U ` e : T and x does not occur free in e, then Γ ` e : T .

    ProofBy induction on Γ,x : U ` e : T .

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 27

    dxe= xd()e= () : unit⇒ ?

    dλx.ee= (λunx.dee) : ?→un ?⇒ ?d(e, f )e= (dee,d f e)un : ?×un ?⇒ ?de f e= (dee : ?⇒ ?→lin ?)d f e

    dletx,y = e in f e= letx,y = (dee : ?⇒ ?×lin ?) ind f edforkee= (fork(dee : ?⇒ unit)) : unit⇒ ?dnewe= new : ?©×lin ?©⇒ ?

    dsende f e= (senddee(d f e : ?⇒ !?. ?©)) : ?©⇒ ?dreceiveee= (receive(dee : ?⇒ ??. ?©)) : ?×lin ?©⇒ ?dselect l ee= (select l (dee : ?⇒⊕{l : ?©})) : ?©⇒ ?

    dcaseeof {li : xi.ei}i∈Ie= case(dee : ?⇒&{li : ?©}i∈I)of {li : yi.letxi = (yi : ?©⇒ ?) indeie}i∈Idcloseee= (close(dee : ?⇒ end!)) : unit⇒ ?dwaitee= (wait(dee : ?⇒ end?)) : unit⇒ ?

    Fig. 14. Embedding of the unityped calculus.

    Lemma 3 (Preservation for ≡)If P≡ Q, then Γ ` P if and only if Γ ` Q.

    ProofBy induction on P ≡ Q. Use Lemmas 1, 2, and basic properties of context splitting (Vas-concelos, 2012; Walker, 2005) for the scope extrusion rules.

    Lemma 4If Γ = Γ1 ◦Γ2 and un(Γ1), then Γ = Γ2.

    ProofBy induction on Γ = Γ1 ◦Γ2.

    Lemma 5If Γ ` v : T and un(T ), then un(Γ).

    ProofBy case analysis on the last rule used to derive Γ ` v : T .

    Lemma 6 (Substitution)If Γ1 ` v : U and Γ2,x : U ` e : T and Γ = Γ1 ◦Γ2, then Γ ` e[v/x] : T .

    ProofBy induction on Γ2,x : U ` e : T with case analysis on the last derivation rule used. Weshow main cases below.

    Case (variables): If e = x and T = U and un(Γ2), then we have, by Lemma 4, Γ = Γ1,finishing the case. If e = y 6= x, then Lemma 2 finishes the case.

    Case (applications): We have e = e1 e2 and Γ11 ` e1 : T2 →m T and Γ12 ` e2 : T2 andΓ,x : U = Γ11 ◦Γ12. We have two subcases depending on whether un(U) or not.

  • ZU064-05-FPR main 15 September 2018 13:52

    28 Igarashi et al.

    Subcase un(U): We have Γ11 = Γ′11,x : U and Γ12 = Γ′12,x : U and Γ = Γ

    ′11 ◦Γ′12. The

    induction hypothesis give us Γ′11 ◦Γ2 ` e1[v/x] : T2→m T and Γ′12 ◦Γ2 ` e2[v/x] : T2.By Lemma 5, we have un(Γ2). The typing rule for applications shows (Γ′11 ◦Γ2) ◦(Γ′12 ◦Γ2) ` (e1 e2)[v/x] : T . Lemma 4 finishes the subcase.

    Subcase lin(U): either (1) Γ11 = Γ′11 and Γ12 = Γ′12,x : U and Γ = Γ

    ′11 ◦Γ′12, in which

    case we have Γ′12 ` e2[v/x] : T1 by the induction hypothesis and also e1[v/x] = e1 andthe typing rule for applications finishes; or (2) Γ11 = Γ′11,x : U and Γ12 = Γ

    ′12 and

    Γ = Γ′11 ◦Γ′12, in which case the conclusion is similarly proved.

    The following two lemmas are adapted from earlier work (Gay & Vasconcelos, 2010).

    Lemma 7 (Sub-derivation introduction)If D is a derivation of Γ ` E[e] : T , then there exist Γ1, Γ2 and U such that Γ = Γ1 ◦Γ2 andD has a sub-derivation D ′ concluding Γ2 ` e : U and the position of D ′ in D correspondsto the position of the hole in E.

    ProofBy induction on E.

    Lemma 8 (Sub-derivation elimination)Γ ` E[ f ] : T holds, if

    • D is a derivation of Γ1 ◦Γ2 ` E[e] : T ,• D ′ is a sub-derivation of D concluding Γ2 ` e : U ,• the position of D ′ in D corresponds to the position of the hole in E,• Γ3 ` f : U , and• Γ = Γ1 ◦Γ3.

    ProofBy induction on E.

    Lemma 9If Γ ` e : T , then flv(Γ) = flv(e).

    ProofEasy induction on Γ ` e : T .

    Theorem 1 (Preservation for expressions)If e−→ f and Γ ` e : T , then Γ ` f : T .

    ProofBy rule induction on the first hypothesis. For β -reduction and let we use the substitutionlemma (Lemma 6), using an ‘inversion of the typing relation’ lemma which we omit.

    Theorem 2 (Preservation for processes)If P−→ Q and Γ ` P, then Γ ` Q.

    Proof

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 29

    By rule induction on the first hypothesis, using basic properties of context splitting (Vas-concelos, 2012; Walker, 2005) and weakening (Lemma 1). Rules that make use of contextuse subderivation introduction (Lemma 7) to build the derivation for the hypothesis, andsubderivation elimination (Lemma 8) to build the derivation for the conclusion. Rules forreduction to blame use Lemma 9. Reduction underneath parallel composition and scoperestriction follow by induction. The rule for ≡ uses Lemma 3. Closure under evaluationcontexts uses Theorem 1.

    Lemma 10 (Ground types, subtyping, and consistent subtyping)1. If T 6= ?, there is a unique ground type T such that T∼ T .2. If S 6= ?©, there is a unique ground session type S such that S∼ S.3. T. U iff T

  • ZU064-05-FPR main 15 September 2018 13:52

    30 Igarashi et al.

    1. agree{c,d}{sendvc, received};2. agree{c,d}{select l j c,cased of {li : xi. fi}i∈I} and j ∈ I;3. agree{c,d}{closec,waitd}.

    A process is an error if it is structurally congruent to some process that contains asubprocess of one of the following forms.

    1. 〈E[ve]〉 and v is not an abstraction;2. 〈E[leta,b = v ine]〉 and v is not a pair;3. 〈E[e]〉 | 〈F [ f ]〉 and subj(e) = subj( f );4. (νc,d)(〈E[e]〉 | 〈F [ f ]〉) and subj(e) = c and subj( f ) = d and not agree{c,d}{e, f}.

    The first two cases are typical of functional languages. The third case ensures no twothreads hold references to the same channel endpoint. The fourth case ensures channelendpoints agree at all times: if one process is ready to send then the other is ready toreceive, and similarly for select and case, close and wait.

    For processes, rather than a progress result, we present a type safety result as our typesystem does not rule out deadlocks, though we do not open new chances for deadlockswhen compared to GV (Gay & Vasconcelos, 2010). Our result holds both for GV andGradual GV alike.

    Theorem 4 (Absence of run-time errors)Let Γ ` P where Γ does not contain function or pair types, and let P−→∗ Q. Then Q is notan error.

    ProofBy induction on the length of reduction steps P −→∗ Q. For the base case, where P = Q,we show P is not an error by showing all error processes cannot be well typed.

    All cases use Lemma 7 and inversion of the typing relation (omitted). The cases forapplication and let follow from the fact that Γ does not contain function or pair types. Thethird case follows from the fact that c, being the subject of expressions, is of a linear type,hence cannot occur in two distinct processes. The fourth case follows from the fact thattypability implies that c and d are of dual types, which in turn implies agree{c,d}(e, f ).

    4.2 Blame Safety

    Following Wadler and Findler (2009) we introduce three new subtyping relations:

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 31

    Positive and negative subtyping T

  • ZU064-05-FPR main 15 September 2018 13:52

    32 Igarashi et al.

    ProofBy induction on types.

    Here the first and second items are an implication, rather than an equivalence as in the thirdand fourth items and previous work. In order to get an equivalence, we would need to altersubtyping such that T

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 33

    We analyse all reduction rules whose contractum includes blame. From Figure 6 take therule with reductum (v : T p⇒ ?) : ? q⇒ U. It may blame p and q, if T 6

  • ZU064-05-FPR main 15 September 2018 13:52

    34 Igarashi et al.

    Theorem 8 states that cast insertion succeeds for well typed external language andpreserves typing. A few lemmas are required in preparation.

    Lemma 18If T1∨T2 = U, then T1 . U and T2 . U.

    ProofImmediate from Lemmas 14 and 16.

    Lemma 19If T . U, then T . U.

    ProofBy case analysis on T . U.

    Theorem 8 (Cast insertion succeeds and preserves typing)If Γ è e : T , then there exists some f such that Γ ` e f : T and Γ ì f : T .

    ProofBy rules induction on the derivation of Γ è e : T . We show main cases below.

    Case application rule: We are given Γ = Γ1 ◦Γ2 and e= e1 e2 and T = T12 and Γ1 ` e1 : T1and Γ2 ` e2 : T2 and T1 . T11→m T12 and T2 . T11.By Γ1 ` e1 : T1 and the IH, Γ1 ` e1 f1 : T1 and Γ1 ` f1 : T1 for some f1.By Γ2 ` e2 : T2 and the IH, Γ2 ` e2 f2 : T2 and Γ2 ` f2 : T2 for some f2.Let f = (f1 : T1

    p⇒? T11→m T12)(f2 : T2p⇒? T11). By the application rule, Γ ` e f : T .

    Now, we assume f1 : T1p⇒? T11 →m T12 equals f1 : T1

    p⇒ T11 →m T12, but even whenf1 : T1

    p⇒? T11→m T12 equals f1, we could use the subsumption rule instead of the castrule in the following proof. We also take similar assumptions in the rest of the proof.By T1 . T11→m T12 and Lemma 19, T1 . T11→m T12. By Γ1 ` f1 : T1 and the cast rule,Γ1 ` (f1 : T1

    p⇒ T11→m T12) : T11→m T12.By Γ2 ` f2 : T2 and T2 . T11 and the cast rule, Γ2 ` (f2 : T2

    p⇒ T11) : T11.Thus, by the application rule, Γ ` f : T .

    Case case rule: We are given Γ = Γ′ ◦∆ and e = casee′ of {lj : xj.ej}j∈J and T = U andΓ′ ` e′ : T ′ and T ′ . &{lj : Rj}j∈J and (∆,xj : Rj ` ej : Uj)j∈J and U =

    ∨{U j} j∈J .

    By Γ′ ` e′ : T ′ and the IH, Γ′ ` e′ f : T ′ and Γ′ ` f ′ : T ′ for some f ′.Take any j ∈ J. By ∆,xj : Rj ` ej : Uj and the IH, we have ∆,xj : Rj ` ej fj : Uj and∆,xj : Rj ` fj : Uj for some fj.Let f = case(f ′ : T

    p⇒? &{lj : Rj}j∈J)of {lj : xj. fj : Ujp⇒? U}j∈J . By the case rule, Γ `

    e f : T .By T ′ . &{lj : Rj}j∈J and Lemma 19, T ′ .&{lj : Rj}j∈J . By Γ′ ` f ′ : T ′ and the cast rule,Γ′ ` (f ′ : T ′ p⇒&{lj : Rj}j∈J) : &{lj : Rj}j∈J .Take any j ∈ J. By U =

    ∨{U j} j∈J and Lemma 18, Uj .U. By ∆,xj : Rj ` fj : Uj and the

    cast rule, ∆,xj : Rj ` (fj : Ujp⇒ U) : U.

    Thus, by the case rule, Γ ` f : T .

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 35

    A type T is static if T does not contain one of the dynamic types: ? or ?©. A typeenvironment Γ is static if Γ contains only static types. An expression e of GGVe is static ifall types declared in e are static.

    Lemma 201. Suppose T,U are static. If T . U, then T

  • ZU064-05-FPR main 15 September 2018 13:52

    36 Igarashi et al.

    By Γ1 ` e1 : T1 and the IH, Γ1 ` |e1| : T1 and T1 is static. By T1 . T11 →m T12 andLemma 20, T1 = T11→m T12 and T11, T12 are static.By Γ2 ` e2 : T2 and the IH, Γ2 ` |e2| : T2 and T2 is static. By T2 . T11 and Lemma 20,T2

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 37

    and already have U

  • ZU064-05-FPR main 15 September 2018 13:52

    38 Igarashi et al.

    it also restores blame, which enables a proof of blame safety: blame for type errors alwayslays with less-precisely typed code—“well-typed programs can’t be blamed”.

    Siek and others (2015b) review desirable properties of gradually-typed languages, whileWadler (2015) discusses the history of the blame calculus and why blame is important.These papers provide overviews of the field, each with many further citations.

    As noted in the introduction, gradual typing may be important as a bridge to typesystems that go beyond what is currently available, including dependent, effect, and sessiontypes. There is a range of gradual type systems for dependent types (Ou et al., 2004;Flanagan, 2006; Greenberg et al., 2010). A gradual type systems for effect types wasexplored by Banados Schwerter and others (2014). Gradual type systems related to sessiontypes include the run-time enforcement of affine typing of Tov and Pucella (2010), andthe gradual typestate of Wolf and others (2011). Thiemann (2014) describes a system withgradual types and session types, but in it only types (and not session types) can be gradual.

    Practical languages exploiting gradual types include type Dynamic in C# (Bierman et al.,2010), TypeScript (Bierman et al., 2014), Hack (Verlaguet, 2013), and Dart (Team, 2014).

    TypeScript TPD (Williams et al., 2017) applies contracts to monitor the gradual typingof TypeScript, and evaluates the successes and shortcomings of contracts in this context.

    5.2 Session Types

    Session types were introduced by Honda, Vasconcelos, and Kubo (1993; 1998). The orig-inal system addressed binary sessions, whereby types describe the interaction betweentwo partners. Binary sessions were eventually extended to the more general setting ofmultiparty session types (Honda et al., 2016). Recent years have seen the introductionof session types in programming languages, and software development tools. We reviewthe most important works.

    Session types inspired the design of several programming languages. Sing# (Fähndrichet al., 2006) constitutes one of the first attempts to introduce session types in programminglanguages. An extension of C, Sing# was used to implement Singularity, an operatingsystem based on message passing. Gay and others (2010) propose attaching session types toclass definitions, allowing to treat channels as objects for session-based communication indistributed systems. SePi (Franco & Vasconcelos, 2013) is a concurrent, message-passingprogramming language based on the pi-calculus, featuring a simple form of refinementtypes. SILL (Toninho et al., 2013; Pfenning & Griffith, 2015) is a higher-order sessionfunctional programming language, featuring process expressions as first class objects viaa linear contextual monad. Concurrent C0 (Willsey et al., 2017) is a type-safe C-likeprogramming language equipped with channel communication governed by session types.Links (Lindley & Morris, 2017) is a functional programming language designed for tierlessweb applications that natively supports binary session types.

    Proposals have been made to retroactively introduce session types in mainstream pro-gramming languages. Session Java (Hu et al., 2008) introduces API-based session primi-tives in Java, while (Hu et al., 2010) presents a Java language extension and type disciplinefor session-based event-driven programming. Featherweight Erlang (Mostrous & Vascon-celos, 2011) imposes a session-based type system to discipline message passing in Erlang.Mungo (Kouzapas et al., 2016) is a tool for checking Java code against session types,

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 39

    presented in the form of typestates. Embedding of session types have been proposed forHaskell (Orchard & Yoshida, 2016; Pucella & Tov, 2008; Sackman & Eisenbach, 2008;Polakow, 2015; Lindley & Morris, 2016a), OCaml (Padovani, 2017), Scala (Scalas &Yoshida, 2016), and Rust (Jespersen et al., 2015). Most of these embeddings delegatelinearity checks on the run-time system.

    Session types can be used in the software development process under different forms,including languages to describe protocols, specialised libraries to invoke session-basedcommunication primitives, provision for run-time monitoring against session types, andextended type checkers. Scribble (Honda et al., 2011) is a language-agnostic protocoldescription formalism used in many different tools. Multiparty Session C (Ng et al., 2012)uses Scribble, a compiler plug-in, and a C library to validate against session types. Huand Yoshida (2016) generate protocol-specific Java APIs from multiparty session typesdescribed in Scribble. SPY (Neykova et al., 2013) generates run-time monitors for endpointcommunication from Scribble protocols. Neykova and Yoshida (2014) design and imple-mented a session actor library in Python together with a run-time verification mechanism.Bocchi and others (2017) present a theory that incorporates both static typing and dynamicmonitoring of session types. Fowler (2016) describes a framework for monitoring Erlangapplications against multiparty session types. Neykova and Yoshida (2017) investigatefailure handling for Erlang processes in a system that dynamically monitors session types.Dingo Hunter (Ng & Yoshida, 2016) and Gong (Lange et al., 2017) statically detect (par-tial) deadlocks in Go programs by extracting behavioural types from programs.

    6 Conclusions

    We presented the design of Gradual GV, which combines a session-typed language GValong the lines of Gay and Vasconcelos (2010) with a blame calculus along the lines ofWadler and Findler (2009), and with dynamic enforcement of linearity along the lines ofTov and Pucella (2010). We established the expected results for such a language, includingtype safety and blame safety.

    Much remains to be done; we consider just one future direction here. The embeddingof linear types in the unrestricted dynamic type relies on an indirection through a cell inthe store. In our present work, these cells are used once and then discarded. This one-shot policy imposes a certain usage pattern on linear values embedded in the unitypedlanguage. In particular, the send and receive operations on a channel need to be chained asin (close(sendv2 (sendv1 c))). However, one could imagine a unityped language where onemay use the channel non-linearly in an imperative style as in (sendv1 c;sendv2 c;closec),mimicking the style of network programming in conventional languages. This style canalso be supported by a variant of Gradual GV with a multi-shot policy that restores an up-dated channel to the same cell from which it was extracted. We leave the full formalisationof this policy to future work.

    References

    Bañados Schwerter, Felipe, Garcia, Ronald, & Tanter, Éric. (2014). A theory of gradual effectsystems. Pages 283–295 of: International Conference on Functional Programming (ICFP). ACM.

  • ZU064-05-FPR main 15 September 2018 13:52

    40 Igarashi et al.

    Barendregt, H.P.(̇1984). The Lambda Calculus: Its Syntax and Semantics. North-Holland.

    Bauer, Andrej, & Pretnar, Matija. (2015). Programming with algebraic effects and handlers. Journalof logical and algebraic methods in programming, 84(1), 108–123.

    Bierman, Gavin, Abadi, Martín, & Torgersen, Mads. (2014). Understanding TypeScript. Pages 257–281 of: European Conference on Object-Oriented Programming (ECOOP). LNCS, vol. 8586.Springer.

    Bierman, Gavin M., Meijer, Erik, & Torgersen, Mads. (2010). Adding dynamic types to C#. Pages76–100 of: European Conference on Object-Oriented Programming (ECOOP). LNCS. Springer.

    Bocchi, Laura, Chen, Tzu-Chun, Demangeon, Romain, Honda, Kohei, & Yoshida, Nobuko. (2017).Monitoring networks through multiparty session types. Theoretical computer science, 699, 33–58.

    Brady, Edwin. (2013). Idris, a general-purpose dependently typed programming language: Designand implementation. Journal of functional programming, 23(05), 552–593.

    Caires, Luís, & Pfenning, Frank. (2010). Session types as intuitionistic linear propositions. Pages222–236 of: International Conference on Concurrency Theory (CONCUR). LNCS. Springer.

    Caires, Luis, Pfenning, Frank, & Toninho, Bernardo. (2014). Linear logic propositions as sessiontypes. Mathematical structures in computer science, 26(03), 367–423.

    Chlipala, Adam. (2013). Certified programming with dependent types: A pragmatic introduction tothe coq proof assistant. MIT Press.

    Cimini, Matteo, & Siek, Jeremy G. (2016). The Gradualizer: A methodology and algorithmfor generating gradual type systems. Pages 443–455 of: Proceedings of the 43rd AnnualACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL 2016, St.Petersburg, FL, USA, January 20 - 22, 2016.

    Fähndrich, Manuel, Aiken, Mark, Hawblitzel, Chris, Hodson, Orion, Hunt, Galen C., Larus,James R., & Levi, Steven. (2006). Language support for fast and reliable message-basedcommunication in Singularity OS. Pages 177–190 of: European Conference on Computer Systems(EuroSys). ACM.

    Fennell, Luminous, & Thiemann, Peter. (2012). The blame theorem for a linear lambda calculus withtype dynamic. Pages 37–52 of: Trends in Functional Programming. LNCS, vol. 7829. Springer.

    Findler, Robert Bruce, & Felleisen, Matthias. (2002). Contracts for higher-order functions. Pages48–59 of: International Conference on Functional Programming (ICFP). ACM.

    Flanagan, Cormac. (2006). Hybrid type checking. Pages 245–256 of: Principles of ProgrammingLanguages (POPL). ACM.

    Fowler, Simon. (2016). An Erlang implementation of multiparty session actors. Pages 36–50 of:Interaction and Concurrency Experience.

    Franco, Juliana, & Vasconcelos, Vasco Thudichum. (2013). A concurrent programming languagewith refined session types. Pages 15–28 of: SEFM. LNCS, vol. 8368. Springer.

    Gay, Simon, & Hole, Malcolm. (2005). Subtyping for session types in the pi calculus. Actainformatica, 42(2-3), 191–225.

    Gay, Simon, & Vasconcelos, Vasco. (2010). Linear type theory for asynchronous session types.Journal of functional programming, 20(01), 19–50.

    Gay, Simon J., Vasconcelos, Vasco Thudichum, Ravara, António, Gesbert, Nils, & Caldeira,Alexandre Z. (2010). Modular session types for distributed object-oriented programming. Pages299–312 of: Principles of Programming Languages (POPL). ACM.

    Girard, Jean-Yves. (1987). Linear logic. Theoretical computer science, 50(1), 1–101.Greenberg, Michael, Pierce, Benjamin C., & Weirich, Stephanie. (2010). Contracts made manifest.

    Pages 353–364 of: Principles of Programming Languages (POPL). ACM.

    Honda, K., Mukhamedov, A., Brown, G., Chen, T., & Yoshida, N. (2011). Scribbling interactionswith a formal foundation. Pages 55–75 of: ICDCIT. LNCS, vol. 6536. Springer.

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 41

    Honda, Kohei. (1993). Types for dyadic interaction. Pages 509–523 of: International Conference onConcurrency Theory (CONCUR). LNCS, vol. 715. Springer.

    Honda, Kohei, Vasconcelos, Vasco, & Kubo, Makoto. (1998). Language primitives and typediscipline for structured communication-based programming. Pages 122–138 of: EuropeanSymposium on Programming (ESOP). LNCS. Springer.

    Honda, Kohei, Yoshida, Nobuko, & Carbone, Marco. (2008). Multiparty asynchronous session types.Pages 273–284 of: Principles of Programming Languages (POPL). ACM.

    Honda, Kohei, Yoshida, Nobuko, & Carbone, Marco. (2016). Multiparty asynchronous session types.Journal of the acm, 63(1), 9.

    Hu, Raymond, & Yoshida, Nobuko. (2016). Hybrid session verification through endpoint APIgeneration. Pages 401–418 of: Fundamental Approaches to Software Engineering (FASE). LNCS,vol. 9633. Springer.

    Hu, Raymond, Yoshida, Nobuko, & Honda, Kohei. (2008). Session-based distributed programmingin Java. Pages 516–541 of: European Conference on Object-Oriented Programming (ECOOP).LNCS, vol. 5142. Springer.

    Hu, Raymond, Kouzapas, Dimitrios, Pernet, Olivier, Yoshida, Nobuko, & Honda, Kohei. (2010).Type-safe eventful sessions in Java. Pages 329–353 of: European Conference on Object-OrientedProgramming (ECOOP). LNCS, vol. 6183. Springer.

    Igarashi, Atsushi, Thiemann, Peter, Vasconcelos, Vasco T., & Wadler, Philip. (2017). Gradual sessiontypes. PACMPL, 1(ICFP), 38:1–38:28.

    Jespersen, Thomas Bracht Laumann, Munksgaard, Philip, & Larsen, Ken Friis. (2015). Session typesfor Rust. Pages 13–22 of: Workshop on Generic Programming (WGP). ACM.

    Kobayashi, Naoki, Pierce, Benjamin C., & Turner, David N. (1999). Linearity and the pi-calculus.ACM trans. program. lang. syst., 21(5), 914–947.

    Kouzapas, Dimitrios, Dardha, Ornela, Perera, Roly, & Gay, Simon J. (2016). Typecheckingprotocols with Mungo and StMungo. Pages 146–159 of: Principles and Practice of DeclarativeProgramming (PPDP). ACM.

    Lange, Julien, Ng, Nicholas, Toninho, Bernardo, & Yoshida, Nobuko. (2017). Fencing offGo: Liveness and safety for channel-based programming. Pages 748–761 of: Principles ofProgramming Languages (POPL). ACM.

    Leijen, Daan. (2017). Type directed compilation of row-typed algebraic effects. Pages 486–499 of:POPL. New York, NY, USA: ACM.

    Lindley, Sam, & Morris, J. Garrett. (2016a). Embedding session types in Haskell. Pages 133–145of: Symposium on Haskell. ACM.

    Lindley, Sam, & Morris, J Garrett. (2016b). Talking bananas: Structural recursion for session types.Pages 434–447 of: International Conference on Functional Programming (ICFP). ACM.

    Lindley, Sam, & Morris, J. Garrett. (2017). Behavioural types: from theory to tools. River Publishers.Chap. Lightweight functional session types.

    Lindley, Sam, McBride, Conor, & McLaughlin, Craig. (2017). Do be do be do. Pages 500–514 of:Principles of Programming Languages (POPL). ACM.

    Milner, Robin, Parrow, Joachim, & Walker, David. (1992). A calculus of mobile processes, I.Information and computation, 100(1), 1–40.

    Mostrous, Dimitris, & Vasconcelos, Vasco T. (2011). Session typing for a featherweight Erlang.Pages 95–109 of: Coordination Models and Languages (COORDINATION). LNCS, vol. 6721.Springer.

    Neykova, Rumyana, & Yoshida, Nobuko. (2014). Multiparty session actors. Pages 131–146 of:Coordination Models and Languages (COORDINATION). LNCS, vol. 8459. Springer.

    Neykova, Rumyana, & Yoshida, Nobuko. (2017). Let it recover: Multiparty protocol-inducedrecovery. Pages 98–108 of: International Conference on Compiler Construction (CC). ACM.

  • ZU064-05-FPR main 15 September 2018 13:52

    42 Igarashi et al.

    Neykova, Rumyana, Yoshida, Nobuko, & Hu, Raymond. (2013). SPY: local verification of globalprotocols. Pages 358–363 of: International Conference on Runtime Verification (RV). LNCS, vol.8174. Springer.

    Ng, Nicholas, & Yoshida, Nobuko. (2016). Static deadlock detection for concurrent Go by globalsession graph synthesis. Pages 174–184 of: International Conference on Compiler Construction(CC). ACM.

    Ng, Nicholas, Yoshida, Nobuko, & Honda, Kohei. (2012). Multiparty Session C: Safe parallelprogramming with message optimisation. Pages 202–218 of: International Conference onModelling Techniques and Tools for Computer Performance Evaluation (TOOLS). LNCS, vol.7304. Springer.

    Norell, Ulf. (2009). Dependently typed programming in Agda. Pages 1–2 of: Proceedings of the 4thInternational Workshop on Types in Language Design and Implementation. TLDI ’09. ACM.

    Orchard, Dominic, & Yoshida, Nobuko. (2016). Effects as sessions, sessions as effects. Pages 568–581 of: Principles of Programming Languages (POPL). ACM.

    Ou, Xinming, Tan, Gang, Mandelbaum, Yitzhak, & Walker, David. (2004). Dynamic typing withdependent types. Pages 437–450 of: IFIP International Conference on Theoretical ComputerScience, vol. 155. Springer.

    Padovani, Luca. (2017). A simple library implementation of binary sessions. Journal of functionalprogramming, 27, e4.

    Pfenning, Frank, & Griffith, Dennis. (2015). Polarized substructural session types. Pages 3–22 of:International Conference on Foundations of Software Science and Computation Structures. LNCS,vol. 9034. Springer.

    Polakow, Jeff. (2015). Embedding a full linear lambda calculus in Haskell. Pages 177–188 of:Symposium on Haskell. ACM.

    Pucella, Riccardo, & Tov, Jesse A. (2008). Haskell session types with (almost) no class. Pages 25–36of: Symposium on Haskell. ACM.

    Sackman, Matthew, & Eisenbach, Susan. (2008). Session types in Haskell: Updating messagepassing for the 21st century.

    Scalas, Alceste, & Yoshida, Nobuko. (2016). Lightweight session programming in Scala. Pages21:1–21:28 of: European Conference on Object-Oriented Programming (ECOOP). LIPIcs.Schloss Dagstuhl.

    Siek, Jeremy, Thiemann, Peter, & Wadler, Philip. (2015a). Blame and coercion: Together again forthe first time. Pages 425–435 of: Programming Language Design and Implementation (PLDI).

    Siek, Jeremy G., & Taha, Walid. 2006 (Sept.). Gradual typing for functional languages. Pages 81–92of: Scheme and Functional Programming Workshop (Scheme).

    Siek, Jeremy G., & Taha, Walid. (2007). Gradual typing for objects. Pages 2–27 of: ECOOP. LectureNotes in Computer Science, vol. 4609. Springer.

    Siek, Jeremy G., Vitousek, Michael M., Cimini, Matteo, & Boyland, John T. (2015b). Refined criteriafor gradual typing. Pages 274–293 of: Summit on Advances in Programming Languages (SNAPL).LIPIcs, vol. 32. Schloss Dagstuhl.

    Team, The Dart. (2014). Dart programming language specification. Google, 1.2 edition.

    Thiemann, Peter. (2014). Session types with gradual typing. Pages 144–158 of: TGC. LNCS, vol.8902. Springer.

    Toninho, Bernardo, & Yoshida, Nobuko. (2018). Depending on session-typed processes. Pages128–145 of: FoSSaCS. Lecture Notes in Computer Science, vol. 10803. Springer.

    Toninho, Bernardo, Caires, Luís, & Pfenning, Frank. (2013). Higher-order processes, functions,and sessions: A monadic integration. Pages 350–369 of: European Symposium on Programming(ESOP). LNCS, vol. 7792. Springer.

  • ZU064-05-FPR main 15 September 2018 13:52

    Gradual Session Types 43

    Tov, Jesse A., & Pucella, Riccardo. (2010). Stateful contracts for affine types. Pages 550–569 of:European Symposium on Programming (ESOP). LNCS, vol. 6012. Springer.

    Vasconcelos, Vasco Thudichum. (2012). Fundamentals of session types. Information andcomputation, 217, 52–70.

    Verlaguet, Julien. (2013). Facebook: Analysing PHP statically. Workshop on Commercial Uses ofFunctional Programming (CUFP).

    Wadler, Philip. (2012). Propositions as sessions. Pages 273–286 of: International Conference onFunctional Programming (ICFP). ACM.

    Wadler, Philip. (2014). Propositions as sessions. Journal of functional programming, 24(2-3), 384–418.

    Wadler, Philip. (2015). A complement to blame. Pages 309–320 of: 1st Summit on Advances inProgramming Languages (SNAPL). LIPIcs, vol. 32. Schloss Dagstuhl.

    Wadler, Philip, & Findler, Robert Bruce. (2009). Well-typed programs can’t be blamed. Pages 1–16of: European Symposium on Programming (ESOP). LNCS, vol. 5502. Springer.

    Walker, David. (2005). Advanced topics in types and programming languages. MIT Press. Chap.Substructural Type Systems, pages 3–43.

    Williams, Jack, Morris, J. Garrett, Wadler, Philip, & Zalewski, Jakub. (2017). Mixed messages:Measuring conformance and non-interference in typescript. Pages 28:1–28:29 of: EuropeanConference on Object-Oriented Programming (ECOOP). LIPIcs, vol. 74. Dagstuhl, Germany:Schloss Dagstuhl.

    Willsey, Max, Prabhu, Rokhini, & Pfenning, Frank. (2017). Design and implementation ofconcurrent C0. Pages 73–82 of: International Workshop on Linearity. EPTCS, vol. 238.

    Wolff, Roger, Garcia, Ronald, Tanter, Éric, & Aldrich, Jonathan. (2011). Gradual typestate. Pages459–483 of: European Conference on Object-Oriented Programming (ECOOP). LNCS, vol. 6813.Springer.

    Yoshida, Nobuko, & Vasconcelos, Vasco. (2007). Language primitives and type discipline forstructured communication-based programming revisited: Two systems for higher-order sessioncommunication. Entcs, 171(4), 73–93.

    Yoshida, Nobuko, Hu, Raymond, Neykova, Rumyana, & Ng, Nicholas. (2014). The Scribble protocollanguage. Pages 22–41 of: International Symposium on Trustworthy Global Computing. LNCS,vol. 8358. Springer.

    A Typechecking Algorithm for the External Language

    We give a typechecking algorithm for GGVe and show that it is correct. The typecheckingalgorithm is slightly involved due to linearity: CHECKEXPR(Γ,e) outputs a pair of type Tand a set X of variables, containing the linear variables occurring free in e.

    function CHECKEXPR(Γ,e)case e of| z⇒

    assert z ∈ dom(Γ)T := Γ(z)if lin(T ) then return T , {z}else return T , /0

    | ()⇒ return unit, /0| λmx:T1.e1 ⇒

    T2,Y := CHECKEXPR((Γ,x : T1),e1)

  • ZU064-05-FPR main 15 September 2018 13:52

    44 Igarashi et al.

    if lin(T1) and m = un thenassert Y = {x}return T1→un T2, /0

    else if lin(T1) and m = lin thenassert x ∈ Yreturn T1→lin T2, Y \{x}

    else if un(T1) and m = un thenassert Y = /0return T1→un T2, /0

    else return T1→lin T2, Y| e1 e2 ⇒

    T1,X := CHECKEXPR(Γ,e1); T2,Y := CHECKEXPR(Γ,e2)assert X ∩Y = /0T11→m T12 := MATCHINGFUN(T1)assert T2 . T11return T12, X ∪Y

    | (e1, e2)m ⇒T1,X := CHECKEXPR(Γ,e1); T2,Y := CHECKEXPR(Γ,e2)assert X ∩Y = /0if m = un then assert un(T1) and un(T2)return