• Tidak ada hasil yang ditemukan

8 Discussion and Related Work

Dalam dokumen Programming Languages and Systems (Halaman 80-88)

The behavioural logics considered in this paper are designed for the purpose of clarifying the notion of ‘behavioural property’, and for defining behavioural equivalence. As infinitary propositional logics, they are not directly suited to practical applications such as specification and verification. Nevertheless, they serve as low-level logics into which more practical finitary logics can be trans- lated. For this, the closure of the logics under infinitary propositional logic is important. For example, there are standard translations of quantifiers and least and greatest fixed points into infinitary propositional logic. Also, in the case of global store, Hoare triples translate into logical combinations of modal formulas.

Our approach, of basing logics for effects on behavioural modalities, may potentially inform the design of practical logics for specifying and reasoning about effects. For example, Pitts’evaluation logic was an early logic for general computational effects [18]. In the light of the general theory of modalities in the present paper, it seems natural to replace the built-in and ♦ modalities of evaluation logic, with effect-specific modalities, as in Sect.3.

Thelogic for algebraic effects, of Plotkin and Pretnar [23], axiomatises effect- ful behaviour by means of an equational theory over the signature of effect oper- ations, following the algebraic approach to effects advocated by Plotkin and Power [22]. Such equational axiomatisations are typically sound with respect to more than one notion of program equivalence. The logic of [23] can thus be used to soundly reason about program equivalence, but does not in itself determine a notion of program equivalence. Instead, our logic is specifically designed as a vehicle for defining program equivalence. In doing so, our modalities can be viewed as a chosen family of ‘observations’ that are compatible with the effects present in the language. It is the choice of modalities that determines the equa- tional properties that the effect operations satisfy.

The logic of [23] itself makes use of modalities, calledoperation modalities, each associated with a single effect operations in Σ. It would be natural to replace these modalities, which are syntactic in nature, with behavioural modal- ities of the form we consider. Similarly, our behavioural modalities appear to offer a promising basis for developing a modality-based refinement-type sys- tem for algebraic effects. In general, an important advantage we see in the use of behavioural modalities is that our notion of strong decomposability appears related to the availability of compositional proof principles for modal properties.

This is a promising avenue for future exploration.

A rather different approach to logics for effects has been proposed by Gon- charov, Mossakowski and Schr¨oder [3,16]. They assume a semantic setting in which the programming language is rich enough to contain apure fragmentthat itself acts as a program logic. This approach is very powerful for certain effects.

For example, Hoare logic can be derived in the case of global store. However, it appears not as widely adaptable across the range of effects as our approach.

Our logics exhibit certain similarities in form with the endogenous logic devel- oped in Abramsky’sdomain theory in logical form [2]. Our motivation and app- roach are, however, quite different. Whereas Abramsky shows the usefulness of an axiomatic approach to a finitary logic as a way of characterising denotational equality, the present paper shows that there is a similar utility in considering an infinitary logic from a semantic perspective (based on operational semantics) as a method of defining behavioural equivalence.

The work in this paper has been carried out for fine-grained call-by-value [13], which is equivalent to call-by-value. The definitions can, however, be adapted to work for call-by-name, and even call-by-push-value [11]. Adding type construc- tors such as sum and product is also straightforward. We have not checked the generalisation to arbitrary recursive types, but we do not foresee any problem.

An omission from the present paper is that we have not said anything about contextual equivalence, which is often taken to be the default equiva- lence for applicative languages. In addition to determining the logically defined preorders/equivalences, the choice of the set O of modalities gives rise to a natural definition of contextual preorder, namely the largest compatible pre- order that, on computations of unit type 1, is contained in therelation from Sect.4. The compatibility of V+ established in the present paper means that we have the expected relation inclusionsV V+ ctxt. It is an interesting question whether the logic can be restricted to characterise contextual equiva- lence/preorder. A more comprehensive investigation of contextual equivalence is being undertaken, in ongoing work, by Aliame Lopez and the first author.

The crucial notion of modality, in the present paper, was adapted from the notion ofobservationin [8]. The change from a set of trees of typeN(an observa- tion) to a set of unit-type trees (a modality) allows value formulas to be lifted to computation formulas, analogously topredicate liftingin coalgebra [7], which is a key characteristic of our modalities. Properties ofScott-openness anddecompos- abilityplay a similar role the present paper to the role they play in [8]. However, the notion of decomposability for modalities (Definition11) is more subtle than the corresponding notion for observations in [8].

There are certain limitations to the theory of modalities in the present paper.

For example, for the combination of probability and nondeterminism, one might naturally consider modalities ♦Pr and Pr asserting the possibility and neces- sity of the termination probability exceeding r. However, the decomposability property fails. It appears that this situation can be rescued by changing to a quantitative logic, with a corresponding notion of quantitative modality. This is a topic of ongoing research.

Acknowledgements. We thank Francesco Gavazzo, Aliaume Lopez and the anony- mous referees for helpful discussions and comments.

References

1. Abramsky, S.: The lazy λ-calculus. In: Research Topics in Functional Program- ming, pp. 65–117 (1990)

2. Abramsky, S.: Domain theory in logical form. Ann. Pure Appl. Log.51(1–2), 1–77 (1991)

3. Goncharov, S., Schr¨oder, L.: A relatively complete generic Hoare logic for order- enriched effects. In: Proceedings of the 28th Annual Symposium on Logic in Com- puter Science (LICS 2013), pp. 273–282. IEEE (2013)

4. Hennessy, M., Milner, R.: Algebraic laws for nondeterminism and concurrency. J.

ACM (JACM)32(1), 137–161 (1985)

5. Howe, D.J.: Equality in lazy computation systems. In: Proceedings of the 4th IEEE Symposium on Logic in Computer Science, pp. 198–203 (1989)

6. Howe, D.J.: Proving congruence of bisimulation in functional programming lan- guages. Inf. Comput.124(2), 103–112 (1996)

7. Jacobs, B.: Introduction to Coalgebra: Towards Mathematics of States and Obser- vation. Cambridge University Press, Cambridge (2016)

8. Johann, P., Simpson, A., Voigtl¨ander, J.: A generic operational metatheory for algebraic effects. In: Logic in Computer Science, pp. 209–218 (2010)

9. Ugo, D.L., Gavazzo, F., Levy, P.B.: Effectful applicative bisimilarity: Monads, rela- tors, and the Howe’s method. In: Logic in Computer Science, pp. 1–12 (2017) 10. Lassen, S.B.: Relational Reasoning about Functions and Nondeterminism. Ph.D.

thesis, BRICS (1998)

11. Levy, P.B.: Call-by-push-value: decomposing call-by-value and call-by-name.

Higher-Order Symbol. Comput.19(4), 377–414 (2006)

12. Levy, P.B.: Similarity quotients as final coalgebras. In: Hofmann, M. (ed.) FoSSaCS 2011. LNCS, vol. 6604, pp. 27–41. Springer, Heidelberg (2011).https://doi.org/10.

1007/978-3-642-19805-2 3

13. Levy, P.B., Power, J., Thielecke, H.: Modelling environments in call-by-value pro- gramming languages. Inf. Comput.185(2), 182–210 (2003)

14. Milner, R.: A Calculus of Communicating Systems. Springer, Heidelberg (1982).

https://doi.org/10.1007/3-540-10235-3

15. Moggi, E.: Notions of computation and monads. Inf. Comput.93(1), 55–92 (1991) 16. Mossakowski, T., Schr¨oder, L., Goncharov, S.: A generic complete dynamic logic for reasoning about purity and effects. Formal Aspects Comput.22(3–4), 363–384 (2010)

17. Park, D.: Concurrency and automata on infinite sequences. In: Deussen, P. (ed.) GI-TCS 1981. LNCS, vol. 104, pp. 167–183. Springer, Heidelberg (1981).https://

doi.org/10.1007/BFb0017309

18. Pitts, A.: Evaluation logic. In: Birtwistle, G. (ed.) 4th Higher Order Workshop.

Workshops in Computing, pp. 162–189. Springer, London (1990).https://doi.org/

10.1007/978-1-4471-3182-3 11

19. Pitts, A.: Parametric polymorphism and operational equivalence. Math. Struct.

Comput. Sci.10, 321–359 (2000)

20. Plotkin, G.: LCF considered as a programming language. Theor. Comput. Sci.

5(3), 223–255 (1977)

21. Plotkin, G., Power, J.: Adequacy for algebraic effects. In: Honsell, F., Miculan, M. (eds.) FoSSaCS 2001. LNCS, vol. 2030, pp. 1–24. Springer, Heidelberg (2001).

https://doi.org/10.1007/3-540-45315-6 1

22. Plotkin, G., Power, J.: Notions of computation determine monads. In: Nielsen, M., Engberg, U. (eds.) FoSSaCS 2002. LNCS, vol. 2303, pp. 342–356. Springer, Heidelberg (2002).https://doi.org/10.1007/3-540-45931-6 24

23. Plotkin, G., Pretnar, M.: A logic for algebraic effects. In: Proceedings of the Logic in Computer Science, pp. 118–129 (2008)

24. Pnueli, A.: The temporal logic of programs. In: Proceedings of the 18th Annual Symposium on the Foundations of Computer Science, pp. 46–57 (1977)

25. Thijs, A.M.: Simulation and fixpoint semantics. Ph.D. thesis (1996)

Open Access This chapter is licensed under the terms of the Creative Commons Attribution 4.0 International License (http://creativecommons.org/licenses/by/4.0/), which permits use, sharing, adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons license and indicate if changes were made.

The images or other third party material in this chapter are included in the chapter’s Creative Commons license, unless indicated otherwise in a credit line to the material. If material is not included in the chapter’s Creative Commons license and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder.

Amr Hany Saleh1(B), Georgios Karachalias1, Matija Pretnar2, and Tom Schrijvers1

1 Department of Computer Science, KU Leuven, Leuven, Belgium ah.saleh@cs.kuleuven.be

2 Faculty of Mathematics and Physics, University of Ljubljana, Ljubljana, Slovenia

Abstract. As popularity of algebraic effects and handlers increases, so does a demand for their efficient execution. Eff, an ML-like language with native support for handlers, has a subtyping-based effect system on which an effect-aware optimizing compiler could be built. Unfortu- nately, in our experience, implementing optimizations for Eff is overly error-prone because its core language is implicitly-typed, making code transformations very fragile.

To remedy this, we present an explicitly-typed polymorphic core cal- culus for algebraic effect handlers with a subtyping-based type-and-effect system. It reifies appeals to subtyping in explicit casts with coercions that witness the subtyping proof, quickly exposing typing bugs in pro- gram transformations.

Our typing-directed elaboration comes with a constraint-based infer- ence algorithm that turns an implicitly-typed Eff-like language into our calculus. Moreover, all coercions and effect information can be erased in a straightforward way, demonstrating that coercions have no computa- tional content.

1 Introduction

Algebraic effect handlers [17,18] are quickly maturing from a theoretical model to a practical language feature for user-defined computational effects. Yet, in practice they still incur a significant performance overhead compared to native effects.

Our earlier efforts [22] to narrow this gap with an optimising compiler from Eff [2] to OCaml showed promising results, in some cases reaching even the performance of hand-tuned code, but were very fragile and have been postponed until a more robust solution is found. We believe the main reason behind this fragility is the complexity of subtyping in combination with the implicit typing of Eff’s core language, further aggravated by the “garbage collection” of subtyping constraints (see Sect.7).1

1 For other issues stemming from the same combination see issues #11 and #16 at https://github.com/matijapretnar/eff/issues/.

c The Author(s) 2018

For efficient compilation, one must avoid the poisoning problem [26], where unification forces a pure computation to take the less precise impure type of the context (e.g. a pure and an impure branch of a conditional both receive the same impure type). Since this rules out existing (and likely simpler) effect systems for handlers based on row-polymorphism [8,12,14], we propose a polymorphic explicitly-typed calculus based on subtyping. More specifically, our contributions are as follows:

– First, in Sect.3 we present ImpEff, a polymorphic implicitly-typed calculus for algebraic effects and handlers with a subtyping-based type-and-effect sys- tem.ImpEffis essentially a (desugared) source language as it appears in the compiler frontend of a language like Eff.

– Next, Sect.4presentsExEff, the core calculus, which combines explicit Sys- tem F-style polymorphism with explicit coercions for subtyping in the style of Breazu-Tannen et al. [3]. This calculus comes with a type-and-effect system, a small-step operational semantics and a proof of type-safety.

– Section5specifies the typing-directed elaboration ofImpEffintoExEffand presents a type inference algorithm forImpEffthat produces the elaborated ExEffterm as a by-product. It also establishes that the elaboration preserves typing, and that the algorithm is sound with respect to the specification and yields principal types.

– Finally, Sect.6 definesSkelEff, which is a variant of ExEff without effect information or coercions.SkelEffis also representative of Multicore Ocaml’s support for algebraic effects and handlers [6], which is a possible compilation target of Eff. By showing that the erasure fromExEfftoSkelEffpreserves semantics, we establish thatExEff’s coercions are computationally irrelevant and that, despite the existence of multiple proofs for the same subtyping, there is no coherence problem. To enable erasure,ExEffannotates its types with (type) skeletons, which capture the erased counterpart and are, to our knowledge, a novel contribution.

– Our paper comes with two software artefacts: an ongoing implementation2 of a compiler from Eff to OCaml with ExEff at its core, and an Abella mechanisation3 of Theorems 1, 2, 6, and7. Remaining theorems all concern the inference algorithm, and their proofs closely follow [20].

The full version of this paper includes an appendix with omitted figures and can be found athttp://www.cs.kuleuven.be/publicaties/rapporten/cw/CW711.abs.

html.

2 Overview

This section presents an informal overview of theExEffcalculus, and the main issues with elaborating to and erasing from it.

2 https://github.com/matijapretnar/eff/tree/explicit-effect-subtyping.

3 https://github.com/matijapretnar/proofs/tree/master/explicit-effect-subtyping.

2.1 Algebraic Effect Handlers

The main premise of algebraic effects is that impure behaviour arises from a set of operations such asGetandSetfor mutable store,ReadandPrintfor interactive input and output, orRaisefor exceptions [17]. This allows generalizing exception handlers to other effects, to express backtracking, co-operative multithreading and other examples in a natural way [2,18].

Assume operations Tick : Unit Unit and Tock : Unit Unit that take a unit value as a parameter and yield a unit value as a result. Unlike special built-in operations, these operations have no intrinsic effectful behaviour, though we can give one through handlers. For example, the handler{Tickx k→ (Print “tick”;k unit),Tockx k Print “tock”} replaces all calls of Tick by printing out “tick” and similarly forTock. But there is one significant difference between the two cases. Unlike exceptions, which always abort the evaluation, operations have a continuation waiting for their result. It is this continuation that the handler captures in the variablekand potentially uses in the handling clause. In the clause for Tick, the continuation is resumed by passing it the expected unit value, whereas in the clause for Tock, the operation is discarded.

Thus, if we handle a computation emitting the two operations, it will print out

“tick” until a first “tock” is printed, after which the evaluation stops.

2.2 Elaborating Subtyping

Consider the computation do x← Tick unit;f x and assume that f has the function type Unit Unit ! {Tock}, taking unit values to unit values and perhaps calling Tock operations in the process. The whole computation then has the typeUnit!{Tick,Tock}as it returns the unit value and may callTick andTock.

The above typing implicitly appeals to subtyping in several places. For instance, Tick unit has type Unit !{Tick} and f x typeUnit !{Tock}. Yet, because they are sequenced withdo, the type system expects they have the same set of effects. The discrepancies are implicitly reconciled by the subtyping which admits both {Tick}{Tick,Tock}and{Tock}{Tick,Tock}.

We elaborate the ImpEff term into the explicitly-typed core language ExEff to make those appeals to subtyping explicit by means of casts with coercions:

dox←((Tick unit)γ1); (f x)γ2

A coercion γ is a witness for a subtyping A ! Δ A ! Δ and can be used to cast a term c of typeA ! Δ to a term c γ of typeA ! Δ. In the above term, γ1 andγ2 respectively witness Unit !{Tick}Unit !{Tick,Tock} and Unit !{Tock}Unit! {Tick,Tock}.

2.3 Polymorphic Subtyping for Types and Effects

The above basic example only features monomorphic types and effects. Yet, our calculus also supports polymorphism, which makes it considerably more

expressive. For instance the type of f in let f = (fung→g unit) in . . . is generalised to:

∀α, α.∀δ, δ.αα ⇒δδ(Unit→α!δ)→α !δ

This polymorphic type scheme follows the qualified types convention [9] where the type (Unit α ! δ) α ! δ is subjected to several qualifiers, in this caseαα and δδ. The universal quantifiers on the outside bind the type variablesαandα, and the effect set variablesδandδ.

The elaboration of f into ExEff introduces explicit binders for both the quantifiers and the qualifiers, as well as the explicit casts where subtyping is used.

Λα.Λα.Λδ.Λδ (ω: αα)(ω:δδ).fun(g:Unit→α!δ)(gunit)(ω!ω) Here the binders for qualifiers introduce coercion variablesωbetween pure types andωbetween operation sets, which are then combined into a computation coer- cionω!ω and used for casting the function applicationgunitto the expected type.

Suppose that h has type Unit Unit!{Tick} and f h type Unit!{Tick,Tock}. In theExEffcalculus the corresponding instantiation off is made explicit through type and coercion applications

fUnit Unit{Tick} {Tick,Tock1γ2h

where γ1 needs to be a witness for Unit Unit and γ2 for {Tick}

{Tick,Tock}.

2.4 Guaranteed Erasure with Skeletons

One of our main requirements for ExEff is that its effect information and subtyping can be easily erased. The reason is twofold. Firstly, we want to show that neither plays a role in the runtime behaviour of ExEffprograms. Secondly and more importantly, we want to use a conventionally typed (System F-like) functional language as a backend for the Eff compiler.

At first, erasure of both effect information and subtyping seems easy: simply drop that information from types and terms. But by dropping the effect variables and subtyping constraints from the type of f, we get ∀α, α.(Unit α) →α instead of the expected type∀α.(Unit→α)→α. In our naive erasure attempt we have carelessly discarded the connection between αand α. A more appro- priate approach to erasure would be to unify the types in dropped subtyping constraints. However, unifying types may reduce the number of type variables when they become instantiated, so corresponding binders need to be dropped, greatly complicating the erasure procedure and its meta-theory.

Fortunately, there is an easier way by tagging all bound type variables with skeletons, which are barebone types without effect information. For example, the skeleton of a function type A→ B !Δ isτ1 →τ2, whereτ1 is the skeleton of

Aandτ2the skeleton ofB. InExEffevery well-formed type has an associated skeleton, and any two types A1 A2 share the same skeleton. In particular, binders for type variables are explicitly annotated with skeleton variablesς. For instance, the actual type off is:

∀ς.∀(α:ς),(α :ς).∀δ, δ.αα⇒δδ(Unit→α!δ)→α !δ The skeleton quantifications and annotations also appear at the term-level:

Λς.Λ(α:ς)(α:ς).Λδ.Λδ(ω:αα)(ω:δδ). . . .

Now erasure is really easy: we drop not only effect and subtyping-related term formers, but also type binders and application. We do retain skeleton binders and applications, which take over the role of (plain) types in the backend language.

In terms, we replace types by their skeletons. For instance, forf we get:

Λς.fun(g:Unit→ς)→gunit : ∀ς.(Unit→ς)→ς

Fig. 1.ImpEffSyntax

Dalam dokumen Programming Languages and Systems (Halaman 80-88)