1. Trang chủ
  2. » Tất cả

Combining control effects and their models: game semantics for a hierarchy of static, dynamic and delimited control effects

31 4 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 31
Dung lượng 737,52 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Combining control effects and their models Game semantics for a hierarchy of static, dynamic and delimited control effects Annals of Pure and Applied Logic 168 (2017) 470–500 Contents lists available[.]

Trang 1

Contents lists available at ScienceDirect

Annals of Pure and Applied Logic

www.elsevier.com/locate/apal

Game semantics for a hierarchy of static, dynamic and delimited

This paper develops operational and denotational semantics for a hierarchy of programming languages which include combinations of locally declared control prompts to which a program can escape, with first-class continuations which may either capture their enclosing prompts, or be delimited by them We describe two different hierarchies of models, both based on categories of games and strategies with a computational monad, but obtained using different methodologies By

relaxing combinations of behavioural constraints on strategies with control flow represented by annotation with control pointers we are able to give direct and explicit characterizations of control operators and their effects, including examples characterizing their macro-expressiveness By constructing a parallel hierarchy of models by applying sequences of monad transformers, and relating these to the direct interpretation of control effects, we obtain games interpretations of higher- level abstractions such as continuations and exceptions, which can be used as the basis for equational reasoning about programs.

© 2016 The Author Published by Elsevier B.V This is an open access article under the CC BY license ( http://creativecommons.org/licenses/by/4.0/ ).

1 Introductionandrelatedwork

and returnto controlpoints inavarietyofways (e.g withstaticor dynamicbinding, local orglobal ables, delimited or undelimitedcontinuations).Combining control effects canhighlight and amplify thesedifferences, whichmayhavesignificantimpacts,andleadtocomplicatedcontrolflow.Therefore,principlesfor reasoning about combinations of control effects are important in producing safe and expressive pro-

vari-E-mail address:jiml@cs.bath.ac.uk

http://dx.doi.org/10.1016/j.apal.2016.10.011

0168-0072/© 2016 The Author Published by Elsevier B.V This is an open access article under the CC BY license

Trang 2

to combining effects Constructions such as computational monads [19,18] and continuation-passing-style

interpretation[6],andalgebraic theories [8]arevaluabletoolsforreasoningaboutprograms,althoughtheytypically impose additional layers of definition and interpretation through which this must be filtered,particularly inthepresence of multipleeffects or propertiessuchas locality.Bycontrast, game semantics

providesasettinginwhichtomodelcombinationsofeffectsmoredirectlybytherelaxationofconstraintsonstrategiesrepresentingfunctional programs.Thisapproachhasbeenusedsuccessfullytogivefully abstract

interpretations ofmanyfeatures,includinganaccount oflocality forfeaturessuchas state[2,1].However,the combinatorialnatureof gamesmodels meansthatreasoning aboutdenotations —even proving basicsoundnessresults—canbedifficultintheabsenceofstructuringprinciples.Thusitcanbeusefultorelatethedirect(games)andindirect(monads)approachesto effects,to gaintheadvantagesofbothrepresenta-tions.This paperwilldo soforcontroleffects whichincludestaticallybound,first-class continuationsandlocally declared,dynamicallybound prompts.Determiningtheinteractionbetweenthesefeatures presents

uswithabasicchoice:doescall-with-current-continuationcaptureitsenclosingprompts,ordotheyactas

delimiters forcontinuations?Allowingeither,bothorneitheroftheseoptionsleadsustoasimplehierarchy

ofprogramminglanguagesandtheirsemantics

Supposewehaveamodelofthecomputationalλ-calculus(aλ C-model)[18]—i.e.apair(C,T) consisting

of:

• acategoryC withfinite productsand

• astrongmonad(T, η,(_)∗ , t) on C,andexponentials A ⇒ TB for eachpairofobjectsA, B in C.

AssumingthatC alsohas(distributive)coproducts (andthusaninitialobject0 andterminalobject1),wemaydefinefurtherλ C-models viathefollowingmonad transformers [24]:

• Thecontinuations monad transformer,whichsends T tothestrongmonadTC= (_⇒ T0) ⇒ T0.

• Themaybe transformer,whichsendsT tothestrongmonadTP = T(_ + 1).

The latteris oftencalled the exceptions monad — we will also useit to interpret continuation-delimiting

byalternatingthecontinuationsandmaybetransformerswemayobtainahierarchyofdifferentλ C-models:

Trang 3

As we will show, the order in which the sum and continuations monad transformers are applied mines the precedence between the corresponding control abstractions: TCP allows us to model contin-uations which capture prompts (which behave as exception handlers) whereas TP C describes promptswhich delimit continuations. By iterating these monad transformers we can combine both of these be-haviours.

Howcanthesemodelsbasedoncomputationalmonadsberelatedtoadirect,gamesemanticaccountandusedtogiveafullyabstractmodel?Inthecaseoffirst-classcontinuationsthereisasimplecorrespondencebetween thegames andmonadic interpretations,whichis describedin[11] —relaxing thewell-bracketing

monad ΣC,unifyingdirectandindirect(continuation-passingstyle)interpretationsof call/cc

Locally declared exceptions can also be interpreted directly by relaxing the bracketing condition,but fully capturing dynamic exception handling also requires new information to be added to strate-gies in the form of additional “control pointers” attached to sequences [12] This yields a richer uni-verse of models, which we explore here — in particular, we show that there are two different senses inwhich the “weak bracketing condition” on this model may be relaxed, corresponding to delimited andundelimited versions of callcc We also establish a relationship between models with control point-ers and the exceptions monad transformer (described in preliminary form in [14]): the latter may becharacterized as introducing the option to either participant of playing an “exception move” — weshow that pointers can replace sequences of such exception moves, which are then hidden, yielding

mod-els

Another approach in [20] also uses an exceptions monad on a category of games — the object ing to correctly capture the behaviour of exceptions passed as names using “nominal game semantics”.This appears to be consistent with our approach, which simplifies the nominal aspect of control effects

be-in order to focus on the complexities of control flow Laurent’s model of classical logic [15] uses ers ina setting which also has connectionswith controloperators via the Curry–Howard correspondencefor classical logic; however, the connection with the control pointers described here seems rather indi-rect

point-2 Ahierarchyofeffectfulprogramminglanguages

Weshalldescribeasimply-typedfunctional metalanguagebasedon[18],extendedwithminimalsyntaxrequiredfortheintendedinterpretationofsideeffects.Workinginthecomputationalλ-calculus,ratherthan

inacall-by-value λ-calculus(asin[1], forexample)allowsrepresentation ofthecontinuationsand monadtransformers withinourmetalanguage,while havingawell-understoodrelationshipwithcall-by-name andcall-by-value languageswitheffects

of typeA tocomputationsoftypeT Thustypesaregivenbythegrammar:

We write 1 forthe unittype 0+ 1,com for thecorresponding computationtype1, and ⊥ for the“emptycomputationtype”0

Trang 4

Γ,x:A x:A Γvoid(M):TΓM:0

ΓM:A

Γreturn(M):A ΓM:AΓlet x=M in N:B Γ,x:A N:B

Γ∗:A+1 Γinj(M):A+1ΓM:A ΓL:A+1Γcase L as x.M or N:T Γ,x:A M:T ΓN:T

Γ,x:A M:T

Fig 1 Typing judgements for λ C.

[[∗ : A + 1]]Γ = u[[Γ]]; in r(u is the terminal morphism).

[[x i : A i]]x1:A1, ,x n :A n = π i

[[inj(M ) : A + 1]]Γ = [[M : A]]Γ ; in l

[[λx.M : A → T ]]Γ = Λ([[M : T ]] Γ,x:A)

[[void(M ) : T ]]Γ = [[M : 0]]Γ; i [[T ]] (i is the initial morphism).

[[return(M ) : A]]Γ = [[M : A]]Γ; η [[A]] (η : 1 → T is the unit of T)

[[M N : T ]]Γ = [[M : A → T ]]Γ, [[N : A]]Γ; eval [[A]],[[T ]]

[[case L as x.M or N : T ]]Γ = [[Γ]], [[L : A + 1]]Γ; d; [[[ M : T ]] Γ,x:A , [[N : T ]]Γ ]

(d is the distribution of product over coproduct).

[[let x = M in N : B]]Γ = [[Γ]], [[M : A]]Γ; t [[Γ]],[[A]] ; [[N : B]] ∗ Γ,x:A

Fig 2 Interpretation of terms in a λ C-model.

let x = M in M | void(M) | M M | case L as x.M or M

where C ranges over aset of typed side-effecting constants,detailed below.Typing judgements aregiven

by the rules in Fig 1 We write M ; N for let x = M in N , if x is not free in M or N , and skip forreturn(∗): com

Givenaλ C-model(C,T),thetypesareinterpretedasobjectsofC:[[0] = 0 (theinitialobject)[[A+ 1] =

[[A]+ 1,[[A] = T[[A]] and[[A → T ] = [[A] ⇒ [[T ]].(NotethatC hasexponentialsof[[T ]] foranycomputation

type T )

Terms x1: A1, , x n : A n  M : B areinterpretedasmorphismsfrom[[A1]× .×[[A n]] to[[B]] asdefined

inFig 2, subjectto appropriate denotationsof theside-effecting constants.A functor ofλ C-models from(C,T) to (C  ,T) isafunctorJ : C → C  whichpreserves allstructure(products,coproducts,exponentials,

andthestrongmonad)uptonaturalisomorphism

Computational effects will be introduced viaconstants: new_loc, new_prompt, calldcc and calluccfor declaring general references and prompts, and capturing delimitable and undelimited continuations,

respectively

References are declared with new_locA : (A → (A → com) → B) → B which generates afresh location

Trang 5

forreadingfromandassigningtoa.Althoughreferencesarenotacontroleffect,theyexistinsomeform inmostprogramminglanguageswith controleffects andare relevanttomacroexpressivenessissues[25].Onthesemanticssidetheirinclusionsimplifiestheconstructionofafullyabstractmodel

oflocallydeclaredprompts,andenablesthelattertoberepresentedasflagvariablesinthepresence

ofasingleglobalprompt

Prompts aredeclaredbynew_promptA : ((A → B) → (⊥ → A) → C) → C whichgeneratesafreshprompt

point withp andforescaping tothenearest suchmarkedpoint Asobservedbelow,prompts may

be viewed either as simple idealizations of exceptions or as control delimiters, depending on the control operators with which they interact.

Delimitable continuations arereifiedbytheconstantcalldccA : ((A → B) → A) → A which capturesthe

current continuationupto thenearestenclosing prompt (ifany) andpasses itto itsargument —i.e.intheabsenceofprompts,calldcc behavesasregularcallcc;itisadelimitable ratherthana

Undelimited continuations are reified by calluccA : ((A → B) → A) → A which captures the entire

currentcontinuation(includinganyprompts)asafunctionandpassesittoitsargument.Notethatfirst class continuationsare representedas functions with argument type A rather than A, sincetheycanacceptside-effectingargumentsandtrapraisedprompts

continua-Sincethissyntaxisnotpartofthetermlanguage,itisnotincludedinthetypingsystem,butinformally,

we note that ifa isalocation storing valuesof type A then read(a) and write(a) may be typed with A

be typedwith⊥ → A and A → B (forsomearbitraryB),respectively,andifD[_], E[_] arecontextswithholesoftypeA, thenthrowd(D[ •]) andthrowu(K[D[ •]]) maybe typedwithA → B forsomearbitraryB.

Wewill alsosugarnew_loc λxλy.M as new_loc a in M [read(a)/x, write(a)/y] and new_prompt λxλy.M

asnew_prompt p in M [abort(p)/x, set(p)/y].

Formally,programs (P ), delimitable continuations (D[_])and delimiting continuations (K[_]) aregiven

bythefollowing grammars:

let x = P in P | void(P ) | P P | case P as x.P or P

new_loc| callucc| new_prompt | calldcc

write(a) | read(a) | abort(p) | set(p)

throwu(K[D[ •]]) | throwd(D[ •])

Trang 6

E[case inj(Q) as x.P1or P2], E −→ E[P1[Q/x]], E E[case ∗ as x.P1or P2], E −→ E[P2], E E[let x = return(Q) in P ], E −→ E[P [Q/x]], E E[(λx.P ) Q1 Q n ], E −→ E[P [Q1/x] Q2 Q n ], E E[new_loc P ], E −→ E[(P read(a)) write(a)]], E ∪ {a}

E[new_prompt P ], E −→ E[(P abort(p)) set(p)], E ∪ {p}

E[write(a) P ], E −→ E[skip], E[a → P ] E[read(a)], E −→ E[return(P )], E (E(a) = P ) E[set(p) E p [abort(p) P ]], E −→ E[return(P )], E

E[callucc P ], E −→ E[P throwu(E[ •])], E E[throwu(E [•]) P ], E −→ E  [P ], E

K[D[calldcc P ]], E −→ K[D[P throwd(D[ •])]], E K[D[throwd(D [•]) P ]], E −→ K[D  [P ]], E

Fig 3 Operational semantics.

Note thatany evaluation context is uniquelyexpressibleas the compositionK[D[_]] of adelimiting tinuationandadelimitable continuation.WedenotebyE p[_] anevaluationcontextwithoutaset(p)_ inthespine—i.e

con-E p[_] ::= [_]| let x = E p [_] in P | set(q) E p[_]

whereq = p.

fromtheformertothesetofprograms.The“small-step”reductionrulesforpairsP, E ofaprogramandanenvironmentaregiveninFig 3.Locationandpromptnamesnotoccurringontheleftofaruleareassumedfresh

For programscontaining delimitable continuations, soundness ofthese rulesdepends on wrappinggrams in either a top-level delimiter or an explicit top-level continuation: for a closed term P : com,

pro-we write P ⇓ if P ; (κ ∗),∅ reduces to κ ∗, E for some environment E (where κ is not free in P ). Wenote (without proof) that we could equivalently add top-level delimiters — that P ⇓ if and only if

set(p) let x = P in abort(p) (x),−→ ∗ skip, E for some E. (Using a top-level continuation simplifiestheproofofsoundness.)

Ourlanguagehasthreecontroloperators —new_prompt,calldcc andcallucc.Thuswemayconsiderthe “cube” of eight language fragments which include each combination of these constants — and hencethe corresponding effects In fact, it is easy to see that in the absence of delimiting prompts, calldccand callucc are observationally equivalent, as theysatisfy the sameoperational rules Thus we considerundelimitedcontinuations(callucc)onlyinthecontext ofprompts which maybecaptured (Thischoice

is basedon asemantic insight: extension of ourgame semantics with prompts preserves the denotationalmeaningofcalldcc ratherthancallucc.)

Thisgivessixprogramminglanguagescorrespondingtodistinctcombinationsofcontroleffects:itedContinuations,PromptsanddelimitableContinuations,respectively.Theseformthehierarchydepicted

undelim-inFig 4:thesubscripts correspondto theprecedencebetweeneffects —i.e.L CP hascontinuationswhichcapture prompts,L P C hascontinuationswhich aredelimitedbyprompts andL CP C hasboth.(Theyalsocorrespond tothesequenceofmonadtransformers usedto interpreteachcombinationofeffects.) Foreacheffectcombination W ,we haveacorrespondingnotionof observational approximationand equivalenceonterms of L W: M W N if for all closing L W-contexts C[_] : com, C[M ] ⇓ implies C[N ] ⇓ M ≈ W N if

Trang 7

Fig 4 A hierarchy of programming languages with control operators.

Wedescribeeachlanguagefragmentbriefly,withsomemacrosforrelatedcontroloperators

generalreferencesdescribedin[1]withitsgamesmodel,presentedinaλ C-calculussetting

L C combinesreferenceswithfirst-classcontinuations,asinScheme

L P haspromptswithoutfirst-classcontinuations—inthissetting,set andabort areessentiallysimplecatchandthrowofexceptionsasine.g.Lisp,MLorJava-styleexceptionhandling —i.e.includingcode

to be runif and onlyif agiven exception is raised — canbe expressed by escapingfrom thehandlercontextifanexceptionisnotraised.Forexample,define

handle(e)in M as x in N 

new_prompt(p)in

set(p) (let x = set(e) let y = M in (abort(p) y) in (abort(p) N )).

L CP combines prompts and first-class, undelimitedcontinuations —i.e continuations capture allclosingprompts.Thisisausefulcombination—forinstanceitcanmacro-expressresumable exceptions,

en-whichreturntothepointatwhichtheywereraisedafterhandling.Forexample ifwedefinearesumableexceptione oftypeA toconsistofapromptp eoftypeA andalocation eoftypeA → ⊥,thenwemaydefine:raise_resumable(e)  λx.callucc λk.(write(l e)k); (abort(p e)x)),whichcapturesthecurrentcontinuation and escapes to the nearest prompt, and handle_resumable(e) in M with N  let y = set(p e)M in (read(l e)(N y)) which traps theprompt, handlesit with N and resumesfrom the point

at whichitwasraised

L P C combinesnamed prompts with first-class continuations delimitedby those prompts Interms ofdelimitedcontrol,thiscombinationliesbetween shift and reset[4]—whichdonotcarrylocalnames

at all —and set and cupto [7]— which captures thecontinuation upto aprompt witha matchingname

L CP C combinespromptswithundelimitedanddelimitedcontinuations.Thiscombinationmaybeseen

Anaturalquestion:doesthehierarchyofcontroloperatorscollapseatanypoint—isanyofourlanguages

new_prompt (or, respectively,callucc orcalldcc),butisobservationally equivalent to it.Note thatthis

is stricter than requiring that e.g there is a sound translation from one fragment to another — such(CPS) translationsare described inSection 5 One role for our denotational semantics is incontributing

to the understandingof the relative expressiveness of control effects.In particular, the semantics furnish

Trang 8

counterexamples to the collapse of our hierarchy of control operators of the following kind, proposed byFelleisen[5].

Proposition 2.1 Suppose L W is macro-reducible to L W  Then for all M, N in L W  , M W  N implies

Proposition 2.2 For any M : A and N : B, let x = (calldccA M ) in N and calldccB λk.let x =

(M λy.let x = y in k N ) in N are observationally equivalent in L C and L P C

This equivalence isaversion of therule C lif twhich is akeyaxiom ofSabry and Felleisen’s equationaltheory ofthe λ-calculuswith callcc [23] Asinloc cit theCPS interpretationinSection4canbe used

to establish its soundness with respect to λ C-theory of translated terms However, because undelimitedcontinuationscapture enclosing prompts,the latter canbreak this equivalence, even between terms which

do not contain prompts.LetM1 (callucc1f );skip andM2 callucc1λk.((f λy.y; (k skip));skip).Proposition2.3 The terms M1 and M2 are not equivalent in L CP

Proof LetC[_] = new_prompt(p) in (λf.[_]) N ,whereN : (1 → ⊥) → 1 = λg.set(p) (g (abort(p) ∗)).

ThenC[M1]−→ (callucc λg.set(p) (g (abort(p) ∗)));skip

−→ ∗ (set(p)throw

u(•;skip)(abort(p) ∗));skip

−→ ∗ (abort(p) ∗);skip — i.e.C[M1] throwsanuncaughtexception

butC[M2]−→ ∗call

ucc1λk.((λg.set(p) (g (abort(p) ∗))) λy.y; (k skip));skip

−→ ∗ ((λg.set(p) (g (abort(p) ∗))) λy.y;(throwu(•)skip));skip

−→ ∗ (set(p) (abort(p) ∗);(throwu(•)skip));skip−→ ∗skip. 2

Remark2.4.Thefactthatdynamicallyboundexceptionscannotbemacro-expressedincontrolcalculibased

onfirst-classcontinuationssuchasλ C or λμ iswellknown(seee.g.[22]),althoughtheymaybeimplemented

using ahandler continuation stored ina global reference However,this example shows thatthese calculiare notevensound for reasoningaboutexception-freeprograms ifthere isthe possibility thattheymightinteractwithexceptions.Thisisanimportantpointofdifferencebetweencontrolcalculiandtheequationaltheoryofthecomputationalλ-calculus,whichisbydefinitionrobustinthepresenceofmonadicside-effects

Wenow give anexample showingthat delimitedcontinuationscannot be macro-expressed using limited continuations,via an equivalence of L P termswhich holds in L CP butnot L P C (i.e.it is broken

unde-bycalldcc,butnotbycallucc).Considerλz.new_prompt(p) in set(p) (let y = z in abort(p) y),of type

A → A. This will denote the identity inour semantics of L CP and is therefore equivalent to λz.z in theabsenceofdelimitable continuations.However,thisequivalence canbe brokenbycallcc

Trang 9

Proposition 2.5 λz.new_prompt(p) in set(p) let y = z in (abort(p) y) is not observationally equivalent to λz.z in L P C

Proof Let C[_] = let x= [_](calldcc λk.return(k return(skip))) in x.

d(let x=• in x)return(skip))in x −→ ∗skip

let x = (set(p) let y = (calldcc λk.return(k return(skip))) in (abort(p) y)) in x

definingD[ •]  let y = • in abort(p) y,this reducesto

let x = (set(p) let y = return(throwd(D[ •])return(skip))in (abort(p) y)) in x

— i.e.thisprogramraisesanuncaughtexception 2

3 Gamesemantics

We will construct our monad-transformerinterpretationof control operators from asemantics of L —

aλ C-modelbasedonacategoryofarenasandthread-independent,well-bracketed strategieswith a“liftedsum”monad andadenotationfornew_loc — describedin[3,1],towhichwereferforfurtherdetails

Anarena A isabipartitelabelledforest—atriple A ,  A , λ A ,whereM A isthesetofnodes(moves),

 A ⊆ M A × M A (theenabling relation) is theset of edges, and λ A : M A → {Q, A } is alabelling functionwhich partitionsmovesasanswers (A) or questions (Q),suchthatanswersare enabledbyquestions.Theset of root nodes of the forest is denoted M I

A — these are called initial moves. Partitioning of M A into

and thatPlayermovesareenabledbyOpponentmovesandvice-versa

Key constructionsonarenasare:

• Thedisjointsumofforests(categoricalproduct): A × B = (M A + M B ,  A+ B , [λ A , λ B])

• The graft of A onto the roots of B (categorical exponential): A ⇒ B = (m ∈M I

Ajustified sequence overthearenaA isafinitesequenceoverM Ainwhicheachoccurrenceofanon-initial

(i.e.m  A n).WewriteL AforthesetofjustifiedsequencesonA whicharealternating betweenOpponentand Playermoves.Thepending question (ifany)ofajustifiedsequenceisaprefixdefined:

• pending(sq) = sq if q is aquestion

• pending(sqta) = pending(s),ifa is ananswerjustifiedbyq,

i.e ifplayingaquestionmovepushesitontoa“stack”ofopenquestions,andansweringitpopsit,andallsubsequentmovesoffthestack,thenpending(s) representsthetopofthestackof openquestions

Definition3.1.Astrategyσ onanarenaA isanon-empty,even-prefix-closedsetofeven-lengthalternatingjustified sequencesoverA,satisfyingthefollowingconditions:

Determinacy Ifsa, sb ∈ σ then b = c.

Thread-independence If r, s, t areeven-lengthjustified sequencessuchthatt isaninterleaving ofr and s,

thent ∈ σ ifandonlyifr, s ∈ σ.

Trang 10

Well-bracketing EveryPlayeranswer-moveint ∈ σ isjustifiedbythequestionpendingwhenitwasplayed

—i.e.ifrq · sa isanevenprefixoft inwhicha isjustifiedbyq then pending(rq · s) = rq.

Compositionof σ : A ⇒ B with τ : B ⇒ C is byparallel compositionof σ and τ withhidingof moves

inB:

Definition3.2.Letthesetofinteraction sequences σ |τ consistofthejustifiedsequencest on (A ⇒ B) ⇒ C

TheidentityonA isthe“copycat”strategyonA consistingofevenlengtht ∈ L A⇒Aforwhicheacheven

prefixrestrictstothesamesequenceoneachcopyofA.ThesedefinitionsyieldaCartesianclosedcategory

ofarenasandstrategiesG,inwhichthedisjointsumofarenasistheproduct,andA ⇒ B istheexponential

ofB by A[1]

Following [3], we may define a λ C-model by giving a strong monad on the category of “pre-arenas”obtained by applying the Fam(_) construction (small co-product completion) to G. For any category C,

morphismsinC.Thishasco-products,givenbythedisjointunionofindexedfamilies,andifC isCartesianclosedthenso isFam(C),withdistributiveproducts:

{A i | i ∈ I} × {B j | j ∈ J}={A i × B j | j ∈ I × J}.

{A i | i ∈ I} ⇒ {B j | j ∈ J}={Π i∈I (A i ⇒ B f (i))| f : I → J}.

We maydefine astrong monad on Fam(G) based on the lifted sum construction [17,3] This hasa single(question) root node, beneath which are (answer) nodes a i for each i ∈ I, beneath each of which is theforestA i

Definition3.3 TheliftedsumΣA of A={A i | i ∈ I} isdefinedasfollows:

• M ΣA={q} ∪ {a i | i ∈ I} ∪i∈I M A i

 ΣA={(q, a i)| i ∈ I} ∪ {(a i , m) | i ∈ I, m ∈ M A i } ∪i ∈I M A i

• λ ΣA (m)={(q, Q) } ∪ {(a i , A) | i ∈ I} ∪ [λ A i | i ∈ I].

Asdescribed in[17,3],Σ is aweak, distributive coproduct on G,yielding astrongmonad Σ: Fam(G) →

η = {inj i : A → Σ i ∈I A i },aco-pairing operationsending afamilyofstrategies{σ i : A i → ΣB | i ∈ I} to

[σ i | i ∈ I] {Σ i A i → ΣB},and a(natural)distributivity morphismd : B × Σ i∈I A i → Σ i∈I (B × A i)

To give a semantics of L in (Fam(G),Σ) it therefore suffices to define the denotation of the constantnew_locA : (A → (A → com) → B) → B. This may be derived by composition (in the Kleisli category

of Σ)withthestrategycellA : Σ(Σ[[A] × ([[A] ⇒ Σ1)) definedin[1],whichbehavesasareferencecellwhichreturns onthe left side theargument last assigned on the right,by playingcopycat betweenthe relevantcopies of[[A]] —i.e.currying yieldsamorphismα : ΣA × (A ⇒ Σ1) → (ΣA ⇒ (A ⇒ Σ1) ⇒ ΣB) ⇒ ΣB,

suchthatwemaydefine[[new_loc ] = cell ;α ∗

Trang 11

Fig 5 Hierarchy of lifting, continuation and maybe monads.

4 Monadtransformers andCPSinterpretation

WecannowgiveinterpretationsofcontinuationsandpromptsinFam(G),usingcontinuationsandmaybemonad transformers to construct new monads from the lifted sum Σ Specifically, we have the followingstrongmonads, yieldingλ C-modelsonFam(G):

trans-• 0C = 0,

• (A+ 1)C = A C+ 1,

• A C = (A C → ⊥) → ⊥.

Trang 12

ObservethatthedenotationofA C in(aλ C-model)(C,T) isequalto thedenotationof A in(C,TC).Termsx1: A1, , x n : A n  M : B are translatedastermsx1: A C1, , x n : A C n  M C : B C as follows:

• new_locC = λf.new_loc λa.λb.f (λx.let u = a in x u) λy.λz.b y; z ∗

• new_promptC = λf.new_prompt λa.λb.f (λx.λy.a x) λx.λy.let u = b x in y u

• calluccC = λf.λκ.callucc λk.(f λx.λy.k (x κ)) κ

• calldccC = λf.λκ.(f λx.λy.(x κ)) κ

Notethat(undelimited) callucc istranslatedusinganinstance ofitselftocapturethedelimitingation.Weshowthatevaluation ofprogramsof emptytypeto head-normalformtracks evaluationof theirCPStranslationsinthefollowingsense:

continu-Proposition4.1.For any term M : ⊥, M,−→ ∗ κ Q

1 Q n , E for some E if and only if M C λx.return(x),

−→ ∗ (κ Q C

1 Q C

Proof SeeAppendix 2

From the maybe transformer, we derive a “prompt-passing-style” translation (_)P from L CP to L C

(whichrestrictsto atranslationfrom L P to L).Typesare translatedas follows(note thatthe translation

ofacomputationtypeisacomputationtype):

• 0P = 0,

• (A+ 1)P = A P + 1,

• A P = A P+ 1

ObservethatthedenotationofA P in(C,T) isequaltothedenotationofA in(C,TP)

ThetranslationofL CP termsx1: A1, , x n : A n  M : B as L Ctermsx1: A P

Trang 13

• new_promptP = λf.new_loc a in (write(a) ∗);

(f λx.write(a) inj(x);return(∗))

(λx.(x; let y = read(a) in (write(a) ∗); return(inj(y))))

Theinterpretationoflocalpromptsusesthelocalstateinourunderlyingmodel/metalanguage:eachprompt

generates anewlocationforp andapplies itsargumentto anabort function—which storesitsargument

inp,andraisestheglobalprompt —andaset function—whichtraps theglobal promptand returnsthevaluestoredinp,havingresetitto∗.

Proposition 4.2 For any program M : ⊥, M,−→ ∗ κ Q

1 Q n , E for some E if and only if M P ,−→ ∗

κ Q P1 Q P n , E for some E.

Proof See Appendix 2

Note thatcallucc isinterpreted as aninstance of calldcc, eliminating undelimited continuations.So

bycomposingthecontinuation-passingandprompt-passingtranslations,foreacheffect-combinationW we

mayobtainatranslation(_)W :L W → L andthusaninterpretationof L W in(Fam(G),ΣW):

L CP C C

L CP P

L P C C

L P C

L C P

L

Soundness and adequacy for each of these models is established by reduction to the result for L [1] viasoundness ofthecomponenttranslations(Propositions 4.1 and4.2)

Proposition 4.3 For any program M : com of L W , M ⇓ if and only if [[M ] W = [[skip]W

Proof Consider e.g.the full language L CP C By Propositions 4.1 and 4.2, M ; (κ ∗),−→ ∗ κ ∗, E if andonlyif(M ; κ ∗) CP C λx.return(x) P C λy.return(y),−→ ∗ κ ∗ λx.return(x) P C λy.return(y), E.

BycomputationaladequacyofthesemanticsofL in(Fam(G),Σ)[1](suitablyadjusted),(M ; κ ∗) CP C λx.

return(x) P C λy.return(y),∅ reduces to κ ∗ λx.return(x) P C λy.return(y), E for some E if and only if

[[(M ; κ ∗) CP C] = [[κ ∗]] — equivalently,ifandonlyif[[M ] = [[skip]] 2

Note, however,thatthis interpretationofprompts contains“junk”strategies whicharenotdenotedbyterms Inparticular, our semantics does not capture the privacyof prompt names — if Opponent raises

a prompt then Playercan catch it by handling the global exception and vice-versa (this could arguably

and new_loc(a) in read(a) both fail to converge, the first because it raises an exception which cannot

be caught,the second becauseit reads from an unassigned cell.However, theydenote different strategies(in theformer, Player answersthe opening question,whereas the latteris the empty strategy).Whilst it

is relatively straightforward to characterize propagation of privatelynamed exceptions on their own (see

Trang 14

adifferentrepresentationofstrategies

5 Controlstrategies

Inthissection,wegiveamoredirect gamesemanticsofourhierarchyofcontroloperators.Thiswillmakethe controlflow behaviourof these operators more explicit; inparticular it may be described sufficientlypreciselytoestablishfull abstraction resultsforeachlanguagefragment.Ourmodelextendstherepresenta-tionofinteractiontoallowtheinterpretationoflocally declaredpromptsanddelimitable continuations,byadding control-flowinformation to justified sequencesinthe form of“controlpointers”, whichwereintro-ducedin[12]tointerpretacall-by-namelanguagewithexceptions.Notethat(incontrastwiththemonadicinterpretationof controleffects) these annotations of gamepositions do notrequireany furtherstructure

atthelevelofarenas

Definition5.1.Acontrol sequence s onanarenaA isanalternatingjustifiedsequence|s| on A,togetherwith

|s| toprefixesof s suchthat:

• Each movepointstoaprecedingquestionorε — φ s (t)  t andifφ s (t) = t  m then λ(m) = Q.

• Each answerpointstoitsjustifyingquestion—ifλ(a) = A then φ s (rqta) = rq, whereq justifies a.

• Opponent movespoint toPlayermoves (orε)and vice-versa— φ s (t) iseven-lengthifand onlyif t is

oddlength

satisfyingthethread-independencecondition(i.e.foranycontrolsequencet whichisaninterleavingofevenlengthcontrolsequencesr and s, t ∈ σ ifandonlyifr ∈ σ and s ∈ σ).

Inorder to extend ourdefinition ofcomposition to controlstrategies, we needto define the restrictionoperator oncontrol sequences, to replace “dangling” control pointersto hidden movesby following thembackuntilanunhiddenmoveisreached

Definition 5.2 The set of open questions of a control sequence is a set of non-empty prefixes occurrences)definedas follows:

(move-open(ε)={},

open(sqta) = open(s),ifa isananswermovewith acontrolpointerto sq,

open(stq) = open(s) ∪ {stq} if q is aquestionwithacontrolpointertos.

The set of open moves may be viewed as a representation of the control stack inwhich the currentlyactivecontrolpromptsareinferredfromcontrolpointers.Notethatthependingquestionins isalwaysthemostrecentmoveinopen(s).

We extend the restriction operation to control sequences by requiring that every move in s B has acontrolpointerto the mostrecentpreceding movewhichis both inB and openin s (orto ε, otherwise)

Bydefinition,therefore:

Lemma5.3 For any control sequence s, open(s B) = open(s) B.

Thus we may define the composition of control strategies as in Definition 3.2, for which the proof ofassociativity extendsstraightforwardly viaLemma 5.3 Todefine theidentity control strategy (andother

“copycat”controlstrategies),weintroducethenotionoflocal controlsequence:

Trang 15

Definition 5.4 The set LocA of local control sequences on A consists of controlsequences s such that if

t  E s then φ s (t) = pending(t) —i.e.everyPlayermoveins hasacontrolpointerto itspending question.

Notethatanysequencewhichsatisfiescontrollocalityalsosatisfies(Player)well-bracketing(sinceanswersalways point to their justifying questions).Define the identity controlstrategy idA on A to consist of alllocal controlsequencess on A ⇒ A suchthattheunderlyingjustifiedsequence|s| is inidA

Lemma 5.5.idA is a well-defined identity for composition.

Proof Givenσ : A → B,weneedtoshowthatidA;σ = σ;idB = σ.Forexample,givenevenlengthjustifiedsequences on (A − ⇒ A+)⇒ B,suchthats A − ⇒ A+∈ id Aweneedtoshowthats A+⇒ B = s A − ⇒ B

— i.e they have the same control pointer annotation We establish by induction on s that each copiedquestion played by the identity strategy hereditarily points via the preceding move to the same set ofmoves 2

Thuswehaveawell-definedcategoryG CP ofarenasandcontrolstrategies.Liketheidentity,wemaylift

points toitspendingquestion

Definition 5.6.Givenastrategyσ on A,define thecontrolstrategy σ = {s ∈ Loc A | |s| ∈ σ}.

Lemma5.7.For strategies σ : A → B and τ : B → C, σ; τ = σ; τ.

Proof Givens ∈ σ; τ, |s| ∈ σ; τ andeveryPlayermoveins pointstothependingquestion,andsos ∈  σ; τ

Conversely, givens ∈  σ; τ thenthere exists aninteraction sequence|t| ∈ σ|τ suchthat|s|=|t| A ⇒ C

which maybe decorated withpointersto giveacontrolsequence t suchthateachPlayermoveinA ⇒ C,

and every movein B pointsto the pending question,and each Opponentmove inA ⇒ C pointsto m if

and onlyifitpointsto m in s, sothatt A ⇒ C = s.Thent A ⇒ B ∈ σ and t B ⇒ C ∈ τ andso t ∈ σ|τ,

and hences ∈ σ; τ asrequired 2

Bydefinition,_ preserves theidentityandthusdefinesafaithful,identity-on-objectsfunctorJ CP :G →

G CP sendingeachmorphismσ : A → B to σ.Wemaycharacterisetheimage ofthisfunctoras follows:Definition 5.8.Acontrolstrategyσ is local if σ = {|s| | s ∈ σ}.

Inotherwords,σ isalocalcontrolstrategyifitconsistsoflocalcontrolsequencesand itsbehaviourdoesnot dependon controlpointersfrom Opponent moves.Wedefine asubcategory of G CP by weakening the

localityconditionas follows:

Definition 5.9 A controlsequence s satisfies weak locality if t  E s implies φ s (t) ∈ open(t) — i.e everyPlayermoveins pointstoanopenmove.Astrategyσ isweaklylocal ifeverysequences ∈ σ satisfies thiscondition

Proposition 5.10 If σ : A → B and τ : B → C are weakly local control strategies then σ; τ : A → C is weakly local.

Proof Supposes isacontrolsequenceon(A ⇒ B) ⇒ C, wheres A ⇒ B ∈ σ and s B ⇒ C ∈ τ.Weshow

byinductionons thateachmoveins whichisaPlayermoveineitherA ⇒ B or B ⇒ C hereditarilypoints

to anopenmoveinA or C,byweaklocalityofσ and τ ByLemma 5.3,open(s A ⇒ C) = open(s) A ⇒ C,

Ngày đăng: 19/11/2022, 11:49

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm