Remerciements

Je remercie tous les membres du jury de s'être déplacés pour assister à cette soutenance. Merci en particulier à Shin-Ya et Bas pour leur relecture attentive de ce manuscript et leurs multiples questions pertinentes.

Je tiens d'abord à remercier les multiples personnes qui m'ont introduit à la recherche, académique ou pas, notamment Masahito Hasegawa, Paul-André Melliès, Rosen Diankov et Nikhil Swamy qui m'ont encadré au cours de long stages à Kyoto, Paris, Tokyo et Seattle. Les points de vue variés sur la recherche qu'ils ont partagés m'ont fortement inspiré tout au long de ma thèse.

L'équipe Prosecco m'a accueilli malgré un parcours et un bagage scienti que un peu étranger à leur coeur de métier. Si j'ai pu me sentir perdu, plongé dans des domaines pour moi très exotiques, je remercie tous les membres de l'équipe pour le lieu stimulant qu'ils ont fait vivre : Nadim pour ses protocoles agrémentés de chatons kawaii, Marc pour ses questions sur G(rothendieck)tk, Natalia, Ben et Marina pour les multiples occasions de débugger un contexte SMT défaillant, Tomer pour son ambition de réécrire F* en λ-prolog, Victor pour son stoïcisme devant des tâches qui en auraient rebuté plus d'un, Danel pour ses explications des catégories de compréhension avec ou sans modalités, Mathieu pour son soutient discret et e cace, Karthik et Bruno pour avoir monté Prosecco. Au fur et à mesure, Théo, Rob, Carmine, Jérémy, Blipp, Éric, Exe, Antoine et autres trublions sont venus mettre leur grain de sel, faisant parfois évoluer l'équipe au point que les termes d'(∞, 1)-catégories, d'univalence, de paramétricité et de recollement d'Artin sont devenus fréquents dans un certain groupe de lecture. Je n'oublie pas Jonathan et Guido, membres intermittents, passant régulièrement comme des spoutniks et dont les apports scienti ques comme gastronomiques ont considérablement enrichi mon expérience de doctorant.

Cette thèse n'a aussi été possible qu'avec le soutient continu des doctorants (sur plusieurs générations) et chercheurs de l'ex-pôle PPS que j'ai continué à hanter pendant longtemps, au point de se demander dans quel laboratoire j'e ectuais ma thèse. Je me dois donc de remercier Daniel et ses éponges, Rémi et ses émois, les catégories terroristes Pierre, Chaït, Axel, Leonard, ainsi que Théo, Léo, Zeïnab, Nicolas, Victor, Tomaso, Simona qui ont organisé gâteaux, bières et autres séances de cinéma clandestines.

Merci à Gabriel pour m'avoir régulièrement poussé à me mettre au boulot et notamment lancé un grand mouvement d'étude sur le µμ (à poil ras) et la polarisation. Ce fut l'occasion de faire connaissance avec les membres de l'équipe Galinette dont l'expérience en µμ et en Coq m'a souvent été d'une grande aide. Merci donc à Guillaume, Xavier, Étienne, Théo, Simon et à l'ensemble de cette formidable équipe.

L'environnement scienti que riche de Paris m'a certainement fourni l'occasion de cultiver ma compréhension de domaines connexes, que ce soit des catégories de modèle ou du ROP 1 , cependant je me dois de remercier les organisateurs d'évènements extra-muros, en particulier des rencontres ChoCoLa à Lyon, des réunions GeoCal-LAC puis plus tard de celles de SCalP et LHC pour permettre un brassage plus large des idées et des personnalités. À l'international e , les rencontres EUTYPES m'ont beaucoup apporté, et m'ont permis entre autres d'alourdir mon bilan carbone.

1 Return Oriented Programming iii iv Je ne sais comment remercier Cătălin pour avoir accepté d'encadrer ma thèse dans un contexte ubuesque 2 sur un sujet aussi prometteur qu'ardu. Il n'y pas de doute que son suivi, ses conseils, sa motivation et son travail acharné ont permis au volume sous vos yeux de voir le jour.

Les nombreuses années passées à Paris ont été rythmées par l'intervention de nombreux joyeux lurons : merci Abel, Julie, Basile, Ambre, Annali, Guillaume, Ulysse, Anaël, Najib, Athanarik pour les expériences de cuisine un peu folle, les après-midi jeux et d'avoir été là.

Un remerciement très particulier à Marina et Jun qui ont subi à longueur d'années des expérimentations culinaires plus ou moins douteuses en fonction de mes sautes d'humeur fréquentes; à Anya qui m'a fait découvrir tant de choses que j'ignorais.

2 Je prétendais étudier la cohomologie des faisceaux et ai soudainement décidé de partir programmer des robots déplaceur de boulons au Japon, comme quoi la cuisine mène à pleins de choses. . .

This manuscript is not dedicated to the art of cuisine, but to the science of computers and more precisely to programs, which are the recipes used by computers. From this point of view, a computer can be seen as a cook faithfully executing each step of a recipe in order to obtain a result. Since we are a picky customer, we do not accept just any kind of result though, and require the best quality, provided by formally veri ed programs.

The rst task of program veri cation is to describe the expected behaviour of a program, via a formal description called a speci cation. The crux of program veri cation is to prove that the behavior of the program indeed satis es the speci cation. For a simple example, consider the following program computing the Fibonacci sequence: What can we say about this program? From a mathematical point of view, we can solve the recursive equation u n+2 = u n+1 + u n with initial conditions u 0 = 0, u 1 = 1, obtaining the closed form u n = 1 √ 5 (ϕ nϕ n ) where ϕ = 1+ √ 5 2 and ϕ = -1 ϕ . We could then specify that for any n ≥ 0, b n computes u n , and to obtain a complete speci cation of b, we should also explain what happens for negative integers n < 0, namely that it returns n. However, formally proving such a precise speci cation can be di cult. In this particular case, it entails replaying the standard mathematical proof providing the closed form u n , an accessible but time consuming task. In certain scenarios, it might be enough for our purpose to prove a weaker, less precise speci cation, but much easier to show, for instance that b n ≥ 0. In general, there are many di erent speci cations that we can assign to a program for the purpose of veri cation. Now, suppose that some careless programmer were to write the following variation to compute the Fibonacci sequence: This implementation does not change much from the previous, the condition n ≤ 1 was just replaced by n = 0 || n = 1 and, for n ≥ 0 it actually computes the same values. However, if you were to feed a negative integer, say -38, to b', the following in nite reduction sequence unrolls . . . and will continue executing for quite some time, since it will never hit the base case n == 0 || n == 1. We call such a program that sometimes never returns a value a divergent or partial program, by opposition to a total program that always answers after computing for a nite -but arbitrary -number of steps. While this simple example is quite contrived, considering partial programs is a necessity if we want to implement expressive programs such as an evaluator for a Turingcomplete programming language. And from a program veri cation perspective, it means that we need to be able to specify such partial programs and consequently speci cations should have the ability to specify not only the value a program may return but also how partial it is. This is the point where computations take their independence from the idealistic world of pure, total, mathematical functions. Concretely, side-e ects can be used to distinguish the evaluation strategy employed to evaluate a program, so the latter can no longer be naively modelled as function returning a result. Nonetheless, to achieve anything, a useful program must at some point trigger e ects to interact with the external world. Examples of such interactions are querying a user for input, storing persistent data to the le system, or exploring an unbounded search space, possibly nondeterministically. Since e ects are ubiquitous in our daily programming activity, we would like to understand them deeply. We seek a solid and general theory explaining what e ects are, how we can use them to write useful programs, and most importantly, how we can reason about the properties of such programs. As such, our work builds upon the general model of side-e ects as computational monads [START_REF] Moggi | Computational lambda-calculus and monads[END_REF], which can naturally capture e ects such as stateful computations, exceptions, non-termination, nondeterminism, or probabilities.

The aim of this thesis is to deepen our conceptual understanding of these monadic e ects and to work out the general principles of program veri cation for programs with arbitrary monadic side-e ects. To this end, we study a few areas of program veri cation and systematically associate to a program logic (i.e., a deductive system for proving assertions about programs) an algebraic semantic counterpart. These algebraic objects consist of various generalizations of monads and morphisms preserving the monadic structure. In the following sections we introduce these objects and how they help program veri cation: speci cation monads to describe the behaviour of programs, e ect observation to connect computations with speci cations, and Dijkstra monads to bind the three together, as well as their relational variants. A running idea throughout is that that the common algebraic laws underlying the semantics of various program logics for speci c e ects provides insight into the nature of e ects themselves.

Reasoning About Monadic Programs

Many approaches have been proposed for formally verifying e ectful programs. In an imperative setting, [START_REF] Hoare | An axiomatic basis for computer programming[END_REF] introduced a program logic to reason about properties of programs. The judgments of this logic are Hoare triples of the form { pre } c { post }. Intuitively, if the precondition pre is satis ed, then running the program c leaves us in a situation where post is satis ed, provided that c terminates. For imperative programs-i.e., statements changing the program's state-pre and post are predicates over the initial and the nal state. These Hoare triples are derived using inference rules such as

H S { q } skip { q } H S { pre } c 1 { q } { q } c 2 { post } { pre } c 1 ; c 2 { post } (1.1)
Hoare's approach can be directly adapted to the monadic setting by replacing imperative programs c with monadic computations m : M A. This approach was rst proposed in Hoare Type Theory (Nanevski et al., 2008a,b), where a Hoare monad of the form HST pre A post augments the state monad over A with a precondition pre : S → P and postcondition post : A × S → P. So while preconditions are, like in Hoare logic, predicates over initial states, postconditions are now predicates over both nal states and results. Using this Hoare monad, we can re ect the inference rules of Hoare logic inside the typing judgements HTT S Γ skip : HST (λs. post ((), s)) 1 post HTT S Γ c 1 : HST pre 1 q Γ c 2 : HST (λs. q ((), s)) A post Γ c 1 ; c 2 : HST pre A post where we write skip for the monadic program returning () and c 1 ; c 2 for the sequential composition of monadic programs dropping the (irrelevant) result of c 1 . While this approach was successfully extended to a few other e ects [START_REF] Delbianco | Hoare-style reasoning with (algebraic) continuations[END_REF]Nanevski et al., 2008a[START_REF] Nanevski | Dependent type theory for veri cation of information ow and access control policies[END_REF], until our work, there was no general story on how to de ne a Hoare monad or even just the shape of pre-and postconditions for an arbitrary e ect.

A popular alternative to proving properties of imperative programs is [START_REF] Dijkstra | Guarded commands, nondeterminacy and formal derivation of programs[END_REF] weakest precondition calculus. The main insight of this calculus is that from the syntax of a program c we can directly compute a weakest precondition wp(c, post) such that the formula pre ⇒ wp(c, post) is valid if and only if the triple { pre } c { post } is derivable, which allows to partly automate the veri cation process by reducing it to a logical validity problem. [START_REF] Swamy | Verifying higher-order programs with the Dijkstra monad[END_REF] observed that it is possible to adopt Dijkstra's technique to ML programs with state and exceptions elaborated to monadic style. They propose a notion of Dijkstra monad of the form DST A wp, classifying stateful programs with exceptions returning values in A and where wp is a predicate transformer that speci es the behavior of the monadic computation. These predicate transformers are represented as functions that, given a postcondition on the nal state, and either the result value of type A or an exception of type E, calculate a corresponding precondition on the initial state. The type of such predicate transformers can be written as follows (where P is the type of propositions):

W ML A = ((A + E) × S → P) postconditions → (S → P) preconditions .
In subsequent work, [START_REF] Swamy | Dependent types and multi-monadic e ects in F*[END_REF] extended this to programs that combine multiple sube ects. They compute more e cient weakest preconditions with respect to the actual e ects of the code, instead of verifying everything using W ML above. For example, pure computations are given speci cations of type:

W Pure A = Cont P A = (A → P) → P, while stateful (but exception-free) computations are veri ed using speci cations of type:

W St A = (A × S → P) → (S → P). An important observation underlying this technique is that predicate transformers have a natural monadic structure ensuring that analogs of the inference rules 1.1 hold for each of these settings. For instance, it is not hard to see that the predicate transformer type W Pure is simply the continuation monad with answer type P, that W St is the state monad transformer applied to W Pure , and that W ML is the state and exceptions monad transformers applied to W Pure . While this observation was historically made for W Pure and W St , where the monad structure is more obvious, we realized in retrospective that the pre-/post-conditions used in Hoare logic also have such a monadic structure inducing exactly the rules (1.1):

PP St A = (S → P) × (A × S → P) Generalizing over these examples, we introduce the notion of speci cation monad, capturing abstractly this class of monads expressing speci cations. These monadic structures are a key ingredient of both Hoare monads and Dijkstra monads, providing a uni ed view of the specications indexing these objects. Moreover, we investigate generic constructions of such specication monads, in particular based on monad transformers, which reveals a rich theory that can account for speci cations for a variety of side-e ects.

Understanding Dijkstra monads

Generalizing over the previous discussion, a Dijkstra monad D A w is a monad-like structure that classi es e ectful computations returning values in A and speci ed by w : WA, where W is what we call a speci cation monad. 1 The pragmatic observation that Dijkstra monads and the associated veri cation methodology is e ective for various e ects [START_REF] Swamy | Dependent types and multi-monadic e ects in F*[END_REF] led us to a quest to generalize Dijkstra monads to arbitrary monadic e ects. The main questions to answer are: Given a monadic e ect, how do we nd a suitable speci cation monad for it? Is there a single speci cation monad that we can associate to each e ect? If not, what are the various alternatives, and what are the constraints on this association for obtaining a proper Dijkstra monad?

Our Dijkstra Monads for Free (DM4Free) approach [START_REF] Ahman | Dijkstra monads for free[END_REF] provides partial answers to these questions: from a computational monad de ned as a term in a metalanguage called DM, a (single) canonical speci cation monad is automatically derived through a syntactic translation. Unfortunately, while this approach works for stateful and exceptional computations, it cannot handle several other e ects, such as input-output (IO), due to various syntactic restrictions in DM.

To better understand and overcome such limitations, we observe that a computational monad in DM is essentially a monad transformer applied to the identity monad; and that the speci cation monad is obtained by applying this monad transformer to the continuation monad Cont P A = (A → P) → P. Returning to the example of state, the speci cation monad W St A can be obtained from the state monad transformer StT M A = S → M (A × S). This reinterpretation of the DM4Free approach sheds light on its limitations: For a start, the class of supported computational monads is restricted to those that can be decomposed as a monad transformer applied to the identity monad. However, this rules out various e ects such as nondeterminism or IO, for which no practical monad transformer is known [START_REF] Adámek | Coproducts of monads on set[END_REF][START_REF] Bowler | Exploring the boundaries of monad tensorability on set[END_REF][START_REF] Hyland | Combining algebraic e ects with continuations[END_REF].

Further, obtaining both the computational and speci cation monads from the same monad transformer introduces a very tight coupling. In particular, in DM4Free one cannot associate different speci cation monads with a particular e ect. For instance, the exception monad Exc A = A + E is associated by DM4Free with the speci cation monad W Exc A = ((A + E) → P) → P, by applying the exception monad transformer ExcT M A = M (A + E) to Cont P . This specication monad requires the postcondition to account for both the success and failure cases. While this is often desirable, at times it may be more convenient to use the simpler speci cation monad Cont P directly, allowing exceptions to be thrown freely, without having to explicitly allow this in speci cations. Likewise, for IO, one may wish to have rich speci cations that depend on the history of interactions with the external world, or simpler context-free speci cations that are as local as possible. In general, one should have the freedom to choose a speci cation monad that is expressive enough for the veri cation task at hand, but also simple enough so that veri cation is manageable in practice.

Moreover, even for a xed computational monad and a xed speci cation monad there can be more than one way to associate the two in a Dijkstra monad. For instance, to specify exceptional computations using Cont P , we could allow all exceptions to be thrown freely-as explained above, which corresponds to a partial correctness interpretation-but a di erent choice is to prevent any exceptions from being raised at all-which corresponds to a total correctness interpretation. Similarly, for specifying nondeterministic computations, two interpretations are possible for Cont P : a demonic one, in which the postcondition should hold for all possible result values [START_REF] Dijkstra | Guarded commands, nondeterminacy and formal derivation of programs[END_REF], and an angelic one, in which the postcondition should hold for at least one possible result [START_REF] Floyd | Nondeterministic algorithms[END_REF].

The key idea at this point is to decouple the computational monad and the speci cation monad: instead of insisting on deriving both from the same monad transformer as in DM4Free, we consider them independently and only require that they are related by an e ect observation (Katsumata, 2014), i.e., a mapping between two monads that respects their monadic structure. M θ --------→ W computational e ect observation speci cation monad monad

For instance, an e ect observation from nondeterministic computations could map a nite set of possible outcomes to a predicate transformer in (A → P) → P. Given a nite set R of results in A and a postcondition post : A → P, there are only two reasonable ways to obtain a single proposition: either take the conjunction of post v for every v in R (demonic nondeterminism), or the disjunction (angelic nondeterminism). For the case of IO, in our framework we can consider at least two e ect observations relating the IO monad to two di erent speci cation monads, W Fr and W Hist , where E is the alphabet of IO events: W Fr X = (X × E * → P) → P ←-IO -→ W Hist X = (X × E * → P) → (E * → P)

While both speci cation monads take postconditions of the same type (predicates on the nal value and the produced IO events), the produced precondition of W Hist X has an additional argument E * , which denotes the history of interactions (i.e., IO events) with the external world.

How do these e ect observations compare to Dijkstra monads? It turns out that they are two sides of the same coin: from an e ect observation one can reconstruct a Dijkstra monad and conversely. In particular, thanks to the many degrees of freedom allowed by e ect observations, we construct various novel Dijkstra monads in a uniform way.

Relational reasoning for arbitrary e ects

Generalizing unary properties, which describe single program runs, relational properties describe relations between multiple runs of one or more programs (Abate et al., 2019;[START_REF] Clarkson | [END_REF]. Formally verifying relational properties has a broad range of practical applications. For instance, one might be interested in proving that the observable behaviors of two programs are related, showing for instance that the programs are equivalent [START_REF] Blanchet | Automated veri cation of selected equivalences for security protocols[END_REF][START_REF] Chadha | Automated veri cation of equivalence properties of cryptographic protocols[END_REF][START_REF] Ştefan Ciobâcă | A language-independent proof system for full program equivalence[END_REF][START_REF] Godlin | Inference rules for proving the equivalence of recursive procedures[END_REF][START_REF] Hur | The marriage of bisimulations and kripke logical relations[END_REF][START_REF] Hur | A logical step forward in parametric bisimulations[END_REF][START_REF] Kundu | Proving optimizations correct using parameterized program equivalence[END_REF][START_REF] Timany | A logical relation for monadic encapsulation of state: proving contextual equivalences in the presence of runST[END_REF][START_REF] Wang | Verifying equivalence of database-driven applications[END_REF][START_REF] Yang | Relational separation logic[END_REF], or that one re nes the other [START_REF] Timany | Mechanized relational veri cation of concurrent programs with continuations[END_REF]. In other cases, one might be interested in relating two runs of a single program, but, as soon as the control ow can di er between the two runs, the compositional veri cation problem becomes the same as relating two di erent programs. This is for instance the case for noninterference, which requires that a program's public outputs are independent of its private inputs [START_REF] Antonopoulos | Decomposition instead of self-composition for proving the absence of timing channels[END_REF][START_REF] Banerjee | Relational logic with framing and hypotheses[END_REF][START_REF] Barthe | Verifying relational properties using trace logic[END_REF][START_REF] Clarkson | [END_REF][START_REF] Nanevski | Dependent type theory for veri cation of information ow and access control policies[END_REF][START_REF] Sabelfeld | Language-based information-ow security[END_REF][START_REF] Sousa | Cartesian Hoare logic for verifying k-safety properties[END_REF]. The list of practical applications of relational veri cation is, however, much longer, including showing the correctness of program transformations [START_REF] Benton | Simple relational correctness proofs for static analyses and program transformations[END_REF], cost analysis [START_REF] Çiçek | Relational cost analysis[END_REF][START_REF] Qu | Relational cost analysis for functional-imperative programs[END_REF][START_REF] Radicek | Monadic re nements for relational cost analysis[END_REF], program approximation [START_REF] Carbin | Proving acceptability properties of relaxed nondeterministic approximate programs[END_REF][START_REF] He | Verifying relative safety, accuracy, and termination for program approximations[END_REF], semantic di ng [START_REF] Girka | A mechanically checked generation of correlating programs directed by structured syntactic di erences[END_REF][START_REF] Girka | Veri able semantic di erence languages[END_REF][START_REF] Lahiri | SYMDIFF: A language-agnostic semantic di tool for imperative programs[END_REF][START_REF] Wang | Verifying equivalence of database-driven applications[END_REF], cryptographic proofs [START_REF] Barthe | Formal certi cation of code-based cryptographic proofs[END_REF](Barthe et al., , 2013a[START_REF] Barthe | Probabilistic relational veri cation for cryptographic implementations[END_REF][START_REF] Petcher | The foundational cryptography framework[END_REF][START_REF] Unruh | Quantum relational Hoare logic[END_REF], di erential privacy (Barthe et al., 2013b[START_REF] Barthe | Higher-order approximate relational re nement types for mechanism design and di erential privacy[END_REF][START_REF] Gavazzo | Quantitative behavioural reasoning for higher-order e ectful programs: Applicative distances[END_REF][START_REF] Zhang | LightDP: towards automating di erential privacy proofs[END_REF], and even machine learning [START_REF] Sato | Formal veri cation of higherorder probabilistic programs: reasoning about approximation, convergence, bayesian inference, and optimization[END_REF].

As such, many di erent relational veri cation tools have been proposed, making di erent trade-o s, for instance between automation and expressiveness (see section 6.5 for further discussion). In this manuscript, we focus on relational program logics, which are a popular formal foundation for various relational veri cation tools. Relational program logics are proof systems whose rules can be used to prove that a pair of programs meets a rich relational speci cation. As such they are very expressive, and can in particular handle situations in which verifying the desired relational properties requires showing the full functional correctness of certain pieces of code. Yet they can often greatly simplify reasoning by leveraging the syntactic similarities between the programs we relate. Since [START_REF] Benton | Simple relational correctness proofs for static analyses and program transformations[END_REF] seminal Relational Hoare Logic, many relational program logics have been proposed [START_REF] Aguirre | A relational logic for higher-order programs[END_REF][START_REF] Banerjee | Relational logic with framing and hypotheses[END_REF]Barthe et al., 2013b[START_REF] Barthe | Probabilistic relational veri cation for cryptographic implementations[END_REF][START_REF] Barthe | Higher-order approximate relational re nement types for mechanism design and di erential privacy[END_REF][START_REF] Barthe | Product programs and relational program logics[END_REF][START_REF] Carbin | Proving acceptability properties of relaxed nondeterministic approximate programs[END_REF][START_REF] Nanevski | Dependent type theory for veri cation of information ow and access control policies[END_REF][START_REF] Petcher | The foundational cryptography framework[END_REF][START_REF] Qu | Relational cost analysis for functional-imperative programs[END_REF][START_REF] Radicek | Monadic re nements for relational cost analysis[END_REF][START_REF] Sato | Formal veri cation of higherorder probabilistic programs: reasoning about approximation, convergence, bayesian inference, and optimization[END_REF][START_REF] Sousa | Cartesian Hoare logic for verifying k-safety properties[END_REF][START_REF] Unruh | Quantum relational Hoare logic[END_REF][START_REF] Yang | Relational separation logic[END_REF][START_REF] Zhang | LightDP: towards automating di erential privacy proofs[END_REF]. However, each of these logics is speci c to a particular combination of side-e ects that is completely xed by the programming language and veri cation framework; the most popular side-e ects these logics bake in are mutable state, general recursion, cost, and probabilities.

Leveraging the ideas developed in the unary (i.e., non-relational) setting outlined in section 1.2, we distill the generic relational reasoning principles that work for many, if not all, monadic side-e ects and that underlie relational program logics. An important insight is that the notion of speci cation monad can be extended to encompass relational speci cations capturing a shared behaviour or a comparison of the behaviours of two programs, while keeping a compositional monad-like structure. For instance, considering two stateful programs c 1 : St S 1 A 1 and c 2 : St S 2 A 2 , we can specify their behaviour by a pair of a precondition pre : S 1 × S 2 → P relating the initial states of the two programs and a postcondition post : (A 1 × S 1 ) × (A 2 × S 2 ) → P relating their results and nal states. The speci cation monad structure on PP St carries over to the type constructor

PP St rel (A 1 , A 2 ) = (S 1 × S 2 → P) × ((A 1 × S 1 ) × (A 2 × S 2 ) → P)
providing return and bind operations that make PP St rel a relational speci cation monad. These relational speci cations account for pairs of programs returning values in potentially distinct types. Likewise, our framework can relate programs using di erent computational monadic e ects M 1 , M 2 . Relational e ect observations bridge the gap between these two computational monads and a relational speci cation monad W rel : ---------------→ W rel left and right relational relational computational monads e ect observation speci cation monad

M 1 , M 2 θ rel --
The diagram above provides a generic reconstruction of the semantics of relational program logics for arbitrary monadic e ects. The game is then to reconstruct as canonically as possible the inference rules of relational program logics. In particular we observe that a clean separation can be achieved between logical rules independent of the computational e ects, generic monadic rules ensuring compositionality of reasoning induced by the algebraic properties of relational e ect observations, and e ect speci c rules that capture the speci c details of the computational e ects at hand. We show that logical and generic rules can be derived generically, independently of the e ect, and we also provide a recipe for deriving the e ect speci c rules in our framework.

Contributions

We provide a general theory of speci cation monads and e ect observations that is useful for program veri cation. For speci cations we identify various elementary specication monads such as Dijkstra-style predicate transformers as well as Hoare-style pre-/postconditions, and extend the expressivity of these speci cation monads by applying monad transformers. For e ect observations we use relative monad morphisms to provide a exible interpretation of e ects, allowing for instance the choice between total and partial correctness, or between angelic and demonic nondeterminism.

We develop a metalanguage for de ning (speci cation) monad transformers whose design was inspired by the categorical analysis of the relationship between monad transformers and algebras for a monad. We implement the metalanguage in Coq, ultimately providing an e ective method to derive correct-by-construction monad transformers out of a standard monad de nition in the metalanguage.

We provide the rst formal de nition of Dijkstra monads and unveil their close relationship to e ect observations, yielding an e ective method to build a variety of Dijkstra monads, and a practical methodology to verify e ectful code for arbitrary monadic e ects.

We extend the notions of speci cation monads and e ect observations to the relational setting, by introducing a general semantic framework for deriving relational program logics for arbitrary monadic e ects.

We identify and overcome conceptual challenges that prevented previous relational program logics from properly dealing with exceptions. For this, we propose a novel way of combining unary and relational speci cations resulting in the rst relational program logic for exceptions.

We work out a theory of relative monads and use it to provide a uni ed conceptual foundation for speci cation monads and e ect observations both in the unary and relational setting, as well as a presentation of Dijkstra monads as the lifting of relative monads.

This thesis is based on two recent papers: one that appeared at ICFP 2019 (Maillard et al., 2019a) and one currently under submission (Maillard et al., 2019b). This is the culmination of a line of collaborative research in which I was involved during my PhD, which also resulted in other publications [START_REF] Ahman | Dijkstra monads for free[END_REF][START_REF] Ahman | Recalling a witness: Foundations and applications of monotonic state[END_REF][START_REF] Bhargavan | Everest: Towards a veri ed, drop-in replacement of HTTPS[END_REF][START_REF] Grimm | A monadic framework for relational veri cation: Applied to information security, program equivalence, and optimizations[END_REF].

Foundations, Conventions & Notations

We work as much as possible in a constructive metatheory that is loosely modelled on Coq, i.e., Martin-Löf Type Theory with dependent product (x:A) → B, dependent sums (x:A) ×B, a predicative hierarchy of universes Type i and an impredicative universe of proposition P. Throughout the manuscript we assume extensionality for dependent products and sums, and propositions:

f = g : (x : A) → B ⇐⇒ ∀(a : A), f a = g a : B[a/x] u = v : (x : A) × B ⇐⇒ π 1 u = π 1 v : A ∧ π 2 u = π 2 v : B[π 1 u/x] p = q : P ⇐⇒ p ⇐⇒ q
We use the notation 1 to describe a terminal object, either a singleton or the category with one object and one identity arrow depending on the context. The unique morphism to 1 will be written ! X where X is the domain of the morphism. When writing programs, we use either * or () to denote the unique inhabitant of 1.

We naively assume from times to times that equality on arbitrary types is proof-irrelevant, that is we assume Uniqueness of Identity Type (UIP), but we expect that most of the development could be achieved in a metatheory where UIP does not hold by restricting some of our constructions -e.g., indexed algebraic structures with equations such as Dijkstra monads -to types for which it hold, i.e., hsets in the terminology of Homotopy Type Theory [START_REF] Univalent | Homotopy Type Theory: Univalent Foundations of Mathematics[END_REF]. The exception is chapter 3 which uses quite a few classical results from the category theory literature whose constructive nature we ignore. Nevertheless, our implementation in Coq derived from the ideas of that chapter comfort us in the opinion that there should be little obstruction, but a long and hard work to fully formalize it in a constructive metatheory.

Most of the programs illustrating this manuscript are written in a syntax freely inspired from F , with the exception of a few code listings in chapter 4 describing the Coq implementation and consequently written directly in Coq. A substantial amount of the formalization done during the thesis preparation can be found at https://gitlab.inria.fr/kmaillar/ dijkstra-monads-for-all. Sections and proofs that have been formalized end with a .

Outline

We close this introduction with a plan of the coming chapters and their logical dependencies presented in Figure 1.1.

Chapter 2 rst introduces computational monads from a programmer perspective, illustrating various e ects that can be expressed as monads. This is followed by a few examples of monad transformers, which are the traditional way to build the zoo of monads modularly. The main contributions of this chapter are the introduction of speci cation monads and the investigation of e ect observations, essential bridges between computational monads and speci cation monads.

Chapter 3 dives into the categorical world. It starts by recalling the formal theory of monads in a 2-category, introducing the main theoretical concepts enabling an abstract study of monads. The goal of this chapter is then to extend this formal theory to relative monads, a generalization that we achieve thanks to the notion of framed bicategory. A particular instantiation of relative monads in a framed bicategory provides an abstract de nition of speci cation monads amenable to uniform generalizations to other settings such as relational veri cation.

Chapter 4 introduces a methodology for building correct monad transformers. While the theoretical foundations of this methodology is categorical, a more practical approach based on a syntactic meta-language for de ning monad transformers is also introduced. We present the design choices guiding the implementation of this meta-language in the Coq proof assistant, ultimately providing an e ective tool for generating veri ed monad transformers in Coq. Chapter 5 studies Dijkstra monads, a pragmatic approach to program veri cation, based on computation types indexed by speci cations, which is used heavily in the F programming language. After de ning Dijkstra monads, we provide some examples of their wide applicability. The main result of this chapter is the correspondence between Dijkstra monads and e ect observations. A connection with graded monads [START_REF] Fujii | Towards a formal theory of graded monads[END_REF] is sketched using the unifying notion of relative monad.

Chapter 6 enters the realm of relational reasoning. We extend the notions of speci cation monad and e ect observation to that setting, providing a general semantic foundation upon which we can de ne relational program logics for a variety of monadic e ects. The case of exceptions is especially challenging and we explain how our framework can relate programs with exceptions by intertwining unary and relational reasoning.

Chapter 2

Enter the monad This chapter provides a scenery of the basic notions that will be manipulated in the rest of the manuscript. The rst two sections recall the well-known notions of computational monads and monad transformers. We explain how the former encapsulates side-e ects in a uniform algebraic structure and how the latter provides a way to extend monads, achieving some amount of modularity.

We then introduce the novel notion of speci cation monad, a class of monads capturing speci cations for e ectful computations, casting speci cations on the same footing as computations. Finally, our rst tool for veri cation of programs with arbitrary monadic e ects consist of a bridge between computations and speci cations that we call an e ect observation since it encodes a choice observation of a computational e ect in a speci cation monad. Articulating computational monads and speci cation monads with e ect observations turns out to provide a modular method to de ne veri cation system.

We provide examples for each introduced notion, and we will return to these examples throughout the thesis. Most of them have been de ned inside Coq as part of an e ort to provide a mechanized formalization of the content of this manuscript.

Monads for the working programmer

Side e ects are an important part of programming. They arise in a multitude of shapes, be it imperative algorithms, nondeterministic operations, potentially diverging computations, or interactions with the external world. These various e ects can be uniformly captured by the algebraic structure known as a computational monad [START_REF] Benton | Monads and e ects[END_REF][START_REF] Moggi | Computational lambda-calculus and monads[END_REF].

De nition 2.1.1 ( ). A monad is a type constructor M : Type → Type, equipped with two operations

ret : A → M A and bind : M A → (A → M B) → M B
de ned for any types A, B, moreover satisfying the following equations

bind M (ret M a) f = f a bind M m ret M = m bind M m (λx. bind M (f x) g) = bind M (bind M m f ) g for any a : A, f : A → M B, m : M A, g : B → M C.
Intuitively, a computational monad provides a uniform interface MA for computations returning values of type A, for instance state passing functions with result type A for stateful computations. ret M coerces a value v : A to a trivial computation, for instance seeing v as a stateful computation leaving the state untouched. bind M m f sequentially composes the monadic computations m : MA with f : A → MB, for instance threading through the state.

The generic monad interface (M, ret M , bind M ) is, however, not enough to write programs that exploit the underlying e ect. To this end, each computational monad also comes with operations for causing and manipulating e ects. Algebraic operations form an important class of such operations introduced in [START_REF] Plotkin | Notions of computation determine monads[END_REF]. An operation op : A × (M X) B → M X is said to be algebraic when the following equation holds bind (op (a, f )) g = op (a, λb. bind (f b) g) Any such algebraic operation corresponds bijectively to a generic e ect gen op : A → M B, and we will usually employ this latter presentation, often closer to the programming practice. Slightly abusing the terminology and following [START_REF] Piróg | Syntax and semantics for operations with scopes[END_REF], we will also call "operation" more general functions manipulating the e ects provided by a monad, for instance handlers [START_REF] Plotkin | Handlers of algebraic e ects[END_REF]. In the next subsections, we recall a few examples of computational monads and their operations to illustrate the range of computational e ects that monad can account for.

Identity

The simplest monad is the identity monad Id A = A with ret Id a = a and bind Id m f = f m satisfying trivially the monad laws. It does not support any operations but it will be useful when discussing monad transformers in section 2.2.

Partiality

A simple model for partial computations is given by adding a new element that expresses divergence, i.e. Div A = A + {⊥}. Returning a value v is the obvious injection, while sequencing m with f is given by applying f to m if m is a terminating value, or ⊥ if m was already diverging. A partial computation can diverge with the operation Ω : Div 0, implemented as Ω = inr ⊥.

In a classical metatheory, Div A is the free ω-cpo on A, so by standard domain theoretic results [START_REF] Amadio | Domains and lambda-calculi[END_REF]), there is a xpoint operator on Div A 1 . However in a constructive metatheory, e.g., Coq, this simple model is too limited to implement a useful xpoint 1 at least for ω-continuous functions, as provided by Kleene xpoint operation. Various more sophisticated approach can provide solutions to that problem. [START_REF] Delbianco | Hoare-style reasoning with (algebraic) continuations[END_REF] use complete lattices such as P and Knaster-Tarski xpoints. [START_REF] Altenkirch | Partiality, revisited -the partiality monad as a quotient inductive-inductive type[END_REF] directly de ne the free ω-cpo on a type using quotient-inductiveinductive types to describe the standard construction of completing a type with a bottom element, limits of ω-chains and quotienting by the equivalence relation induced by the natural preorder on these.

A di erent approach, more in phase with the topics of this manuscript is to describe the syntax of programs with recursion. [START_REF] Mcbride | Turing-completeness totally free[END_REF] describes a free monad (see subsection 2.1.7) with one operation call playing the role of a recursive call. Given a complete recursive de nition, one can then handle these call operations in any monad supporting partiality. We illustrate how to de ne the skeleton of a function computing the Fibonacci sequence and how such a handling looks like if we were to have a primitive xpoint operation below

type GenRec A B X = | Ret : X → GenRec A B X | Call : a:A → (B a → GenRec A B X) → GenRec A B X let b (n:N) : GenRec N (λ _. N) N= if n ≤ 1 then 1 else Call (n-1) (λ r 1 . Call (n-2) (λ r 2 . Ret (r 1 + r 2 ))) let rec xGenRec 0 (f : (a:A) → GenRec A B (B a)) (m : GenRec A B X) : X = match m with | Ret x → x | Call a k → xGenRec 0 f (k ( xGenRec 0 f (f a))) let xGenRec (f : (a:A) → GenRec A B (B a)) (a:A) : B a = xGenRec 0 f (f a)
In a language without arbitrary xpoints, for instance in Coq, we will instead use xpoints provided by a suitable monad as above.

Exceptions

A computation that can potentially throw exceptions of type E can be represented by the monad

Exc A = A + E.
Returning a value v is the obvious left injection, while sequencing m with f is given by applying f to v if m = Inl v, or Inr e if m = Inr e, i.e., when m raised an exception.

let ret Exc (v:A) : Exc A = Inl v let bind Exc (m : Exc A) (f : A → Exc B) : Exc B = match m with | Inl v → f v | Inr e → Inr e
The operation throw : E → Exc 0 is de ned by right injection of E into Exc 0 = 0 + E. Such an exception can be caught by the handler catch

let catch (m : Exc A) (exc : E → Exc A) : Exc A = match m with | Inl v → Inl v | Inr e → exc e
When we take E = 1, exceptions coincide with the simple model of partiality, the monad

Div A = A + 1.

State

A stateful computation can be modeled as a state-passing function, i.e. This basic account of stateful computations can be re ned by employing a structured state, for instance a store S = Loc → Val where Loc is a set of locations and Val is the type of (ground) value that can be written to the store. In that case, we can also re ne the operations get and put, parametrizing them by accessed location in the store:

let get L (l : Loc) : St Val= λs. (s l,s) let put L (l : Loc) (v : Val) : St 1 = λs. ((), λl'. if l' = l then v else s l')
We will see in section 5.1, this idea is the basis of stateful veri cation in F , however with a much more complex memory model.

Nondeterminism

A nondeterministic computation can be represented by a nite set of possible outcomes, i.e.

NDet A = P fin (A). Returning a value v is provided by the singleton { v }, whereas sequencing m with f amounts to forming the union v∈m f v. This monad comes with an operation pick : NDet B = {true, false}, which nondeterministically chooses a boolean value, and an operation fail : NDet 0 = ∅, which unconditionally fails.

Interactive input-output (IO)

An interactive computation with input type I and output type O can be represented by the inductively de ned monad

type IO A = | Ret : A → IO A | Input : (I → IO A) → IO A | Output : O → IO A → IO A
which describes three possible kinds of computations: either return a value (Ret), expect to receive an input and then continue (Input), or output and continue (Output). The monadic function ret IO constructs a unique leaf tree using Ret and bind IO does tree grafting. The operations perform input and output, and they are directly captured using the corresponding constructors.

Free monads & monads presented by an equational theory

The monads for identity, exception, general recursion GenRec and interactive input-output are examples of free monads, that is monads inductively generated by a set of algebraic operations. Given any signature (S, P ) consisting of a set S of operations and a function P : S → Type assigning to each operation its arity, we can construct the following monad consisting of terms on the signature (S, P ):

type Free S P X = | Ret : X → Free S P X | Op : (s:S) → (P s → Free S P X) → Free S P X let retFree (x:X) : Free S P X = Ret x let rec bindFree (m:Free S P X) (f:

X → Free S P Y) : Free S P Y = match m with | Ret x → f x | Op s k → Op s (λ r. bindFree (k r) f)
with an associated generic e ect let op (s:S) : Free S P (P s) = Op s (λr. Ret r).

More generally, we could consider an equational theory (S, P, E), that is a signature (S, P ) equipped with a set of equations E between terms on the signature (S, P ) -formally a set E of pairs of terms. The monad associated to such a theory is the quotient of terms modulo the equivalence relation induced by the congruence closure of E. All the previous examples of monads are such presented monads. However, in absence of arbitrary e ective quotients which may require instances of axiom of choice [START_REF] Blass | Words, free algebras, and coequalizers[END_REF] or quotient inductive types (QITs) [START_REF] Altenkirch | Type theory in type theory using quotient inductive types[END_REF], we will refrain from using these in a constructive setting and prefer the previous per-e ect presentation of the monads.

Probabilities

A probabilistic computation is a sub-probability distribution on possible outcomes, i.e., for a countable type A, Prob A represents functions f : A → [0; 1] such that a∈A f a ≤ 1. Restricting our attention to countable discrete probabilities, there is a monad structure on Prob known as the Giry monad [START_REF] Giry | A categorical approach to probability theory[END_REF]. Returning a value v is the Dirac distribution at v, that is the distribution assigning weight 1 to v and 0 to any other value. Binding a distribution m : Prob A to a function f : A → Prob B amounts to computing the distribution on B given by λy. Σ x∈supp(m) f x y. We can consider various basic distributions on countable spaces as operations, for instance flip : [0; 1] → Prob B provides a Bernoulli distribution on booleans (with parameter given by the argument) and unif : n : N → Prob (fin n) provides a uniform distribution on the nite type fin n with n elements.

Continuations

Continuation passing style programming is captured by the continuation monad

let Cont R A = (A → R) → R let retCont (a:A) : Cont R A = λk. k v let bindCont (m:Cont R A) (f : A → Cont R B) : Cont R B = λk. m (λ a. f a k)
Returning a value v : A is just evaluating the continuation to this value, while sequencing two continuation-passing computations m : Cont R A and f : A → Cont R B is a matter of building a suitable continuation for m with f . The continuation monad hosts an operation call_cc:

let call_cc (f : (A → Cont R R) → Cont R R) : Cont R A = λk. f (λ a. retCont (k a)) (λ r. r)
The continuation monad is a canonical example of a monad without rank, meaning that it is not presentable by a (small) theory. Intuitively, this is due to the fact that we would need operations of arbitrary arity to present the continuation monad.

Taming the monad zoo: a rst glance at monad transformers

The previous section presented a variety of computational monads covering most of the e ect spectrum. However programs usually use more than a single e ect at a time. An important question thus is how to combine these e ects and the corresponding monads.

This question is actually harder than one could expect at rst. Indeed, given two monads M 1 , M 2 there might be one way to compose them, or multiple ways to do so, or even none.

The various ways to compose M 1 and M 2 are encoded by distributive laws [START_REF] Beck | Distributive laws[END_REF]. Finding distributive laws for every pair of monads one wants to compose in a program is not only tedious but hardly practical. Two approaches try to bypass this problem and recover some amount of modularity.

One canonical way to compose monads can be obtained by restricting our attention to monads arising from algebraic e ects, that is e ects described only in terms of algebraic operations and equations between these operations [START_REF] Hyland | Combining e ects: Sum and tensor[END_REF].

Otherwise, instead of insisting on composing two monads, we can consider monad transformers extending a base monad with new operations. Concretely, monad transformer T maps a monad M to a monad T M and provides for any type A a coercion lift T : M A → T M A materializing how T M extends M. Since we need to consider monads not arising from algebraic e ects, in this manuscript we take in this second approach. The de nition and construction of monad transformers is studied in depth in chapter 4. In this section, we informally present examples of such transformers. As a particular case, applying a monad transformer T with the identity monad Id provides a plain monad, often corresponding to one described in the previous section.

State

The state transformer StT on a xed type of states S extends a monad M using state passing

StT M A = S → M(A × S) to provide operations get : 1 → StT M S and put : S → StT M1.
The lifting operation is de ned by

let liftStT (m : M A) : StT M A = λs. bind M m (λ a. ret M (a,s))

Exceptions

The exception transformer ExcT adds a set of exceptions E to the possible results of a monad

M, that is ExcT M A = M(A + E), providing an operation throw : E → ExcT M 0. Lifting a computation from M to ExcT M is de ned as let liftExcT (m:M A) : ExcT M A = bind M m (λ a. ret M (Inl a))

Reader, writer and other update transformers

If we want to extend a computation with a read-only environment S, the reader transformer

RdT M A = S → M A
UpdT M A = S → M(A × O)
The monad structure on UpdT M and the lift from M are given by let retUpdT (a:A) :

UpdT M A = λs. ret M (a, e) let bindUpdT (m:UpdT M A) (f:A → UpdT M B) : UpdT M B = λs 0 . bind M (m s 0 ) (λ (a, o 1 ). bind M (f a (o 1 s 0 )) (λ (b, o 2 ). ret M (b, o 2 * o 1 ))) let liftUpdT (m:M A) : UpdT M A = λs. bind M m (λ a. ret M (a, e))
The reader transformer arises as the update monad associated to the pair (S, 1), where the trivial monoid 1 acts on S by identity. The writer transformer arises as the pair (1, list O) where the free monoid list O acts trivially on the unit state.

Monotonic state and dependent update transformers

Moving to a dependently typed example, the monotonic state transformer MonStT is a re nement of the state transformer where the state updates are restricted along a xed preorder on states ⊂ S × S:

MonStT M A = (s 0 : S) → M (A × { s 1 : S | s 0 s 1 })
As advocated by [START_REF] Ahman | Recalling a witness: Foundations and applications of monotonic state[END_REF], only extending the computational monad with monotonic manipulations of stateful could enable monotonic reasoning, a cheap but e cient method to prove various stateful properties.

The monotonic state transformer can be seen as an instance of a dependent update transformer, a generalization of update transformers where the parametrizing monoid O is replaced by a dependent family P : S → Type indexed by the states and an adequate notion of action, forming together a directed container (S, P) [START_REF] Ahman | Update monads: Cointerpreting directed containers[END_REF]. For a state s : S, the type P s describes the possible way to act in state s. The data of a directed container (S, P) actually correspond to a category where S is the object set and P s are the morphism with domain s. The dependent update monad transformer maps a monad M to a monad on the carrier

DUpdT M A = (s : S) → M(A × P s).
The case of monotonic state transformer is recovered by a directed container structure on the pair (S, λs 0 . { s 1 : S | s 0 s 1 }).

Speci cations from monads

As explained in section 1.1, the realization that predicate transformers form monads [START_REF] Ahman | Dijkstra monads for free[END_REF][START_REF] Jacobs | Dijkstra monads in monadic computation[END_REF][START_REF] Jacobs | Dijkstra and Hoare monads in monadic computation[END_REF][START_REF] Swamy | Verifying higher-order programs with the Dijkstra monad[END_REF][START_REF] Swamy | Dependent types and multi-monadic e ects in F*[END_REF] is the starting point to provide a uniform notion of speci cations. This is true not only for weakest precondition transformers, but also for strongest postconditions, and pairs of pre-and postconditions as explained in details in the following subsections. We call collectively this class of monads speci cation monads. Intuitively, elements of a speci cation monad can be used to specify properties of some computation, e.g., W Pure can specify pure or nondeterministic computations, and W St can specify stateful computations.

What is a speci cation monad ? A conceptual de nition will be given in Def. 3.5.2, but for the time being we will be using the following elementary de nition.

De nition 2.3.1. A speci cation monad is a monad W such that WA is equipped with a preorder ≤ WA for each type A, and bind W is monotonic in both arguments:

∀(w 1 ≤ WA w 1 ). ∀(w 2 w 2 : A → WB). (∀x : A. w 2 x ≤ WB w 2 x) ⇒ bind W w 1 w 2 ≤ WB bind W w 1 w 2
This order allows speci cations to be compared as being either more or less precise. For example, for the speci cation monads W Pure and W St , the ordering is given by

w 1 ≤ w 2 : W Pure A ⇔ ∀(p : A → P). w 2 p ⇒ w 1 p w 1 ≤ w 2 : W St A ⇔ ∀(p : A × S → P)(s : S). w 2 p s ⇒ w 1 p s
For W Pure and W St to form ordered monads, it turns out that we need to restrict our attention to monotonic predicate transformers, i.e., those mapping (pointwise) stronger postconditions to stronger preconditions. This technical condition, quite natural from the point of view of verication, will be assumed implicitly for all the predicate transformers. We consider several basic speci cation monads, whose relationship is summarized by Figure 2.1.

Predicate monad

Arguably the simplest way to specify a computation is to provide a postcondition on its outcomes. This can be done by considering the speci cation monad Pred A = A → P (the covariant powerset monad) with order p 1 ≤ Pred p 2 ⇐⇒ ∀(a : A). p 1 a ⇒ p 2 a. To specify the behavior of returning values, we can always map a value v : A to the singleton predicate ret Pred v = λy. (y = v) : Pred A. And given a predicate p : Pred A and a function f : A → Pred B, the predicate on B de ned by bind Pred p f = λb. ∃a. p a ∧ f a b speci es the behavior of sequencing two computations, where the rst computation produces a value a satisfying p and, under this assumption, the second computation produces a value satisfying f a. While a speci cation p : Pred A provides information on the outcome of the computation, it cannot require preconditions, so computations need to be de ned independently of any logical context. To give total correctness speci cations to computations with non-trivial preconditions, for instance specifying that the division function div x y requires y to be non-zero, we need more expressive speci cation monads.

Pre-/postcondition monad

One more expressive speci cation monad is the monad of pre-and postconditions

PrePost A = P × (A → P),
bundling a precondition together with a postcondition. Here the behavior of returning a value v :

A is speci ed by requiring a trivial precondition and ensuring as above a singleton postcondition: The resulting precondition ensures that the precondition of the rst computation holds and, assuming the postcondition of the rst computation, the precondition of the second computation also holds. The resulting postcondition is then simply the conjunction of the postconditions of the two computations. The order on PrePost naturally combines the pointwise forward implication order on postconditions with the backward implication order on preconditions. We formally show that this speci cation monad is more expressive than the predicate monad above: Any predicate p : Pred A can be coerced to ( , p) : PrePost A, and in the other direction, any pair (pre, post) : PrePost A can be approximated by the predicate post, giving rise to a Galois connection, as illustrated in Figure 2.1. While the monad PrePost is intuitive for humans, generating e cient veri cation conditions is generally easier with predicate transformers [START_REF] Leino | E cient weakest preconditions[END_REF].

ret PrePost v = ( ,

Forward predicate transformer monad

The predicate monad Pred can be extended in an alternative way. Instead of xing a precondition as in PrePost, a speci cation can be a function from preconditions to postconditions, for instance producing the strongest postcondition of computation for any precondition pre:P given as argument. Intuitively, such a forward predicate transformer on A should have type P → (A → P). However, to obtain a monad (i.e., satisfying the expected laws), we have to consider the smaller type SPost A = (pre:P) mon ---→ (A → P /pre ) of predicate transformers that are monotonic with respect to pre, where P /pre is the subtype of propositions implying pre. Returning a value v : A is speci ed by the predicate transformer

ret SPost v = λpre a. pre ∧ a = v,

Backward predicate transformer monad

As explained in section 1.1, backward predicate transformers can be described using the continuation monad with propositions P as the answer type, namely, Cont P A = (A → P) → P.

Elements w : Cont P A are predicate transformers mapping a postcondition post : A → P to a precondition w post : P, for instance the weakest precondition of the computation. Pointwise implication is a natural order on Cont P A:

w 1 ≤ w 2 : Cont P A ⇔ ∀(p : A → P). w 2 p ⇒ w 1 p
However, Cont P is not an ordered monad with respect to this order because its bind is not monotonic. In order to obtain an ordered monad, we restrict our attention to the submonad W Pure of Cont P containing the monotonic predicate transformers, that is those w : Cont P A such that

∀(p 1 p 2 : A → P). (∀(a : A). p 1 a ⇒ p 2 a) ⇒ w p 1 ⇒ w p 2 ,
which is natural in veri cation: we want stronger postconditions to map to stronger preconditions. This speci cation monad is more expressive than the pre-/postcondition one above. Formally, a pair (pre, post) : PrePost A can be mapped to the monotonic predicate transformer λ(p : A → P). pre ∧ (∀(a : A). post a ⇒ p a) : W Pure A, and vice versa, a predicate transformer w : W Pure A can be approximated by the pair ( w (λa. ) , λa. (∀p. w p ⇒ p a) ) : PrePost A These two mappings de ne a Galois connection, as illustrated in Figure 2.1. Further, this Galois connection exhibits PrePost A as the submonad of W Pure A of conjunctive predicate transformers, i.e., predicate transformers w commuting with non-empty conjunctions/intersections.

A speci cation monad of relations between pre-and postconditions

Finally, both W Pure and SPost can be embedded into an even more expressive speci cation monad RelPrePost consisting of relations between preconditions and postconditions satisfying a few conditions, the full details of which can be found in our Coq formalization.

SPost

Pred PrePost W Pure RelPrePost ∼ = Each pair of parallel arrows forms a Galois connection.

Speci cation monads from transformers

Once we have a few basic speci cation monads as the one described above, a powerful way to construct speci cation monads is to apply monad transformers to existing speci cation monads. For instance, applying ExcT M A = M (A + E) to W Pure we get

W Exc A = ExcT W Pure A = ((A+E) → P) → P ∼ = (A → P) → (E → P) → P
W Exc is a natural speci cation monad for programs that can throw exceptions, transporting a normal postcondition in A → P and an exceptional postcondition in E → P to a precondition in P.

Besides accounting for exceptional termination, varying the monad transformer extend speci cations to have access to ghost state or to provide information about footprints. An important point is that monad transformer provides an important modularity property: when specifying code, we can use as little facilities as needed and consequently produce less clutter in veri cation conditions. Further speci cation monads using this idea will be introduced along with the examples in section 2.4.

Since speci cation monads also carry a preorder, we need the monad transformers to preserve this ordered structure. We will see in chapter 4 that it is the case of all examples of monad transformers of section 2.2.

Quantitative variations

Nothing prevents à priori to de ne speci cations monads based on preorders di erent from propositions. For instance, the example of the backward predicate transformer monad for instance would have the structure of a speci cation monad independently of the choice of the ordered return type (R, ) replacing P.

Taking R to be the extended reals [0; ∞], we recover a monad to specify pre-expectations of probabilistic programs [START_REF] Audebaud | Proofs of randomized algorithms in coq[END_REF][START_REF] Kaminski | Weakest precondition reasoning for expected run-times of probabilistic programs[END_REF].

Another possibility is to take R to be a set of available resources, for instance natural number to count the number of steps a program could take. This can be re ned to positive rational or real numbers, obtaining a speci cation monad for cost analysis.

We did not pursue much further the analysis of such quantitative variants of speci cation monads, but expect that a sensible amount of the work developed here could extend to the quantitative setting.

E ect observations

Now that we have a presentation of speci cations as elements of a monad, we need to relate computational monads to such speci cations. Since an object relating computations to speci cations provides a particular insight on the e ects exhibited by the computation, they have been called e ect observations [START_REF] Katsumata | Parametric e ect monads and semantics of e ect systems[END_REF]. As explained in section 1.2, a computational monad can have e ect observations into multiple speci cation monads, or multiple e ect observations into a single speci cation monad. Using the exceptions computational monad Exc as running example, we argue that monad morphisms provide a natural notion of e ect observation in a unary monadic setting, and we provide instances of e ect observations supporting this claim. Then, we revisit the computational monads from section 2.1, and present various natural e ect observations for them since there is generally a large variety of options regarding both the speci cation monads and the e ect observations when specifying and verifying monadic programs.

E ect observations are monad morphisms

As explained in section 2.1, computations throwing exceptions can be modeled by monadic expressions m : Exc A = A + E. A natural way to specify m is to consider the speci cation monad W Exc A = ((A + E) → P) → P and to map m to the predicate transformer θ Exc (m) = λp. p m : W Exc A, applying the postcondition p to the computation m.

The mapping θ Exc : Exc → W Exc relating the computational monad Exc and the specication monad W Exc is parametric in the return type A, and it veri es two important properties with respect to the monadic structures of Exc and W Exc . First, a returned value is speci ed by itself:

θ Exc (ret Exc v) = θ Exc (inl v) = λp. p (inl v) = ret W Exc v
and second, θ preserves the sequencing of computations:

θ Exc (bind Exc (inl v) f ) = θ Exc (f v) = bind W Exc (ret W Exc v) (θ Exc •f ) = bind W Exc θ Exc (inl v) (θ Exc •f ) θ Exc (bind Exc (inr e) f ) = θ Exc (inr e) = bind W Exc θ Exc (inr e) (θ Exc • f )
These properties together prove that θ Exc is a monad morphism. More importantly, they allow us to compute speci cations from computations compositionally, e.g., the speci cation of bind can be computed from the speci cations of its arguments. This leads us to the following de nition: De nition 2.4.1 (E ect observation). An e ect observation θ is a monad morphism from a computational monad M to a speci cation monad W. More explicitly, it is a family of maps θ A : M A -→ W A, natural in A and such that for any v : A, m : M A and f : A → M B the following equations hold:

θ A (ret M v) = ret W v θ B (bind M m f ) = bind W (θ A m) (θ B • f )

Speci cation monads are not canonical

When writing programs using the exception monad, we may want to write pure sub-programs that actually do not raise exceptions. In order to make sure that these sub-programs are pure, we could use the previous speci cation monad and restrict ourselves to postconditions that map exceptions to false (⊥): hence raising an exception would have an unsatis able precondition. However, as outlined in section 1.2, a simpler solution is possible. Taking as speci cation monad W Pure , we can de ne the following e ect observation θ ⊥ : Exc → W Pure by

θ ⊥ (inl v) = λp. p v θ ⊥ (inr e) = λp. ⊥
This e ect observation gives a total correctness interpretation to exceptions, which prevents them from being raised at all. As such, we have e ect observations from Exc to both W Exc and W Pure .

E ect observations are not canonical

Looking closely at the e ect observation θ ⊥ , it is clear that we made a rather arbitrary choice when mapping every exception inr e to ⊥. Mapping inr e to true ( ) instead also gives us an e ect observation, θ : Exc → W Pure . This e ect observation assigns a trivial precondition to the throw operation, providing a partial correctness interpretation: given a program m : Exc A and a postcondition p : A → P, if θ (m)(p) is satis able and m evaluates to inl v then p v holds; but m may also raise any exception instead. Thus, θ ⊥ , θ : Exc → W Pure are two natural e ect observations into the same speci cation monad. Even more generally, we can vary the choice for each exception; in fact, e ect observations θ : Exc → W Pure are in one-to-one correspondence with maps E → P (see subsection 2.4.8 for a general account of this correspondence).

E ect observations from monad transformers

Even though there is, in general, no canonical e ect observation for a computational monad, we can build an e ect observation in the particular case of a monad of the shape T (Id), i.e., a monad obtained by the application of a monad transformer to the identity monad. In that setting, xing any we can build a canonical speci cation monad, namely T (W Pure ), and a canonical e ect observation into it. The e ect observation is obtained simply by lifting the ret W Pure : Id → W Pure function through the T transformer. For instance, for the exception monad Exc = ExcT(Id) and the speci cation monad W Exc = ExcT (W Pure ), the e ect observation θ Exc arises as simply θ Exc = ExcT(ret W Pure ) = λm p. p m. More generally, for any monad transformer T (e.g.

StT, ExcT, StT • ExcT, ExcT • StT) and any speci cation monad W (so not just W Pure , but also e.g., any basic speci cation monad from section 2.3) we have a monad morphism

θ T : T (Id) T (ret W ) ---------→ T (W)
providing e ect observations for stateful computations with exceptions, or for computations with rollback state. However, not all computational monads arise as a monad transformer applied to the identity monad. The following examples illustrate the possibilities in such cases.

E ect observations for free monads

In order to give an e ect observation θ F ree from a free monad induced by a signature (S, P ) (subsection 2.1.7) to a speci cation monad W, it is enough to provide for each operations s : S a speci cation w op (s) : W (P s).

let rec θ F ree (w op : (s:S) → W (P s)) (m: Free P S A)

: W A = match m with | Ret a → retW a | Op s k → bindW (w op s) (λ ps. θ F ree (k ps))
Conversely, any e ect observation θ F ree induces a speci cation for each operations

w op = θ F ree • gen op : (s: S) → W (P s).
This correspondence is bijective and characteristic of free monads.

Observing nondeterminism

The computational monad NDet admits e ect observations to the speci cation monad W Pure . Given a nondeterministic computation m : NDet A represented as a nite set of possible outcomes, and a postcondition post : A → P, we obtain a set P of propositions by applying post to each element of m. There are then two natural ways to interpret P as a single proposition:

we can take the conjunction p∈P p, which corresponds to the weakest precondition such that any outcome of m satis es post (demonic nondeterminism); or we can take the disjunction p∈P p, which corresponds to the weakest precondition such that at least one outcome of m satis es post (angelic nondeterminism).

To see that both these choices lead to monad morphisms θ ∀ , θ ∃ : NDet → W Pure , it is enough to check that taking the conjunction when P = { p } is a singleton is equivalent to p, and that a conjunction of conjunctions a∈A p∈Pa p is equivalent to a conjunction on the union of the ranges p∈ a∈A Pa p-and similarly for disjunctions. Both conditions are straightforward to check.

Observing Interactive Input-Output

Let us now consider programs in the IO monad (section 2.1). We want to de ne an e ect observation θ : IO → W, for some speci cation monad W to be determined. A rst thing to note is that since no equations constrain the read and write operations, IO is a free monad, we can specify their interpretations θ(read) : W I and ∀(o : O). θ(write o) : W 1 separately from each other. Simple e ect observations for IO can already be provided using the speci cation monad W Pure . The interpretation of the write operation in this simple case needs to provide a result in P from an output element o : O and a postcondition p : 1 → P. Besides returning a constant proposition (like for θ ⊥ , θ in subsection 2.4.2), a reasonable interpretation is to forget the write operation and return p * (where * is the unit value). For the de nition of θ(read) : (I → P) → P, we are given a postcondition post : I → P on the possible inputs and we need to build a proposition. Two canonical solutions are to use either the universal quanti cation ∀(i : I). post i, requiring that the postcondition is valid for the continuation of the program for any possible input; or the existential quanti cation ∃(i : I). post i, meaning that there exists some input such that the program's continuation satis es the postcondition, analogously to the two modalities of evaluation logic [START_REF] Moggi | A semantics for evaluation logic[END_REF][START_REF] Pitts | Evaluation logic[END_REF].

To get more interesting e ect observations accounting for inputs and outputs we can, for instance, extend W Pure with ghost state [START_REF] Owicki | Verifying properties of parallel programs: An axiomatic approach[END_REF] capturing the list of executed IO events. 2 We can do this by applying the state monad transformer with state type list E to W Pure , obtaining the speci cation monad W HistST A = (A × list E → P) → list E → P, for which we can provide interpretations of read and write that also keep track of the history of events via ghost state: This speci cation monad is however somewhat inconvenient in that postconditions are written over the global history of events, instead of over the events of the expression in question. Further, one can write speci cations that "shrink" the global history of events, such as λp log. p * , [] , which no expression satis es. For these reasons, we introduce an update monad (Ahman and Uustalu, 2013) variant of W HistST , written W Hist , which provides a more concise way to describe the events. In particular, in W Hist the postcondition speci es only the events produced by the expression, while the precondition is still free to specify any previously-produced events, allowing us to de ne:

θ Hist (write o) = λ(p : 1 × list E→P) (log : list E). p * , [Out o] : W Hist (1) θ Hist (read) = λ(p : I × list E→P) (log : list E). ∀i. p i, [In i] : W Hist (I)
While W Hist = W HistST , the two monads di er in their ret and bind functions. For instance, bind W HistST w f = λp log. w λ x, log . f x p log log bind W Hist w f = λp log. w λ x, log . f x λ(y, log ). p (y, log ++log ) (log ++log ) log

where the former overwrites the history, while the latter merely augments it with new events. While W Hist provides a good way to reason about IO, some IO programs do not depend on past interactions. For these, we can provide an even more parsimonious speci cation monad by applying the writer transformer to W Pure . The resulting speci cation monad W Fr then allows us to de ne

θ Fr (write o) = λ(p : 1 × list E→P). p ( * , [Out o]) : W Fr (1) θ Fr (read) = λ(p : I × list E→P). ∀i. p (i, [In i]) : W Fr (I)
This is in fact a special case of W Hist where the history is taken to be 1 [START_REF] Ahman | Update monads: Cointerpreting directed containers[END_REF].

In fact, there is even more variety possible here, e.g., it is straightforward to write specications that speak only of output events and not input events, and vice versa. It is also easy to extend this style of reasoning to combinations of IO and other e ects. For instance, we can simultaneously reason about state changes and IO events by considering computations in IOSt A = S → IO(A × S), resulting from applying the state monad transformer to IO, together with the speci cation monad W IOSt A = (A × S × list E → P) → S → list E → P. As such, we recover the style proposed by [START_REF] Malecha | Trace-based veri cation of imperative programs with I/O[END_REF], though they also cover separation logic.

Being able to choose between speci cation monads and e ect observations allows one to keep the complexity of the speci cations low when the properties are simple, yet increase it if required.

E ect Observations from Monad Algebras

While monad transformers T enable us to derive complex speci cation monads, they can only help us to automatically derive e ect observations of the form θ T : T (Id) -→ T (W ), which only slightly generalize the DM4Free construction. In all other cases, we had to de ne e ect observations by hand. However, when the speci cation monad has a speci c shape, such as W Pure , there is in fact a simpler way to de ne e ect observations. For instance, e ect observations θ ⊥ , θ : Exc → W Pure were used to specify the total and partial correctness of programs with exceptions, by making a global choice of allowing or disallowing exceptions. Here we observe that such hand-rolled e ect observations can in fact be automatically derived from M -algebras.

As shown by [START_REF] Hyland | Combining algebraic e ects with continuations[END_REF], there is a one-to-one correspondence between monad morphisms M → Cont R and M-algebras M R → R. We can extend this to the ordered setting: for instance, e ect observations θ : M → W Pure correspond one-to-one to M-algebras α : M P → P that are monotonic with respect to the free lifting on M P of the implication order on P. Intuitively, α describes a global choice of how to assign a speci cation to computations in M in a way that is compatible with ret M and bind M , e.g., such as disallowing all (or perhaps just some) exceptions.

Based on this correspondence, the e ect observations θ ⊥ and θ arise from the Exc-algebras α ⊥ = λ_. ⊥ and α = λ_. . Similarly, the e ect observations for nondeterminism arise from the NDet-algebras α ∀ and α ∃ , taking respectively the conjunction and disjunction of a set of propositions in NDet(P), as follows:

θ ∀ (m) = λp. α ∀ (NDet(p) m) and θ ∃ (m) = λp. α ∃ (NDet(p) m).
Conversely, we can recover the NDet-algebra α ∀ as λm. θ ∀ P (m) id P , respectively α ∃ as λm. θ ∃ P (m) id P . Importantly, this correspondence is not limited to W Pure , but applies to continuation monads with any answer type. For instance, taking the answer type to be S → P, we can recover the effect observation θ St : St → W St , where W St A ∼ = MonCont S→P A = (A → (S → P)) → (S → P), from the St-algebra α St = λ(f : S → (S → P) × S) (s : S). (π 1 (f s)) (π 2 (f s)) : St(S → P) → S → P.

Conclusion & Related work

Following a well established tradition in functional programming languages [START_REF] Benton | Monads and e ects[END_REF][START_REF] Moggi | Computational lambda-calculus and monads[END_REF][START_REF] Wadler | Comprehending monads[END_REF], we presented a variety of monads encapsulating computational effects such as state, nondeterminism and interactive input output, and explained how an important subset of these arise from monad transformers.

The notion of speci cation monad is inspired by a line of categorical work on weakest precondition. [START_REF] Jacobs | Dijkstra monads in monadic computation[END_REF][START_REF] Jacobs | Dijkstra and Hoare monads in monadic computation[END_REF][START_REF] Jacobs | A recipe for state-and-e ect triangles[END_REF] studies adjunctions between state transformers and predicate transformers, obtaining a class of speci cation monads from the state monad transformer and an abstract notion of logical structures. He gives abstract conditions for the existence of such speci cation monads. [START_REF] Hasuo | Generic weakest precondition semantics from monads enriched with order[END_REF] builds on the state-predicate adjunction of Jacobs to provide algebra-based e ect observations (in the style of subsection 2.4.8) for various computation and speci cation monads. Working inside type theory, our work focus on concrete recipes for building speci cation monads useful for practical veri cation.

E ect observations as monad morphisms were introduced by [START_REF] Katsumata | Parametric e ect monads and semantics of e ect systems[END_REF] in his study of graded monads to give semantics to type-and-e ect systems. For each of these computational monads, we proposed e ect observations to multiple speci cation monads providing multiple options in order to verify programs using these e ects. The actual choice of the e ect observation to use depends on various trade-o s between expressivity of the speci cation, di culty of the properties to verify (e.g., partial or total termination), modularity with respect to context. We argue that the possibility to adapt to various context and at minor implementation cost thanks to the decorrelation between the computational monad, the speci cation and the e ect observation is a key asset of this framework, that should be developed further in a practical implementation.

We now review further related work that was not presented yet.

Alternative representation of e ects [START_REF] Levy | Call-By-Push-Value: A Functional/Imperative Synthesis[END_REF] re nes the approach to e ects advocated by [START_REF] Moggi | Computational lambda-calculus and monads[END_REF] replacing a computational monad M with an adjunction F U . This allow a ner treatment of the order of evaluation, admitting a treatment of side-e ects in both call-byvalue and call-by-name settings together with a well-behaved equational theory. To our knowledge, program logics for CBPV are yet to be de ned and studied.

Local state & monads on resource indexed families An important variation on stateful computations not presented in this chapter is the possibility of allocating and deallocating chunks of memory. The local state monad introduced in [START_REF] Plotkin | Notions of computation determine monads[END_REF] provides such capabilities at the cost of more complex state-indexed types. Instead of considering monads on plain types, we could also consider monads on families of types indexed by some notion of resource3 . This leads to monads tracking not only stateful computations but also allocations and deallocations [START_REF] Maillard | A brational account of local states[END_REF][START_REF] Melliès | Local states in string diagrams[END_REF][START_REF] Power | Semantics for local computational e ects[END_REF][START_REF] Staton | Completeness for algebraic theories of local state[END_REF], manipulating addresses in a heap [START_REF] Kammar | A monad for full ground reference cells[END_REF] or even a set of qbits [START_REF] Staton | Algebraic e ects, linearity, and quantum programming languages[END_REF].

Combining theories Instead of accumulating monad transformers on top of a basic monad, an important body of work focus on the direct combination of e ects, in particular for those presented by an equational theory [START_REF] Hyland | Combining e ects: Sum and tensor[END_REF]. The combination of these algebraic e ects with continuations is studied in [START_REF] Hyland | Combining algebraic e ects with continuations[END_REF], and provides in particular a negative results about the combination of interactive input-output and continuations (in the category of sets) that apply as well to Coq. [START_REF] Katsumata | Relating computational e ects by -lifting[END_REF] gives a semantic account of [START_REF] Lindley | Reducibility and -lifting for computation types[END_REF]'s -lifting, a generic way of lifting relations on values to relations on monadic computations, parameterized by a basic notion of relatedness at a xed type. Monad morphisms M A → ((A → P) → P), i.e. e ect observations from M to the backward predicate transformer speci cation monad W Pure , are also unary relational liftings (A → P) → (M A → P), and could be generated by -lifting. Further, binary relational liftings could be used to generate monadic relations that yield Dijkstra monads by the construction in chapter 5. In both cases, what is speci able about the underlying computation would be controlled by the chosen basic notion of relatedness.

Predicate transformer semantics

In another recent concurrent work, [START_REF] Swierstra | A predicate transformer semantics for e ects[END_REF] study the predicate transformer semantics of monadic programs with exceptions, state, non-determinism, and general recursion. Their predicate transformer semantics appears closely related to our e ect observations, and their compositionality lemmas are similar to our monad morphism laws. We believe that some of their examples of performing veri cation directly using the e ect observation, could be easily ported to our framework. Their goal, however, is to start from a speci cation and incrementally write a program that satis es it, in the style of the re nement calculus [START_REF] Morgan | Programming from Speci cations (2nd Ed[END_REF]. It could be an interesting future work direction to build a uni ed framework for both veri cation and re nement, putting together the ideas of both works.

First-order approach to veri cation with generic side-e ects [START_REF] Rauch | Generic Hoare logic for order-enriched e ects with exceptions[END_REF] provide a generic veri cation framework for rst-order monadic programs. Their work is quite di erent from ours, even beyond the restriction to rst-order programs, since their speci cations are "innocent" e ectful programs, which can observe the computational context (e.g., state), but not change it. This introduces a tight coupling between computations and speci cations, while we provide much greater exibility through e ect observations. The FreeSpec framework [START_REF] Letan | Modular veri cation of programs with e ects and e ect handlers in coq[END_REF] uses algebraic e ects and handlers to de ne in Coq a set of components interacting through interfaces. The speci cation are given pairs of pre-/postconditions and attached to each components.

Logical approach to e ects Generic reasoning about computational monads dates back to [START_REF] Moggi | Computational lambda-calculus and monads[END_REF] seminal work, who proposes an embedding of his computational metalanguage into higher-order logic. Pitts & Moggi's evaluation logic [START_REF] Moggi | A semantics for evaluation logic[END_REF][START_REF] Pitts | Evaluation logic[END_REF] later introduces modalities to reason about the result(s) of computations, but not about the computational context. [START_REF] Plotkin | A logic for algebraic e ects[END_REF] propose a generic logic for algebraic e ects that encompasses Moggi's computational λ-calculus, evaluation logic, and Hennesy-Milner logic, but does not extend to Hoare-style reasoning for state. [START_REF] Simpson | Behavioural equivalence via modalities for algebraic e ects[END_REF] and [START_REF] Matache | A sound and complete logic for algebraic e ects[END_REF] explore logics for algebraic e ects by specifying the e ectful behaviour of algebraic operations using a collection of e ect-speci c modalities instead of equations. Their modalities are closely related to how we derive e ect observations θ : M → W Pure and thus program specications from M -algebras on P in subsection 2.4.8, as intuitively the conditions they impose on their modalities ensure that these can be collectively treated as an M -algebra on P. In recent work concurrent to ours, Voorneveld (2019) studies a logic based on quantitative modalities by considering truth objects richer than P, including S → P for stateful and [0, 1] for probabilistic computation.

The notion of speci cation monad we use is quite simple, counting the bare minimum to start talking about speci cation. However it is lacking for actually de ning a logic. This choice was voluntary in order not to restrict the applicability of the framework, in particular for quantitative reasoning as would be needed when reasoning about costs or probabilities. In practice, most of the examples we presented support a rich logic and we would like to re ect this in the de nition of more restricted classes of speci cation monads from which we could de ne a logic.

Reasoning directly about e ectful semantics Relating monadic expressions is natural and very wide-spread in proof assistants like Coq, Isabelle [START_REF] Lochbihler | E ect polymorphism in higher-order logic (proof pearl)[END_REF], or F (Grimm et al., Chapter 3

Abstracted away

『そしてそこには出口がない。出口を見つけられる 可能性すらない。君は時の迷 宮の中に迷いこんでし まっている。なによりもいちばん大きな問題は、そ こから出てい きたいという気持ちを君がまったく抱 けないでいることだ。そうだね?』 村上 春樹, 海辺のカフ カ, 2006
Computational monads are the key algebraic structure to obtain compositionality of sequential programs even in an e ectful setting. A conceptual understanding of the tools enabling veri cation of such program should make use of this monadic structure, as for instance specication monads. However, plain monads do not fully account for these objects that we use to study monadic program veri cation. Beside being monads, speci cation monads comes with a preorder structure and various axioms ensuring the well-behavedness of these preorders with respect to the monadic operations. We would like to obtain these conditions as an instance of a more general notion of monad. We hope by pursuing this goal that a general approach will lead to simpler proofs, not cluttered by the details of the objects we are manipulating.

In this chapter, we introduce a few abstract categorical constructions generalizing that of plain monads and used extensively in the following chapters. Our starting point is the formal theory of monads, following [START_REF] Street | The formal theory of monads[END_REF], that provides a general formulation of monads and associated concepts in an arbitrary 2-category. In particular the theory applies to enriched settings and, keeping in mind speci cation monads, we are foremost interested in the Pos-enriched case.

The monad-like structure arising in the context of monadic program veri cation however are often not endofunctors: we present the theory of relative monads [START_REF] Altenkirch | Monads need not be endofunctors[END_REF] that was developed for that purpose. Motivated by enriched variants of relative monads, for instance on preorders, we sketch the foundations of a formal theory of relative monads. Framed bicategories [START_REF] Shulman | Framed bicategories and monoidal brations[END_REF]) is a natural setting to pursue such a generalization. We present framed bicategories, introduce relative monads in those, and de ne notions of algebras. We close the chapter by showing that to some extent the formal theory of relative monads we present here naturally extends that of monads.

Elements of the formal theory of monads

The notion of monad admits a general de nition in an arbitrary 2-category or even a bicategory due to [START_REF] Bénabou | Introduction to bicategories[END_REF]. We begin this chapter recalling brie y the notion of 2-/bi-category, before presenting a few elements of the formal theory of monads as developed in [START_REF] Kelly | Review of the elements of 2-categories[END_REF][START_REF] Lack | The formal theory of monads ii[END_REF][START_REF] Street | The formal theory of monads[END_REF]. A far more complete reference on the topics touched here is [START_REF] Lack | A 2-categories companion[END_REF].

CHAPTER 3. ABSTRACTED AWAY 3.1.1 A brief introduction to 2-categories De nition 3.1.1. A bicategory B consists of a set of 0-cells |B|,
for each pair of 0-cells x, y ∈ |B|, a category B(x, y) whose objects are called 1-cells and morphisms are called 2-cells, with identity 1-cell id x for each 0-cell x, and a bifunctorial composition • x,y,z : B(y, z) × B(x, y) → B(x, z) for 0-cells x, y, z ∈ |B|, such that the following unitality and associativity square commute up to natural isomorphisms λ, ρ, α called respectively left unitor, right unitor and associator

B(x, y) × B(y, y) B(x, y) B(y, y) × B(x, y) B(x, y) • • idy×B(x,y) B(x,y)×idx ρ λ B(y, z) × B(x, y) × B(w, x) B(x, z) × B(w, x) B(y, z) × B(w, y) B(w, z) •×B(w,x) B(y,z)ו • • ⇓ α
and such that the following two coherence diagrams commute where we abbreviated B(x, y) by B x,y and noted • for functor composition as well as action of functors on natural transformations.

•

• (• × B x,y ) • (B y,z × id y × B x,y ) • • (B y,z × •) • (B y,z × id y × B x,y ) • x,y,z α•(By,z×idy×Bx,y) ••(ρ×Bx,y) ••(By,z×λ) • • (• × B v,w ) • (• × B x,w × B v,w ) • • (• × B v,w ) • (B y,z × • × B v,w ) • • (• × •) • • (B y,z × •) • (B y,z × • × B v,w ) • • (B y,z × •) • (B y,z × B x,y × •) ••(α×Bv,w) α•(•×Bx,w×Bv,w) α•(By,zו×Bv,w) α•(By,z×Bx,yו) ••(By,z×α)
The rst coherence diagram means that simplifying identities on the left or on the right using the adequate unitor gives the same result and the second coherence diagram enforces associativity of the associator.

A bicategory B where the associator and unitors are identities is called a strict 2-category. A folklore result from [START_REF] Curien | Revisiting the categorical interpretation of dependent type theory[END_REF]; [START_REF] Power | A general coherence result[END_REF] shows that any bicategory can be stricti ed to a strict 2-category in the sense that a bicategory B can be embedded in a strict 2-category such that the embedding is an equivalence of bicategories. Another way to state this coherence theorem is that all diagrams built out of associators and unitors commute, and so we will omit them in all diagrams since they can be inserted in an essentially unique way.

Examples of 2-categories

Cat is the 2-category of small categories, functors and natural transformations.

For an enriching category V, VCat is the 2-category of V-enriched categories, V-enriched functors and V-enriched natural transformations.

There is another natural 2-category whose 0-cells are small categories, the bicategory Distr whose 1-cells are distributors between categories and 2-cells are natural transformations between distributors. The relationship between Cat and Distr can be seen as a categori cation of the relationship between the (1-)categories Set of set and functions and Rel of sets and relations.

An adequate notion of morphism between 2-categories is that of 2-functor1 .

De nition 3.1.2. A 2-functor F from a 2-category B to a 2-category K consists of: a function |F | : |B| → |K| mapping 0-cells of B to 0-cells of K a functor F x,y : B(x, y) → K(F x, F y) for each pair of 0-cells x, y ∈ |B| with invertible 2-cells i x : id F x ∼ -→ F id x for each 0-cell x ∈ |B| and m f,g : F g • F f ∼ -→ F (g • f ) for each pair of composable 1-cells f, g in B, natural in f, g
satisfying three coherence diagrams similar to those for a monoidal functor ensuring that unitors and associators are respected.

Working with 2-categories: string diagrams Since working inside a 2-category involves manipulating objects at three distinct levels, the usual diagrammatic notations can quickly become hard to read and obscure the actual proof. String diagrams, formally introduced in Joyal and [START_REF] Joyal | The geometry of tensor calculus, i[END_REF], provide a graphical calculus that can greatly simplify de nitions and proofs inside a 2-category. The key idea is that proofs in a 2-category primarily manipulate 2-cells so they should be the most visible. This is achieved by taking the Poincaré dual of the standard diagrams: 0-cells become surfaces and 2-cells become points, whereas 1-cells are still represented as lines.

0-cell x x x 1-cell f ∈ B(x, y) x y f x y f f 2-cell α ∈ B x,y (f, g) x y g f ⇓ α g α f x y
We leave out the name of 0-cells in further diagrams since these can be inferred from the 1-cells. Vertical juxtaposition of string diagrams correspond to composition of 1-cells -and its functorial action on 2-cells -whereas horizontal juxtaposition is composition of 2-cells. Note that we take here the slightly non-standard convention of reading string diagrams from top to bottom and from right to left in order to have compatible notations with the graphical calculus for framed bicategories in section 3.3. A monad in a bicategory B is noted (X, t) leaving the unit and multiplication implicit. There is a natural notion of morphism between monads in a bicategory B.

Monads in a 2-category

De nition 3.1.3. A monad in a 2-category B consists of a 1-cell t : X → X on a 0-cell X of B with 2-cells η : id X → t
De nition 3.1.4. A monad morphism between monads (X, t) and (Y, s) is consists of A 1-cell f : X → Y and a 2-cell θ : s • f → f • t s θ t f f
such that the following identities hold

η s θ t f f t f f η t = s µ s θ s t f f µ t t θ θ f f s s = De nition 3.1.5. A monad morphism transformation between monad morphisms (f, θ) and (g, φ) from (X, t) to (Y, s) consists of a 2-cell ν : f → g such that s θ t f ν g s φ t f ν g =
We can put these de nitions together to form a 2-category Mnd(B) whose 0-cells are monads in B, 1-cells are monad morphisms and 2-cells are monad morphism transformations. We de ne a (2-)functor U from Mnd(B) to B forgetting everything related to monads. In more details, U sends a monad (X, t) to X, a monad morphism (f, θ) to f and a monad morphism transformation to its underlying 2-cell.

Object of algebras

De nition 3.1.6. An algebra for a monad (T, η, µ) on a category C is given by An object c ∈ C called the carrier of the algebra and a morphism α ∈ C(T c, c) called the structure map of the algebra such that the two following identities hold The formal theory of monads also extends the notion of algebra to an arbitrary 2-category. A monad (X, t) in a 2-category B induces by post-composition a monad B(A, t) on the category

α • η c = id c α • µ c = α • T α A T -algebra morphism from (c, α) to (c , α ) consists of a morphism f ∈ C(c, c ) such that f • α = α •T f . T -
B(A, X) for any 0-cell A ∈ B. The mapping sending a 0-cell A ∈ B to the Eilenberg-Moore category B(A, X) B(A,t) extends to a 2-functor Alg t : B op(1) → Cat. An Eilenberg-Moore object for t is, when it exists, a 0-cell X t ∈ B representing the functor Alg t , that is such that Alg t (A) ∼ = B(A, X t ) naturally in A ∈ B op(1) .
When Eilenberg-Moore objects exist for two monads (X, t) and (Y, s), monad morphisms

(f, θ) : (X, t) → (Y, s) are in bijection with pairs of 1-cells (f, f ) where f : X → Y and f : X t → Y s .

Relative monads

The classical theory of monads is not enough to capture all the structure we need to model formal veri cation of programs. In particular speci cation monads (section 2.3) already go beyond the classical theory since they need to be equipped with orders. We could hope that it would be enough to move from a Set-enriched setting to a Pos-enriched setting, in the sense of enriched category theory [START_REF] Kelly | Basic Concepts of Enriched Category Theory[END_REF], however there is no reason a priori for a speci cation monad on

Set to lift to Pos. Thus the formal monad theory in PosCat falls short of describing our peculiar use-case.

In order to provide a formal categorical account for speci cation monads, and for other monad-like objects developed for relational reasoning (chapter 6), we commit ourselves to a generalization of monads known as relative monads. A relative monad relax the notion of monad by endowing a monad-like structure to functors that need not to be endofunctors [START_REF] Altenkirch | Monads need not be endofunctors[END_REF]. For this notion to make sense, we need to specify relative monads with respect to a base functor J : I → C, and the classical notion of monad is recovered when taking J = Id. The price to pay for this generalization is a more technical theory, in particular to connect relative monads to a notion of monoid in an abstract enough setting.

De nition 3.2.1 (Relative monad in Cat). Let J : I → C be a functor between categories I, C. A J -relative monad is given by a function on objects M : |I| → |C|, a family of morphisms ret x ∈ C(J x, M x) for any x ∈ I, a family of functions bind x,y :

C(J x, M y) → C(M x, M y) such that the following equations hold bind x,x (ret x ) = id x bind x,y (f ) • ret x = f bind x,z (bind y,z (g) • f ) = bind y,z (g) • bind x,y (f )
The de nition of a relative monad generalizes directly the presentation familiar to programmers of a plain monad on a category C as a Kleisli triple (T, η, (-) † ) where we write (-) † for the Kleisli extension operation C(X, T Y ) → C(T X, T Y ).

As hinted before, our examples of speci cation monads can be understood as relative monads from Set to Pos, relative to the functor Disc sending a set to itself seen as a discrete poset. However, since bind is required to be monotonic in both arguments, we will also need to consider a Pos-enriched setting. Note that the bind operation is de ned as a function between hom-sets and need not to be representable as a "multiplication" natural transformation: there is in general no way to compose M twice. This means that in order to enrich this de nition in a category V, for instance V = Pos, we need to consider not only V-categories, V-functors and V-natural transformations, but also the structure of V-hom objects, namely V-profunctors. The further generalization to framed bicategories [START_REF] Shulman | Framed bicategories and monoidal brations[END_REF] in the next sections will provide a synthetic and convenient context to consider these objects together.

Relative monads as presented in [START_REF] Altenkirch | Monads need not be endofunctors[END_REF] also come with their notions of morphism and algebras that we recall here. Until the end of this section, we x categories I, C, a base functor J : I → C and J -relative monads M, M .

De nition 3.2.2. A J -relative monad morphism from M to M is a natural transformation θ : M → M such that θ x • ret M x = ret M x θ y • (bind M x,y f ) = bind M x,y (θ y • f ) • θ x
for any objects x, y ∈ I and f ∈ C(J x, M y).

De nition 3.2.3. An Eilenberg-Moore algebra, or simply M-algebra, is an object a ∈ C together with a natural transformation

α x : C(J x, a) . - → C(M x, a)
satisfying the two identities

α x (f ) • ret x = f α y (bind f • g) = α x (f ) • g for any x, y ∈ I, f : J x → a, g : J y → M x.
M-algebras together with the appropriate notion of morphism form a category EM(M). The Kleisli category Kl(M) is the category with object set |I| and with morphisms Kl(M)(x, y) = C(J x, M y). Any morphism of relative monad θ : M → M induces two factorizations

Kl(θ) : Kl(M) → Kl(M )
and EM(θ) : EM(M ) → EM(M).

Framed bicategories

We would like to extend the notion of relative monads to categories other than Cat, in particular to the ordered setting, however 2-categories does not seem to be the right setting for a formal theory of relative monads. Indeed, an object of an arbitrary 2-category does not necessarily have the hom-structure that we would need in order to de ne a bind operation. The notion of framed bicategory introduced by [START_REF] Shulman | Framed bicategories and monoidal brations[END_REF] provides this data. In this section, we brie y present this notion and recall the instances that we will use further.

De nition 3.3.1. A framed bicategory F is a double category with a distinguished class of 2-cells verifying a universal property, that is a set of objects or 0-cells |F|;

for each pair of objects X, Y ∈ |F|, a set of vertical arrows or vertical 1-cells F v (X, Y ), and a set of pro-arrows or horizontal 1-cells F h (X, Y ). We write f :

X → Y for a vertical arrow f ∈ F v (X, Y ) and h : X - - → Y for a proarrow M ∈ F h (X, Y ).
for each frame as on the left, a set of

2-cells f F g (M, N ), where α ∈ f F g (M, N ) is noted as on the right X Y X Y f M g N X Y X Y f M g N ⇓ α
vertical and horizontal units and compositions • and noted as follows,

X Y X Y M M X X Y Y f X f Y X 1 Y 1 X 2 Y 2 X 3 Y 3 f M1 f g M2 g M3 ⇓ α ⇓ β = X 1 Y 1 X 3 Y 3 gf M1 g f M3 ⇓ βα X Y Z X Y Z u M1 v M2 w N1 N2 ⇓ α ⇓ β = X Z X Z u M1 M2 w N1 N2 ⇓ α β
Vertical composition is associative and unital, whereas the horizontal composition is usually associative and unital only up to coherent natural isomorphisms, the associator and unitors2 . We do not explicitly write those, appealing to the fact that they can be stricti ed in the same fashion as for (weak) 2-categories. The two compositions are related by a distributivity law that in ne ensures that all diagrams have a unique well-de ned reading.

for any vertical cells f, g and horizontal cell M as on the left, a cartesian ller for the niche formed by

f, M, g, that is a 2-cell χ ∈ f F g (f * M g * , M ).
Being cartesian means here that χ satis es the following universal property: any other ller α

∈ f h F gk (N, M ) of the niche, factors through χ, yielding a 2-cell f * αg * ∈ h F k (N, f * M g * ) unique up to unique globular isomorphism (that is a 2-cell whose vertical borders are identities). X 1 Y 1 X 2 Y 2 f g M X 1 Y 1 X 2 Y 2 f f * M g * g M ⇓ χ X 1 Y 1 X 3 Y 3 f h N gk M ⇓ α = X 1 Y 1 X 2 Y 2 X 3 Y 3 h N k f f * M g * g M ⇓ χ ⇓ f * αg *
The framed category Distr The canonical example of a framed bicategory is given by Distr whose objects are (small) categories C, D ∈ Distr, abou, 2000), that is bifunctors H : D op × C → Set, and

vertical arrows J ∈ Distr v (C, D) are functors J : C → D, horizontal arrows H ∈ Distr h (C, D) are distributors H : C - -→ D (a.k.a. profunctors) (Ben-
2-cells α ∈ J Distr K (G, H) are natural transformations α c,d : G(d, c) . - → H(Kd, J c) C D C D J G K H ⇓ α
Vertical identities and composition are identity functors and functor composition as in Cat.

Horizontal identities C(-, -) : C --→ C are hom-sets bifunctors and horizontal composition

H G : C - -→ E for distributors H : C - -→ D, G : D - - → E is given by the coend formula H G(e, c) = d∈D G(e, d) × H(d, c) If F, G : C → D are functors, we note that vertical 2-cells α ∈ F Distr G (C(-, -), D(-, -)) are in natural bijection with natural transformations G . - → F , witnessed by the following calcu- lation [C op × C, Set](C(-, -), D(G-, F -)) ∼ = (c,c )∈C op ×C Set(C(c, c ), D(G c, F c )) ∼ = c ∈C c∈C op Set(C(c, c ), D(G c, F c )) ∼ = c ∈C [C op , Set](C(-, c ), D(G -, F c )) ∼ = c ∈C D(G c , F c ) ∼ = [C, D](G, F )
where the second isomorphism holds by Fubini, the fourth by Yoneda lemma and the others by formulation of the set of natural transformations as a end.

Because of this correspondence, we will more generally note α :

g . - → f for a 2-cell α ∈ f F g (C, D
) in an arbitrary framed bicategory F with identities as horizontal domains and codomains.

The framed category V-Distr If V is a complete and cocomplete symmetric monoidal closed category, we can generalize the de nition of Distr to the V-enriched setting [START_REF] Kelly | Basic Concepts of Enriched Category Theory[END_REF], obtaining a framed bicategory V-Distr consisting of V-categories, V-functors, V-distributors and V-natural transformations between distributors. We will frequently use this example with V a cartesian closed-category.

Underlying 2-categories A framed bicategory F naturally induces two di erent 2-categories: the 2-category F v consisting of 0-cells, vertical arrows and vertical 2-cells, that is 2-cells such that the horizontal domains and codomains are identities:

X X Y Y f X g Y ⇓ α
the 2-category F h consisting of 0-cells, horizontal arrows and globular 2-cells, that is 2cells such that the vertical arrows are identities:

X Y X Y M N ⇓ α
Depending on the context, we will sometimes consider the underlying 1-category of the (strict)

2-category F v keeping the same notation.

String diagrams notations To ease calculations in framed bicategories, we will use a variant of the string diagram notation developed in [START_REF] Myers | String diagrams for double catgeories and equipments[END_REF]. As it is usually the case with string diagrams, we represent a cell on the left by its Poincaré dual on the right.

X 1 Y 1 X 2 Y 2 f M g N ⇓ α N M f g α
A 0-cell is corresponds to an area, a vertical arrow to an horizontal simple line, an horizontal arrow to a double line and a 2-cell to a point, represented by a labelled node. We read these diagrams from top to bottom and right to left. This convention is taken to be coherent with the direction of natural transformations in Distr: a natural transformation α :

K . - → J between functors K, J : C → D, that is α ∈ J Distr K (C, D)
, will be drawn as as follows.

C D D D J C K D ⇓ α J K α
String diagrams also account for cartesian llers by bending the strings. Given a niche as on the left, a cartesian ller for this niche is depicted on the right.

f ? g M f g M f * M g * f * αg * k h N M α k h N f g =
Applying the property to the adequate niche, we have for any vertical arrow f :

X → Y , horizontal arrows f * Y : X - - → Y and Y f * : Y - - →
X called respectively the companion and conjoint of f . The relationship between f , f * Y and Y f * is described by the following string diagrams:

f * Y f f * Y f f Y f * f Y f * f f = f f f f = f f f * Y f * Y = f * Y f * Y Y f * Y f * = Y f * Y f *
Since vertical arrows can be be bent both to a companion and conjoint, we mark the direction of the arrow to keep track of which we are talking about: a single vertical line is a companion when it is directed from top to bottom, and a conjoint when directed from bottom to top. We will sometimes abbreviate both f * Y and Y f * by just f * on diagrams to simplify notations, leaving to the reader the task to infer whether we are talking about the conjoint or companion of f from the non-ambiguous direction of arrows.

Framed functor, framed representability

In order to de ne objects by universal properties in a framed bicategory, we develop the basic notions of framed representability. We start by recalling the notions of (strong) framed functor and framed natural transformation de ned in [START_REF] Shulman | Framed bicategories and monoidal brations[END_REF].

De nition 3.4.1. Let F, G be framed bicategories. A (strong) framed functor K : F → G is a vertically strict, horizontally strong double functor between the underlying double categories of F and G. In components, it consists of:

a function K : |F| → |G| from 0-cells in F to 0-cells in |G|, a functorial action on vertical 1-cells K v : F v (X, Y ) → G v (K X, K Y ), a pseudo-functorial action on horizontal 1-cells K h : F h (X, Y ) → G h (K X, K Y ) with globular 2-cells K h M K h N ∼ = K h (M N ) and K h X ∼ = K X satisfying the coherence axioms for a strong 2-functor, a functorial assignment of 2-cells X 1 Y 1 X 2 Y 2 f M g N ⇓ α -→ K X 1 K Y 1 K X 2 K Y 2 Kvf K h M Kvg K h N ⇓ Kα
Fixing a framed bicategory F, any object C ∈ |F | de nes a "framed presheaf" よ C , that is a framed functor from F op , the framed category obtained from F by formally reversing the direction of vertical 1-cells and 2-cells, to the framed bicategory Distr of categories, functors, distributors and natural transformations. The framed functorよ C maps:

a 0-cell X ∈ |F| to the categoryよ C (X) = F v (X, C) of vertical morphisms from X to C and vertical 2-cells; a vertical 1-cell f ∈ F op v (X, Y ) = F v (Y, X) to the functor F v (X, C) → F v (Y, C) ob- tained by precomposition by f ; an horizontal 1-cell M ∈ F h (X, Y ) to the distributor whose component at h X ∈ F v (X, C), h Y ∈ F v (Y, C) consists of the set of 2-cellsよ C (M ) h X ,h Y = { α | α ∈ h X F h Y (M, C
) } as represented below on the left, and the functorial action is given by composition of vertical

2-cells α X : g X . - → h X , α Y : h Y .
-→ g Y on the sides as described on the right -→ L between framed functors K, L : F → G consists of a family ν X : K X → L X of vertical 1-cells of G indexed by 0-cells X ∈ |F| natural with respect to vertical 1-cells in F and a compatible family

X Y C C h X M h Y C ⇓ α X X Y Y C C C C g X X h X M h Y Y g Y C C C ⇓ α X ⇓ α ⇓ α Y a 2-cell γ ∈ f F op g (M, N ) = f F op g (N, M ) to the natural transformation between distrib- utors よ C (γ) : よ C (M ) . - → よ C (N ) given at component h X ∈ F v (X, C), h Y ∈ F v (Y, C) by the function よ C (γ) h X ,h Y = X Y C C h X M h Y C ⇓ α -→ X Y X Y C C f N g h X M h Y C ⇓ α ⇓ γ Given a vertical 1-cell f : C → C in F, we can de ne functorsよ f (X) : よ C (X) → よ C (X)
ν M ∈ ν X G ν Y (K h M, L h M ) indexed by horizontal 1-cells M ∈ F h (X, Y ) natural with respect to 2-cells in F satisfying addi- tionally the two equations K X K Z L X L Z ν X K h M ν Y L h M ⇓ ν M N = K X K Y K Z L X L Y L Z ν X K h M ν Y K h N ν Y L h M L h N ⇓ ν M ⇓ ν M K X K X L X L X ν X K X ν X L X ⇓ ν X = K X K X L X L X ν X K X ν X L X
where we silently use the isomorphisms witnessing pseudo-functoriality for horizontal composition and identities.

It is shown in [START_REF] Shulman | Framed bicategories and monoidal brations[END_REF]) (proposition 6.17) that framed bicategories, framed functors and framed natural transformations form a strict 2-category. We use part of that fact to state the following lemma: Lemma 3.4.1. For any framed bicategory F, the assignment C → よ C extends to a functor よ : Distr] where F v is the 1-category de ned by vertical arrows in F and [F op , Distr] is the category of framed functors from F op to Distr and framed natural transformations.

F v → [F op ,
Proof. We already proved thatよ C : F op → Distr is a framed functor. Given a 1-cell f : C → C , the framed natural transformationよ f : よ C .

-→ よ C is given on a 0-cell X by the functor de ned by postcomposition by f , and on a horizontal 1-cell M by the natural transformation between distributorsよ C (M ) .

-→ よ C (M ) induced by postcomposition with the identity 2-cell on f . Lemma 3.4.2 (framed (weak) Yoneda lemma). Let F be a framed category, C an object of F and H : F op → Distr a framed functor. There is a natural bijection

[F op , Distr](よ C , H) ∼ = |H(C)| Proof. The bijection ϕ : [F op , Distr](よ C , H) ∼ -→ |H(C)| is de ned by ϕ(ν) = ν C (id C ). For an object h ∈ H(C), its inverse ϕ -1 (h) is the framed natural transformation given at components X ∈ |F| and M : X - - → Y by ϕ -1 (h) X = f ∈ よ C (X) = F v (X, C) → H(f )(h) ∈ H(X) ϕ -1 (h) M = α ∈ よ C (M ) → H(α)(id h ) ∈ H(M )
where

id h ∈ Id H(C) (h, h) ∼ = H(Id C )(h, h
) is the element of the distributor H(Id C ) representing the identity on h. To prove that they are inverse to each other, we rst compute ϕ

• ϕ -1 (h) = ϕ -1 C (id C ) = H(id C )(h) = h.
For the other equality, we observe that, by naturality, any natural

transformation ν ∈ [F op , Distr](よ C , H) veri es the identities ν X (f ) = ν X •よ C (f )(id C ) = H(f ) • ν C (id C ) ν M (α) = ν M •よ C (α)(Id C ) = H(α) • ν Id C (id Id C ) where X ∈ F, f ∈ よ C (X) = F v (X, C), M : X - - → Y, α ∈ よ C (M ) = f,g f F g (M, C) In particular, we have ϕ -1 (ϕ(ν)) X (f ) = H(f )(ϕ(ν)) = H(f ) • ν C (id C ) = ν X (f ) ϕ -1 (ϕ(ν)) M (α) = H(α)(id ϕ(ν) ) = H(α) • ν Id C (id Id C ) = ν M (α) that is ϕ -1 • ϕ(ν) = ν. Corollary 3.4.1. The functorよ : F v → [F op , Distr] is full and faithful. Proof. For any objects C, D ∈ |F v |, [F op , Distr](よ C ,よ D ) ∼ = |よ D (C)| = F v (C, D)
We say that a framed functor H : F op → Distr is represented by an object C ∈ |F| if there is a framed natural isomorphism H ∼ = よ C , and H is representable if there exists an object C representing it.

Dually, any object C ∈ |F| de nes a framed functor c よ C : F → Distr whose action on

0-cell is given by c よ C (X) = F v (C, X)
. Dualizing all the previous discussion, c よ de nes a full and faithful functor

F v → [F, Distr] op . A framed functor G : F → Distr is said to be co- representable if it is isomorphic to c よ C for some C ∈ |F|.

Relative monad in a framed bicategory

Having in hand the powerful notion of framed bicategory, we now set out to de ne what is a relative monad inside a framed bicategory. The idea is that thanks to the horizontal morphisms playing the role of a hom-structure on the objects of a framed bicategory F, we can almost reenact the de nition in Cat in F, replacing the base functor by a vertical arrow.

De nition 3.5.1 (Relative monad). Let F be a framed bicategory, j :

I → C be a vertical 1-cell of F. A j-relative monad is a triple (m, ret, bind) composed of a vertical 1-cell m : I → C, a 2-cell ret : j . - → m, or diagrammatically I I C C m j ⇓ ret ret j m a 2-cells bind : C(j, m) . - → C(m, m), where we note C(h, k) = k * Ch * , I I I I C(j,m) C(m,m) ⇓ bind m * C Cj * m * C Cm * bind inducing a mapping (-) † from 2-cells to 2-cells mb F ja (M, C) → mb F ma (M, C) for vertical arrows a : A → C, b : B → C and horizontal arrow M : B - - → A α † a m m b R α a j m b R m m bind =
such that the following equations hold

ret † = id m α † • ret = α (β † • α) † = β † • α † for any objects X, Y, Z ∈ F, vertical 1-cells f : X → i, g : Y → i, h : Z → i and 2-cells α : j • f . - → m • g, β : j • g . - → m • h.
In string diagrams notations, the relative monad equations give respectively

m m bind ret = m m m * C Cj * m * C bind ret j m * C j m * C Cj * = m * C Cj * m * C bind m * C Cj * Cm * bind m * C Cj * bind Cj * m * C Cm * bind m * C =
Inside Distr A relative monad in Distr is the same thing as a a relative monad over a functor (Def. 3.2.1) between small categories. Given such a j-relative monad m in Distr, j being a vertical arrow therein, it is quite immediate that m has the structure of a relative monad over the functor j and satis es the required equations. Conversely, in order to show that a relative monad (M, ret, bind) over a functor J : I → C is a relative monad in Distr, it is enough to show that M extends to a functor I → C and that ret and bind are natural in the appropriate sense. The relevant proof can be found in [START_REF] Altenkirch | Monads need not be endofunctors[END_REF].

Speci cation monads as relative monads in Pos-Distr Speci cation monads are our original motivation for moving to relative monads in the enriched setting of Pos-Distr. Indeed, the two ingredients needed to de ne speci cation monads are:

1. a carrier for speci cation monads mapping sets to preorders, and 2. preordered hom-sets, and natural transformations between preorder enriched posets that are monotonic so that the bind operation is monotonic in both arguments.

The main protagonists for a formal de nition of speci cation monads are the Pos-categories

Set and Pos3 where the former is seen as an enriched category through the monoidal 4 functor Disc : Set → Pos sending a set to itself equipped with the discrete preorder, and the latter by cartesian closedness. We note Disc : Set → Pos the lifting of Disc to Pos-functor.

De nition 3.5.2. A speci cation monad is a Disc-relative monad in Pos-Distr. This can be seen as a more abstract presentation of preorder-enriched monads [START_REF] Katsumata | Preorders on monads and coalgebraic simulations[END_REF][START_REF] Rauch | Generic Hoare logic for order-enriched e ects with exceptions[END_REF].

Eilenberg-Moore Algebras We x a base vertical arrow j : I → C and a j-relative monad m in F. We want to extend the notion of algebra for a relative monad. Of course, in a general framed bicategory we may not have a "unit object, " as we do in Cat, so we need to de ne algebras with respect to an arbitrary vertical arrow instead of an "object of C" , in a similar way as using generalized elements in ordinary category theory.

De nition 3.5.3. An m-algebra is an object A ∈ F, a vertical arrow a : A → C together with a natural transformation α : C(j, a)

.

-→ C(m, a) satisfying the two identities

α x (f ) • ret x = f α y (α x (f ) • g) = α x (f ) • bind g for any x, y ∈ I, f : J x → a, g : J y → M x. α a * C Cj * a * C Cm * α a * C Cj * a * C ret j j a * C Cj * a * C = a * C Cj * a * C α m * C Cj * Cm * bind a * C Cj * α Cj * a * C Cm *
B → C, β) from B to an m-algebra (A, bf : A → C, β f ) where β f is de ned as follow using that (bf ) * C ∼ = f * b * C: β b * C Cj * b * C Cm * f * C On a horizontal 1-cell M : A - - → B, Alg m (M ) is the distributor whose component at (a : A → C, α), (b : B → C, β) is given by the set of 2-cells ν ∈ a F b (M, C) such that ν β α ν M a m a M = b * j * b * j * m
Finally, the action of Alg m on a 2-cell is given by vertical precomposition.

De nition 3.5.5. An Eilenberg-Moore object for a j-relative monad m in F is a representing object for the framed functor Alg m (in the sense of section 3.4). When it exists, it is noted EM m .

The relative monad m always has a canonical m-algebra structure given by bind, so it induces a factorization in [F op , Distr]

Alg m よ I よ C u よm m
where u forgets the m-algebra structure and only keep the underlying arrows in F. When m has an Eilenberg-Moore object, this factorization happens directly inside F v by the framed Yoneda lemma Lem. 3.4.2.

In the case of the framed bicategory V-Distr for V a suitable category for enrichment, these Eilenberg-Moore objects exists up to size conditions. Let J : I → C be a V-functor between V-categories I, C and M : I → C be a J -relative monad (in V-Distr). The V-category C M has as underlying set of objects pairs (c, α) composed of an object c ∈ |C| and a V-natural transformation α : C(J -, c) .

-→ C(M-, c) between V-presheaves. The object of morphism between (c 1 , α 1 ) and (c 2 , α 2 ) is obtained as the equalizer

C M ((c 1 , α 1 ), (c 2 , α 2 )) C(c 1 , c 2 ) x∈|I| [C(J x, c 1 ), C(M x, c 2 )]
where the arrows on the right are obtained by currying the two maps

C(J x, c 2 ) C(c 1 , c 2 ) ⊗ C(J x, c 1 ) C(M x, c 2 ) C(c 1 , c 2 ) ⊗ C(M x, c 1 ) α 2 × α 1 • • Theorem 3.5.1. C M is the Eilenberg-Moore object of M in V-Distr.
Proof. We need to show that the described V-category C M is a representing object for the functor Alg M , that is to exhibit a framed natural isomorphism ϕ :

よ C M ∼ = Alg M .
On object X ∈ V-Distr v , we de ne ϕ X by projecting out the components

(uc, α(c)) out of an algebra c ∈ C M . For f ∈ よ C M (X) = V-Distr v (X, C M ), we de ne a J -relative M-algebra structure on uf : X → C by α(f ) a,b : C(J a, uf b) → C(M a, uf b)) whose naturality in b is provided by functoriality of f . A vertical 2-cell θ : f . - → g is mapped to ϕ X (θ) = uθ : uf → ug.
It is a J -relative M-algebra homomorphism since each components of θ are.

Conversely, we de ne

ϕ -1 (f, α) = f ∈ よ C M (X) for (f, α) ∈ Alg M (X)
by setting f x = f x on objects x ∈ X and obtaining the action of f on X(x 1 , x 2 ) ∈ V from the universal property of the V-hom of C M using the fact that α is an M-algebra structure on f :

X(x 1 , x 2 ) C M ((f x 1 , α x1 ), (f x 2 , α x2 )) C(f x 1 , f x 2 ) x∈|I| [C(J x, f x 1 ), C(M x, f x 2 )] f f For a vertical 2-cell θ : (f, α) . - → (g, β), we de ne the vertical 2-cell ϕ -1 X (θ) = θ : f .
-→ g by another application of the universal property (where θx is the special case of the diagram below precomposed with id x )

X(x 1 , x 2 ) C M ((f x 1 , α x1 ), (g x 2 , β x2 )) C(f x 1 , g x 2 ) x∈|I| [C(J x, f x 1 ), C(M x, g x 2 )] θx 2 •f =g•θx 1 θx 1 •f =g• θx 2 ϕ -1
X is indeed an inverse to ϕ X by unicity of the universal property. Since the action of よ C M and Alg M on vertical arrows is given by precomposition and the de nition of ϕ X and its inverse only act on the codomain, there are natural with respect to vertical arrows. The de nition of ϕ on horizontal arrows M : X --→ Y then proceeds similarly to the case of vertical 2-cells.

Kleisli algebras

We introduce the dual notion to Eilenberg-Moore algebras for a relative monad, corresponding to a right module on a monad. Since they are not modules, and by lack of a suitable terminology, we call them here Kleisli algebras.

De nition 3.5.6. A Kleisli algebra is a a vertical arrow f : I → X to some object X ∈ F together with a 2-cell α ∈ I F I (C(j, m), X(f, f )) satisfying the two following equations where λ and ρ are framed natural transformation de ned at a 0-cell X ∈ F as follows λ forgets the Kleisli algebra structure and maps a pair (f :

f f α ret = f f m * C Cj * f * C α m * C Cj * Cf * α m * C Cj * bind Cj * f * C Cf *
: X - - → Y de nes a profunctor Kl m (M ) : Kl m (X) - - → Kl m (Y ) whose component at (f, α) ∈ Kl m (X) and (g, β) ∈ Kl m (Y ) is the set of 2-cells χ ∈ f F g (I, M ) such that α m * C Cj * χ M g f χ M g f β m * C Cj * = 2-cells ϕ ∈ h F h (M,
I → X, α) ∈ Kl m (X) to f ∈ c よ I (X) = F v (I, X); ρ sends a vertical arrow f ∈ c よ C (X) = F v (C, X) to the Kleisli algebra (f m, α) where α is induced by the bind operation from m α m * j * m * f * f * m * bind m m * j * m * m * f * f * =
We say that a j-relative monad m in F has a Kleisli object if the framed functor Kl m is corepresented by a 0-cell C m ∈ F. In that situation, the factorization c よ m = λ • ρ through Kl m above induces vertical arrows l : I → C m and r : C m → C such that m = rl.

In the particular case of F = V-Distr for an enriching category V, any J -relative monad M ∈ V-Distr(I, C) has a Kleisli object C M . The explicit construction of C M is quite standard: take |I| as the set of objects |C M | and for x, y ∈ |I| de ne C M (x, y) = C(J x, M y) with identity given by ret M x ∈ C(J x, M x) and composition induced by bind M , namely

C(J y, M z) × C(J x, M y) bind M ×id ------→ C(M y, M z) × C(J x, M y) • -→ C(J x, M z).
Lemma 3.5.1. C M is the Kleisli object of M in V-Distr.

Morphisms of relative monads

Morphisms between two monads relative to the same base functor has been de ned in [START_REF] Altenkirch | Monads need not be endofunctors[END_REF]. Here we generalize the de nition of morphisms to relative monads in a framed bicategory F over possibly di erent base arrows.

Let F be a framed bicategory and j 1 :

I 1 → C 1 , j 2 : I 2 → C 2 two vertical morphisms in F. A morphism from j 1 → j 2 is a pair of vertical cells u dom : I 1 → I 2 and u cod : C 1 → C 2 and an invertible 2-cell ϕ : u cod • j 1 ⇒ j 2 • u dom . ϕ j 2 u dom j 1 u cod ϕ -1 j 2 u dom j 1 u cod
Equivalently, reinterpreting j 1 and j 2 as 2-functors from the arrow category 2 to the 2category F v , (u dom , u cod , ϕ) is the data of a pseudo-natural transformation.

I 1 C 1 I 2 C 2 j 1 u dom u cod j 2 ∼ = ϕ
De nition 3.5.8 (Morphism of relative monad). Let u = (u dom , u cod , ϕ) :

j 1 → j 2 . A morphism of relative monads θ : m 1 → u m 2 from a j 1 -relative monad m 1 to a j 2 -relative monad m 2 over u is a 2-cell θ : u cod • m 1 . - → m 2 • u dom θ m 2 u dom m 1 u cod such that θ m 2 u cod u dom ret 1 j 1 ϕ m 2 u cod u dom j 1 ret 2 = m 1 θ m 2 u dom u cod = m 2 m 1 u cod θ ϕ -1 u dom bind 1 m * 1 j * 1 bind 2 θ m * 1 j * 1 u cod m 2 u dom
It is not totally clear that we obtained the right de nition and the following lemma shows that at the very least a property that we would expect in the classical monadic case still hold, namely that relative monad morphisms factor through the Kleisli algebras objects when those exists. 5Conjecture 3.5.1. Assume the Kleisli objects C m 1 and C m 2 exists, inducing factorizations m 1 = r 1 l 1 and m 2 = r 2 l 2 . Then relative monad morphisms θ : m 1 → u m 2 factorize as pairs of a vertical arrows v : C m 1 → C m 2 and a vertical 2-cell θ : u cod r 1 .

-→ r 2 ν tting in the following diagram

I 1 C 1 m 1 C 1 I 2 C 2 m 2 C 2 u dom l 1 v r 1 u cod l 2 r 2 ⇓ θ
Proof idea. Let θ : m 1 → u m 2 be a relative monad morphism, we de ne v by co-representability, so we construct a framed natural transformation

ν : c よ C 2 m 2 ∼ = Kl m 2 -→ c よ C 1 m 1 ∼ = Kl m 1 .
Given an object X, a Kleisli algebra (a :

I 2 → X, α) ∈ Kl m 2 (X) is sent to the Kleisli algebra ν X (a, α) ∈ Kl m 1 (X) composed of a u dom : I 1 → X together with the algebra structure α a u dom j * 1 m * 1 a u dom ϕ -1 θ j 2 m 2
u cod ν X acts on Kleisli algebra morphisms by precomposition with u dom . Given a proarrow M :

X - - → Y , ν M sends natural transformations in Kl m 2 (M )((a, α), (b, β)) to natural transformations in Kl m 1 (M )(ν X (a, α), ν Y (b, β
)) also by precomposition with u dom .

In order to nish the proof we would need to exhibit θ but this would require us an notion of framed modi cation between framed natural transformation c よ θ : c よ r 1 • c よ u cod → ν • c よ r 2 and an adequate representation theorem, which would go far beyond the purpose of this chapter. We leave this proof un nished but note that we have a canonical candidate for this would-be

c よ θ evaluated at a component X ∈ |F| and f ∈ c よ C 2 (X) = F v (C 2 , X), namely the Kleisli algebra morphism (f u cod m 1 , bind m 1 ) → ν X (f m 2 , bind m 2 ) = (f m 2 u dom , . . .) induced by θ : u cod m 1 . - → m 2 u dom .

The 2-category of relative monads

Given a framed bicategory F, we obtain a 2-category RelMon(F) of relative monads in F:

A 0-cell m = (I, C, j, m) of RelMon(F) consists of a pair of objects I, C ∈ |F|, a vertical morphism j : I → C and a j-relative monad m.

A 1-cell θ = (u dom , u cod , ϕ, θ) : m 1 → m 2 consists of 1-cells u dom : i 1 → i 2 , u cod : c 1 → c 2 , an invertible 2-cells ϕ ∈ u dom F u cod (j 1 , j 2
) and a morphism of relative monad θ from m 1 to m 2 over ϕ.

Finally a 2-cell ζ : θ → θ , where θ = (u dom , u cod , ϕ, θ), θ = (v dom , v cod , ψ, θ ), is given by a pair (ζ cod , ζ dom ) of 2-cells in F ζ dom u dom v dom ζ cod u cod v cod such that ϕ j 1 u cod j 2 v dom ψ j 1 u cod j 2 v dom ζ cod ζ dom = θ m 1 u cod m 2 v dom θ m 1 u cod m 2 v dom ζ cod ζ dom =
A vertical arrow j ∈ F v (I, C) can be alternatively seen as a (2-)functor from the category

2 = • → • to the 2-category F v . This observation leads to a 2-functor U : RelMon(F) → [2, F v ] ps from RelMon(F) to the functor 2-category [2, F v ] ps of 2-functors from 2 to F v ,
pseudo-natural transformations and modi cations. U is de ned by projecting out the relevant data. It has a left 2-adjoint, sending a vertical cell j ∈ F v (I, C) to the j-relative monad j with return and bind being identities.

We will often restrict our attention to subcategories of RelMon(F) over a particular vertical arrow j ∈ F v (I, C). We note RelMon(F) j the full 2-subcategory of RelMon(F) on 0-cells mapped to j by U and 1-cells mapped to the identity of j.

Correspondence to monads As a consistency check, we prove that relative monads in F over identities are the same as monads in the 2-category F v . To do so, we rst restrict RelMon(F) to the 2-category RelMon(F) id of those relative monads over an identity. RelMon(F) id can be built as the strict 2-pullback

RelMon(F) id RelMon(F) F v [2, F v ] ps U δ
where δ : ) and RelMon(F) id are isomorphic.

F v → [2, F v ]
Note that the direction of the 2-cells in F v has to be reversed when building the category of monads. This is because the notion of relative monad morphism we introduced corresponds to morphisms between Kleisli objects and not between Eilenberg-Moore objects.

Proof. The proof is a generalization of the usual correspondence between monads and Kleisli triples, amounting to unfold the de nitions and checking that everything still makes sense. We proceed by dimension of the cells. The converse, sending a monad m to a relative monad over the identity is similar, de ning bind

as bind = m * m * m * µ m * m * m *
For 1-cells. Given a relative monad morphism θ = (u dom , u cod , θ) : m 1 → m 2 between relative monads m 1 and m 2 respectively over the identity of C 1 , C 2 ∈ |F|, we have rst a 1-cell

u = u dom = u cod : C 1 → C 2 .
Then the 2-cell θ : um 1 → m 2 u satisfy the simpli ed equations

ret m1 ret m2 = θ η 1 = m 2 η 2 = u u θ m 2 u u u u m 2 m 2 u u µ 1 m 1 m 1 m 1 m 1 bind m1 m 2 m 1 m 1 bind m2 = = = θ m 2 u u θ m 2 u u θ u θ u µ 2 m 2 θ θ u u m 1 m 1 corresponding exactly to a 1-cell in Mnd(F op(2) v
).

Conclusion & Related work

We brie y recalled the basic de nitions of the theory of 2-categories [START_REF] Bénabou | Introduction to bicategories[END_REF] to access elements of the formal theory of monads [START_REF] Kelly | Review of the elements of 2-categories[END_REF][START_REF] Lack | The formal theory of monads ii[END_REF][START_REF] Street | The formal theory of monads[END_REF], in particular the synthetic de nition of a monad in a 2-category, the construction of the category of monads and the general de nition of Eilenberg-Moore object (as well as Kleisli objects) as representing objects. We use a similar methodology for relative monads [START_REF] Altenkirch | Monads need not be endofunctors[END_REF] in the context of framed bicategories [START_REF] Shulman | Framed bicategories and monoidal brations[END_REF], de ning in full generality a 2category of relative monads and adequate notions of Eilenberg-Moore and Kleisli objects. Since this encompass enriched relative monads, the theory applies directly to speci cation monads. We then further prove that our extension is compatible with the formal theory of monads when restricting our attention to monads relative to identities.

We prove only modests results on relative monads in a framed bicategory, but these already demonstrate that it is possible to carry out a formal theory of relative monads at a high-level of generality and with simple proofs thanks to string diagrams. As future work, we consider extending and formalizing these results inside type theory, e.g., Coq, not only for formally (re-)proving these results, but also to use them directly to derive actual instances such as speci cation monads.

We now review further related work.

Other generalizations of relative monads [START_REF] Fiore | Relative pseudomonads, kleisli bicategories, and substitution monoidal structures[END_REF] introduce the notion of relative pseudo-monad to study the construction of category of presheaves and deal with size issues, generalizing relative monads to a bicategorical setting.

A close line of work is the study of skew-monoids: [START_REF] Altenkirch | Monads need not be endofunctors[END_REF] shows that assuming some property on a functor J : I → C, we can give to the functor category a skew-monoidal structure ⊗ J such that J -relative monads coincide with skew-monoids, the adequate notion of monoids for ⊗ J . The study of skew monoidal categories and related structure is a rather recent but dynamic research eld [START_REF]Remarks on units of skew monoidal categories[END_REF]Bourke and Lack, 2018a,b;[START_REF] Lack | Skew-monoidal re ection and lifting theorems[END_REF][START_REF] Szlachányi | Skew-monoidal categories and bialgebroids[END_REF][START_REF] Uustalu | The sequent calculus of skew monoidal categories[END_REF]. In particular, skew monoids often yields construction closer in spirit to the traditional theory of monads, however important examples we consider in chapter 6 do not t immediately in that framework, whereas they do yield relative monads.

Alternative to framed bicategories We chose to work in this chapter with framed bicategories, but other choices are available such as proarrow equipments [START_REF] Wood | Abstract pro arrows i[END_REF][START_REF] Wood | Proarrows ii[END_REF], Yoneda structures [START_REF] Street | Yoneda structures on 2-categories[END_REF] or yosegi boxes [START_REF] Liberti | On the unicity of formal category theories[END_REF]. This latter work shows that under a few hypothesis these di erent structures yield equivalent formal category theory. It would be interesting to understand how much of the formal theory of relative monads we sketch here could be achieved in the other settings. We use monad transformers [START_REF] Liang | Monad transformers and modular interpreters[END_REF] to construct all kind of complex monadic objects on top of simple basic blocks: sophisticated computational monads of course, but also expressive speci cation monads, as well as e ect observations section 2.4. However, de ning a monad transformer and proving that it satis es all the expected laws requires signi cant e ort. This is in sharp contrast with the impression that quite a few examples of monad transformers are, at least intuitively, mild generalization of naturally occurring monads, and consequently should be almost as easy to de ne. In this chapter, we present a methodology to reduce the denition of a monad transformer to that of a monad in an adequate metalanguage. We rst review more precisely the notion of monad transformer, exploring its generalization to relative monads and then set out to de ne a domain speci c language that we call the Speci cation Metalanguage (SM) adapted to the task of de ning monad transformers. The goal of SM is to de ne monad transformers preserving speci cation monads, and we detail a few interesting point of its implementation in the Coq proof assistant. We close the chapter with a more categorical viewpoint on SM, potentially leading to future extensions.

What is a monad transformer ?

Informally, a monad transformer takes a monad as input and outputs another monad, often extended with further capabilities as demonstrated by the examples in section 2.2. To be useful in practice, it must come with a way to lift computations from the original monad into the transformed monad. We expect a monad transformer to also apply to monad morphisms so that embedding between monads (so-called sube ecting in F ) give rise to a monad morphism between the transformed monads. The lift has to be consistent with respect to this action on monad morphisms, resulting in the following de nition.

T id m = id T m , T (θ • θ ) = T θ • T θ ,
and such that the monad morphism lift m is natural in m, that is for any monad morphism θ :

m 1 → m 2 , T θ • lift m 1 = lift m 2 • θ
Following [START_REF] Lüth | Composing monads using coproducts[END_REF], we can concisely rephrase this de nition by saying that We will see shortly that all the examples of monad transformers in section 2.2 actually lift to such speci cation monad transformers.

a

Towards a language for de ning monad transformers

If we want to build a monad transformer, we could consider at a rst approximation that it consists of a function taking a monad as a parameter and returning a monad. Thinking syntactically for a short while, we can describe such functions from the data of a monad in a context containing variables standing for a monad M and its operations. Leveraging this simple idea, we want to design a language SM equipped with a type former M X for a type X standing for an abstract monad variable, such that a monad T in SM naturally elaborates to a monad transformer by substituting an actual monad to the monad variable M:

T M A = T[M/M] A (4.1)
This language SM should build upon a base language L describing the base category C over which the elaborated monad transformers T are de ned.

What is missing in this picture for T to de ne an actual monad transformer ? First, we need T to be functorial in M. Second, we need a lifting coercion from the M to T M. A simplistic solution for the rst problem is to require all type constructors of SM to be covariant in their type arguments so that we can elaborate a functorial action for T by design. For the second problem, Lemma 4.2.1. Let M 1 , M 2 be monads (on a category C). There is a bijective correspondence between:

C ::= MA | C 1 × C 2 | (x : A) C | C 1 C 2 A ∈ Type L t ::= ret | bind | (t 1 , t 2 ) | π i t | x | λ x. t | t 1 t 2 | λx. t | t u u ∈ Term L
1. monad morphisms θ : M 1 . - → M 2 , 2. liftings L : C → C M 1 of M 2 along U : C M 1 → C the forgetful functor from the category of M 1 -algebra C M1 C C U L M2
such that the multiplication of M 2 lifts to an M 1 -algebra morphism,

for each

A ∈ C, assignments of M 1 -algebra structure α A : M 1 M 2 A → M 2 A such that for any f : A → M 2 B, bind M 2 f : M 2 A → M 2 B is an M 1 -algebra morphism.
Proof. 2 and 3 can be readily seen to be in bijective correspondence by the usual correspondence between multiplication-based presentation and bind-based presentation of monads (see the proof of Thm. 3.5.2). The correspondence between 1 and 3 follows from instantiating Lem. 4.5.2 to the special case of relative monads over the identity functor of C in Distr.

Since we want such a lifting for every monad M, naturally in M, we should generalize the previous lemma to collection of monads, however that generalization turns out to be rather technical and we defer it to section 4.5 where we develop this categorical approach in more details. The important point to keep in mind is that a type in SM should in particular be elaborated to a family consisting of M-algebra for each monad M in the base language L (or correspondingly on the base category C). This dependency on the argument monad can be naturally expressed by a dependent product and provides an important motivation for developing our language SM on top of a dependently typed language.

A DSL for speci cation monad transformers

In this section, we introduce the Speci cation Metalanguage, SM, and a translation from SM to correct-by-construction monad transformers in a base dependent type theory L (where L is a parameter of SM). More precisely, the translation takes as input a monad in SM subject to two extra conditions, covariance and linearity corresponding to the two points raised in previous subsection, and produces a speci cation monad transformer in L.

∆ L ∆; • SM ∆; Γ SM C ∆; Γ, x : C SM ∆ L A ∆; Γ SM ∆; Γ SM MA ∆; Γ SM C 1 ∆; Γ SM C 2 ∆; Γ SM C 1 × C 2 ∆, x : A; Γ SM C ∆; Γ SM (x : A) C ∆; Γ SM C 1 ∆; Γ SM C 2 ∆; Γ SM C 1 C 2 ∆; Γ SM A : Type ∈ ∆ ∆; Γ SM ret : A MA ∆; Γ SM A, B : Type ∈ ∆ ∆; Γ SM bind : MA (A MB) MB ∆; Γ SM x : C ∈ Γ ∆; Γ x : C ∆, x : A; Γ SM t : C ∆; Γ SM λx. t : (x : A) C ∆; Γ L u : A ∆; Γ SM t : (x : A) C ∆ SM t u : C[u/x] ∆; Γ, x : C 1 SM t : C 2 ∆; Γ SM λ x. t : C 1 C 2 ∆; Γ SM t 2 : C 1 ∆; Γ SM t 1 : C 1 C 2 ∆; Γ SM t 1 t 2 : C 2 ∆; Γ SM t i : C i ∆; Γ SM (t 1 , t 2 ) : C 1 × C 2 ∆; Γ SM t : C 1 × C 2 ∆; Γ SM π i t : C i

Presentation of the language SM

The design of SM, whose syntax is presented in Figure 4.1, has been informed by the goal of de ning monad transformers. First, since we want a mapping from monads to monads, we introduce the type constructor M standing for an arbitrary base monad, as well as terms ret and bind.

Second, in order to describe monads internally to SM, we add function types (x :

A) → C[x]
and C 1 → C 2 . We allow dependent function types only when the domain is in L, leading to two di erent type formers. We write dependent abstractions as λx. t, whereas we write the nondependent abstraction where the domain is a type in SM as λ x. t. In Figure 4.2 we present the typing rules of SM which are mostly standard. We assume that L has three judgements ∆ L , ∆ L A and ∆ L u : A de ning respectively well-formed contexts in L (that we will always note ∆), well-formed types in a context (noted A, B) and well-typed terms. We also assume that L has at least one universe Type that we use for dependent products. We then de ne the judgements ∆; Γ SM for well-formed contexts of SM, ∆; Γ SM C for well-formed types and ∆; Γ SM t : C for well-formed terms. We implicitly assume a conversion rule with respect to convertibility in L1 . The main rules of the equational theory of SM are given in Figure 4.3. SM is expressive to de ne many di erent monads in a natural way using structure of the underlying dependent type theory L2 , for example 1. reader Rd(X : Type) = I M X;

∆ L a : A ∆; Γ SM f : A M B ∆; Γ SM bind (ret a) f ≡ f a : M B ∆; Γ SM m : M A ∆; Γ SM bind m ret ≡ m : M A ∆; Γ SM m : M A 1 ∆; Γ SM f : A 1 M A 2 ∆; Γ SM g : A 2 M A 3 ∆; Γ SM bind m (λx. bind (f x) g) ≡ bind (bind m f ) g : M A 3 ∆; Γ SM t 1 : C 1 ∆; Γ SM t 2 : C 2 ∆; Γ SM π i (t 1 , t 2 ) ≡ t i : M C i ∆; Γ SM t : C 1 × C 2 ∆; Γ SM (π 1 t, π 2 t) ≡ t : C 1 × C 2 ∆, x : A; Γ SM t : C ∆ L u : A ∆; Γ SM (λx. t) u ≡ t{u/x} : C ∆; Γ SM t : (x : A) C ∆; Γ SM λx. t x ≡ t : (x : A) C ∆; Γ, x : C 1 SM t 1 : C 2 ∆; Γ SM t 2 : C 1 ∆; Γ SM (λ x. t 1 ) t 2 ≡ t 1 {t 2 /x} : C 2 ∆; Γ SM t : C 1 C 2 ∆; Γ SM λ x. t x ≡ t : C 1 C 2 ∆; Γ SM t 1 ≡ t 2 : (x : A) C ∆ L u 1 ≡ u 2 : A ∆; Γ SM t 1 ≡ t 2 : C[u 1 /x]
+ re exivity, symmetry, transitivity and congruence for all other term constructors 5. monotonic state MonSt(X) = (s 0 : S) M(X × (s 1 : S) × s 0 s 1 ), where is some preorder on states S; and 6. continuations Cont Ans (X) = (X M Ans) M Ans.

The covariance condition states that the symbol M standing for an arbitrary base monad appears only in the codomain of arrows. The more involved linearity condition concerns the bind of these monads. With the exception of continuations (see subsection 4.3.5), all these SM monads satisfy these extra conditions and thus lead to proper monad transformers, in particular all examples from section 2.2 can be obtained from a de nition in SM.

Elaborating speci cation monads and lift

To de ne a monad transformer, we use monads internal to SM, given by a type constructor X : Type;

• SM C[X]; terms A : Type; • SM ret C : A → C[A]
A, B : Type;

• SM bind C : (A → C[B]) → C[A] → C[B];
such that the monadic laws (see Def. 2.1.1) are derivable in the equational theory of SM. Now, given a monad C internal to SM, we want to de ne the corresponding monad transformer T C evaluated at a monad M in the base language L, essentially as the substitution of M for M (Equation 4.1). In order to make this statement precise, we de ne in Figure 4.4 a denotation -M of SM types as types in L equipped with an order parametrized by a speci cation monad M. In the base case C = M A, the order is given by the speci cation monad M, whereas the order is given pointwise in all the other cases. The only surprise happens in the case C = C 1 C 2 where we restrict the denotation to functions monotonic with respect to the orders on C 1 and C 2 . This restriction is needed to ensure the monotonicity of the denotation of terms (Thm. 4.3.1).

MA M = MA C 1 × C 2 M = C 1 M × C 2 M (x : A) → C M = (x : A) C M C 1 C 2 M = (f : C 1 M → C 2 M ) × (∀(m 1 ≤ C 1 m 1 ). f m 1 ≤ C 2 f m 1 ) m ≤ M A m = m ≤ M A m (m 1 , m 2 ) ≤ C 1 ×C 2 (m 1 , m 2 ) = m 1 ≤ C 1 m 1 ∧ m 2 ≤ C 2 m 2 f ≤ (x:A) C[x] f = ∀(x : A). f x ≤ C[x] f x f ≤ C 1 C 2 f = ∀(m 1 : C 1 M ). f m 1 ≤ C 2 f m 1 Figure 4.4: Elaboration of types from SM to L ret δ;γ M = ret M bind δ;γ M = bind M (t 1 , t 2 ) δ;γ M = t 1 δ;γ M , t 2 δ;γ M π i t δ;γ M = π i t δ;γ M x δ;γ M = γ(x) λ x C 1 . t M = λx C 1 M . t δ;γ[x:=x] M t 1 t 2 δ;γ M = t 1 δ;γ M t 2 δ;γ M λx A . t δ;γ M = λx A[δ] . t δ[x:=x];γ M t u δ;γ M = t δ;γ M u[δ]
The denotation of terms -or rather of typing derivations for terms -is presented in Fig- Provided that L has extensional dependent products and pairs, meaning that surjective pairing and functional extensionality are valid in L, this denotation preserves the equational theory of SM and produces monotonic terms in the following sense:

Theorem 4.3.1 (Monotonicity of denotation). Let M be an ordered monad, ∆; Γ SM t : C a term in SM, L δ : ∆ a substitution for the L context ∆, ( L γ i : Γ M ) i=1,2 substitutions for the SM context Γ such that ∀(x : C 0 ) ∈ Γ. γ 1 (x) ≤ C 0 γ 2 (x). Then t δ;γ 1 M ≤ C t δ;γ 2 M .
The proof of preservation of the equational theory is a long but rather straightforward induction on the derivation of an equality between SM terms. We only reproduce here the proof of monotonicity.

Proof. By induction on the typing derivation of t:

Case t = ret A : A MA, by re exivity ret A δ;γ 1 M = ret M A ≤ A MA ret M A = ret A δ;γ 2 M Case t = bind A,B : (A MB) (MA MB), by re exivity, that holds because bind M is monotonic bind A,B δ;γ 1 M = bind M A,B ≤ (A MB) (MA MB) bind M A,B = bind A,B δ;γ 2 M Case t = (t 1 , t 2 ) : A × B, by induction hypothesis t 1 M δ;γ 1 ≤ A t 1 M δ;γ 2 t 2 M δ;γ 1 ≤ B t 2 M δ;γ 2 so (t 1 , t 2 ) M δ;γ 1 = t 1 M δ;γ 1 , t 2 M δ;γ 1 ≤ A×B t 1 M δ;γ 2 , t 2 M δ;γ 2 = (t 1 , t 2 ) M δ;γ 2
Case t = π i t : A i , by induction hypothesis and extensionality

π 1 t δ;γ 1 M , π 2 t δ;γ 1 M = t δ;γ 1 M ≤ A 1 ×A 2 t δ;γ 2 M = π 1 t δ;γ 2 M , π 2 t δ;γ 2 M so π i t δ;γ 1 M ≤ A i π i t δ;γ 2 M Case t = λx. t : (x : A) C, by induction hypothesis for any v : A, t δ[x:=v];γ 1 M ≤ C[v/x] t δ[x:=v];γ 2 M
we conclude by reduction since

λx. t δ;γ 1 M v = (λy. t δ[x:=y];γ 1 M ) v = t δ[x:=v];γ 1 M Case t = t v : C{v/x} , by induction hypothesis ∀v 0 : A. t δ;γ 1 M v 0 ≤ C[v 0 /x] t δ;γ 2 M v 0 so t v δ;γ 1 M = t δ;γ 1 M v ≤ C[v/x] t δ;γ 2 M v = t v δ;γ 2 M Case t = λ x. t : C 1 C 2 , for any m 1 ≤ C 1 m 2 , γ 1 [x := m 1 ] ≤ Γ,x:C 1 γ 1 [x := m 2 ]
and by induction

t δ;γ 1 [x:=m 1 ] M ≤ C 2 t δ;γ 2 [x:=m 2 ] M and we conclude since for i = 1, 2 ( λ x. t δ;γ i [x:=y] M ) m i = (λy. t δ;γ i [x:=y] M ) m i = t δ;γ i [x:=m i ] M Case t = t 1 t 2 : C 2 , by induction hypothesis applied to t 2 : C 1 , t 2 δ;γ 1 M ≤ C 1 t 2 δ;γ 2 M
so by induction hypothesis applied to t

1 : C 1 C 2 t 1 δ;γ 1 M t 2 δ;γ 1 M ≤ C 2 t 1 δ;γ 2 M t 2 δ;γ 2 M
From these results, we deduce that a monad C internal to SM induces the following mapping from speci cation monads to speci cation monads:

T C : (M, ret, bind) -→ ( C M , ret C M , bind C M )
For instance, taking C = St, the de nition evaluates to T St M = X → S → M(X × S).

To build the lift for T C , we adapt Lem. 4.2.1 to the current setting. The denotation C M of an SM type C in L is by design canonically endowed with an M-algebra structure α C M : M C M → C M . This M-algebra structure is de ned by induction on the structure of the SM type C, using the free algebra when C = MA and the algebra de ned pointwise in all the other cases. Inspecting the proof of the lemma (or rather of Lem. 4.5.2), we obtain that this M-algebra structure induces a lifting function from the monad M to the monad C M as follows:

lift C M,X : M(X) M(ret C M ) -------→ M C M (X) α C M,X ---→ C M (X) = T C M(X)
For instance, for the state transformer, the lift functions is given by

lift St M,X (m : M X) = λ(s : S). M(λ(x : X). (x, s)) m : S → M(X × S).
The result that SM type formers are automatically equipped with an algebra structure explains why SM features products, but not sums since the latter cannot be equipped with an algebra structure in general.

Elaborating the action on monad morphism

To de ne a monad transformer, we still need to build a functorial action mapping monad morphism θ :

M 1 → M 2 between monads M 1 , M 2 in L to a monad morphism C M 1 → C M 2 .
However, the denotation of the arrow C 1 C 2 does not allow for such a functorial action since C 1 necessarily contains a subterm M in a contravariant position. In order to get an action on monad morphisms, we rst build a (logical) relation between the denotations. Given M 1 , M 2 monads in L and a family of relations

R A ⊂ M 1 A × M 2 A indexed by types A, we build a relation {|C|} R M 1 ,M 2 ⊂ C M 1 × C M 2 as follows m 1 {|MA|} m 2 = m 1 R A m 2 (m 1 , m 1 ) {|C 1 × C 2 |} (m 2 , m 2 ) = m 1 {|C 1 |} m 2 ∧ m 1 {|C 2 |} m 2 f 1 {|(x : A) → C|} f 2 = ∀(x : A). f 1 x {|C x|} f 2 x f 1 {|C 1 → C 2 |} f 2 = ∀m 1 m 2 . m 1 {|C 1 |} m 2 ⇒ f 1 m 1 {|C 2 |} f 2 m 2
Now, when a type C in SM comes with the data of an internal monad, the relational denotation {|C|} - M,W maps not only families of relations to families of relations, but also preserves the following structure that we call a monadic relation:

De nition 4.3.1 (Monadic relation). A monadic relation 3 R : M 1 ↔ M 2 between monads M 1 and M 2 , consists of: a family of relations R A : M 1 A × M 2 A → P indexed by types A, such that returned values are related (ret M 1 v) R A (ret M 2 v) for any value v : A,
and such that sequencing of related computations is related

m 1 R A m 2 ∀(x : A). (f 1 x) R B (f 2 x) (bind M 1 m 1 f 1 ) R B (bind M 2 m 2 f 2 ) for any m 1 : M 1 A, m 2 : M 2 A, f 1 : A → M 1 B, f 2 : A → M 2 B.
If moreover M 1 , M 2 are speci cation monads, we say that R is monotonic when it is compatible with the orders

∀A (m 1 ≤ M 1 A m 1 ) (m 2 ≤ M 2 A m 2 ). m 1 R A m 2 ⇒ m 1 R A m 2 . that is each R A is and ideal of M 1 A × M 2 A.
The simplest example of monadic relation is the graph of a monad morphism θ : M → W. In the frequent case where M is a computational monad and W is a speci cation monad, we can consider M as equipped with a discrete order and θ induces a monotonic relation R θ de ned as m R θ w ⇐⇒ θ m ≤ W w. Given a monadic relation, we extend the relational translation to terms and obtain the so-called fundamental lemma of logical relations. Theorem 4.3.2 (Fundamental lemma of logical relations). For any monads

M 1 , M 2 in L, monadic relation R : M 1 ↔ M 2 , term Γ SM t : C and substitutions γ 1 : Γ M 1 and γ 2 : Γ M 2 , if for all (x : C ) ∈ Γ, γ 1 (x) {|C |} R M 1 ,M 2 γ 2 (x) then t γ 1 M 1 {|C|} R M 1 ,M 2 t γ 2 M 2 .
Moreover this relational interpretation preserves the order induced by the input speci cation monad.

Theorem 4.3.3 (Monotonicity of relational interpretation). Let ∆ SM C type, M 1 , M 2 two spec- i cation monads and (R A ) A a family of monotonic relations R A : M 1 A × M 2 A → P, then {|C|} R M 1 ,M 2 is monotonic.
Proof. by induction on the derivation of C :

Case C = M A, {|M A|} R M 1 ,M 2 = R A is monotonic by assumption Case C = C 1 × C 2 , suppose (m 1 , m 2 ) {|C 1 ×C 2 |} R M 1 ,M 2 (n 1 , n 2 ), (m 1 , m 2 ) ≤ C 1 ×C 2 (m 1 , m 2 ), (n 1 , n 2 ) ≤ C 1 ×C 2 (n 1 , n 2 ) then by induction hypothesis m 1 {|C 1 |} R M 1 ,M 2 n 1 and m 2 {|C 2 |} R M 1 ,M 2 n 2 so (m 1 , m 2 ){|C 1 × C 2 |} R M 1 ,M 2 (n 1 , n 2 ) Case C = (x : A) → C , suppose f {|(x : A) → C |} R M 1 ,M 2 g, f ≤ (x:A)→C f and g ≤ (x:A)→C g then for any v : A, (f v) {|C {v/x}|} R M 1 ,M 2 (g v), f v ≤ C {v/x} f v, g v ≤ C {v/x} g v so by inductive hypothesis (f v) {|C {v/x}|} R M 1 ,M 2 (g v), hence f {|(x : A) → C |} R M 1 ,M 2 g Case C = C 1 → C 2 , suppose f {|C 1 → C 2 |} R M 1 ,M 2 g, f ≤ C 1 →C 2 f and g ≤ C 1 →C 2 g , for any m {|C 1 |} R M 1 ,M 2 n, (f m) {|C 2 |} R M 1 ,M 2 (g n), m ≤ C 1 m and n ≤ C 2 n so f m ≤ C 2 f m and g n ≤ C 2 g n, hence by induction hypothesis (f m) {|C 2 |} R M 1 ,M 2 (g n)
As a corollary, an internal monad C in SM induces a mapping from (monotonic) monadic relations to (monotonic) monadic relations, the relational interpretation of ret C and bind C providing witnesses to the preservation of the monadic structure. In particular, any monad morphism

θ : M 1 → M 2 de nes a monadic relation {|C|} R θ M 1 ,M 2 : C M 1 ↔ C M 2 .
It turns out that if C is moreover covariant, meaning that it does not contain any occurrence of an arrow C 1 → C 2 where C 1 is a type in SM, then the relational denotation {|C|} R θ M 1 ,M 2 with respect to any monad morphism θ : M 1 → M 2 is actually the graph of a monad morphism.

The last missing bit in order to obtain a speci cation monad transformer out of C is to prove that the elaborated lift C M : M → C M is natural, that is, that the following diagram should commute:

M A M C M A C M A M B M C M B C M A M(ret C A ) M f α C M,A M C M f C M f M(ret C B ) α C M,B ?
for any A, B and f : A → B. Observe that the left square commutes automatically by the naturality of M (ret C ). However, for the right square to commute

C M f = bind C M (ret C M •f )
needs to be an M-algebra homomorphism, which is exactly the condition required by Lem. 4.2.1.

The next section explains how to capture this semantic condition syntactically using a linear type system. We call that syntactic condition on the monad (C, ret C , bind C ) internal to SM the linearity of bind C .

To summarize the results of our approach language-base approach to monad transformers, we have: Theorem 4.3.4 (Construction of monad transformer from SM). Given a monad C internal to SM such that bind C satis es the linearity criterion, we obtain:

if C is covariant, then T C equipped with lift C M :M→T C M is a (ordered) monad transformer;
if C is not covariant, T C de nes a pointed endofunctor on the category of (ordered) monads and monadic relations.

Linear type system for SM

In this section, we elaborate a simplistic syntactic criterion on a monad C internal to SM ensuring the semantic condition that bind C maps functions to M-algebra homomorphisms. To do so, we recast the homomorphism condition as a linearity condition in a modi ed type system for SM equipped with a stoup: a distinguished variable in the context such that the term typed in the judgement is linear with respect to that variable [START_REF] Egger | The enriched e ect calculus: syntax and semantics[END_REF][START_REF] Munch-Maccagnoni | Syntax and Models of a non-Associative Composition of Programs and Proofs[END_REF]. We note such distinguished contexts Γ | Ξ where Γ is a normal SM context and Ξ is the stoup. The stoup can be either empty or containing one variable of a type C from SM. Linear types are a re nements of types from SM given by the following grammar

L := C | C 1 C 2 | L 1 × L 2 | (x : A) → L | L 1 → L 2 where A ∈ Type L , C, C 1 , C 2 ∈ Type SM .
In particular the linear function space C 1 C 2 should be understood as a subtype of C 1 → C 2 whose denotation ought to be a set of homomorphisms with respect to the algebra structures on the denotations of its domain and codomain, thus cannot be nested. A linear judgement is of the form ∆; Γ | Ξ lin t : L with the invariant that if Ξ is non-empty then Ξ = x : C 1 and L = C 2 for SM types SM C 1 and SM C 2 .

The following theorem explains the aim of the linear type system: Theorem 4.3.5 (linear terms are homomorphisms). Let M be a monad, Γ |lin t : C 1 C 2 a term in SM and γ : Γ M , then the following diagram commutes

M C 1 M C 1 M M C 2 M C 2 M α C 1 M M t γ M t γ M α C 2 M Γ | Ξ lin t 1 t 2 : C 2 Γ | -lin t 2 : C 1 Γ | Ξ SM t 1 : C 1 → C 2 Γ | Ξ lin t 1 t 2 : C 2
M A M C M A C M A M B M C M B C M A M(ret C A ) M f α C M,A M C M f C M f M(ret C B ) α C M,B
Thus, under the assumption that bind C has a linear typing derivation (a syntactic object), we prove that its denotation is homomorphic with respect to the relevant M -algebra structure.

In order to prove the Thm. 4.3.5, we need to :

provide an interpretation of the linear types;

show that linear derivations yield a denotation in this interpretation;

prove using a logical relation that the linear interpretation of a term is related to the monotonic interpretation.

Case t = t 1 t 2 , otherwise, (|t 1 t 2 |) δ;γ;ξ M = (|t 1 |) δ;γ;ξ M (|t 2 |) δ;γ;- M and λξ. (|t 1 |) δ;γ;ξ M (|t 2 |) δ;γ;- M is an M - algebra map whenever λξ. (|t 1 |) δ;γ;ξ M is an M -algebra map
Given a linear type L, we can forget all the linear annotations, obtaining a type SM |L| in SM. In the same fashion, given a derivation ∆; Γ | Ξ lin t : L, we can obtain a derivation ∆; |Γ, Ξ| SM t : |L|. In order to relate (|t|) M and t M , we introduce the following relation

|L| M ⊆ (|L|) M × |L| M : m |C| M m ⇐⇒ m = m f |C 1 C 2 | M f ⇐⇒ f = f (x 1 , x 2 ) |L 1 × L 2 | M x 1 , x 2 ⇐⇒ x 1 |L 1 | M x 1 ∧ x 2 |L 2 | M x 2 f |(x : A) → L| M f ⇐⇒ ∀(x : A). f x |L| M f x f |L 1 → L 2 | M f ⇐⇒ (∀x x . x |L 1 | M x → f x |L| M f x )
We extend component-wise this relation to context, and a straightforward but tedious induction shows that for any linear derivation ∆; Γ | Ξ lin t : L and context L δ : ∆, L γ :

(|Γ | Ξ|) M , γ : |Γ, Ξ| M , if γ |Γ | Ξ| M γ then (|t|) δ;γ M |L| M t δ;γ
M where the right hand side denotation is obtained from the SM derivation ∆; |Γ, Ξ| SM t : |L|. In the particular case where Ξ is empty and all types in Γ are free from linear annotations, we obtain Thm. 4.3.5.

The Continuation Monad Pseudo-Transformer

Crucially, the internal continuation monad Cont Ans does not verify the conditions to de ne a monad transformer since it is not covariant in M. We study this (counter-)example in detail since it extends the de nition of [START_REF] Jaskelio | Monad transformers as monoid transformers[END_REF] to monadic relations and clari es the prior work of [START_REF] Ahman | Dijkstra monads for free[END_REF], where a Dijkstra monad was obtained in a similar way.

While SM gives us both the computational continuation monad Cont Ans Id = Cont Ans and the corresponding speci cation monad Cont Ans Cont P = Cont Cont P (Ans) , we only get a monadic relation between the two and not a monad morphism. We write this monadic relation as follows:

Cont Ans Id ←-
m {|Cont Ans |} ret Id,Cont P w ⇔ ∀(k : X → Ans) (w k : X → Cont P (Ans)). (∀(x : X). ret (k x) = w k x) ⇒ ret (m k) = w w k ⇔ ∀(k : X → Ans). ret (m k) = w (λx. ret (k x)) ⇔ ∀(k : X → Ans) (p : Ans → P). w (λx q. q (k x)) p = p (m k)
For illustration, if we take Ans = 1, the last condition reduces to ∀(p : P). w (λx q. q) p = p, in particular any sequence x 0 , . . . , x n induces an element w = λk p. k x 0 (. . . k x n p) : Cont Ans Cont P (X) that can be seen as a speci cation revealing some intensional information about the computation m at hand, namely, that the continuation k was called with the arguments x 0 , . . . , x n in this particular order. Computationally however, in the case of Ans = 1, m is extensionally equal to λk. * : Cont 1 .

Embedding SM in Coq

We have formalized the SM language presented in the previous section in Coq, taking Gallina as the base language L and providing an implementation of the denotation of SM terms and logical relation-based elaboration to speci cation monad transformers. The original goals of this implementation was to provide modular construction of monad transformers helping us in the de nition of speci cation monads, ultimately leading to constructions of Dijkstra monads as explained in section 5.1. For this purpose, the equality proofs witnessing the monadic laws of speci cation monads have to be as simple as possible, even holding de nitionally when achievable. As a consequence, our implementation of SM should:

1. generate monad transformers whose monadic operations are elaborated terms that compute inside Coq; and 2. whenever an elaborated monad transformer is applied to a speci cation monad whose monadic laws hold de nitionally, the resulting speci cation monad also has de nitional monadic laws.

With these goals in mind, we start by explaining our design choices for implementing SM, in particular the representation of binders. An unexpected di culty arise when trying naively to prove equalities between SM terms, and we explain how we bypass this problem by implementing an abstract machine.

The implementation (https://gitlab.inria.fr/kmaillar/dijkstra-monads-for-all) uses the Equations library [START_REF] Sozeau | Equations reloaded: High-level dependently-typed functional programming and proving in coq[END_REF] 4 and covers all the previously discussed aspects of SM but the linear type system.

Implementation of the language SM

Two main possibilities arise when implementing a domain speci c language (DSL) such as SM: either de ne a deep embedding, that is an object of the host language describing the syntax, or shallowly embed it in the host language itself, reusing all available features.

On the one hand, a full deep embedding of SM would require to implement a dependently typed language inside Coq and to provide all the features of Gallina that we assume in instances of monad transformers, for instance sum types. This option was dismissed as seemingly to costly.

On the other hand, an embedding using higher-order abstract syntax [START_REF] Pfenning | Higher-order abstract syntax[END_REF] would take care of all the conversions in L, but require some care for the λ x. t binders since they are not straightforwardly elaborated to Gallina's functions.

We implemented the latter, with intrinsically typed syntax, meaning that the type describing the term syntax of SM is actually a type-family indexed by the type of SM types (named ctype in the implementation).

An unconvincing attempt: Parametric Higher-Order Abstract Syntax Our rst tentative for the term syntax of SM uses PHOAS [START_REF] Chlipala | Parametric higher-order abstract syntax for mechanized semantics[END_REF] to encode the λ x. t binders and is presented in Figure 4.7. The idea is to de ne the term syntax with respect to an arbitrary type of variables VarType , and to quantify universally over this type. A term t : forall '{ VarType}, cterm c can then be elaborated to a variety of other formats by instantiating with the right type of variables carrying some polymorphic substitution as explained in [START_REF] Atkey | Unembedding domain-speci c languages[END_REF]. For instance, taking the type of variables to be the type-family cterm itself, we easily recover syntactic substitution of terms. The denotation t M of an SM term with respect to a monad M can also be obtained in this fashion. We could wonder whether the type forall '{ VarType}, cterm c actually captures faithfully the syntax of SM. After all, nothing prevent us from implementing a function in that type that rst inspects the given instance of VarType before choosing which term to return. The solution to this problem is to restrict our attention to parametric terms of that type. Indeed [START_REF] Atkey | Syntax for free: Representing syntax with binding using parametricity[END_REF] shows that the only parametric inhabitant of this type are actual pieces of syntax. This result is however external to the type theory and, in order to actually prove lemmas on the elaboration, we need to accompany every term t : forall '{ VarType}, cterm c with a proof of (unary) parametricity. Furthermore, to build a relation between two elaborations of a term, for instance between the denotations t M and t M , we need a witness of (binary) relational parametricity whose type is shown in Figure 4.8. This starts to be a bit tedious but the problem only gets worse: since we want to prove property on our (proof-relevant) relation, we need a proof that the witness of parametricity itself is parametric. The fact that writing by hand parametricity types and witnesses is hardly achievable was an expected problem and [START_REF] Chlipala | Parametric higher-order abstract syntax for mechanized semantics[END_REF] uses an axiom providing uniformly proofs of parametricity. Beside the fact that it would make Coq inconsistent, we did not use this approach because we want to de ne objects that compute out out of the parametricity witness, a property broken by such an axiom. We also tried using the paramcoq plugin 5 , an external tool to derive automatically the types and witnesses of parametricity. However the generated code turned out to be di cult to use in practice: for our application we only need parametricity in the parameter VarType whereas paramcoq provides parametricity of all parameters which results in a much more complex object. To carry out practically an approach using PHOAS, it would be convenient to work inside a type theory with internalized parametricity such as those described in [START_REF] Bernardy | Type-theory in color[END_REF]; [START_REF] Bernardy | A presheaf model of parametric type theory[END_REF].

| Pair : forall {c1 c2}, cterm (c1 c2 c1 × c2) | Proj1 : forall {c1 c2}, cterm(c1 × c2 c1) | Proj2 : forall {c1 c2}, cterm(c1 × c2 c2) | Abs : forall A (c: forall x:A, ctype), ( forall x:A, cterm (c x)) → cterm (CArr c) | App : forall {A} { c: forall x:A, ctype} ( v : A), cterm (CArr c) → cterm (c v) | CVar : forall {c:ctype}, var c → cterm c | CAbs : forall (c1:ctype) (c2: ctype), ( var c1 → cterm c2) → cterm (c1 c2) | CApp : forall {c1:ctype} { c2: ctype}, cterm (c1 c2) → cterm c1 → cterm c2. End CTerm.
A mixed approach: De Bruijn meets HOAS In our second attempt, we implement SM terms using at the same time higher-order abstract syntax (HOAS) for the λx. t binders and De Bruijn indices for the λ x. t ones. This mixed approach frees us from handling explicitly dependent products (x : A) C, relying instead on Gallina, while it provides the exibility we need on the non-dependent product C 1 C 2 .

Section CTermRel. Context (var1 var2 : VarType) (varR : forall c, var1 c → var2 c → Type).

Inductive cterm_rel : forall {c}, @cterm var1 c → @cterm var2 c → Type : We build the functional version of the logical relation for a covariant type C, but omit the linear type system6 . Instead, the Coq version of Thm. 4.3.4 assumes a semantic hypothesis requiring that the denotation of bind is homomorphic (where ctype_alg M c : M c M → c M is the algebra structure on the elaboration):

= | MRetRel : forall A, cterm_rel (MRet A) (MRet A) | MBindRel : forall A B, cterm_rel (MBind A B) (MBind A B) | AbsRel : forall {A c ct1 ct2} ( cr : forall x:A, @cterm_rel (c x) (ct1 x) ( ct2 x)), cterm_rel (Abs A c ct1) ( Abs A c ct2) | AppRel : forall {A c} { ct1 ct2 : cterm (CArr c)} ( v: A), cterm_rel ct1 ct2 → cterm_rel (ct1 @• v) (ct2 @• v) | CVarRel : forall {c v1 v2}, varR c v1 v2 → cterm_rel (CVar v1) (CVar v2) | CAbsRel : forall {c1 c2} { f1 : var1 c1 → cterm c2} {f2 : var2 c1 → cterm c2}, ( forall x1 x2, varR c1 x1 x2 → cterm_rel (f1 x1) (f2 x2)) → cterm_rel (CAbs c1 c2 f1) (CAbs c1 c2 f2) | CAppRel : forall {c1 c2} { ct11 ct12 : cterm (c1 c2)} {ct21 ct22}, cterm_rel ct11 ct12 → cterm_rel ct21 ct22 → cterm_rel (ct11 @• ct21) (ct12 @• ct22). End CTermRel.
, icterm Γ (c x)) → icterm Γ (CArr c) | IApp : forall {Γ c} (H:isArr c) ( v: arrDom H), icterm Γ c → icterm Γ (arrCod H v) | ICVar : forall {Γ} (n:nat) ( H: in_ctx n Γ), icterm Γ (lookup H) | ICAbs : forall {Γ c1 c2}, icterm (c1:: Γ) c2 → icterm Γ (c1 c2) | ICApp : forall {Γ c} (H:isArrC c), icterm Γ c → icterm Γ (arrCDom H) → icterm Γ (arrCCod H).
Definition homomorphism c1 c2 (f : c1 M → c2 M ) := let α 1 := ctype_alg M c1 in let α 2 := ctype_alg M c2 in forall m, f ( α 1 m) = α 2 (f <$> m).
Assuming this condition hold on the (partial) elaboration of an internal monad c, we can then derive the full monad transformer (including all the laws). In practice, this condition hold denitionally on our examples, for instance for the state monad presented in Figure 4.10, so there is no proof overhead. The implementation of the embedding together with the necessary lemmas about the metatheory of SM (substitution, weakening lemma. . . ), the elaborations and the logical relation, as well as a few examples of monad internal to SM amount to 4kloc, evenly separated between specications and proofs.

Proving equalities between SM terms

As explained in section 4.3, the construction of monad transformer takes as input monad internal to SM. For most of the examples at the beginning of that section, the de nition of the underlying type constructor and monadic operations is tedious but not di cult to encode in the deep embedded syntax. However, it turned out that providing the required equality proof witnessing the monadic laws explicitly as equational derivation is hardly manageable even for a simple example such as state (Figure 4.10). Acknowledging the di culty, we explain here how we sidestepped this task by de ning an abstract machine re ning the equational theory of SM. The key idea is rst to provide an evaluator for SM putting SM terms into canonical forms; and then proving the correctness of the evaluator with respect to the equational theory, generating a witness that a term is equal to its normal form as a byproduct.

A con guration of the abstract machine is a triple (t, π, σ) consisting of a term t, a stack π and an environment σ (a substitution) for SM terms. We use the notation t || π σ for con gurations. The implementation of stacks in Coq as well as the type of the functions reducing con gurations of the abstract machine and rebuilding terms out of con gurations are presented in Figure 4.12. In order to describe the abstract machine we use the following notations: the empty stack is , a rei ed continuation is noted Cont(t), projections are noted π i , consing a Coq value v on top of a stack π is v • π and an SM term t is t π. The transitions of the abstract machine per-se are noted . When the abstract machine reaches a con guration t || π σ where t is a returned value or a variable bound to a neutral term in the environment, it switches to the rebuilding procedure noted . The rebuilding phase apply to con gurations t • π, dismantling the stack π -essentially corresponding to an inside-out one-hole term context C π [-] -to reconstruct a term t ≡ C π [t]. Since abstract machine con gurations ultimately produce a term, we make a small abuse of notations in the rule reducing @•, placing directly the result of evaluating the con guration t 2 || * id on the top stack.

As shown in the declared type of reduce, the implementation in Coq uses step-indexing (the argument ( fuel:nat)) to enforce termination. We introduced this abstract machine for a pragmatic purpose, and in that respect this trick achieve the goal successfully at a low implementation cost. Nonetheless, termination of the abstract machine should be provable without, since the part of SM the abstract machine is reducing is essentially simply typed.

Towards a categorical approach to relative monad transformers

Beside the implemented version of SM, we wish to have a more conceptual understanding of the limitations and potential extensions of the SM language. In particular, the Coq development of SM is specialized to produce speci cation monad transformers, however most of the proofs seem to be of general nature, enabling an extension to other kind of relative monad transformers. In this section, extend Lem. 4.2.1 in two di erent directions. First, we extend it to account for a collection of monads, or rather to natural transformations θ : F .

-→ G between functors F, G : K → Mnd(C) from a category K to to monads on a category C, objects that we call (K-)indexed

ret v || π σ ret v[σ] • π t • * t bind t 1 t 2 || π t 1 Cont(λx. t 2 x || π ) t • Cont(f ) f † t (t 1 , t 2 ) || π i • π t i || π t • π i • π π i t • π π i t || π t || π i • π t • v • π t @• v • π λx. t || v • π t[x/v] || π t • t 1 π t @• v • π t @• v || π t || v • π x || π σ σ(x) • π when σ(x) is neutral x || π σ σ(x) || π id otherwise λ x. t || t 1 π σ t || π σ[x:=t 1 ] t 1 @• t 2 || π σ t 1 t 2 || id π σ
StckCont : forall A, ( A → icterm Γ c) → stack (CM A) | StckProj1 : forall c' ( H: isProd c'), stack (prodProj1 H) → stack c' | StckProj2 : forall c' ( H: isProd c'), stack (prodProj2 H) → stack c' | StckArg : forall c' ( H: isArr c') ( v: arrDom H), stack (arrCod H v) → stack c' | StckCArg : forall c' ( H: isArrC c'), icterm Γ (arrCDom H) → stack (arrCCod H) → stack c'. Definition reduce (Γ 0 : ctx) (fuel:nat) : forall c0 Γ c (t:icterm Γ c) (π:@stack Γ 0 c0 c) (σ : isubstitution Γ 0 Γ), icterm Γ 0 c0.
Definition rebuild Γ {c0 c} (π : @stack Γ c0 c): forall (t:icterm Γ c), icterm Γ c0. monads in [START_REF] Maillard | A brational account of local states[END_REF]. Second, we explain how to generalize this lemma to the case of relative monads in a framed bicategory, closing the loop with the setting of chapter 3. As a motivation, observe that a simple special case of natural transformations between indexed monads recover the notion of monad transformers. Given categories K, C and functors

F, G : K → Mnd(C), a natural transformation θ : F . - → G is a collection of monad morphisms θ k : F k . - → G k for k ∈ K.
Taking K to be the category Mnd(C) of monads on C and F to be the identity functor Id Mnd(C) , the data of a pair (G, θ) correspond exactly to a monad transformer on C.

In order to state the generalization of Lem. 4.2.1 for indexed monads, we introduce the following notations. Given categories K, C, we note C : K → Cat the constant functor with value

C. If G : K → Mnd(C) is a K-indexed monad, we de ne a transformation t G : C → C, with component at k ∈ K set to t G k = G k : C → C. t G
is not natural but lax-natural, which means that for f ∈ K(k, k ), the following naturality square is lled by a (not necessarily invertible)

2-cell t G f = G f C C C C t G k =G k C f C f t G k =G k ⇓ t G f Moreover, there are modi cations η G : id C → t G and µ G : t G • t G → t G induced
: Id C → G k, µ G k : (G k) 2 → G k
, respectively the unit and multiplication of the monad G k, satisfying for any f ∈ K(k, k ) the identities

C C C C t G k ⇓ t G f ⇓ η G k = C C C C t G k ⇓ η G k C C C C t G k •t G k t G k ⇓ t G f ⇓ µ G k = C C C C t G k •t G k t G k ⇓ µ G k ⇓ t G f • t G f For F : K → Mnd(C), we note C F = Alg • F op : K op → Cat the functor assigning to k ∈ K the category of Eilenberg-Moore algebras C F k . There is a natural transformation u : C F .
-→ C given at each component k by the relevant forgetful functor sending an algebra in C F k to its carrier in C k = C. Since u is natural, it acts by post-composition on lax-natural transformations and modi cations, inducing in particular a functor (of 1-categories)

u * : [K op , Cat] lax (C, C F ) -→ [K op , Cat] lax (C, C).
k : C k → C F k of t G k = G k : C k → C k through u k : C F k → C such that µ G k lifts as μG k . Now, given f ∈ K(k, k
), we need to show that t G f = Gf lifts as a natural transformation tG f lling the naturality diagram below on the left, that is Gf should be an F k-algebra morphism. This is indeed the case since the diagram on the right commutes by naturality of θ k and µ G . Moreover, μG is a modi cation since Gf is a monad morphism.

C C F k C C F k tG k =G k tG k =G k ⇓ tG f C F f F k Gk(c) F k Gk (c) F k Gk (c) Gk Gk(c) Gk Gk (c) Gk(c) Gk (c) θ k,Gk(c) F kGf (c) F f Gk (c) θ k ,Gk (c) µ G k µ G k Gf (c)
(2 ⇒ 1) Conversely, another application of Lem. 4.2.1 provides the de nition of θ k at each k ∈ K. Explicitly, θ k is obtained by extending η G k to an F k homomorphism thanks to the F k-algebras structure on G k (see the proof of Lem. 4.5.2 below). We still need to show that θ is natural in k. Since tG is a lifting of t, for any f ∈ K(k, k ), the underlying natural transformation of tG f is necessarily Gf , and unfolding the lax-naturality condition, Gf is an F k-algebra homomorphism, justifying the following computation (where we write α k for the F k-algebra structure on Gk):

Gf θ k Gf α k α k F f Gf Gk = F k η G k η G k α k F f η G k F f θ k F k = Gk = = Gk F k Gk F k Gk F k
How does Lem. 4.5.1 help us understanding SM ? We can interpret covariant type constructors in SM as lax natural transformations from C n to C where n is the number of type arguments. For instance, the unary type constructor M should be interpreted by t Id Mnd(C) . The choice of type formers accepted in SM should then be induced by the lifting condition along u. Finally, the condition that the multiplication should lift as well can be seen as a counterpart of the linearity condition.

We now explain how to extend Lem. 4.2.1 to the relative monad setting. We will not attempt to generalize Lem. 4.2.1 to the relative setting. Even though we expect some generalization to the relative setting to hold, introducing the structures corresponding to lax-natural transformations and modi cations in the relative monad setting would bring us too far.

In the other direction, if α is an m 1 -algebra structure on m 2 , we de ne the natural transformation θ α as

θ α α = ret m2 m 2 m 1 m 1 m 2 j
θ α is actually a monad morphism using the algebra laws and, for the last step of the second computation, the fact that bind m 2 is an algebra morphism

θ α j m 2 ret m1 = α ret m2 m 2 j j ret m1 = ret m2 m 2 j = j m 2 ret m1 θ α m 2 bind m 1 j * m * 1 = α ret m2 m 2 bind m 1 j * m * 1 = α m 2 α ret m2 j * m * 1 α ret m2 j * m * 1 α m 2 bind ret m2 = α ret m2 j * m * 1 bind m 2 α ret m2 = j * m * 1 bind m 2 θ α θ α m 1 = m 1 m 1 m 1
Finally, the two constructions are inverse of each other:

bind m2 m * 2 m * 2 j * α ret m2 m 1 α ret m2 m 1 bind m2 m * 2 j * m * 2 α m 1 m * 2 m * 2 j * = = α θα m 1 m * 2 m * 2 j * = θ α θ m 1 m 2 bind m2 θ m 1 ret m2 m 2 θ m 1 m 2 = =

Conclusion & Related work

In this chapter we presented the notion of monad transformers, introduced for by [START_REF] Liang | Monad transformers and modular interpreters[END_REF], and extended it to relative monads. In order to derive correct monad transformers and speci cation monad transformers, we introduced a metalanguage SM. The types of this metalanguage capture algebras with respect to an abstract monad M, a notion reminiscent of modular handlers introduced in [START_REF] Schrijvers | Monad transformers and modular algebraic e ects: what binds them together[END_REF] to compare monad transformers with the extensible algebraic e ects with handlers of [START_REF] Kiselyov | Extensible e ects: an alternative to monad transformers[END_REF]. The elaboration of monads internal to SM to monad transformers employ proof-relevant logical relations to provide the action on monad morphisms, a technique inspired by the work of Kaposi et al. (2019) on models of dependent signatures. An implementation of this metalanguage in Coq brings the convenience of de ning monad transformers from a small standard monad speci cation to a practical level. We sketched some ideas on how the theory behind SM could be extended to relative monad transformers beyond the case of speci cation monad transformers. Designing and implementing such an extension is left as an interesting but challenging future work.

At a theoretical level, the work of [START_REF] Jaskelio | Monad transformers as monoid transformers[END_REF] where a thorough study on monoid transformers is carried on is closely related to ours. Monoid transformers on an arbitrary monoidal category are by essence more general than monad transformers, and by consequence harder to describe syntactically in general. They tackle this problem by classifying monadic operations in various classes of expressiveness and provide more or less structure on the monoid transformers dependending on the well-behavedness of these operations. For instance, they derive a monad transformer for continuations without a functorial action on monad morphism, whereas we extend it to monadic relations. A tempting future work would consist in extending their work on monoid transformers to consider relations between monoids preserving the monoid structure. Having examples, theoretical concepts and practical ways to build computational monads, speci cation monads and e ect observations, we now turn to the question of verifying code in practice. E ect observations by themselves provide a rudimentary way to prove properties of programs: given a program c : M A and an e ect observation θ : M → W, we can prove properties on c by exploiting its assigned speci cation θ(c) : W A. However, directly applying θ amounts to run the program with respect to the semantics given by θ. This may lead to a complex, hardly modular speci cation.

This chapter is dedicated to the study of a methodology for verifying unary programs called Dijkstra monads. Dijkstra monads provide a practical and automatable veri cation technique in dependent type theories like F [START_REF] Swamy | Dependent types and multi-monadic e ects in F*[END_REF], where they are a primitive notion, and Coq, where they can be embedded via dependent types. A Dijkstra monad D A w re ne a computational monad with a speci cation index picked out of a speci cation monad. We open this chapter by de ning more formally these objects and then show with examples how a Dijkstra monad can be obtained from a computational monad, a speci cation monad, and an e ect observation relating them, providing a methodology for actual veri cation. The second section then proves that e ect observations and Dijkstra monad are categorically equivalent, providing a principled approach to the construction of Dijkstra monads in the examples. We close the chapter on a brief comparison with graded monads, another indexed monad structure used to capture for instance resource bounds on computations [START_REF] Katsumata | Parametric e ect monads and semantics of e ect systems[END_REF].

De nition & examples

De nition 5.1.1 ( ). A Dijkstra monad over a speci cation monad W is given by a type D A w for each type A and speci cation w : W A, return and bind functions where the index is provided respectively by the return and bind of W

ret D : (x : A) → D A (ret W x) bind D : D A w 1 → ((x : A) → D B w 2 (x)) → D B (bind W w 1 w 2 )
such that the following monadic equations about ret D and bind D hold

bind D m ret D = m bind D (ret D x) f = f x bind D (bind D m f ) g = bind D m (λx. bind D (f x) g)
where m : D A w m , x : A, f : (x : A) → D B (w f x), g : (y : B) → D C (w g y) for A, B, C any types and w m : W A, wf : (x : A) → W B, w g : (y : B) → W C.

Together with a weakening structure re ecting the order on the speci cation monad W weaken :

w 1 ≤ A w 2 × D A w 1 -→ D A w 2
such that the following axioms hold (where we con ate the propositions w 1 ≤w 2 and their proofs)

weaken w≤w, m = m, weaken w 1 ≤w 2 ≤w 3 , m = weaken w 2 ≤w 3 , weaken w 1 ≤w 2 , m , bind D (weaken w m ≤w m , m ) (λa. weaken w f a≤w f a, f a ) = weaken bind W w m w f ≤bind W w m w f , bind D m f .
Intuitively, the type D A w correspond to "computations speci ed by w" and the weakening structure allow to coerce a computation from a stronger to a weaker speci cation as needed.

Note that the Dijkstra monad equations are well-typed only if W satisfy the monadic laws. In HoTT terminology [START_REF] Univalent | Homotopy Type Theory: Univalent Foundations of Mathematics[END_REF], these equations are actually paths over the corresponding equations for W. This has no incidence in an extensional type theory such as F , but it means for our Coq development that we need to pay attention to the equality proofs for our speci cation monads. It explains why we are so often relying on the backward predicate transformer speci cation monad (see subsection 2.3.4) since it has the good taste to satisfy its monad laws de nitionally.

In order to use seamlessly multiple Dijkstra monads, that is multiple e ects, in a single program, we need a way to coerce computations -and speci cations -from one e ect to another. F uses the concept of sube ecting to achieve this. In the implementation, the sube ecting relation is an order on Dijkstra monads generated by a choice of at most one Dijkstra monad morphism between two di erent Dijkstra monads. Such a Dijkstra monad morphism must hence coerce both computations and speci cations.

De nition 5.1.2. A morphism of Dijkstra monads from D 1 A (w 1 : W 1 A) to D 2 A (w 2 : W 2 A) consists of: a speci cation monad morphism Θ W : W 1 → W 2 and a family of maps Θ D A,w 1 : D 1 A w 1 -→ D 2 A (Θ W w 1 )
indexed by types A and speci cations w 1 : W 1 A, satisfying the following identities

Θ D (ret D 1 a) = ret D 2 a, Θ D (bind D 1 m f ) = bind D 2 (Θ D m) (Θ D • f ), Θ D (weaken (w ≤ w , m)) = weaken (Θ W w ≤ Θ W w , Θ D m).
for any types A, B, and terms a : A, w, w : W A, m : D A w, w f : A → W B, f : (a : A) → D B (w f a). Considering Dijkstra monads and Dijsktra monad morphisms together, we obtain a category that we will note DMon.

Using Dijkstra monads for verifying programs

We explain the general methodology for proving code using Dijkstra monads. Consider the following piece of F code de ning a function mapping a natural number k : N to the k-th element of Fibonacci sequence.

let rec b (n:N) : Pure N(requires ) (ensures (λ r. r ≥ n ∧ r ≥ 1)) = if n ≤ 1 then 1 else b (n-1) + b (n -2)
This code does not need any e ect1 and uses implicitly the Dijkstra monad Pure of pure functions provably terminating on the domain given by speci cations drawn from W Pure . Translating the let ... in constructs to their explicit monadic variant and inserting return operation where needed, the de nition of b becomes:

let rec b (n:N) : Pure N(requires ) (ensures (λ r. r ≥ n ∧ r ≥ 1)) = if n ≤ 1 then ret Pure 1 else bind Pure ( b (n-1)) (λ r1. bind Pure ( b (n-2)) (λ r2. ret Pure (r1 + r2)))
By type inference, the type of the body of b is Pure N w body where

w body n = if n ≤ 1 then ret W Pure 1 else bind W Pure (w f ib (n-1)) (λ r1. bind W Pure (w f ib (n-2)) (λ r2. ret W Pure (r1 + r2)))) w f ib n = λpost. ∧ ∀r. r ≥ n ∧ r ≥ 1 =⇒ post r
the second speci cation being derived2 from the declared require and ensure clause of the function b above. For the function b to be well-typed, the following veri cation condition (VC) must hold: ∀n, w body n ≤ W Pure w f ib n. Formally, it corresponds to wrapping the body of b with a weaken operation and providing the proof of the VC as argument. This last step is performed as part of sube ecting in F 's type inference/type checking mechanism. When using Dijkstra monads in Coq -or more generally in any dependent type theory where Dijkstra monads are not a primitive notion -, these weakening must be written explicitly.

How is this methodology any better than just applying an e ect observation to the code ? Observe that the speci cation w body obtained by type inference is close to what we could obtain when applying an e ect observation θ to the body, the di erence being that at the leaves of the speci cation, we have occurrences of w f ib instead of θ applied to some recursive occurrences of b. In this small example it might seem to be a benign di erence, but it means that we have some control over the speci cations that are used and can abstract away irrelevant implementation details. This is an important, albeit rather simple, form of modularity.

Of course, this methodology comes with an important drawback: when de ning a function, we need to come up with the right speci cation that strikes a good balance between being simple and complete enough.

Implementing Dijkstra monads in type theory

The concrete de nition for the type of a Dijkstra monad can vary according to the underlying type theory. For instance, in our Coq development, we de ne it (roughly) as a dependent pair of a computation c : St A and a proof that c is correctly speci ed by w. In F , it is instead a primitive notion.

The Dijkstra monad St of stateful computations

Let us start with stateful computations as an illustrative example, taking the computational monad St, the speci cation monad W St , and the following e ect observation:

θ St : St -→ W St θ St (m) = λpost s 0 . post (m s 0 )
We begin by de ning the Dijkstra monad type constructor, ST : (A : Type) → W St A → Type.

The type ST A w contains all those computations c : St A that are correctly speci ed by w. We say that c is correctly speci ed by w when θ St (c) ≤ w, that is, when w is weaker than (or equal to) the speci cation given from the e ect observation. Unfolding the de nitions of ≤ and θ St , this intuitively says that for any initial state s 0 and postcondition post : A×S → P, the precondition w post s 0 computed by w is enough to ensure that c returns a value v : A and a nal state s 1 satisfying post (v, s 1 ); in other words, w post s 0 implies the weakest precondition of c. The Dijkstra monad ST is equipped with monad-like functions ret ST and bind ST whose de nitions come from the computational monad St, while their speci cations come from the speci cation monad W St . The general shape for the ret and bind of the obtained Dijkstra monad is:3

ret ST = ret St : (v : A) → ST A (ret W St v) bind ST = bind St : (c : ST A w c ) → (f : (x : A) → ST B (w f x)) → ST B (bind W St w c w f )
which, after unfolding the state-speci c de nitions becomes:

ret ST = ret St : (v : A) → ST A (λpost s 0 . post (v, s 0 )) bind ST = bind St : (c : ST A w c ) → (f : (x : A) → ST B (w f x))
→ ST B (λp s 0 . w c (λ (x, s 1 ) . w f x p s 1 ) s 0 )

The operations of the computational monad are also re ected into the Dijkstra monad, with their speci cations are computed by θ St . Given op St : (

x 1 : A 1 ) → • • • → (x n : A n ) → St B, we can de ne op ST = op St : (x 1 : A 1 ) → • • • → (x n : A n ) → ST B (θ St (op St x 1 . . . x n ))
Concretely, for state, we get the following two operations for the Dijkstra monad ST: get : ST S (λp s 0 . p (s 0 , s 0 )), put : (s : S) → ST 1 (λp s 0 . p ( * , s)).

Given this re ned version of the state monad, computing speci cations of (non-recursive) programs becomes simply a matter of doing type inference to compositionally lift the program to a speci cation and then unfolding the speci cation by (type-level) computation. For instance, given modify (f : S → S) = bind ST get (λx. put(f x)), both F and Coq can infer the type ST 1 (bind W St (λp s 0 . p (s 0 , s 0 )) (λs p s 0 . p ( * , f s))) = ST 1 (λp s 0 . p ( * , f s 0 )) which precisely describes the behavior of modify, both in terms of the returned value and of its e ect on the state. Program veri cation then amounts to proving that, given a programmerprovided type-annotation ST 1 w for modifyf , the speci cation w is weaker than the inferred speci cation.

Aparté: State in real life

The basic idea of a Dijkstra monad for state can be extended to apply to more realistic situations using a curated memory model closer to an actual implementation. We brie y explain the model used in F targetting generation of e cient low-level C code to give an idea of how to step up from a toy model to an actual tool for program veri cation. A more complete account of this exposition can be found in [START_REF] Protzenko | Veri ed low-level programming embedded in F*[END_REF].

We already explain in chapter 2 how the state S can be instantiated by a store S = Loc → Val to accommodate for multiple memory cells. Pushing this idea further, we can structure the state as a tree of regions, each region holding its own set of memory cells. This model called hyper-heap in F provides a primitive variant of separation and framing, an important tool to prove that a program does not interfere with regions it does not touch. Specializing some of the regions to re ect the di erences between the heap and the stack in the C memory model, we obtain the hyper-stack model. In more details, the stack is a list-shaped sub-tree of regions, each of these region corresponding to a stack frame, maintaining liveness condition satisfying the stack discipline, e.g., memory cells on the stack cannot outlive their stack frame. The heap on the other hand has a much more liberal discipline.

The hyper-stack model per-se does not use anything F -speci c. However to reason eciently about stateful arguments, monotonicity arguments are heavily used in F [START_REF] Ahman | Recalling a witness: Foundations and applications of monotonic state[END_REF], for instance to discharge the hypothesis that a garbage collected reference that is reachable in a program is always alive, that is both allocated and not freed. If it seems achievable to provide a Dijkstra monad for monotonic state4 , it does not seem possible to obtain the crucial operations witness and recall. In the setting of Coq, the Iris framework [START_REF] Jung | Iris from the ground up: A modular foundation for higher-order concurrent separation logic[END_REF] may be an interesting way to obtain similar reasoning methods.

The demonic Dijkstra monad ND

The previous construction is independent from how the computational monad, the speci cation monad, and the e ect observation were obtained. The exact same approach can be followed for the NDet monad coupled with any of its e ect observations. We use the demonic one here, for which the pick and fail actions for the Dijkstra monad have types: With this, we can de ne and verify F (or Coq) functions like the following:

let rec pickl (l:list α) : NDD α (λ p → ∀x. elem x l =⇒ p x) = match l with | [] → fail () | x::xs → if pick () then x else pickl xs let guard (b:B) : NDD unit (λ p → b =⇒ p ()) = if b then () else fail ()
The pickl function nondeterministically chooses an element from a list, guaranteeing in its speci cation that the chosen value belongs to it. The guard function checks that a given boolean condition holds, failing otherwise. The speci cation of guard b ensures that b is true in the continuation. Using these two functions, we can write and verify concise nondeterministic programs, such as the one below that computes Pythagorean triples. The speci cation simply says that every result (if any!) is a Pythagorean triple, while in the implementation we have some concrete bounds for the search: ; 2; 3; 4; 5; 6; 7; 8; 9; 10] in let (x,y,z) = (pickl l, pickl l, pickl l) in guard (x * x + y * y = z * z); (x,y,z)

let pyths () : NDD (int & int & int) (λ p → ∀x y z. x * x + y * y = z * z =⇒ p (x,y,z)) = let l = [ 1

Interacting with the outer world: the IO Dijkstra monad family

We illustrate Dijkstra monads for multiple e ect observations from IO. First, we consider the context-free interpretation θ Fr : IO → W Fr , for which IO operations have the interface:

read IO Fr : IOFree I (λp. ∀(i : I). p i, [In i] ) write IO Fr : (o : O) → IOFree 1 (λp. p * , [Out o] )
We can de ne and specify a program that duplicates its input (assuming an implicit coercion

I <: O): let duplicate () : IOFree unit (λ p → ∀x. p ((), [In x; Out x; Out x])) = let x=read () in write x; write x
However, with this speci cation monad, we cannot reason about the history of previous IO events. To overcome this issue, we can switch the speci cation monad to W Hist and obtain

read IO Hist : IOHist I (λp h. ∀i. p i, [In i] ) write IO Hist : (o : O) → IOHist 1 (λp h. p * , [Out o] )
The computational part of this Dijkstra monad fully coincides with that of IO Fr , but the specications are much richer. For instance, we can de ne the following computation:

mustHaveOccurred = λ_. ret IO Hist * : (o : O) → IOHist 1 (λp h. Out o ∈ h ∧ p * , [] )
which has no computational e ect, yet requires that a given value o was already been outputted before it is called. This is weakening the speci cation of ret IO Hist * (namely, ret W Hist * = λp h. p * , [] ) to have a stronger precondition. By having this amount of access to the history, one can verify that certain invariants are respected. For instance, the following program will verify successfully: The program has a "trivial" speci cation: it does not guarantee anything about the trace of events, nor does it put restrictions on the previous log. However, internally, the call to mustHaveOccurred has a precondition that i was already output, which can be proven from the postcondition of write i. If this write is removed, the program will (rightfully) fail to verify. Finally, when considering the speci cation monad W IOSt , we have both state and IO operations:

read IOSt : IOSt I (λp s h. ∀i. p i, s, [In i] ) get IOSt : IOSt S (λp s h. p s, s, [] ) write IOSt : (o : O) → IOSt 1 (λp s h. p * , s, [Out o] ) put IOSt : (s : S) → IOSt 1 (λp _ h. p * , s, [] )
where (read IOSt , write IOSt ) keep state unchanged, and (get IOSt , put IOSt ) do not perform any IO. With this, we can write and verify programs that combine state and IO in non-trivial ways, e.g., The program mutates the state in order to compute output from input, possibly interleaved with pure computations, but eventually rolls it back to its initial value, as mandated by its speci cation.

Provably terminating recursion in Pure

The Pure e ect is the most basic e ect, containing only pure, provably total computations. We implement a model of Pure in Coq over the speci cation monad W Pure A = Cont P A (or rather its monotonic re nement). The underlying representation of a pure computation is given by

Pure A w = (p : A → P) → w p → (a : A) × p a
That is, given a postcondition p : A → P, a pure computation c : Pure A w is a total function taking as input a proof that the precondition w p holds and returning values a : A such that p a holds.

We use this simple Dijkstra monad to explain how to combine the ideas from (McBride, 2015) with e ect observations to yield a presentation of provably terminating recursive functions close to what can be found in F . We start by brie y explaining how termination proof work in F . In order to de ne a Pure recursive function f taking arguments of type Arg and returning a result of type R according to the speci cation w : W Pure R, an F user have to specify a measure l which is an arbitrary total expression depending on the arguments of the function, here args. let rec f (args:Arg) : Pure R w (decreases l) = ( * body of f containing recursive calls * ) ... f args' ... This measure acts on the speci cation of f inside its body, inducing the following signature (note that args correspond to the top-level argument and is bound inside the body):

val f : (args' : Arg) → Pure R (λ p. l [args'/args] ≺ l ∧ w [args'/args] p)
Here ≺ is a well-founded relation between arbitrary F terms generated by the subterm order on inductive types 5 . The overall result is that every recursive are guarded in the sense that the function f can only be called on arguments for which the measure provably decreases.

In order to emulate this mechanism in Coq for a recursive function with xed domain Arg, codomain R and speci cation w : W Pure R, we construct a Dijkstra monad from e ect observations on top of the monad GenRec for general recursion presented in subsection 2.1.2. We assume that Arg comes equipped with a well-founded relation ≺ . The speci cation monad we use is simply W Pure , however instead of xing a single e ect observation, we de ne a family of effect observations θ args parametrized by the top-level parameter (args:Arg). Recall that the monad GenRec Arg R is free on a single operation call : (args : Arg) R and that an e ect observation from a free monad is fully de ned by speci cations for each operations subsection 2.4.5, in the present case a single function w call : (args : Arg) -→ W Pure R. Putting these observation together we de ne the family of e ect observations θ args : GenRec Arg R X → W Pure X as induced by w call args let w call (args: Arg) : (args' :

Arg) → W Pure R = λ(p : R → P). args' ≺ args ∧ w[args'/args] p
This induces a family of Dijkstra monads GenREC args X (w : W Pure ) parametrized by args :

Arg. Now, to close the loop, we can de ne a handling construct fix from this newly de ned Dijkstra monad to Pure:

val fix : ((args : Arg) → GenREC args R w) → (args:Arg) → Pure R w
The role of fix is to gather the proofs of well-foundedness carried by each recursive call inside its rst argument thanks to the speci cation w call and to transform it into a witness that the putative xpoint is globally well-de ned.

We presented a program transformation translating F source syntax to describe provably terminating recursive functions into a form admissible in Coq.

E ect polymorphic functions

Even though the operations ret and bind provided by a (strong) monad can seem somewhat restrictive at rst, they still allow us to write functions that are generic in the underlying computational monad. One example is the following mapW function on lists, generic in the monad W (similar to the mapM function in Haskell):

let rec mapW (l : list α) (f : α→ W β) : W (list β) = match l with [] → ret [] | x :: xs → bind (f x) (λ y → bind (mapW xs f) (λ ys → ret (y :: ys)))
When working with Dijkstra monads, we can use the mapW function as a generic speci cation for the same computation when expressed using an arbitrary Dijkstra monad D indexed by W:6 let rec mapD (l : list α) (w :

α→ W β) (f : (a:α) → D β(w a)) : D (list β) (mapW l w) = match l with [] → ret [] | x :: xs → let y = f x in let ys = mapD xs w f in y :: ys
where mapD takes the list l, the speci cation for what is to happen to each element of the list, w, and an implementation of that speci cation, f. It builds an e ectful computation that produces a list, speci ed by the extension of the element-wise speci cation w to the whole list by mapW.

Analogously, we can implement a generic iterator combinator provided we have an invariant Here we use not only the monadic operations but also the possibility to weaken the speci cation bind w (λ() → w) computed from the second branch of the match to the speci cation w by assumption.

In most the examples in this section, we used Dijkstra monads obtained via the same general recipe (see next section for details) from the same kinds of ingredients: a computational monad, a speci cation monad, and an e ect observation from the former to the latter. This enables a uniform treatment of e ects for veri cation, and opens the door for verifying rich properties of e ectful programs.

Equivalence with e ect observations

As illustrated with examples in the previous section, Dijkstra monads can be obtained from e ect observations θ : M → W between computational and speci cation monads. As we shall see this construction is generic and leads to a categorical equivalence between Dijkstra monads and e ect observations. In order to compare this notion of Dijkstra monads to e ect observations, we also introduce a category of monadic relations MonRel and show that there is an adjunction

∫ pre : MonRel -→ DMon. (5.1)
Intuitively, an adjunction establishes a correspondence between objects of two categories, here MonRel and DMon. An adjunction always provides an equivalence of categories if we restrict our attention to objects that are in one-to-one correspondence, those for which the unit (resp. the counit) of the adjunction is an isomorphism. When we restrict the adjunction above, we obtain an equivalence between Dijkstra monads and e ect observations. For the sake of explanation, we proceed in two steps: rst, we consider Dijkstra monads and e ect observations over specication monads with a discrete order (i.e., ordinary monads), describing the above adjunction in this situation; later, we extend this construction to general preorders, thus obtaining the actual adjunction we are interested in.

The discrete setting In this paragraph we take all speci cation monads W to be slightly degenerated, namely discrete. Given a monadic relation R : M ↔ W (Def. 4.3.1) between a computational monad M and a speci cation monad W, we construct a Dijkstra monad pre R on W as follows:

(pre R) A (w : W A) = (m : M A) × m R A w (5.2)
That is (pre R) A w consists of those elements m of M A that are related by R to the speci cation w. When R is the graph of a monad morphism θ (or equivalently, R is functional), pre(R : M ↔ W) maps an element w : W A to its preimage θ -1 (w) = {m : M A | θ(m) = w}. The return and bind operations of preR are given by the return and bind operations of M, using the compatibility of R with respect to the monad operations of M and W. The weakening operation is just the identity since the order on W is assumed to be trivial. Conversely, any Dijkstra monad D over a speci cation monad W with discrete order yields a monad structure on

∫ D A = (w : W A) × D A w (5.3)
and the projection of the rst component is a monad morphism π 1 : ∫ D → W.

In order to explain the relation between these two operations pre and ∫ -, we introduce the category MonRel of monadic relations.

De nition 5.2.1. The category MonRel of monadic relations consists of:

An object of MonRel is a pair of monads M, W together with a monadic relation

R : M ↔ W between them. A morphism between R 1 : M 1 ↔ W 1 and R 2 : M 2 ↔ W 2 is a pair (Θ M , Θ W ) of a monad morphism Θ M : M 1 -→ M 2 and a speci cation monad morphism Θ W : W 1 -→ W 2 such that M 1 A M 2 A W 1 A W 2 A R 1 A Θ M A R 2 A Θ W A ⇒ Θ R A : ∀(m : MA) (w : WA). m R 1 A w =⇒ Θ M (m) R 2 A Θ W (w). (5.4)
The construction pre extends to a functor on MonRel: it sends a morphism (Θ W , Θ M ) :

R 1 → R 2 between monadic relations to a Dijkstra monad morphism (Θ W , Θ D ) : pre R 1 → pre R 2
, where Θ D A,w is de ned as the restriction of Θ M A to the appropriate domain

Θ A,w : (m : M 1 A) × m R 1 A w -→ (m : M 2 A) × m R 2 A (Θ W w) (m, pf ) -→ (Θ M m, Θ R pf ) Conversely, ∫ packs up a Dijkstra monad morphism (Θ W , Θ D ) : (W 1 , D 1 ) → (W 2 , D 2 ) as monadic relation morphism (Θ W , Θ M ), where Θ M A : (w : W 1 A) × D 1 A w -→ (w : W 2 A) × D 2 A w (w, m) -→ (Θ W A w, Θ D A,w m)
Since Θ M maps the inverse image of w -pairs whose rst component is w -to the inverse image of Θ W (w) -pairs whose rst component is Θ W (w)-, condition (5.4) holds. Moreover, this gives rise to a natural bijection

MonRel(∫ D, R) ∼ = DMon(D, pre R)
that establishes the adjunction (5.1). We can restrict (5.1) to an equivalence by considering only those objects for which the unit (resp. counit) of the adjunction is an isomorphism. Every Dijkstra monad D is isomorphic to its image pre (∫ D), whereas a monadic relation R is isomorphic to ∫ (pre R) if and only if it is functional, i.e., a monad morphism. This way we obtain an equivalence of categories between DMon and the category of e ect observations on monads with discrete preorder.

The ordered setting We now consider the general case of speci cation monads equipped with an arbitrary order, that is monadic relations R : M ↔ W where M is a (plain,discrete) monad and W a speci cation monad. The de nition of pre (5.2) still makes sense but for the weakening operation: the Dijkstra monad pre R has a weakening operation exactly when R is monotonic Def. 4.3.1 with respect to the order. Hence, we restrict our attention to the category MonRel ≤ of monotonic monadic relations. Doing so, we obtain a functor pre : MonRel ≤ -→ DMon from the category of monotonic monadic relations to the category of Dijkstra monads.

The special case of a monad morphism θ : M → W ts well in this picture as long as we consider the associated monotonic monadic relation R θ de ned by m R θ w ⇐⇒ θ m ≤ W w. The corresponding weakening structure on pre R θ is given by

weaken w 1 ≤ w 2 , m, θ(m) ≤ w 1 = m, θ(m) ≤ w 1 ≤ w 2 .
Building and explicitly describing a left adjoint ∫ to pre turns out to be slightly more di cult. To explain where the problem lies, consider the case of a monad morphism θ : M → W for which we expect ∫ (pre θ) to be isomorphic to θ. However, using straightforwardly the previous de ni-

tion of ∫ , ∫ (pre θ) is just (ΣM, W, π 1 ) where ΣM A = (w : W A) × (m : M A) × θ A (m) ≤ A w,
which is far from being isomorphic to M . The problem is that we get one copy of m for each admissible speci cation w : W A. These copies, however, are non-essential since the weakening structure of pre θ identi es them. As such, a reasonable de nition of ∫ n the ordered setting need to further quotient them 7 . Consequently, we de ne ∫ D as the monotonic monadic relation

∫ D = (∫ D, W, R ∫ D ) with ∫ D A = ((w : W A) × D A w) / ∼ [w, c] R ∫ D w ⇐⇒ w ≤ w
where ∼ is the equivalence relation induced by (w, c) ∼ (w , weaken(w ≤ w , c)) and [w, c] is the equivalence class of the pair (w, c) in ∫ D. The monad structure on A → (w : W A) × D A w is induces a monad structure on the quotient ∫ D because bind W is monotonic in both arguments and bind D is compatible with the weakening structure in both arguments as well. This de nition reduces to Equation 5.3 when the order on W is discrete.

Theorem 5.2.1. The categories of Dijkstra monads and monadic relations are connected by an adjunction ∫ pre : MonRel ≤ -→ DMon.

Moreover, restricting our attention to speci cation monads W such that any two elements in W A has an upper bound for ≤ W , the adjunction induces an equivalence in the following cases:

the counit ε R : ∫ (pre R) → R is invertible if R = R θ for θ : M → W a (lax) monad morphism 8 .
the unit η D : D → pre (∫ D) is invertible whenever weaken D (w ≤ W w ) : D A w → D A w is one-to-one for any A and w ≤ w : W A.

Proof. The de nition of ∫ given on Dijkstra monads extends Dijkstra monad morphisms:

(Θ W , Θ D ) : (W 1 , D 1 ) → (W 2 , D 2 ) pairs up to provide a monad morphism Θ W A , Θ D A : ((w : W 1 A) × D 1 A w) → ((w : W 2 A) × D 2 A w),
and since θ W is monotonic with respect to the orders on W 1 , W 2 , this natural transformation descend to the quotient by ∼ as Θ ∫ D : ∫ D 1 → ∫ D 2 and we de ne ∫ (Θ W , Θ D ) = (Θ W , Θ ∫ D ), the condition (5.4) being immediate. We check that this assignment is functorial, giving rise to a functor ∫ : DMon → MonRel ≤ .

We now turn to the construction of natural transformations

ϕ : MonRel(∫ D 1 , R 2 ) ∼ ----→ DMon(D 1 , pre R 2 ) MonRel(∫ D 1 , R 2 ) ∼ ←----DMon(D 1 , pre R 2 ) : ψ for (W 1 , D 1 ) a Dijkstra monad and (M 2 , W 2 , R 2 ) a monadic relation. For (Θ M , Θ W ) ∈ MonRel(∫ D 1 , R 2 ), that is Θ M : ∫ D 1 → M 2 and Θ W : W 1 → W 2 , we set ϕ(Θ M , Θ W ) = (Θ W , Θ D )
where Θ D is the Dijkstra monad morphism de ned by

Θ D A,w : D 1 A w -→ (m : M 2 A) × m R 2 (Θ W w) c -→ (Θ M [w, c], _)
In this de nition and the proof of the Dijkstra monad morphism laws below, we leave implicit the witness that the relation R 2 hold obtained from the condition (5.4).

Θ D A,ret W 1 a (ret D 1 a) = Θ M [ret W 1 a, ret D 1 a] = Θ M (ret ∫ D 1 a) = ret M 2 a Θ D A,bind W 1 w m w f (bind D 1 m f ) = Θ M [bind W 1 w m w f , bind D 1 m f ] = Θ M (bind ∫ D 1 [w m , m] (λx. [w f x, f x])) = bind ∫ D 1 Θ M [w m , m] (λx. Θ M [w f x, f x]) = bind ∫ D 1 Θ D A,w m (m) (λx. Θ D A,w f x (f x)) Θ D A,w (weaken (w ≤ w , m)) = Θ M [w , weaken (w ≤ w , m)] = weaken (Θ W w ≤ Θ W w , Θ M [w, m]) = weaken (Θ W w ≤ Θ W w , Θ D A,w m). In the other direction, a Dijkstra monad morphism (Θ W , Θ D ) ∈ DMon(D 1 , pre R 2 ) is sent to the morphism of monadic relations ψ(Θ W , Θ D ) = (Θ M , Θ W ) where Θ M is the monad mor- phism mapping an equivalence class [w, c] ∈ ∫ D 1 A to Θ M [w, c] = π 1 (Θ D A,w c
) which is well de ned because Θ W is monotonic and Θ D is compatible with weaken. The condition (5.4) is provided by the second component of Θ D .

Checking that ϕ and ψ are inverse to each other is straightforward (in an intensional setting, such as Coq, extensionality of functions and products are needed, and we also assumed uniqueness of propositions).

From this concrete description of the adjunction ∫ pre, we obtain the explicit formula for the unit η and counit ε. Considering respectively a Dijkstra monad (W, D) and a monadic relation (M, W, R), we have

η D = (Id W , η D D ) and ε R = (ε M R , Id W ) where η D D : D A w -→ pre (∫ D) A w ε M R : ∫ (preR) A -→ M A c -→ ([w, c], _) [w, (m, _)] -→ m
In the case of ε R , if R = R θ is the monadic relation associated to a possibly lax monad morphism, then we have a section

(ε M R ) -1 mapping m : M A to [θ(m), (m, _)]. Taking c = [w, (m, _)] ∈ ∫ (preR) A, we can nd w ∈ W A such that w ≤ W w and w ≤ W θ m so we have c = [w, (m, _)] = [θ m, (m, _)] = (ε M R ) -1 m and (ε M R ) -1 is onto, so ε R is invertible.
For the unit, η D D is clearly onto. It is also one-to-one when weaken is: if

([w, c], _) = η D D (c) = η D D (c ) = ([w, c ], _) for c, c ∈ D A
w and w ∈ W A, then a straightforward induction on the length of the witness that (w, c) ∼ (w, c ) using the fact that W A has upper bounds of pairs of elements prove that there exists a w ≥ w such that weaken(w ≤ w , c) = weaken(w ≤ w , c ), so c = c by injectivity of weaken.

To summarize, we can construct Dijkstra monads with weakening out of e ect observations and the other way around. Moreover, when starting from an e ect observation θ : M → W, then ∫ (pre θ) is equivalent to θ. This result shows that we do not lose anything when moving from e ect observations to Dijkstra monads, and that we can, in practice, use either the e ect observation or the Dijkstra monad presentation, picking the one that is most appropriate for the task at hand.

Dijkstra monads as relative monads, connection to graded monads

In the same way speci cation monads can be understood as a particular kind of order-enriched relative monads (see Def. 3.5.2), we explain in this section how Dijkstra monads themselves can be framed as (order enriched) relative monads. This point of view on Dijkstra monads provide an interesting bridge to the notion of graded monad [START_REF] Fujii | Towards a formal theory of graded monads[END_REF], another algebraic structure re ning monads with an index, capturing for instance resource usage (cost analysis). The latter can be used to model type-and-e ects system [START_REF] Katsumata | Parametric e ect monads and semantics of e ect systems[END_REF].

In order to introduce the relative monad presentation of Dijkstra monads, we rst reformulate Def. 5.1.1 in terms of indexed families. A family indexed by a set A is a function B → A, the component B a at index a ∈ A being the ber of this function at a. index a ∈ A being the ber of this function at a. A Dijkstra monad D over a speci cation monad W induces an indexed family

A D A A W A ret D id ∂ A ret W A D B A W B f id ∂ B w f -→ D A D B W A W B bind D f id ∂ B bind W w f
Taking into account the order on W and the weaken operation, the Dijkstra monad D can be equivalently described by giving the following data:

for each type A, an indexed family ∂ A : D A → W A between orders such that ∂ A is monotonic and its bers discrete, for each type A, a map of indexed families

(ret W , ret D ) : id A → ∂ A ,
for each pair of type A, B and map of families f = (w f , f ) :

id A → ∂ B , a monotonic extension (bind W w f , bind D f ) : ∂ A → ∂ B also monotonic in f (for the pointwise order on id A → ∂ B ),
satisfying laws analogous to the monadic laws This reformulation exhibits a Dijkstra monads D over the monad W as a relative monad where the domain category consists of sets -the type A of returned values -and the codomain consists of families indexed over a preorder, namely W A. To be more precise, let DiscPosFib be the full subcategory of Pos → whose objects are triples (E, B, f : E → B) consisting of ordered sets E, B and a discrete bration f between them, that is a monotone map f such that for any b 1 ≤ b 2 and e 1 ∈ f -1 (b 1 ) there is a unique e 2 ≥ e 1 with f (e 2 ) = b 2 -in particular the bers f -1 (b) are discrete for all b ∈ B. Explicitly, the morphisms of DiscPosFib between (E, B, f ) and (E , B , f ) is a pair of monotone functions (h dom : E → E , h cod : B → B ) such that the following square commutes:

E E B B h dom f f h cod
The Dijkstra monad D then induces a functor F D with a monad structure relative to the base functor J id , all these objects being enriched over Pos (in the terminology of chapter 3, we are working inside the framed bicategory Pos-Distr).

J id : Set -→ DiscPosFib A -→ (id A : A → A) F D : Set -→ DiscPosFib A -→ (π 1 : (w : W A) × D A w → W A)
Moreover this presentation of D as relative monad can be closely related to the relative monad structure on W (since it is a speci cation monad). Consider the projection functor cod : DiscPosFib → Pos sending a family (E, B, f ) to a its indexing base B. Together with the identity functor on Set, it ts into a morphism of base functor (Id Set , cod) : J id → Disc (illustrated on the left) and the identity natural transformation is a relative monad morphism from F D to W over (Id Set , cod).

Set DiscPosFib

Set Pos

J id Id cod Disc Set DiscPosFib Set Pos F D Id cod W (5.5)
Taking inspiration from [START_REF] Katsumata | A semantic formulation of tt-lifting and logical predicates for computational metalanguage[END_REF][START_REF] Katsumata | Relating computational e ects by -lifting[END_REF] where the case of monads is studied, we say that F D is a lifting of the relative monad W along (Id Set , cod) : J id → Disc to mean that F D is a J id -relative monad such that the identity is a relative monad morphism over (Id Set , cod) to W.

Lemma 5.3.1. A Dijkstra monad D over a speci cation monad W is equivalent to a relative lifting of W along (Id Set , cod) : J id → Disc.

Proof. The previous discussion shows that a Dijkstra monad D indeed de nes a suitable relative monad F D .

Conversely, given a lifting F of W along (Id Set , cod), we reconstruct a Dijkstra monad D F over W by the formula D F A (w : W A) = f -1 (w) where F(A) = (E, B, f : E → B) and B = W A by the lifting condition. The return and bind operations on D F are provided by the relative monad structure on F, using the lifting condition to show that they have the correct type, while the weaken operation is derived from the fact that f above is a bration.

Graded monads

In this section, we present graded monads that were studied in [START_REF] Fujii | Towards a formal theory of graded monads[END_REF]. Dijkstra monads and graded monads share a reasonable amount of similarities: both structure are indexed by an object equipped with a monoid structure, speci cation monads for the former, monoidal categories for the latter; e ect observations were originally introduced in [START_REF] Katsumata | Relating computational e ects by -lifting[END_REF] in order to build graded monad, and section 5.2 shows that they can be used as well for Dijkstra monads.

In order to compare the two structures, we restrict ourselves to the simple case of a monad on sets graded by a monoid.

(G A m 1 ) m 2 → G A (m 1 * m 2 ) natural in A
satisfying laws analogous to the monoid laws We wish to understand better the connection between the two indexed algebraic structure and to that end, we reformulate graded monads in terms of indexed families. As usual, the functorial action and multiplication can alternatively be reformulated in terms of Kleisli extension: for each m : M, set A, B and function A → G B m, an extension G A m → G B (m * m ). We obtain the following presentation of a graded monad G graded by a monoid M.

For each set A, an indexed family τ A : G A → M For each set A, a map of indexed families (e, ret G ) :

! A → τ A A G A 1 M ! A ret G τ A e
For each sets A, B and map of families (m, f ) : ! A → τ B , an extension (m * -, bind G f ) :

τ A → τ B A G B 1 M ! A f τ B m -→ G A G B M M τ A bind G f τ B m * -
This reformulation makes it clear that we can see a monad G graded by a monoid M as a functor F G : Set → Set → equipped with a monad structure relative to the functor J ! :

J ! : Set -→ Set → A -→ (! A : A → 1) F G : Set -→ Set → A -→ (π 1 : (m : M) × G A m → M)
Moreover, this J ! -relative monad structure on F G lifts the monoid structure on M (that can alternatively seen as a monad relative to 1 : 1 → Set) through the morphism of base functors (! Set , cod) : J ! → 1, where we write ! Set : Set → 1 for the unique functor to the terminal category and 1 : 1 → Set for the functor picking a terminal object in Set.

Set

Set → 1 Set

J ! ! Set cod 1 Set Set → 1 Set F G ! Set cod M (5.6)
This analysis of graded monads shows that they admit a similar formal presentation in terms of lifting of relative monad structure as Dijkstra monads do (see diagrams 5.5 and 5.6). Since both kinds of algebraic structure are useful for veri cation purposes, and they do not seem to reduce to each other, it would be interesting as future work to investigate further the common structure provided by relative monad liftings.

Conclusion & Related work

The work presented in this section directly builds on prior work on Dijkstra monads in F [START_REF] Swamy | Verifying higher-order programs with the Dijkstra monad[END_REF][START_REF] Swamy | Dependent types and multi-monadic e ects in F*[END_REF], in particular the DM4Free approach [START_REF] Ahman | Dijkstra monads for free[END_REF]. Our investigation of Dijkstra monad was primarily motivated by syntactic conditions required in the DM4Free approach that were at the time quite obscure, and prevented us from obtaining Dijkstra monads for some e ects, e.g., IO. The construction of section 5.2 together with those of chapter 4 shed some light on these awkward restrictions: the Dijkstra monads derivable with DM4Free are those obtained from e ect observations with shape

T (ret W Pure ) : T (Id) -→ T (W Pure )
where T is a monad transformer and ret W Pure : Id .

-→ W Pure the canonical monad morphism from the identity monad. [START_REF] Katsumata | Parametric e ect monads and semantics of e ect systems[END_REF] uses graded monads to give semantics to type-and-e ect systems, introduces e ect observations as monad morphisms, and constructs graded monads out of e ect observations by restricting the speci cation monads to their value at 1. We extend his construction to Dijkstra monads, showing that they are equivalent to e ect observations, and unify Katsumata's two notions of algebraic operation. We sketched a common framework for graded monads and Dijkstra monad but further investigation of such indexed structure obtained by lifting a relative monad remains to be done. In particular, generic lifting methods for monads such as the monadic -lifting [START_REF] Katsumata | Relating computational e ects by -lifting[END_REF] or the codensity lifting [START_REF] Katsumata | Codensity lifting of monads and its dual[END_REF] may also extend to the case of relative monads.

Dijkstra monads & monotonicity

A long line of work in F uses monotonicity to alleviate the proof e ort in protocols and state intensive programs. The soundness of these reasoning principles rely on some abstraction properties: intuitively state can only be used linearly, so restricting the state updates to be monotonic with respect to a choosen order implies that any monotonic predicate witnessed at some program point will necessarily hold at any later point, independently of the actual state. [START_REF] Ahman | Recalling a witness: Foundations and applications of monotonic state[END_REF] explain how it combines swiftly with the abstract approach to computations provided by Dijkstra monads. A general account of these monotonicity arguments for arbitrary e ects, for instance for IO, is left for future work.

Dijkstra monads as displayed algebras Kaposi and Kovács (2019) propose a framework to de ne expressive signatures and to associate to each signature Σ a category with families consisting of Σ-algebras, Σ-algebra homomorphisms and displayed Σ-algebras. These signature can be used to capture the notion of Dijkstra monad (but for the order) in a concise way: Dijkstra monads arise as display algebras of a signature Σ mon . Concretely, Kovács proposed (in private communication) the following signature Σ mon to capture Dijkstra monads:

M : Set ⇒ U, ret : (A : Set) ⇒ A ⇒ El(M A), (-) † : (AB : Set) ⇒ (Π A M B) ⇒ M A ⇒ El(M A), bind-ret : (A : Set) ⇒ (m : M A) ⇒ Id (M A) (ret † m) m, ret-bind : (A B : Set)(x : A) ⇒ (f : Π A M B) ⇒ Id (M B) (f † (ret x)) (f x), bind-assoc : (A B C : Set) ⇒ (m : MA)(f : Π A M B)(g : Π B M C) ⇒ Id (M C) (g † (f † m)) ((λx. g † (f x)) † m)
Here Π is the constructor for in nitary (A-indexed for any Set A) products. Taking models of this signature in the CwF of sets and families gives monads on Set, and unary logical predicate gives the notion of Dijkstra monad without weakening. In this simpli ed setting, the equivalence between Dijkstra monads and monad morphisms is then a consequence of the CwF structure. An extension of this framework to the ordered setting might provide a simpler and abstract variant of the proof in section 5.2. This chapter is dedicated to relational reasoning, i.e., proving relational properties between multiple runs of one or more programs, such as noninterference or program equivalence(see section 1.3). Our goal is to distill the generic relational reasoning principles that work for arbitrary monadic e ects so that we can reconstruct relational program logics in a generic fashion. Reusing our knowledge from the unary setting, we devise relational variants of speci cation monads and e ect observations providing the semantics of relational judgements.

The logic of relational rules

In this section, we make the simple but useful observation that rules of relational programs logics can be organised in 3 categories depending on their relationship to e ects and then provide a high-level idea of how it leads to our generic relational framework. Exceptional control ows are surprisingly challenging in the relational setting, and we need the full power of our framework to account for them (see section 6.3). However a much simpler system already account for many e ects and we use it to provide a smoother approach in section 6.2.

Syntactic rules

To factor out the fully generic parts, the rules of the relational program logics derived in our framework are divided into three categories, following the syntactic shape of the monadic programs on which their operate: R1 rules for pure language constructs, derived from the ambient dependent type theory (these rules target the elimination constructs for positive types, like if-then-else for booleans, recursors for inductive types, etc.);

R2 rules for the generic monadic constructs return and bind; and

R3 rules for e ect-speci c operations (e.g., get and put for the state monad, or throw and catch for the exception monad).

This organization allows us to clearly separate not only the generic parts (R1&R2) from the e ect-speci c ones (R3), but also the e ect-irrelevant parts (R1) from the e ect-relevant ones (R2&R3).

In its simplest form (section 6.2), the judgment of the relational program logics of our framework has the shape: c 1 ∼ c 2 { w }, where c 1 : M 1 A 1 is a computation in monad M 1 producing results of type A 1 , where c 2 : M 2 A 2 is a computation in monad M 2 producing results of type A 2 , and where w is a relational speci cation of computations c 1 and c 2 drawn from the type W rel (A 1 , A 2 ). Here M 1 and M 2 are two arbitrary and potentially distinct computation monads (e.g., the state monad St A = S → A × S and the exception monad Exc A = A + E), while w could, for instance, be a pair of a relational precondition and a relational postcondition, or a relational predicate transformer-below we will use relational weakest preconditions. For instance, for relating two stateful monads on states S 1 and S 2 , we often use relational speci cations drawn from

W St rel (A 1 , A 2 ) = ((A 1 × S 1 ) × (A 2 × S 2 ) → P) → S 1 × S 2
→ P which are predicate transformers mapping postconditions relating two pairs of a result value and a nal state to a precondition relating two initial states (here P stands for the type of propositions of our ambient dependent type theory). As an example of the judgment above, consider the programs c 1 = bind St (get ()) (λx . put (x + k)), which increments the content of a memory cell, and c 2 = ret St (), which does nothing. These two programs are related by the speci cation w = λϕ (s 1 , s 2 ). ϕ (((), s 1 + k), ((), s 2 )) : W St rel (1, 1) saying that for the postcondition ϕ to hold for the nal states of c 1 and c 2 , it is enough for it to hold for s 1 +k and s 2 , where s 1 are s 2 are the computation's initial states. Note that since c 1 , c 2 , and w are terms of our ambient type theory, free variables (like k) are handled directly by the type theory which save the simple judgment from an explicit context.

For pure language constructs R1, we try to use the reasoning principles of our ambient dependent type theory as directly as possible. For instance, our framework (again in its simplest incarnation from section 6.2) provides the following rule for the if-then-else construct:

if b then c 1 ∼ c 2 w else c 1 ∼ c 2 w ⊥ c 1 ∼ c 2 if b then w else w ⊥
In order to prove that c 1 and c 2 satisfy the relational speci cation ifbthenw elsew ⊥ , it is enough to prove that c 1 and c 2 satisfy both branches of the conditional in a context extended with the value of b. Interestingly, this rule does not make any assumption on the shape of c 1 and c 2 .

Relational program logics often classify each rule depending on whether it considers a syntactic construct that appears on both sides (synchronous), or only on one side (asynchronous). In the rule above, taking c 1 to be of the shape if b then c 1 else c ⊥ 1 and c 2 to be independent of b, we can simplify the premise according to the possible values of b to derive an asynchronous variant of the rule:

c 1 ∼ c 2 w c ⊥ 1 ∼ c 2 w ⊥ if b then c 1 else c ⊥ 1 ∼ c 2 if b then w else w ⊥ (6.1)
By requiring that both commands are conditionals, we can also derive the synchronous rule:

c 1 ∼ c 2 w c ⊥ 1 ∼ c ⊥ 2 w ⊥ if b 1 then c 1 else c ⊥ 1 ∼ if b 2 then c 2 else c ⊥ 2 { w • } (6.2)
where the relational speci cation w • = λϕ s 12 . (b⇔b 1 )∧(b⇔b 2 )∧ifbthenw ϕ s 12 elsew ⊥ ϕ s 12 ensures that the booleans b 1 and b 2 controlling the choice of the branch in each computation share the same value b.

For the monadic constructs R2, the challenge is in lifting the binds and returns of the two computation monads M 1 and M 2 to the speci cation level. For instance, in a synchronous rule one would relate bind M 1 m 1 f 1 to bind M 2 m 2 f 2 by rst relating computations m 1 and m 2 , say via relational speci cation w m , and then one would relate the two functions f 1 and f 2 pointwise via a function w f mapping arguments in A 1 × A 2 to relational speci cations:

m 1 ∼ m 2 { w m } ∀a 1 , a 2 f 1 a 1 ∼ f 2 a 2 w f (a 1 , a 2 ) bind M 1 m 1 f 1 ∼ bind M 2 m 2 f 2 bind W rel w m w f (6.3)
In the conclusion of this rule, we need a way to compose w : W rel (A 1 , A 2 ) and w f :

A 1 × A 2 → W rel (B 1 , B 2
) to obtain a relational speci cation for the two binds. We do this via a bind-like construct:

bind

W rel : W rel (A 1 , A 2 ) → (A 1 × A 2 → W rel (B 1 , B 2 )) → W rel (B 1 , B 2 ) (6.4)
For the concrete case of W St rel , this bind-like construct takes the form

bind W St rel w m w f = λϕ (s 1 , s 2 ). w m (λ ((a 1 , s 1 ), (a 2 , s 2 )). w f (a 1 , a 2 ) (s 1 , s 2 ) ϕ) (s 1 , s 2 ).
This construct is written in continuation passing style: the speci cation of the continuation w f maps a postcondition ϕ : (B 1 ×S 1 )×(B 2 ×S 2 ) → P, to an intermediate postcondition (A 1 ×S 1 )×(A 2 ×S 2 ) → P, then w m turns it into a precondition for the whole computation. Asynchronous rules for bind can be derived from the rule above, by taking m 1 to be ret M 1 () or f 1 to be ret M 1 above and using the monadic laws of M 1 (and symmetrically for M 2 ):

ret M 1 () ∼ m 2 { w m } ∀a 2 c 1 ∼ f 2 a 2 w f a 2 c 1 ∼ bind M 2 m 2 f 2 bind W rel w m (λ((), a 2 ). w f a 2 ) (6.5) c 1 ∼ m 2 { w m } ∀a 1 , a 2 ret M 1 a 1 ∼ f 2 a 2 w f (a 1 , a 2 ) c 1 ∼ bind M 2 m 2 f 2 bind W rel w m w f (6.6)
Finally, for the e ect-speci c operations R3, we provide a recipe for writing rules guided by our framework. For state, we introduce the following asynchronous rules for any a 1 , a 2 and s:

get () ∼ ret a 2 w get l ret a 1 ∼ get () w get r (6.7)

put s ∼ ret a 2 w put l ret a 1 ∼ put s w put r (6.8)

where w get l = λϕ (s 1 , s 2 ). ϕ ((s 1 , s 1 ), (a 2 , s 2 )), w get r = λϕ (s 1 , s 2 ). ϕ ((a 1 , s 1 ), (s 2 , s 2 )),

w put l = λϕ (s 1 , s 2 ). ϕ (((), s), (a 2 , s 2 )) and w put r = λϕ (s 1 , s 2 ). ϕ ((a 1 , s 1 ), ((), s)). Each of these rules describes at the speci cation level the action of a basic stateful operation (get, put) from either the left or the right computations, namely returning the current state for get or updating it for put. From these rules, we can derive two synchronous rules:

get () ∼ get () w get put s ∼ put s w put where w get = λϕ s 1 s 2 . ϕ ((s 1 , s 1 ), (s 2 , s 2 )) and w put = λϕ s 1 s 2 . ϕ (((), s), ((), s )). These rules can be derived from the rule for bind where the last speci cation reduces to w get using the de nition of bind W St rel .

Simple semantics

To de ne a semantics for the judgment above, we make the important observation that W rel (A 1 , A 2 ) is a relative monad (see chapter 3) over the product (A 1 , A 2 ) → A 1 × A 2 , as illustrated by the type of bind W rel above (6.4), where the continuation speci cation is passed a pair of results from the rst speci cation. Similarly, we generalize monad morphisms to relative monads and observe that a relative monad morphism

θ rel : M 1 A 1 × M 2 A 2 → W rel (A 1 , A 2 ) can immediately
give us a semantics for the judgment above:

θ rel c 1 ∼ c 2 { w } = θ rel (c 1 , c 2 )
≤ w, by asking that the speci cation obtained by θ rel is more precise than the user-provided specication w. In the case of state, θ St rel (c 1 , c 2 ) = λϕ (s 1 , s 2 ). ϕ (c 1 s 1 , c 2 s 2 ) simply runs the two computations and passes the results to the postcondition. If we unfold this, and the de nition of w ≤ W St rel w = ∀ϕ s 1 s 2 . w ϕ (s 1 , s 2 ) ⇒ w ϕ (s 1 , s 2 ), (6.9)

we obtain the standard semantics of a relational program logic for stateful computations (but without other side-e ects):

θ St rel c 1 ∼ c 2 { w } = ∀ϕ s 1 s 2 . w ϕ (s 1 , s 2 ) ⇒ ϕ (c 1 s 1 , c 2 s 2 )
Another important point is that the relational e ect observation can help us in deriving simple e ect-speci c rules, such as the ones for get (6.7) and put (6.8) above. For deriving such rules, one rst has to choose c 1 and c 2 (and we hope that the product programs of section 6.4 can provide guidance on this in the future) and then one can simply compute the speci cation using θ. For instance, w get l = λϕ (s 1 , s 2 ). ϕ ((s 1 , s 1 ), (a 2 , s 2 )) in the rst get rule (6.7) really is just θ(get (), ret a 2 ). This idea is further discussed in subsection 6.2.5.

Exceptions, and why the simple semantics is not enough

While the simple construction we described so far works well for state, it does not work for exceptions. For relating computations that can raise exceptions, we often need to use expressive speci cations that can tell whether an exception was raised or not in each of the computations. For instance, such relational speci cations could be drawn from:

W Exc rel (A 1 , A 2 ) = ((A 1 + E 1 ) × (A 2 + E 2 ) → P) → P. A predicate transformer w : W Exc rel (A 1 , A 2
) maps an exception-aware postcondition ϕ : (A 1 + E 1 ) × (A 2 + E 2 ) → P to a precondition, which is just a proposition in P. However, more work is needed to obtain a compositional proof system. Indeed, suppose we have derivations for m 1 ∼ m 2 { w m } and ∀a 1 , a 2 , f 1 a 1 ∼ f 2 a 2 w f (a 1 , a 2 ) with speci cations w m , w f drawn from W Exc rel . In order to build a composite proof relating c 1 = bind Exc m 1 f 1 and c 2 = bind Exc m 2 f 2 we need to be able to compose w m and w f in some way. If w m ensures that m 1 and m 2 terminate both normally returning values, or throw an exception at the same time, we can compose with w f or pass the exception to the nal postcondition. Otherwise, a computation, say m 1 , returns a value and the other, m 2 , raises an exception. In this situation, the speci cation relating c 1 and c 2 needs a speci cation for the continuation f 1 of m 1 , but this cannot be extracted out of w f alone. In terms of the constructs of W Exc rel , this failure is an obstruction to complete the following tentative de nition of bind W Exc rel : Our solution is to pass in two independent unary (i.e., non-relational) speci cations for the continuations f 1 and f 2 as additional arguments for bind: The rst new case corresponds to when m 2 terminated with an exception whereas m 1 returned a value normally. In this situation, we use the unary speci cation w f 2 to further evaluate the rst computation, independently of the second one, which already terminated. It turns out that this bind W Exc rel operation can still be used to de ne a relative monad, but in a more complex relational setting that we introduce in section 6.3. As a consequence of moving to this more complex setting our relational judgment needs to also keep track of unary speci cations, and its semantics also becomes more complex. We tame this complexity by working this out internally to a relational dependent type theory [START_REF] Tonelli | Investigations into a model of type theory based on the concept of basic pair[END_REF]. In practice we can still implement this relational dependent type theory inside our ambient type theory, in our case Coq, and continue using the same tools for veri cation.

let bind W Exc rel w m (w f : A 1 × A 2 → (((B 1 + E 1 ) × (B 2 + E 2 )) → P) → P) (ϕ : (B 1 + E 1 ) × (B 2 + E 2 ) → P) = w m (λx : (A 1 + E 1 ) × (A 2 + E 2 ). match x with | Inl a 1 , Inl a 2 → w f a 1 a 2 ϕ | Inr e 1 ,
let bind W Exc rel w m (w f1 : A 1 → ((B 1 + E 1 ) → P) → P) (w f2 : A 2 → ((B 2 + E 2 ) → P) → P) w f ϕ = w m (λx : (A 1 + E 1 ) × (A 2 + E 2

Simpli ed Framework

In this section we introduce a simple framework for relational reasoning about monadic programs based on (1) relational speci cation monads, capturing relations between monadic programs, and ( 2) relational e ect observations, lifting a pair of computations to their speci cation. By instantiating this framework with speci c e ects, we show how the speci c rules of previous relational program logics can be recovered in a principled way.

Speci cations as (relative) monads

We extend the important idea from section 2.3 of giving the same algebraic footing to both computations and speci cations.

Moving to the relational setting, a relational speci cation for a pair of stateful computations c 1 : St S 1 A 1 and c 2 : St S 2 A 2 consist of a predicate transformer w mapping postconditions relating 2 pairs of a result value and a nal state to a precondition relating 2 initial states, i.e.,

W St rel (A 1 , A 2 ) = ((A 1 × S 1 ) × (A 2 × S 2 ) → P) → S 1 × S 2 → P. (6.10)
W St rel does not posse the monad structure present on its unary variant. To begin with it is not even an endofunctor: it takes two types as input and produces one. However, the monadic operations of the unary variant do extend to the relational setting

let ret W St rel (a 1 ,a 2 ):A 1 × A 2 : W St rel (A 1 ,A 2 ) = λϕ (s 1 , s 2 ). ϕ ((a 1 ,s 1 ), (a 2 ,s 2 )) let bind W St rel (wm : W St rel (A 1 ,A 2 )) (wf:A 1 × A 2 → W St rel (B 1 ,B 2 )) : W St rel (B 1 ,B 2 ) = λϕ (s 1 ,s 2 ). wm (λ ((a 1 ,s 1 '),(a 2 ,s 2 ')). wf (a 1 , a 2 ) ϕ (s 1 ',s 2 '))
These operations satisfy equations analogs to the monadic ones and are part of a relative monad structure in the sense of [START_REF] Altenkirch | Monads need not be endofunctors[END_REF] (see also chapter 3). The relational speci cations for state W St rel are also naturally ordered by ≤ W St rel (see (6.9)) and this ordering is compatible with the relative monad structure, as long as we restrict our attention to monotonic predicate transformers, a condition that we will assume from now on for all monads on predicate transformer. We call such monad-like structure equipped with a compatible ordering a simple relational speci cation monad.

De nition 6.2.1. A simple relational speci cation monad consist of for each pair of types (A 1 , A 2 ), a type W rel (A 1 , A 2 ) equipped with a preorder ≤ W rel an operation ret W rel :

A 1 × A 2 → W rel (A 1 , A 2 ) an operation bind W rel : W rel (A 1 , A 2 ) → (A 1 × A 2 → W rel (B 1 , B 2 )) → W rel (B 1 , B 2 ) monotonic in both arguments satisfying the 3 following equations bind W rel (ret W rel (a 1 , a 2 )) w f = w f (a 1 , a 2 ) bind W rel w m ret W rel = w m bind W rel (bind W rel w m w f ) w g = bind W rel w m (λx. bind W rel (w f x) w g ) for any a 1 : A 1 , a 2 : A 2 , w f : A 1 × A 2 →W rel (B 1 , B 2 ), w m : W rel (A 1 , A 2 ), w g : B 1 × B 2 →W rel (C 1 , C 2 ).
A simple way to produce various examples of simple relational speci cation monads besides

W St
rel is to start from a (non-relational) speci cation monad W, and to compose it with the function Altenkirch et al. (2015) (prop. 2.3.( 1)) then ensures that

(A 1 , A 2 ) → A 1 × A 2 . A result of
W rel (A 1 , A 2 ) = W(A 1 × A 2
) is a simple relational speci cation monad. In the following paragraphs, we illustrate this construction with a few concrete instances showing the exibility of this notion. Depending on the property we want to verify, we can pick simpler or more sophisticated relational speci cation monads among these. For instance, relational speci cation monads based on pre-/postconditions make the connection to relational program logics in the literature more evident.

Backward predicate transformer A stateless version of W St

rel is the predicate transformer W Pure rel (A 1 , A 2 ) = (A 1 × A 2 → P) → P equipped with monadic operations and order derived from the monotonic continuation monad. We call this simple relational speci cation monad Pure because it naturally applies to the relational veri cation of pure code, however it can also be useful to verify e ectful code as we will see for nondeterministic computations in subsection 6.2.5.

Pre-/postconditions Speci cations written in terms of pre-/postconditions are simpler to understand than their predicate transformer equivalents. We show that relational speci cations written as pre-/postcondition also from a relational speci cation monads. The type constructor

PP Pure rel (A 1 , A 2 ) = P × (A 1 × A 2 → P)
models a pair consisting of a precondition in P and a postcondition, that is a relation on nal values of two computations. There is a natural ordering between such pairs, namely

(pre 1 , post 1 ) ≤ PP St rel (pre 2 , post 2 ) ⇐⇒ pre 2 ⇒ pre 1 ∧ ∀(a 1 : A 1 )(a 2 : A 2 ).post 1 (a 1 , a 2 )⇒post 2 (a 1 , a 2 ). The monadic structure is given by let ret PP Pure rel (a 1 , a 2 ) = ( , λ(a 1 ', a 2 '). a 1 = a 1 ' ∧ a 2 = a 2 ' ) let bind PP Pure rel (pre, post) f = let pre' = pre ∧ ∀a 1 , a 2 . post (a 1 , a 2 ) =⇒ π 1 (f (a 1 , a 2 )) in let post' (b 1 , b 2 ) = ∃a 1 , a 2 . post (a 1 , a 2 ) ∧ π 2 (f (a 1 , a 2 )) (b 1 , b 2 ) in (pre', post')
The return operation results in a trivial precondition and a postcondition holding exactly for the given arguments, whereas bind PP Pure rel strengthens the precondition of its rst argument so that the postcondition of the rst computation entails the precondition of the continuation.

Stateful pre-/postconditions Continuing on pre-/postconditions, we consider a stateful variant of PP Pure rel :

PP St rel (A 1 , A 2 ) = (S 1 × S 2 → P) × ((S 1 × A 1 × S 1 ) × (S 2 × A 2 × S 2 ) → P)
These are pairs, where the rst component consists of a precondition on a pair of initial states, one for each sides, while the second component is a postcondition formed by a relation on triples of an initial state, a nal value and a nal state.

The simple relational monadic speci cation structure is similar to the one of PP Pure rel , threading in the state where necessary, and specifying that the initial state does not change for return:

let ret PP St rel (a 1 ,a 2 ) = (λ (s 1 , s 2 ) . , λ((s i 1 , a 1 ', s f 1 ),(s i 1 , a 2 ', s f 2 )) . a 1 = a 1 ' ∧ a 2 = a 2 ' ∧ s i 1 = s f 1 ∧ s i 2 = s f 2 )
There is a natural embedding of stateful pre-/postconditions (pre, post)

: PP St rel (A 1 , A 2 ) into stateful backward predicate transformers W St rel (A 1 , A 2 ) given by λϕ (s i 1 , s i 2 ). pre(s i 1 , s i 2 ) ∧ ∀a 1 , a 2 , s f 1 , s f 2 .post ((s i 1 , a 1 , s f 1 ), (s i 2 , a 2 , s f 2 )) ⇒ ϕ ((a 1 , s f 1 ), (a 2 , s f 2 )) : W St rel (A 1 , A 2 ).
Errorful backward predicate transformer If exceptions turn out to be complex in general, a coarse approach is still possible using the simple relational monad (6.11) This construction represents a predicate transformer that works on either successful computations, or on an indication that at least one of the computations threw an exception, but losing the information of which of the two sides raised the exception. We can actually show that, under mild assumptions, any simple relational speci cation monad accounting for exceptions cannot distinguish the three situations where the left, the right, or both programs are raising exceptions.

W Err rel (A 1 , A 2 ) = ((A 1 × A 2 + 1) → P) → P.
Intuitively, this is due to the fact that the two programs are supposed to run independently but the simple relational speci cation monad impose some amount of synchronization. We return to W Exc rel and solve this problem in section 6.3, while previous relational program logics have generally been stuck with weak speci cation monads in the style of W Err rel (A 1 , A 2 ) above [START_REF] Barthe | Product programs and relational program logics[END_REF].

Relational semantics from e ect observations

The relational judgment c 1 ∼ c 2 { w } should assert that monadic computations c 1 : M 1 A 1 and c 2 : M 2 A 2 satisfy a relational speci cation w : W rel (A 1 , A 2 ) drawn from a simple relational speci cation monad. What does satisfaction mean in our monadic framework? Certainly it requires a speci c connection between the computational monads M 1 , M 2 and the simple relational speci cation monad W rel . Following the idea of the unary e ect observations (section 2.4), we introduce relational e ect observations, families of functions respecting the monadic structure, de ned here from rst principles, but that can be easily seen to be an instance of a relative monad morphism (section 3.2).

De nition 6.2.2. A simple relational e ect observation θ rel from computational monads M 1 , M 2 to a simple relational speci cation monad W rel is given by for each pair of types A 1 , A 2 a function θ rel : M

1 A 1 × M 2 A 2 → W rel (A 1 , A 2 ) such that θ rel (ret M 1 a 1 , ret M 2 a 2 ) = ret W rel (a 1 , a 2 ) θ rel (bind M 1 m 1 f 1 , bind M 2 m 2 f 2 ) = bind W rel (θ rel (m 1 , m 2 )) (θ rel • (f 1 , f 2 ))
As explained in the introduction, for stateful computations a simple relational e ect observation targeting W St rel runs the two computations and passes the results to the postcondition:

θ St rel (c 1 , c 2 ) = λϕ (s 1 , s 2 ). ϕ(c 1 s 1 , c 2 s 2 ).
(6.12)

A more interesting situation happens when interpreting nondeterministic computations (c 1 , c 2 ) :

NDet A 1 ×NDet A 2 into the relational speci cation monad W Pure rel (A 1 , A 2 ). Two natural simple relational e ect observations are given by

θ ∀ rel (c 1 , c 2 ) = λϕ. ∀a 1 ∈ c 1 , a 2 ∈ c 2 . ϕ(a 1 , a 2 ), (6.13) θ ∃ rel (c 1 , c 2 ) = λϕ. ∃a 1 ∈ c 1 , a 2 ∈ c 2 . ϕ(a 1 , a 2 ). (6.14)
The rst one θ ∀ rel prescribes that all possible results from the left and right computations have to satisfy the relational speci cation, corresponding to a demonic interpretation of nondeterminism, whereas the angelic θ ∃ rel requires at least one nal value on each sides to satisfy the relation. These examples are instances of the following theorem, which allows to lift unary e ect observations to simple relational e ect observations. To state it, we rst recall that two computations c 1 : M A 1 and c 2 : M A 2 commute [START_REF] Bowler | Exploring the boundaries of monad tensorability on set[END_REF][START_REF] Führmann | Varieties of e ects[END_REF] when

bind M c 1 λa 1 . bind M c 2 λa 2 . ret M (a 1 , a 2 ) = bind M c 2 λa 2 . bind M c 1 λa 1 . ret M (a 1 , a 2 ) .
The intuition is that executing c 1 and then c 2 is the same as executing c 2 and then c 1 . Theorem 6.2.1. Let θ 1 : M 1 → W and θ 2 : M 2 → W be unary e ect observations, where M 1 and M 2 are computational monads and W is a (unary) speci cation monad. We denote with W rel (A 1 , A 2 ) = W (A 1 ×A 2 ) the simple relational speci cation monad derived from W (see subsection 6.2.1). If for all c 1 : M 1 A 1 and c 2 : M 2 A 2 , we have that θ 1 (c 1 ) and θ 2 (c 2 ) commute, then the following function θ

rel : M 1 A 1 × M 2 A 2 → W rel (A 1 , A 2 ) is a simple relational e ect observation θ rel (c 1 , c 2 ) = bind W θ 1 (c 1 ) λa 1 . bind W θ 2 (c 2 ) λa 2 . ret W (a 1 , a 2 ) .
In general, given a simple relational e ect observation θ rel : M 1 , M 2 → W rel , we de ne the semantic relational judgment by

θ rel c 1 ∼ c 2 { w } = θ rel (c 1 , c 2 ) ≤ W rel w, (6.15)
where we make use of the preorder given by W rel . The following 3 subsections explain how to derive rules for a relational logic parameterized by the computational monads M 1 , M 2 , the simple relational speci cation monad W rel , and the simple relational e ect observation θ rel .

Pure relational rules

We start with rules coming from the ambient dependent type theory. Even though the semantics of the relational judgment depends on the choice of an e ect observation, the soundness of basic pure rules introduced in Figure 6.1 is independent from both the computational monads and e ects observation. Indeed, the proof of soundness of these follows from applying the adequate dependent eliminator coming from the type theory. These rules can then be tailored as explained in the introduction to derive asynchronous (6.1) or synchronous (6.2) rules more suited for applications. For some of the derived rules, there is, however, an additional requirement on the simple relational speci cation monad, so that we can strengthen preconditions.

Most of the examples of speci cation monads we work with actually provide enough structure to strengthen preconditions. An adequate extension of speci cation monads to provide such strengthening operations and solve this shortcoming also relevant in the unary setting is left as future work.

B E if b then c 1 ∼ c 2 w else c 1 ∼ c 2 w ⊥ c 1 ∼ c 2 if b then w else w ⊥ 0 E 1 w ≤ ⊥ c 1 ∼ c 2 { w } N E n : N w = elim N w 0 w suc c 1 [0/n] ∼ c 2 [0/n] { w 0 } ∀n : N, c 1 ∼ c 2 { w n } ⇒ c 1 [S n/n] ∼ c 2 [S n/n] { w suc (w n) } c 1 ∼ c 2 { w n } Figure 6.1: Pure relational rules R a 1 : A 1 a 2 : A 2 ret M 1 a 1 ∼ ret M 2 a 2 ret W (a 1 , a 2 ) W c 1 ∼ c 2 { w } w ≤ w c 1 ∼ c 2 w B m 1 ∼ m 2 { w m } ∀a 1 , a 2 f 1 a 1 ∼ f 2 a 2 w f (a 1 , a 2 ) bind M 1 m 1 f 1 ∼ bind M 2 m 2 f 2 bind W rel w m w f

Generic monadic rules

Given any computational monads M 1 , M 2 and a simple relational speci cation monad W rel , we introduce three rules governing the monadic part of a relational program logic (Figure 6.2). Each of these rules straightforwardly corresponds to a speci c aspect of the simple relational specication monad and are all synchronous. As explained in the introduction (6.5), it is then possible to derive asynchronous variants using the monadic laws of the computational monads.

Theorem 6.2.2 (Soundness of generic monadic rules). The relational rules in Figure 6.2 are sound with respect to any relational e ect observation θ rel , that is

c 1 ∼ c 2 { w } ⇒ ∀θ rel , θ rel c 1 ∼ c 2 { w }.
Proof. For rules R and B , we need to prove that θ rel (ret

M 1 a 1 , ret M 2 a 2 ) ≤ ret W (a 1 , a 2 ) and θ rel (bind M 1 m 1 f 1 , bind M 2 m 2 f 2 ) ≤ bind W (θ rel (m 1 , m 2 )) (θ rel •(f 1 , f 2 )
), which both hold by the relational e ect observation laws and re exivity. For W , we need to show that θ rel (c 1 , c 2 ) ≤ w under the assumptions that θ rel (c 1 , c 2 ) ≤ w and w ≤ w so we conclude by transitivity.

We note that the soundness proof would still be valid if we were to weaken the relational e ect observation laws to inequalities. A few examples for such lax relational e ect observation appears naturally, for instance in order to deal with variants of relational partial correctness, but we will not consider these in this paper. We further discuss this in the future work section (section 6.5).

E ect-speci c rules

The generic monadic rules together with the rules coming from the ambient type theory allow to derive relational judgments for the main structure of the programs. However, these rules are not enough to handle full programs written in the computational monads M 1 and M 2 , as we need rules to reason about the speci c e ectful operations that these monads provide. The soundness of e ect speci c relational rules is established with respect to a particular choice of relational e ect observation θ rel : M 1 , M 2 → W rel . Consequently, we make essential use of θ rel to introduce e ect speci c rules. The recipe was already illustrated for state in the introduction: rst pick a pair of e ectful algebraic operations (or ret for the asynchronous rules), unfold their de nition, and then compute a sound-by-design relational speci cation for this pair by simply applying θ rel . By following this recipe, we are decoupling the problem of choosing the computations on which these rules operate (e.g., synchronous vs. asynchronous rules to which we return in section 6.4) from the problem of choosing sensible speci cations, which is captured in the choice of θ rel .

Non-deterministic computations

The two relational e ect observations θ ∀ rel and θ ∃ rel provide di erent relational rules for the operation pick. As an example of how the recipe works, suppose that we want to come up with an asymmetric rule for non-deterministic computations that works on the left program, and which is sound with respect to θ ∀ rel . This means that the conclusion will be of the form pick ∼ ret a 2 { w } for some w : PP Pure rel . To obtain w, we apply the e ect observation to the computations involved in the rule w = θ ∀ rel (pick, ret a 2 ) = λϕ. ∀b ∈ {true, false}, a ∈ {a 2 }.ϕ(b, a), obtaining thus a rule which is trivially sound:

D L pick ∼ ret a 2 { λϕ. ϕ(true, a 2 ) ∧ ϕ(false, a 2 ) } .
Following the same approach, we can come up with an asymmetric rule on the right as well as a symmetric one. For concreteness, we show the symmetric rule for the e ect observation θ ∃ rel :

A pick ∼ pick λϕ. ϕ(true, true) ∨ ϕ(true, false) ∨ ϕ(false, true) ∨ ϕ(false, false) .

Exceptions using W Err rel

Taking M 1 and M 2 to be exception monads on exception sets E 1 and E 2 , and the relational speci cation monad W Err rel (Equation 6.11 on page 97), we have an e ect observation interpreting any thrown exception as a unique erroneous termination situation, that is

let θ Err ((c 1 , c 2 ) : Exc A 1 ×Exc A 2 ) : WrelErr (A 1 ,A 2 ) = λϕ. match c 1 , c 2 with | Inl a 1 , Inl a 2 → ϕ (Inl (a 1 , a 2 )) | _, _ → ϕ (Inr ())
Under this interpretation we can show the soundness of the following rules:

T L throw e 1 ∼ ret a 2 { λϕ. ϕ(inr ()) } T R ret a 1 ∼ throw e 2 { λϕ. ϕ(inr ()) } C c 1 ∼ c 2 { w } ∀e 1 e 2 c 1 e 1 ∼ c 2 e 2 w ∀e 1 a 2 c 1 e 1 ∼ ret a 2 w ∀a 1 e 2 ret a 1 ∼ c 2 e 2 w catch c 1 c 1 ∼ catch c 2 c 2 { λϕ.w(λa 0 . match a 0 with Inl a → ϕa | Inr () → w ϕ) }
The rules T L and T R can be derived using the recipe above, but the exceptions have to be con ated to the same exceptional result inr (), a situation that is forced by the choice of relational e ect observation and a weak speci cation monad. As a consequence, the C rule has to consider three exceptional cases. The speci cation for C does not follow mechanically from θ Err rel using our recipe since it is a handler and not an algebraic operation.

(f 1 a 1 ) ≤ w f 1 a 1 ∧ . . ., in particular the second hypothesis requires an element a 2 : A 2 that prevents 2 us from concluding by monotonicity of bind W Exc 1 . This problematic hypothesis only depends on the part of the context relevant for the left program and not on the full context, so we introduce structured contexts Γ = (Γ 1 , Γ 2 ) in our judgments, where Γ 1 and Γ 2 are simple contexts. The judgment

Γ c 1 {w 1 } ∼ c 2 {w 2 } | w rel now presupposes that Γ i c i : M i A i , Γ i w i : W i (i = 1, 2) and that Γ 1 , Γ 2 w rel : W rel (A 1 , A 2 )
. The semantics of this judgment is given by

Γ c 1 {w 1 } ∼ c 2 {w 2 } | w rel =   ∀γ 1 : Γ 1 , θ 1 (c 1 γ 1 ) ≤ w 1 γ 1 , ∀γ 2 : Γ 2 , θ 2 (c 2 γ 2 ) ≤ w 2 γ 2 , ∀(γ 1 , γ 2 ) : Γ 1 × Γ 2 , θ rel (c 1 γ 1 , c 2 γ 2 ) ≤ w rel (γ 1 , γ 2 )   (6.16)
A conceptual understanding of this interpretation that will be useful in the following is to consider Γ as a (trivial) relation Γ r = (Γ 1 , Γ 2 , λ(γ 1 : Γ 1 )(γ 2 : Γ 2 ). 1) instead of a pair and de ne the family of relations Θ r (γ) = (Θ 1 (γ 1 ), Θ 2 (γ 2 ), Θ rel γ) dependent over Γ r :

Θ 1 (γ 1 : Γ 1 ) = θ 1 (c 1 γ 1 ) ≤ w 1 γ 1 , Θ 2 (γ 2 : Γ 2 ) = θ 2 (c 2 γ 2 ) ≤ w 2 γ 2 , Θ rel (γ : Γ)(w 1 : Θ 1 γ 1 , w 2 : Θ 2 γ 2 ) = θ rel (c 1 γ 1 , c 2 γ 2 ) ≤ w rel γ.
Then the relational judgment Γ c 1 {w 1 } ∼ c 2 {w 2 } | w rel can be interpreted as a dependent function (γ : Γ r ) → Θ r γ in an appropriate relational dependent type theory.

A relational dependent type theory

Adding unary speci cations in the relational judgment enables a full treatment of exceptions, however the pure rules of section subsection 6.2.3 do not deal with a structured context Γ r = (Γ 1 , Γ 2 , Γ rel ). In order to recover rules dealing with such a context, we apply the same recipe internally to a relational dependent type theory as described by [START_REF] Tonelli | Investigations into a model of type theory based on the concept of basic pair[END_REF]. In practice, this type theory is described as a syntactic model in the sense of Boulier et al. (2017), that is a translation from a source type theory to a target type theory that we take to be our ambient type theory, where a type in the source theory is translated to a pair of types and a relation between them. We call the resulting source type theory RDTT and describe part of its construction in Figure 6.3, 2 Instead of insisting that c1 {w1} ∼ c2 {w2} | w rel proves the correctness of c1 and c2 with respect to w1 and w2 we could try to presuppose it, however this idea does not fare well since it would require a property akin of cancellability with respect to bind θ Exc 1

(bind Exc 1 m1 f1) ≤ bind W Exc 1 w m 1 w f 1 ⇒ θ Exc 1 m1 ≤ w m 1 that has no reason to hold in our examples. A r , B r , Γ r ::= 0 r | 1 r | B r | N r | A r + B r | (a : A r ) × B r a | (a : A r ) → B r a -maps a relational type A r to its underlying representation A r = (A 0 , A 1 , A r ) 0 r = (0, 0, =) 1 r = (1, 1, =) B r = (B, B, =) N r = (N, N, =) A r + B r =       ab 1 : A 1 + B 1 ab 2 : A 2 + B 2 case (ab 1 , ab 2 )   (inl a 1 , inl a 2 ).A rel a 1 a 2 (inr b 1 , inr b 2 ).B rel b 1 b 2 ( _ , _ ). 0         (a : A r ) × B r a =   (a 1 , b 1 ) : (a 1 : A 1 ) × B 1 a 1 , (a 2 , b 2 ) : (a 2 : A 2 ) × B 2 a 2 , (a r : A r a 1 a 2 ) × B r a 1 a 2 a r b 1 b 2   (a : A r ) → B r a =   f 1 : (a 1 : A 1 ) → B 1 a 1 , f 2 : (a 2 : A 2 ) → B 2 a 2 , (a 1 : A 1 )(a 2 : A 2 )(a r : A r a 1 a 2 ) → B r a 1 a 2 a r (f 1 a 1 ) (f 2 a 2 )   Figure 6
.3: Syntax of RDTT and translation to base type theory elim_sum : (P 1 : Moving from our ambient type theory to RDTT informs us on how to de ne rules coming from the type theory. For instance, generalizing the rule for if-then-else, we can use the motive P (ab : A r + B r ) = Θ r (ab) : Type r on the dependent eliminator for sum type elim_sum : (P : (A r +B r )→Type r ) → (a : A r →P a) → (b : B r →P b) → (x : A r +B r )→P x to obtain a rule for case splitting. This eliminator translates to a large term described in Figure 6.4 that induces the following relational rule using w l = (w l 1 , w l 2 , w l rel ), w r = (w r 1 , w r 2 , w r rel ) and the relational speci cations of the conclusion -where we abbreviate pattern matching with a case

A 1 + B 1 → Type) → (P 2 : A 2 + B 2 → Type) → (P rel : ∀(ab 1 : A 1 + B 1 )(ab 2 : A 2 + B 2 ), (A r + B r ) rel ab 1 ab 2 → Type) → (∀(a 1 : A 1 ), P 1 (inl a 1 )) → (∀(a 2 : A 2 ), P 2 (inl a 2 )) → (∀a 1 a 2 (a rel : A r a 1 a 2 ), P rel (inl a 1 ) (inl a
is morphisms (f 1 , f 2 , f rel ) : (C 1 ←C rel →C 2 ) → (D 1 ←D rel →D 2 ) in C such that the following diagram commute C 1 C rel C 2 D 1 D rel D 2 f 1 f rel f 2
We are concerned with the case C = Pos. Since Span(Pos) is cartesian closed, with internal hom between A = A 1 ←A rel →A 2 and B = B 1 ←B rel →B 2 given by the span

A ⇒ B = Pos(A 1 , B 1 ) ← (A ⇒ B) rel → Pos(A 2 , B 2 ) (A ⇒ B) rel = (f 1 : Pos(A 1 , B 1 )) × (f 2 : Pos(A 2 , B 2 )) × (f rel : Pos(A rel , B rel )) × {∀(a rel : A rel ), p 1 (f rel a rel ) = f 1 (p 1 a rel ) ∧ p 2 (f rel a rel ) = f 2 (p 2 a rel )}
we can enrich it over itself, yielding the enrich category Span(Pos). Similarly to the discussion above, we de ne an enriched base functor J × whose de nition on a pair of types (A 1 , A 2 ) is given by the span

J × (A 1 , A 2 ) = Disc A 1 π 1 ← -Disc A 1 × Disc A 2 π 2 -→ Disc A 2 .
Now, a J × -relative monad W is almost what we need to interpret relational speci cations: it consists of a mapping from pairs of types (A 1 , A 2 ) to a spans

W 1 (A 1 , A 2 ) ← W rel (A 1 , A 2 ) → W 2 (A 1 , A 2 ),
together with return and bind operations satisfying monotonicity conditions. We tame the potential dependency of W 1 in A 2 (respectively W 2 in A 1 ) thanks to the following theorem.

Theorem 6.3.1. The mapping (•) from J × -relative monad to J × -relative monad sending

W(A 1 , A 2 ) = W 1 (A 1 , A 2 ) ← W rel (A 1 , A 2 ) → W 2 (A 1 , A 2 ) to W(A 1 , A 2 ) = W 1 (A 1 , 1) ← W rel (A 1 , A 2 ) → W 2 (1, A 2 )
extends to an idempotent monad on the category of J × -relative monads.

In particular any J × -relative monad can be canonically completed so that W 1 and W 2 respectively depend only on A 1 or A 2 when applied to the pair (A 1 , A 2 ).

Proof. Let W be J × -relative monad and W 1

p 1 ← -W rel p 2
-→ W 2 its components. The main idea of the proof is that W 1 (A 1 , A 2 ) cannot depend essentially on A 2 because of the constraints of the J × -relative monad structure. This is made more formal by the following observation: let

A 1 , X 2 , Y 2 be sets, then the map ϕ 1 A 1 ,X 2 ,Y 2 = bind W 1 A 1 ,X 2 ,A 1 ,Y 2 (ret W 1 A 1 ,Y 2 ) ∈ Pos(W 1 (A 1 , X 2 ), W 1 (A 1 , Y 2
)), where we wrote explicitly as subscript the sets at which we instantiate the monadic operations of W, is an isomorphism. Its inverse is ϕ 1 A 1 ,Y 2 ,X 2 as shown by the following elementary computation

ϕ 1 A 1 ,X 2 ,Y 2 • ϕ 1 A 1 ,Y 2 ,X 2 = bind W 1 A 1 ,X 2 ,A 1 ,Y 2 (ret W 1 A 1 ,Y 2 ) • bind W 1 A 1 ,Y 2 ,A 1 ,X 2 (ret W 1 A 1 ,X 2 ) = bind W 1 A 1 ,Y 2 ,A 1 ,Y 2 bind W 1 A 1 ,X 2 ,A 1 ,Y 2 (ret W 1 A 1 ,Y 2 ) • (ret W 1 A 1 ,X 2 ) = bind W 1 A 1 ,Y 2 ,A 1 ,Y 2 (ret W 1 A 1 ,Y 2 ) = id W 1 (A 1 ,Y 2 ) . We note ϕ 2 A 2 ,X 1 ,Y 1 ∈ Pos(W 2 (X 1 , A 2 ), W 2 (Y 1 , A 2
)) the corresponding isomorphism for W 2 . With this observation in hand, we de ne a J × -relative monad structure on

W(A 1 , A 2 ) = W 1 (A 1 , 1) p1 ← -W rel (A 1 , A 2 ) p2 -→ W 2 (1, A 2 ) where p1 = ϕ 1 A 1 ,A 2 ,1 • p 1 and p2 = ϕ 2 A 2 ,A 1 ,1 • p 2 .
The return operation of W is simply the adequate restriction of W where the triangles on both sides commute by naturality of ret

W A 1 A 1 × A 2 A 2 W 1 (A 1 , 1) W 1 (A 1 , A 2 ) W rel (A 1 , A 2 ) W 2 (A 1 , A 2 ) W 2 (1, A 2 ) ret W 1 ret W 1 π 1 π 2 ret W rel ret W 2 ret W 2 W 1 (A 1 ,!) p 1 p 2 W 2 (!,A 2 )
The de nition of bind is slightly more involved. We need to de ne a morphism of span bind

W = (bind W 1 , bind W 2 , bind W rel ) for sets A 1 , A 2 , B 1 , B 2 bind W : Span(Pos)(J × (A 1 , A 2 ), W(B 1 , B 2 )) → Span(Pos)( W(A 1 , A 2 ), W(B 1 , B 2 )).
The components bind W 1 and bind W 2 are provided respectively by the adequate instantiations of bind

W 1 : Pos(A 1 , W 1 (B 1 , 1)) → Pos(W 1 (A 1 , 1), W 1 (B 1 , 1)) and bind W 2 : Pos(A 2 , W 2 (1, B 2 )) → Pos(W 2 (1, A 2 ), W 2 (1, B 2 ))
In order to de ne the component bind

W rel on f = (f 1 , f 2 , f rel ) ∈ Span(Pos)(J × (A 1 , A 2 ), W(B 1 , B 2 )), that is morphisms f 1 ∈ Pos(A 1 , W 1 (B 1 , 1)), f rel ∈ Pos(A 1 × A 2 , W rel (B 1 , B 2 )), f 2 ∈ Pos(A 2 , W 2 (1, B 2 )),
we complete where needed with ϕ (•) and de ne bind W rel f = bind W rel (ϕ 1 A 1 ,1,B 2 • f 1 , ϕ 2 A 2 ,1,B 1 • f 2 , f rel ). The following diagram shows that this indeed de ne a morphism of spans as required (we only show it for the rst projection, the second projection being symmetric).

A 1 A 1 × A 2 W 1 (A 1 , 1) W 1 (A 1 , 1) W 1 (A 1 , A 2 ) W rel (A 1 , A 2 ) bind W 1 f 1 bind W 1 f 1 bind W 1 (ϕ 1 A 1 ,1,A 2 •f 1 ) bind W rel f ϕ 1 A 1 ,1,A 2 ϕ 1 A 1 ,A 2 ,1 p 1
The monadic laws for W are straightforward consequences of the same laws for W. The functorial action of (•) just restricts a J × -relative monad morphism to the adequate components. The return operation of (•) as a monad is the span morphism

(ϕ 1 A 1 ,A 2 ,1 , ϕ 2 A 2 ,A 1 ,1 , id W rel (A 1 ,A 2
) ) : W(A 1 , A 2 ) -→ W(A 1 , A 2 ) while multiplication is the identity, obviously making the monad idempotent. This discussion lead us to the following elementary de nition of a relational speci cation monad.

De nition 6.3.1. A relational speci cation monad consist of for each pair of types (A 1 , A 2 ), types W 1 A 1 , W 2 A 2 and a relation W rel (A 1 , A 2 ) : W 1 A 1 → W 2 A 2 → Type between them, each equipped with a preorder ≤ W ; operations

ret W 1 : A 1 → W 1 A 1 ret W 2 : A 2 → W 2 A 2 ret W rel : (a 1 , a 2 ) : A 1 ×A 2 → W rel (A 1 , A 2 ) (ret W 1 a 1 ) (ret W 2 a 2 ) operations bind W 1 : W 1 A 1 → (A 1 → W 1 B 1 ) → W 1 B 1 bind W 2 : W 2 A 2 → (A 2 → W 2 B 2 ) → W 2 B 2 bind W rel : w m 1 : W 1 A 1 → w m 2 : W 2 A 2 → w m rel : W rel (A 1 , A 2 ) w m 1 w m 2 → w f 1 : (A 1 → W 1 B 1 ) → w f 2 : (A 2 → W 2 B 1 ) → w f rel : (((a 1 , a 2 ) : A 1 × A 2 ) → W rel (B 1 , B 2 ) (w f 1 a 1 ) (w f 2 a 2 )) → W rel (B 1 , B 2 ) (bind W 1 w m 1 w f 1 ) (bind W 2 w m 2 w f 2 )
monotonic in all arguments satisfying equations analogous to the monadic laws as well as monotonic operations τ 1 : w 1 : W 1 A 1 → W rel (A 1 , 1) w 1 (ret W 2 ()) and τ 2 : w 2 : W 2 A 2 → W rel (1, A 2 ) (ret W 1 ()) w 2 satisfying certain compatibility with the monadic operations detailed in the discussion below.

If the presence of the operations τ 1 and τ 2 can seem surprising, they ensure that we can construct exception transformers (see subsection 6.3.6). In order to explain what these operations are, rst note that from a J × -relative monad W = (W 1 ←W rel →W 2 ), we can derive four unary speci cation monads -two for each legs of the span -by combining restrictions of the domain and projections:

W 1 1 A = W 1 (A, 1) W Σ 1 A = (w : W 1 (A, 1)) × W rel (A, 1) w (ret W 2 ()) W 1 2 A = W 2 (1, A) W Σ 2 A = (w : W 2 (1, A)) × W rel (1, A) (ret W 1 ())
w There are obvious projections π 1 : W Σ 1 → W 1 1 and π 2 : W Σ 2 → W 1 2 that preserves the monadic structure. We require τ 1 (resp. τ 2 ) to be induced by a section of π 1 , in particular it needs to be a monad morphism.

In most of our examples the relation part of the monad is actually constant, simplifying further the type of operations to:

ret W rel : A 1 × A 2 → W rel (A 1 , A 2 ) bind W rel : W 1 A 1 → W 2 A 2 → W rel (A 1 , A 2 ) → (A 1 → W 1 B 1 ) → (A 2 → W 2 B 1 ) → (A 1 × A 2 → W rel (B 1 , B 2 )) → W rel (B 1 , B 2 )
This happens for our leading example of exceptions, but also for any relational speci cation monad constructed out of a simple relational speci cation monad. Indeed, we can associate to any simple relational speci cation monad W rel the relational speci cation monad W(A 1 , A 2 ) = (W rel (A 1 , 1), W rel (1, A 2 ), λw 1 w 2 . W rel (A 1 , A 2 )). The monadic operations just discard the super uous arguments and τ 1 , τ 2 are just identities.

W Γ r c 1 {w 1 } ∼ c 2 {w 2 } | w rel w 1 ≤ W 1 w 1 w 2 ≤ W 2 w 2 w rel ≤ W rel w rel Γ r c 1 {w 1 } ∼ c 2 {w 2 } | w rel R Γ 1 a 1 : A 1 Γ 2 a 2 : A 2 Γ r ret M 1 a 1 {ret W 1 a 1 } ∼ ret M 2 a 2 {ret W 2 a 2 } | ret W rel (a 1 , a 2 ) B Γ r m 1 {w m 1 } ∼ m 2 {w m 2 } | w m Γ r , a : A r f 1 a 1 {w f 1 a 1 } ∼ f 2 a 2 {w m 2 a 2 } | w f a Γ r bind M 1 m 1 f 1 {bind W 1 w m 1 w f 1 } ∼ bind M 2 m 2 f 2 {bind W 2 w m 2 w f 2 }
bind W rel w m w f

Relational e ect observations

The adequate notion of morphism between relational speci cation monad is given by relative monad morphisms over (Id Set 2 , J × ) : Id Set 2 → J × (see subsection 3.5.1), that we unravel here for concreteness.

De nition 6.3.2. A relational e ect observation consists of a triple θ = (θ 1 , θ 2 , θ rel ) : M 1 ⊗M 2 →W where θ 1 : M 1 → W 1 , θ 2 : M 2 → W 2 are (plain) monad morphisms, and

θ rel : ((m 1 , m 2 ) : M 1 A 1 × M 2 A 2 ) → W rel (A 1 , A 2 ) (θ 1 m 1 ) (θ 2 m 2 )
verify the two equations with respect to the monadic operations θ rel (ret M 1 a 1 , ret M 2 a 2 ) = ret W rel (a 1 , a 2 ) : W rel (A 1 , A 2 ) (θ 1 (ret M 1 a 1 )) (θ 2 (ret M 2 a 2 ))

θ rel (bind M 1 m 1 f 1 , bind M 2 m 2 f 2 ) = bind W rel (θ 1 m 1 ) (θ 2 m 2 ) (θ rel m rel ) θ 1 •f 1 θ 2 •f 2 θ rel •(f 1 × f 2 )
Given a relational e ect observation θ : M 1 ⊗ M 2 → W, we can de ne in full generality the semantics of the relational judgment by the Equation 6.16. We introduce the generic monadic rules in Figure 6.5, and similarly to the simple setting obtain the following soundness theorem. Theorem 6.3.2 (Soundness of monadic rules). The relational rules in Figure 6.5 are sound with respect to any relational e ect observation θ, that is

Γ r c 1 {w 1 } ∼ c 2 {w 2 } | w rel ⇒ ∀θ, Γ r θ c 1 {w 1 } ∼ c 2 {w 2 } | w rel

Relational speci cation monad transformers

Having a category of relational speci cation monads, we de ne a relational speci cation monad transformer to be a pointed endofunctor on this category [START_REF] Lüth | Composing monads using coproducts[END_REF]. We show that the usual state and exception transformer lifts to this setting, yielding in each case both a leftvariant and a right-variant applying either to the left type A 1 or right one A 2 of a relational speci cation monad W(A 1 , A 2 ). Since the two variants are symmetric, we only detail the left ones.

Adding state The usual state monad transformer maps a monad M to the monad StT(M) A = S → M (A × S). The left relational state monad transformer StT rel maps a relational speci cation monad W (A 1 , A 2 ) = (W 1 A 1 , W 2 A 2 , λw 1 w 2 . W rel (A 1 , A 2 ) w 1 w 2 ) to the relational speci cation monad with carrier

StT rel (W)(A 1 , A 2 ) = (StT(W 1 ) A 1 , W 2 A 2 , λw 1 w 2 . (s 1 : S 1 ) → W rel (A 1 ×S 1 , A 2 ) (w 1 s 1 ) w 2 )

The monadic operations on StT rel (W) 1 are given by the usual state transformer. The added data resides in the ret and bind operations responsible for the relational part: let ret StT(W) rel (a 1 ,a 2 ) : (s 1 : S 1 ) → W rel (A 1 × S 1 ,A 2 ) (ret StT (W )1 (a 1 ,s 1 )) (ret W 2 a 2 ) = λs 1 . ret W rel ((a 1 ,s 1 ), a 2 ) let bind

StT(W) rel (m 1 : StT(W) 1 A 1 ) (m 2 : W 2 A 2 ) (m rel : StT(W) rel (A 1 ,A 2 ) m 1 m 2 ) (f 1 : A 1 → StT(W) 1 B 1 ) (f 2 : A 2 → W 2 B 2 ) (f rel : (a 1 ,a 2 ):A 1 × A 2 → StT(W) rel (B 1 , B 2 ) (f 1 a 1 ) (f 2 a 2 )) : StT(W) rel (B 1 ,B 2 ) (bind StT(W)1 m 1 f 1 ) (bind W 2 m 2 f 2 ) =
λs 1 . bind W rel (m 1 s 1 ) m 2 (m rel s 1 ) (λ (a 1 ,s 1 '). f 1 a 1 s 1 ') f 2 (λ ((a 1 ,s 1 '), a 2 ). f rel (a 1 ,a 2 ) s 1 ')

The operation τ 1 : w 1 : StT(W 1 ) A 1 → (s 1 : S 1 ) → W rel (A 1 × S 1 , A 2 ) (w 1 s 1 ) (ret W 2 ()) is given by let τ

StT(W) rel 1 (w 1 : StT(W) 1 A 1 )= λs 1 . τ W 1 (w 1 s 1 )

Adding exceptions In a similar avor, the exception monad transformer ExcT mapping a monad M to ExcT(M)A = M(A + E 1 ) gives rise to its relational speci cation monad counterpart ExcT rel (W)(A 1 , A 2 ) = (ExcT(W 1 )A 1 , W 2 A 2 , W rel (A 1 + E 1 , A 2 )). The bind operation is more involved here, and makes full use of the presence of the unary speci cations. Note the crucial use of the τ 2 : w 2 : W 2 A 2 → W rel (1, A 2 ) (ret W 1 ()) w 2 in the last error branch. Putting these monad transformer to practice, we can nally de ne the full relational specication monad for exceptions validating the rules in Figure 6.6 by rst lifting the simple relational W Pure rel and applying the exception transformers on both left and right sides. Further, applications would involve speci cations relating state and exceptions with rollback state.

Product programs

The product programs methodology is an approach to prove relational properties that can serve as an alternative to relational program logics [START_REF] Barthe | Secure information ow by self-composition[END_REF][START_REF] Barthe | Product programs and relational program logics[END_REF]. In this section we show how to understand this methodology from the point of view of our framework.

Product programs reduce the problem of verifying relational properties on two programs c 1 and c 2 to the problem of verifying properties on a single product program c capturing at the same time the behaviors of c 1 and c 2 . To prove a relational property w on programs c 1 and c 2 , the methodology tells us to proceed as follows. First, we construct a product program c of c 1 and c 2 . Then, by standard methods, we prove that the program c satis es the property w seen as a In what follows, we show how these three steps would be understood in our framework if we wanted to prove θ c 1 ∼ c 2 { w }.

First of all, we need a notion of product program. In the setting of monadic programs, we capture a product program of c 1 : M 1 A 1 and c 2 : M 2 A 2 as a program c : P(A 1 , A 2 ), where P is a relative monad over (A 1 , A 2 ) → A 1 × A 2 (see section 3.2). We can think of c : P(A 1 , A 2 ) as a single computation that is computing both a value of type A 1 and a value of type A 2 at the same time. We expect P to support the e ects from both M 1 and M 2 , mixing them in a controlled way. As a concrete example, we can de ne products of stateful programs -M 1 A 1 = St S 1 A 1 and M 2 A 2 = St S 2 A 2 -inhabiting the relative monad P St (A 1 , A 2 ) = St S 1 ×S 2 (A 1 × A 2 ). To complete the de nition of product programs, we also need to explain when a concrete product program c : P(A 1 , A 2 ) is capturing the behavior of c 1 : M 1 A 1 and c 2 : M 2 A 2 . We propose to capture this in a relation c 1 ×c 2 c that exhibits the connection between between pairs of computations and their potential product programs. This relation should be closed under the monadic construction of the e ects, that is

a 1 : A 1 a 2 : A 2 ret M 1 a 1 ×ret M 2 a 2 ret P (a 1 , a 2 ) m 1 ×m 2 m rel ∀a 1 a 2 , f 1 a 1 ×f 2 a 2 f rel (a 1 , a 2 )
bind M 1 m 1 f 1 ×bind M 2 m 2 f 2 bind P m rel f rel but also spells out how particular e ects that P supports correspond to the e ects from M 1 and

M 2 .
Second, to fully reproduce the product program methodology, we need to explain how specications relate to product programs. We can use simple relational speci cation monads (subsection 6.2.1) for specifying the properties on products programs. The lifting of unary speci cation monads described there extends to unary e ect observations, providing an important source of examples of e ect observations for product programs. For example, going back to the example of state, we can specify product programs in P(A 1 , A 2 ) = St S 1 ×S 2 (A 1 × A 2 ) with specications provided by the simple relational speci cation monad W St where σ : (A 1 ×A 2 )×(S 1 ×S 2 )→(A 1 ×S 1 )×(A 2 ×S 2 ) simply swaps the arguments. Then, the concrete proof verifying the property w in this step consists of proving ζ(c) ≤ w as usual.

Finally, the third step simply relies on (proving and then) applying a soundness theorem for product programs as stated below. For state, this theorem is proved by analyzing the relation c 1 ×c 2 c and showing in each case that our choice of θ rel and ζ agree.

The interpretation of product programs as computations in a relative monad accommodate well the product program methodology. In particular we expect that algebraic presentations of these relative monads used for product programs could shed light on the choice of primitive rules in relational program logics, in a Curry-Howard fashion. We leave this as a stimulating future work.

Related work

Many di erent relational veri cation tools have been proposed, making di erent trade-o s, especially between automation and expressiveness. This section surveys this prior work, starting with the techniques that are closest related to ours.

Relational program logics Relational program logics are very expressive and provide a formal foundation for various tools, which have found practical applications in many domains. [START_REF] Benton | Simple relational correctness proofs for static analyses and program transformations[END_REF] introduced Relational Hoare Logic (RHL) as a way to prove the correctness of various static analysis and optimizing transformations for imperative programs. [START_REF] Yang | Relational separation logic[END_REF] extended this to the relational veri cation of pointer-manipulating programs. [START_REF] Barthe | Formal certi cation of code-based cryptographic proofs[END_REF] introduced pRHL as an extension of RHL to discrete probabilities and showed that pRHL can provide a solid foundation for cryptographic proofs, which inspired further research in this area [START_REF] Barthe | Probabilistic relational veri cation for cryptographic implementations[END_REF][START_REF] Basin | CryptHOL: Game-based proofs in higher-order logic[END_REF][START_REF] Petcher | The foundational cryptography framework[END_REF][START_REF] Unruh | Quantum relational Hoare logic[END_REF] and lead to the creation of semi-automated tools such as EasyCrypt (Barthe et al., 2013a). Barthe et al. (2013b) also applied variants of pRHL to di erential privacy, which led to the discovery of a strong connection (Barthe et al., 2017) between coupling proofs in probability theory and relational program logic proofs, which are in turn connected to product programs even without probabilities [START_REF] Barthe | Product programs and relational program logics[END_REF]. [START_REF] Carbin | Proving acceptability properties of relaxed nondeterministic approximate programs[END_REF] introduced a program logic for proving acceptability properties of approximate program transformations. [START_REF] Nanevski | Dependent type theory for veri cation of information ow and access control policies[END_REF] proposed Relational Hoare Type Theory (RHTT), a veri cation system for proving rich information ow and access control policies about pointer-manipulating programs in dependent type theory. [START_REF] Banerjee | Relational logic with framing and hypotheses[END_REF] addressed similar problems using a relational program logic with framing and hypotheses. [START_REF] Sousa | Cartesian Hoare logic for verifying k-safety properties[END_REF] devised Cartesian Hoare Logic for verifying k-safety hyperproperties and implement it in the D tool. Finally, [START_REF] Aguirre | A relational logic for higher-order programs[END_REF] introduced Relational Higher-Order Logic (RHOL) as a way of proving relational properties of pure programs in a simply typed λ-calculus with inductive types and recursive de nitions. RHOL was later separately extended to two different monadic e ects: cost [START_REF] Radicek | Monadic re nements for relational cost analysis[END_REF] and continuous probabilities with conditioning [START_REF] Sato | Formal veri cation of higherorder probabilistic programs: reasoning about approximation, convergence, bayesian inference, and optimization[END_REF].

Each of these logics is speci c to a particular combination of side-e ects that is xed by the programming language and veri cation framework. We instead introduce a general framework for de ning program logics for arbitrary monadic e ects.

Relators [START_REF] Gavazzo | Quantitative behavioural reasoning for higher-order e ectful programs: Applicative distances[END_REF] recently proposed a type system for di erential privacy that is parameterized by a signature of algebraic e ects. The type system is given a relational interpretation in terms of relators, which lift relations on values to relations on monadic computations: Γ : (A 1 × A 2 → P) → M A 1 × M A 2 → P. [START_REF] Lochbihler | E ect polymorphism in higher-order logic (proof pearl)[END_REF] also used relators in a recent library for e ect polymorphic de nitions and proofs in Isabelle/HOL, based on value-monomorphic monads. There seems to be a strong connection between such relators and the e ect observations going into one of the simplest relational speci cation monads we consider: (A 1 × A 2 → P) → P. Such an e ect observation has type

M A 1 × M A 2 → (A 1 × A 2 → P) → P,
which is isomorphic to the type of the relator Γ above (this is obvious to see by just swapping the two arguments). While further investigating this connection is very interesting, since relators are inherently lax this requires rst working out the theory of lax e ect observations, for which the relative monad morphism laws hold with ≤ instead of = (see the end of subsection 6.2.2). While we expect such an extension to our framework to be possible and generally useful, the technical development is involved even for the simple setting of section 6.2, so we leave it for future work.

Relational models of type theory The relational dependent type theory RDTT we employ in section 6.3 and the translation from the ambient type theory to RDTT is inspired by the parametricity translations for dependent type theory of [START_REF] Bernardy | Realizability and parametricity in pure type systems[END_REF]. Relations on types can also be internalized inside dependent type theory, making them rst class citizens, as in the work of [START_REF] Nuyts | Degrees of relatedness: A uni ed framework for parametricity, irrelevance, ad hoc polymorphism, intersections, unions and algebra in dependent type theory[END_REF] where it is used to characterize various properties such as continuity or parametricity. The work of [START_REF] Cavallo | Parametric cubical type theory[END_REF] on cubical models of type theory introduce an interesting property on these internalizations called relativity, playing a similar role as univalence for equivalences.

Type systems and static analysis tools Various type systems and static analysis tools have been proposed for statically checking relational properties in a sound, automatic, but overapproximate way. The type systems for information ow control generally trade o precision for good automation [START_REF] Sabelfeld | Language-based information-ow security[END_REF]. Various specialized type systems and static analysis tools have also been proposed for checking di erential privacy [START_REF] Barthe | Higher-order approximate relational re nement types for mechanism design and di erential privacy[END_REF]Gaboardi et al., 2013;[START_REF] Gavazzo | Quantitative behavioural reasoning for higher-order e ectful programs: Applicative distances[END_REF][START_REF] Winograd-Cort | A framework for adaptive di erential privacy[END_REF][START_REF] Zhang | LightDP: towards automating di erential privacy proofs[END_REF][START_REF] Zhang | Fuzzi: A three-level logic for di erential privacy[END_REF] or doing relational cost analysis [START_REF] Çiçek | Relational cost analysis[END_REF][START_REF] Qu | Relational cost analysis for functional-imperative programs[END_REF].

Product program constructions Product program constructions and self-composition are techniques aimed at reducing the veri cation of k-safety hyperproperties [START_REF] Clarkson | [END_REF] to the veri cation of traditional (unary) safety proprieties of a product program that emulates the behavior of multiple input programs. Multiple such constructions have been proposed [START_REF] Barthe | Product programs and relational program logics[END_REF] targeted for instance at secure IFC [START_REF] Barthe | Secure information ow by self-composition[END_REF][START_REF] Naumann | From coupling relations to mated invariants for checking information ow[END_REF][START_REF] Terauchi | Secure information ow as a safety problem[END_REF][START_REF] Yasuoka | Quantitative information ow as safety and liveness hyperproperties[END_REF], program equivalence for compiler validation [START_REF] Zaks | CoVaC: Compiler validation by program analysis of the cross-product[END_REF], equivalence checking and computing semantic di erences [START_REF] Lahiri | SYMDIFF: A language-agnostic semantic di tool for imperative programs[END_REF], program approximation [START_REF] He | Verifying relative safety, accuracy, and termination for program approximations[END_REF]. [START_REF] Sousa | Cartesian Hoare logic for verifying k-safety properties[END_REF] D tool for k-safety properties also creates k copies of the program, but uses lockstep reasoning to improve performance by more tightly coupling the key invariants across the program copies. [START_REF] Antonopoulos | Decomposition instead of self-composition for proving the absence of timing channels[END_REF] develop a tool that obtains better scalability by using a new decomposition of programs instead of using self-composition for k-safety problems. [START_REF] Eilers | Modular product programs[END_REF] propose a modular product program construction that permits hyperproperties in procedure speci cations. Recently, [START_REF] Farzan | Automated hypersafety veri cation[END_REF] propose an automated veri cation technique for hypersafety properties by constructing a proof for a small representative set of runs of the product program.

Logical relations and bisimulations Many semantic techniques have been proposed for reasoning about relational properties such as observational equivalence, including techniques based on binary logical relations (Ahmed et al., 2009;[START_REF] Benton | Relational semantics for e ect-based program transformations: higher-order store[END_REF][START_REF] Benton | Proof-relevant logical relations for name generation[END_REF]Benton et al., , 2014;;Dreyer et al., 2010[START_REF] Dreyer | Logical step-indexed logical relations[END_REF][START_REF] Dreyer | The impact of higher-order state and control e ects on local relational reasoning[END_REF][START_REF] Mitchell | Representation independence and data abstraction[END_REF]), bisimulations (Dal Lago et al., 2017;[START_REF] Koutavas | Small bisimulations for reasoning about higher-order imperative programs[END_REF][START_REF] Sangiorgi | Environmental bisimulations for higher-order languages[END_REF][START_REF] Sumii | A complete characterization of observational equivalence in polymorphic lambdacalculus with general references[END_REF], and combinations thereof [START_REF] Hur | The marriage of bisimulations and kripke logical relations[END_REF][START_REF] Hur | A logical step forward in parametric bisimulations[END_REF]. While these powerful techniques are often not directly automated, they can still be used for veri cation [START_REF] Timany | Mechanized relational veri cation of concurrent programs with continuations[END_REF] and for providing semantic correctness proofs for relational program logics (Dreyer et al., 2010[START_REF] Dreyer | Logical step-indexed logical relations[END_REF] and other veri cation tools (Benton et al., 2016;[START_REF] Gavazzo | Quantitative behavioural reasoning for higher-order e ectful programs: Applicative distances[END_REF].

Other program equivalence techniques Beyond the ones already mentioned above, many other techniques targeted at program equivalence have been proposed; we brie y review several recent works: [START_REF] Benton | Relational semantics for e ect-based program transformations: higher-order store[END_REF] do manual proofs of correctness of compiler optimizations using partial equivalence relations. [START_REF] Kundu | Proving optimizations correct using parameterized program equivalence[END_REF] do automatic translation validation of compiler optimizations by checking equivalence of partially speci ed programs that can represent multiple concrete programs. [START_REF] Godlin | Inference rules for proving the equivalence of recursive procedures[END_REF] propose proof rules for proving the equivalence of recursive procedures. [START_REF] Lucanu | Program equivalence by circular reasoning[END_REF] and Ştefan Ciobâcă et al. (2016) generalize this to a set of co-inductive equivalence proof rules that are language-independent. [START_REF] Wang | Verifying equivalence of database-driven applications[END_REF] verify equivalence between a pair of programs that operate over databases with di erent schemas using bisimulation invariants over relational algebras with updates. Finally, automatically checking the equivalence of processes in a process calculus is an important building block for security protocol analysis [START_REF] Blanchet | Automated veri cation of selected equivalences for security protocols[END_REF][START_REF] Chadha | Automated veri cation of equivalence properties of cryptographic protocols[END_REF].

Conclusion

We introduced in this chapter semantics tools to analyse relational program logics for arbitrary monadic e ects by extending the notions of speci cation monads and e ect observations to this relational setting. We can then reconstruct relational program logics for speci c e ects in a principled way using the general building blocks provided in subsection 6.2.4 and combining them with e ect speci c rules along the lines of subsection 6.2.5. An interesting research direction, opened by the correspondence with product programs, would be to develop techniques to select which proof rules should be considered as primitive, using proof-theoretical tools like focusing [START_REF] Zeilberger | The Logical Basis of Evaluation Order and Pattern-Matching[END_REF], but also investigating at the categorical level notions of presentations of relative monads, in connection with the theory of monads with arities [START_REF] Berger | Monads with arities and their associated theories[END_REF]. Finally, it also remains to be seen whether our notion of relational e ect observations can be generalized to turn the laws from equalities to inequalities. The proof of Thm. 6.2.2 from subsection 6.2.4 would be easy to extend, and this extension would allow for more examples, including the ones previously done using relators such as simulations for nondeterminism (Dal Lago et al., 2017), and would also make certain examples such as relational partial correctness easier. Yet a technical development following the ideas of chapter 3 seems more involved, even for the simple setting of section 6.2.

  mot, la cuisine, sans cesser d'être un art, deviendra scienti que et devra soumettre ses formules, empiriques trop souvent encore, à une méthode et à une précision qui ne laisseront rien au hasard.» Auguste Esco er, Le Guide culinaire, 1907

  let rec b (n : Z) : Z= if n ≤ 1 then n else b (n -1) + b (n -2)

  let rec b' (n : Z) : Z= if n = 0 || n = 1 then n else b' (n -1) + b' (n -2)

  b' -38 b' -39 + b' -40 ( b' -40 + b' -41) + ( b' -41 + b' -42)

  Figure 1.1: Chapter dependencies

  let read : IO I = Input (λi . ret IO i) let write (o : O) : IO 1 = Output o (ret IO ())

  ts our needs. Dually, if we only want to log informations, it's the writer monad WrT M A = M(A × list O) that we should use. As explained by Ahman and Uustalu (2013) for the case of plain monads, the two transformers are instances of a family of monad transformers called update transformers parametrized by a pair of a type S of states and a monoid (O, * , e) of updates acting on the states : O × S → S:

  λa. a = v) : PrePost A. And, given p = (pre, post) : PrePost A and a function f = λa. (pre a, post a) : A → PrePost B, the sequential composition of two computations is naturally speci ed by de ning bind PrePost p f = pre ∧ ∀a. post a =⇒ pre a , λb. ∃a. post a ∧ post a b : PrePost B

  and the sequential composition of two computations is speci ed as the predicate transformer bind SPost m f = λpre b. ∃a. f a (m pre a) b, for m : SPost A and f : A → SPost B. Any speci cation post : Pred A gives raise to a forward predicate transformer spostOfPred post = λ(pre : P) (a : A). pre ∧ post a : SPost A and conversely a forward predicate transformer sp : SPost A induces a canonical postcondition predOfSpost sp = sp : Pred A If forward predicate transformer in SPost could seem more expressive than Pred, it turns out that the two functions spostOfPred and predOfSpost are inverse of each others.

Figure 2 . 1 :

 21 Figure 2.1: Relationships between basic speci cation monads

θ

  HistST (write o) = λ(p : 1 × list E→P) (log : list E). p ( * , (Out o) :: log) : W HistST (1) θ HistST (read) = λ(p : I × list E→P) (log : list E). ∀i. p (i, (In i) :: log) : W HistST (I)

  algebras and T -algebra morphisms form a category called the Eilenberg-Moore category of T and note C T .

  for any object X ∈ |F| by postcomposition with f . We can extend this family of functors to de ne a framed natural transformationよ f : よ C . -→ よ C De nition 3.4.2. A framed natural transformation ν : K .

==

  De nition 3.5.4. An m-algebra morphism between m-algebras (A, a, α) and (B, b, β) is a pair of a vertical arrow f : A → B and a 2-cell ϕ : a . -→ bf satisfying the equation There is a framed functor Alg m : F op v → Distr sending an object A to the category of m-algebras and m-algebra morphisms between them. The action of Alg m on a vertical 1-cell f : A → B gives a functor Alg m (f ) : Alg m (B) → Alg m (A) sending an m-algebra (B, b :

=

  De nition 3.5.7. A morphism of Kleisli algebras from (X, f, α) to (Y, g, β) is a pair of a vertical arrow h : X → Y and a 2-cell ν : hf . In a similar fashion to Eilenberg-Moore algebras, a j-relative monad m : I → C in F give raise to a framed functor Kl m : F → Distr with the following components: An object X ∈ F is mapped to the category Kl m (X) of m-Kleisli algebras with codomain X and m-Kleisli morphisms whose rst component is the identity; A vertical arrow f : X → Y de nes a functor Kl m (X) → Kl m (Y ) by postcomposition; An horizontal arrow M

  N ) induce a natural transformations between profunctors by vertical postcomposition. The framed natural transformation c よ m : c よ C . -→ c よ I induced by the j-relative monad m always factors through Kl m

  ps is the 2-functor sending a 0-cell C to the functor corresponding to the identity id C : C → C, a 1-cell f : C → D to the pseudo-natural transformation (f, f, id f ) and a 2-cell ν : f → g to the modi cation (ν, ν). Theorem 3.5.2. The 2-categories Mnd(F op(2) v

For 0 -

 0 cells. From a relative monad m over the vertical identity of an object C in F, we de ne the following two cells in F vThe monadic laws follow from the equations of relative monads

For 2 -

 2 cells. In the same fashion, a 2-cell ζ = (ζ dom , ζ cod ) : θ → θ between relative monad morphisms θ = (u, θ) and θ = (v, θ ) have to verify that ζ = ζ dom = ζ cod by the rst equation, so that the second equation becomes ζ m 2 • θ = θ • m 1 ζ, which is exactly the condition for a monad transformation

"

  As a coq developer, we have no idea what we are doing[. . . ]" PMP, CoqPL'19

De nition 4

 4 .1.1. A monad transformer T on a category C (Liang et al., 1995) consists of a function T mapping monads m : C → C on C to monads T m : C → C, equipped with a monad morphism lift m : m → T m for each monad m on C, assigning functorially to each monad morphism θ : m 1 →m 2 a monad morphism T θ : T m 1 →T m 2 ,

  monad transformer on C is a pointed endofunctor on Mnd(C) Here, Mnd(C) is the sub-1-category of Mnd(Cat) (see section 3.1) whose objects are sent to C by the forgetful functor U : Mnd(Cat) → Cat and morphisms are sent to the identity functor on C. By the results of subsection 3.5.2, we can equivalently see Mnd(C) as the (1-)category RelMon(Distr) Id C of relative monads over the identity functor of C. This observation invite us to the following generalization of monad transformers for relative monads. De nition 4.1.2. Let F be a framed category, j ∈ F v (I, C) a vertical arrow and note RelMon(F) j the 1-category of j-relative monads. A j-relative monad transformer T is a pointed endofunctor on RelMon(F) j , that is a functor T : RelMon(F) j → RelMon(F) j equipped with a natural transformation lift : Id RelMon(F ) j → T To see what it means for speci cation monads, we unfold this de nition in the case of framed bicategory of Pos-enriched categories and distributors Pos-Distr, taking as base functor Disc : Set → Pos (see Def. 3.5.2 for details). Then what we could call a speci cation monad transformer T consists of a function T mapping speci cation monads W : Set → Pos to speci cation monads T W : Set → Pos, equipped with a monotonic monad morphism lift W : W → T W for each speci cation monads W, acting functorially on speci cation monad morphisms, such lift W is natural in W.

Figure 4 . 1 :

 41 Figure 4.1: Syntax of SM

Figure 4 . 2 :

 42 Figure 4.2: Typing rules for SM

Figure 4 . 3 :

 43 Figure 4.3: Equational theory of SM

Figure 4 . 5 :

 45 Figure 4.5: Denotation of SM terms

  ure 4.5. Given a derivation ∆; Γ SM t : C and substitutions δ : ∆, γ : Γ[δ/∆] M , we write t δ;γ M : C M for the denotation of the term t in L.

Figure 4 . 6 :

 46 Figure 4.6: Typing rules for SM with linearity condition

  Class VarType := var : ctype → Type. Section CTerm. Context '{VarType}. Inductive cterm : ctype → Type := | MRet : forall A, cterm (A CM A) | MBind : forall A B, cterm (( A CM B) (CM A CM B))

Figure 4 . 7 :

 47 Figure 4.7: PHOAS de nition of the term syntax of SM

Figure 4 .

 4 Figure 4.8: Binary parametricity predicate

Figure 4 . 9 :

 49 Figure 4.9: Term syntax of SM using De Bruijn indices

Figure 4 .

 4 Figure 4.10: Implementation of the state monad internally to SM

Figure 4 .

 4 Figure 4.11: Reduction of abstract machine con gurations

Figure 4 . 12 :

 412 Figure 4.12: Stacks and Abstract machine reduction for SM

Lemma 4 .

 4 5.1. Let C, K be categories, and F, G : K → Mnd(C) be functors to monads on C. There is a bijective correspondence between 1. natural transformations θ : F . -natural liftings tG : C → C F of t G through u such that the modi cation µ G also lifts to μG : tG • t G → tG . Proof. (1 ⇒ 2) The component at k ∈ K of the natural transformation θ : F . -→ G provides a monad morphism θ k : F k → G k. By Lem. 4.2.1 point 2, we obtain for each k ∈ K a lifting tG

  to rule them all, One Ring to nd them, One Ring to bring them all and in the darkness bind them[. . . ]" J.R.R. Tolkien, The Lord of the Rings, The Fellowship of the Ring

  pick ND: ND B (λp. p true ∧ p false) fail ND : ND 0 (λp. )

  let print_increasing (i:int) : IOHist unit (λ p h → ∀h'. p ((), h')) = write i; ( * pure computation * ) mustHaveOccurred i; ( * another pure computation * ) write (i+1)

  let do_io_then_rollback_state () : IOST unit (λ s h p → ∀i . p (() , s , [In i; Out (s+i+1)])) = let x = get () in let y = read () in put (x+y); ( * pure computation * ) let z = get () in write (z+1); put x

w

  : W unit for the loop body : N→ D unit w such that the invariant satis es bind w (λ() → w) ≤ w: let rec forin (range : list N) (body : N→ D unit w) : D unit w = match range with | [] → () | i :: range → body i ; forin range body

∂

  A : D A → W A where D A = (w : W A) × D A w and ∂ A is the rst projection. Then the for any type A, the return operations of W and D make the diagram on the left commute, whereas bind W and bind D induce the function on the right:

De nition 5

 5 .3.1. A graded monad on Set graded by a monoid (M, * , e) is a lax-monoidal functor G : M → [Set, Set], that is: For each m : M and set A, a set G A m For each m : M, sets A, B and function f : A → B a functorial action G A m → G B m For each set A, a unit A → G A e natural in A For each m 1 , m 2 : M and set A, a multiplication G

Figure 6 . 2 :

 62 Figure 6.2: Generic monadic rules in the simple framework

2 )

 2 Figure 6.4: Translation of the eliminator for sums in RDTT

Figure 6 . 5 :

 65 Figure 6.5: Generic monadic rules in the full relational setting

  let ret ExcT(W) rel (a 1 ,a 2 ) : W rel (A 1 + E 1 , A 2 ) (ret ExcT(W)1 a 1 ) (ret W2 a 2 ) = ret W rel (Inl a 1 , a 2 ) let bind ExcT(W) rel (m 1 : ExcT(W) 1 A 1 ) (m 2 : W 2 A 2 ) (m rel : ExcT(W) rel (A 1 ,A 2 ) m 1 m 2 ) (f 1 : A 1 → ExcT(W) 1 B 1 ) (f 2 : A 2 → W 2 B 2 ) (f rel : (a 1 ,a 2 ):A 1 × A 2 → ExcT(W) rel (B 1 , B 2 ) (f 1 a 1 ) (f 2 a 2 )) : ExcT(W) rel (B 1 ,B 2 ) (bind ExcT(W)1 m 1 f 1 ) (bind W2 m 2 f 2 ) = bind W rel m 1 m 2 m rel (λ ae 1 . match ae 1 with | Inl a 1 → f 1 a 1 | Inr e 1 → ret W1 (Inr e 1 )) f 2 (λ ae 1 a 2 . match ae 1 with | Inl a 1 → f rel a 1 a 2 | Inr e 1 → bind W rel (τ 2 (f 2 a 2 )) (λ ((), b 2 ) . ret W rel (Inr e 1 , b 2 )))

Figure 6

 6 Figure 6.6: Rules for exceptions

  rel , and the e ect observation ζ : P → W St rel obtained by lifting the unary e ect observation θ St : St → W St from section 2.4, resulting inζ (f : S 1 × S 2 → (A 1 × A 2 ) × (S 1 × S 2 )) = λϕ (s 1 , s 2 ) . ϕ σ(f (s 1 , s 2 ))

  Theorem 6.4.1 (Soundess of product programs). If c 1 ×c 2 c and ζ(c) ≤ w, then θ rel c 1 ∼ c 2 { w }.

  {|Cont Ans |} ret Id,Cont

P -→ Cont Ans Cont P One probably wonders what are the elements related by this relation? Unfolding the de nition, we get that a computation m : Cont Ans Id (X) and a speci cation w : Cont Ans Cont P (X) are related if

  by the pointwise monad structure of t G k and the fact that t G f are monad morphisms. In details, for each k ∈ K we have natural transformations η G k

  Ça n'est pas une question scienti que... -Moi, je vais te questionner Einstein, et si tu ne peux répondre, tout s'éteindra !! [. . . ] Quel est mon nom ? Et comme il ne pouvait répondre, tout bascula dans le néant.» F'murr, Le Génie des alpages n • 5, les intondables

	Chapter 6
	Relational reasoning
	«-

  W rel , since by the monadic equations we can replace for instance get () ∼ get () w get by the following derivation ret () ∼ get () w get l ∀u : 1, s 2 : S 2 get u ∼ ret s 2 w get r bind St S 1 (ret ()) get ∼ bind St S 2 (get ()) ret St S 2 bind W St rel w get l (λ(u, s 2 ). w get r )

  ). match x with ... | Inl a 1 , Inr e 2 → w f1 a 1 (λbe. ϕ be (Inr e 2 )) | Inr e 1 , Inl a 2 → w f2 a 2 (λbe. ϕ (Inr e 1 ) be) )

  Γ r throw e 1 {λϕ 1 . ϕ 1 (inr e 1 )} ∼ ret Exc a 2 {ret W Exc 2a 2 } | λϕ. ϕ (inr e 1 , inl a 2 ) Γ r ret Exc a 1 {ret W Exc 1 a 1 } ∼ throw e 2 {λϕ 2 . ϕ 2 (inr e 2 )} | λϕ. ϕ (inl a 1 , inr e 2 ) Γ r c 1 {w 1 } ∼ c 2 {w 2 } | w rel Γ r c err 1 {w err 1 } ∼ c err 2 {w err 2 } | w err rel Γ r catch c 1 c err 1 {w catch w 1 w err 1 } ∼ catch c 2 c err 2 {w catch w 2 w err 2 } | w catch rel w rel w err let w catch (w : W Exc A) (werr : E → W Exc A) : W A = λϕ. w (λ ae. match ae with | Inl a → ret W Exc a ϕ | Inr e → werr e ϕ) Exc rel (A 1 ,A 2 )) (werr 1 : E 1 → W Exc 1 A 1 ) (werr 2 : E 2 → W Exc 2 A 2 ) (werr rel : E 1 × E 2 → W Exc rel (A 1 ,A 2 )) : W Exc rel (A 1 ,A 2 ) = λϕ. w (λ (ae 1 , ae 2 ). match ae 1 , ae 2 with | Inl a 1 , Inl a 2 → ret W Exc rel (a 1 ,a 2 ) ϕ | Inr e 1 , Inl a 2 → werr 1 e 1 (λ ae 1 → ϕ (ae 1 , Inl a 2 )) | Inl a 1 ,Inr e 2 → werr 2 e 2 (λ ae 2 → ϕ (Inl a 1 , ae 2 )) | Inr e 1 , Inr e 2 → werr rel (e 1 ,e 2 ) ϕ)

	let w catch rel	(w:W

Prior work has used the term "Dijkstra monad" both for the indexed structure D and for the index W(Ahman et al.,

2017;[START_REF] Jacobs | Dijkstra monads in monadic computation[END_REF][START_REF] Jacobs | Dijkstra and Hoare monads in monadic computation[END_REF][START_REF] Swamy | Verifying higher-order programs with the Dijkstra monad[END_REF][START_REF] Swamy | Dependent types and multi-monadic e ects in F*[END_REF]. In order to prevent confusion, we use the term "Dijkstra monad" exclusively for the indexed structure D and the term "speci cation monad" for the index W .

Importantly, the ghost state only appears in speci cations and not in user programs; these still use only (stateless) IO.

It would corresponds to changing the underlying category to be some category of presheaves, which might be achievable inside type theory using the work of(Boulier et al., 2017;[START_REF] Jaber | Extending type theory with forcing[END_REF][START_REF] Jaber | The de nitional side of the forcing[END_REF]

We only use in this manuscript the notion of strong

2-functor and not the more general notion of lax 2-functor de ned in[START_REF] Bénabou | Introduction to bicategories[END_REF]

We are actually describing a pseudo double category.

In order to see these as objects of Pos-Distr, we need to distinguish two levels of smallness, as provided by di erent universes. Since our constructions are independent of the universe level -they are universe polymorphicwe keep the same notations for all levels

.4 for the cartesian product monoidal structure on Set and Pos.

However, in sharp contrast with the non-relative case, it is not enough to reverse the direction of θ to obtain a notion of monad morphism factoring through the Eilenberg-Moore objects. It seems di cult to de ne such a notion over an arbitrary morphism u of base functors.

Because of our implementation choices, no conversion rule appear explicitly in our implementation in Coq, seesection 4.4

We assume for these examples that L has (dependent) sums and products

To our knowledge there is no general de nition of this notion; the idea underlying the de nition of a relation compatible with an algebraic structure is however a recurrent one and particularly well-explained in[START_REF] Hermida | Logical relations and parametricity -A reynolds programme for category theory and programming languages[END_REF]

A |lin ret : A → MA A, B |lin bind : MA (A → MB) → MB Γ | x : C x : C (x : C) ∈ Γ Γ |x : C Γ | Ξ lin t i : C i Γ | Ξ lin (t 1 , t 2 ) : C 1 × C 2 Γ | Ξ lin t : C 1 × C 2 Γ | Ξ lin π i t : C i Γ, x : A | Ξ lin t : C Γ | Ξ SM λ. xt : (x : A) → C Γ | Ξ L u : A Γ | Ξ lin t : (x : A) → C Γ lin t u : C[u/x] Γ | x : C 1 lin t : C 2 Γ |lin λ x. t : C 1 C 2 Γ, x : C 1 | Ξ lin t : C 2 Γ | Ξ lin λ x. t : C 1 → C 2 Γ |lin t : C 1 C 2 Γ |lin t : C 1 → C 2 Γ | Ξ lin t 2 : C 1 Γ | -SM t 1 : C 1 C 2

An early attempt also used the library of Timany and Jacobs (2016) for categorical de nitions, but it turned out to be impractical for our use-case.

https://github.com/coq-community/paramcoq

Since we are working with intrinsically typed term, providing the linear type system would amount to implement yet another time a type of terms corresponding to linear type derivations.

Beside the xpoint that can be shown to be total; we return to this point when reconstructing Pure.

The transformation from pairs of pre/postconditions to backward predicate transformer is actually part of the adjunction described in section 2.3

If the representation of the Dijkstra monad is dependent pairs, then the code here does not type-check as-is and requires some tweaking. For this section we will assume Dijkstra monads are de ned as re nements of the computational monad, without any explicit proof terms to carry around. In our Coq implementation we use Program and existensial variables (evars) to hide such details.

Using the monotonic state transformer from section 4.3.

The actual relation in F also bake in the decreasing order on natural numbers and a construction for lexicographic order.

These e ect polymorphism last examples are written in F syntax, but only implemented in Coq, since Dijkstra monads are not rst class in F .

We conjecture that an alternative and more symmetric solution would be to equip our Dijkstra monads with an additional order, but this does not correspond to the examples we obtain in practice.

By a lax monad morphism θ : M → W, we mean a lax natural transformation θ -that is such that the naturality square commutes up to the order on W-preserving the monadic operations in the weaker sense that θ(ret M ) ≤ ret W and θ(bind M m f ) ≤ bind W (θ m) (θ • f ).

Assuming that W rel contains a top element ⊥ that entails falsity of the precondition; this is the case for all our examples.

The interpretation of linear types is quite straightforward, mainly enforcing that the linear function space to be interpreted by homomorphisms: Proof. By induction on the linear typing derivation (each case corresponding to one derivation rule in Figure 4.6):

and bind M a homomorphism between the respective M -algebra structures Case t = x is linear, (|x|) δ;γ;ξ M = ξ and the identity is an M -algebra map Case t = x is not linear, (|x|) δ;γ;-

and it is and M -algebra map by induction hypothesis

, the denotation of the term is the same, we just forget that it is an homomorphism

Generic Framework

While the simple framework works well for a variety of e ects, it falls short of providing a convincing treatment of e ects with control such as exceptions or non-termination. This limitation is due to the fact that simple relational speci cation monads merge tightly together the speci cation of two independent computations. We now explain how to overcome these limitations starting with the example of exceptions, and how it leads to working inside a relational dependent type theory. Informed by the generic constructions on relative monads underlying the simple setting, we derive notions of relational speci cation monad and relational e ect observation in this enriched setting. These relational speci cation monads require an important amount of operations so we introduce relational speci cation monad transformers for state and exceptions, simplifying the task of building complex relational speci cation monad from simpler ones.

Exceptional control ow in relational reasoning

We explained in subsection 6.2.5 how to prove relational properties of programs raising exceptions, as long as we give up on the knowledge of which program raised an exception at the level of relational speci cations. This restriction prevents us from even stating natural speci cations such as simulations "if the left program raises, so does the right one".

In order to go beyond this unsatisfying state of a airs, we consider a type of relational speci cations allowing to write speci cations consisting of predicate transformers mapping a postcondition on pairs of either a value or an exceptional nal state to a proposition:

For instance, the speci cation above can be stated as λϕ. ∀ae 1 ae 2 .(Inr?ae 1 ⇒ Inr?ae 2 ) ⇒ ϕ(ae 1 , ae 2 ) : W Exc rel (A 1 , A 2 ), where Inr? ae = match ae with Inr _ → | _ → ⊥. As explained in section 6.1, this type does not admit a monadic operation bind w m w f using only a continuation of type w

) due to the fact that w m could result in an intermediate pair consisting of a normal value on one side and an exception on the other side. Our solution is to provide to bind W Exc rel the missing information it needs in such cases.

To that purpose, we use the unary speci cation monads

)→P to provide independent speci cations of each program. With the addition of these, we can write a function that relies on the unary speci cations when the results of the rst computations di er (one raise an exception and the other returns).

wm (λ ae :

| Inr e 1 , Inl a 2 → f 2 a 2 (λ be → ϕ (Inr e 1 ) be))

A problem of context

In order to keep track of these unary speci cations drawn from W Exc 1 and W Exc 2 in the relational proofs, we extend the relational judgment to

Here, w 1 : W Exc 1 A 1 is a unary speci cation for c 1 : Exc 1 A 1 , symmetrically w 2 : W Exc 2 A 2 is a unary speci cation for c 2 : Exc 2 A 2 , and w rel : W Exc rel (A 1 , A 2 ) speci es the relation between the construction -as arguments to the eliminator

As in the simple setting, we can then re ne this rule to obtain synchronous or asynchronous rules specifying a prescribed shape for the programs c 1 , c 2 .

Relational speci cation monads

Motivated by the case of exceptions, we now de ne the general notion of a relational speci cation monad. This de nition is obtained by instantiating the de nitions of an (enriched) relative monad from chapter 3 to our relational dependent type theory, ensuring that we obtain a theory uniform with the simple setting, and crucially that we can use the same methodology to introduce relational rules. What we ought to call a relational speci cation monad should assign to any pair of types

)) corresponding respectively to the type of unary speci cations for the left and right programs, together with the type of relational speci cations. This description would invite us to consider relational speci cation monad as Pos-enriched functors Set 2 → Pos 3 with a relative monad structure with respect to the base functor

There is however a small discrepancy: if W is such a J -relative monad, its value at a pair of types

where the rst and second component can respectively depend on A 2 and A 1 , a feature that we do not expect from a relational speci cation monad.

A rst way to solve this discrepancy would be by enforcing that the rst and second projections come from unary speci cation monads. If W 1 , W 2 are two (unary) speci cation monads, we can pair these together to de ne a monad relative to Disc × Disc :

Since we have a commuting triangle of (Pos-enriched) functors

we could de ne a relational speci cation monad W to be J -relative monad lifting W 1 × W 2 along the functor π 12 : Pos 3 -→ Pos 2 . We choose to use a second, slightly more convoluted solution, that has the bene t of making clearer the connection with the relational dependent type theory of the previous section. Moreover, it provides a de nition that does not involve any lifting condition, presumably simpler to implement inside an intensional type theory such as Coq.

Recall the following categorical presentation of relations. If C is a category, the category Span(C) consists of spans in C, that is diagrams C 1 ←C rel →C 2 in C, and morphisms of spans, that ABSTRACT Computational monads are a convenient algebraic gadget to uniformly represent side-effects in programming languages, such as mutable state, divergence, exceptions, or non-determinism. Various frameworks for specifying programs and proving that they meet their specification have been proposed that are specific to a particular combination of side-effects. For instance, one can use Hoare logic to verify the functional correctness of programs with mutable state with respect to pre/post-conditions specifications, which are predicates on states. The goal of this thesis is to devise a principled semantic framework for verifying programs with arbitrary monadic effects in a generic way with respect to such rich specifications. One additional challenge is supporting various interpretations of effects, for instance total vs partial correctness, or angelic vs demonic nondeterminism. Finally, the framework should also accommodate relational verification, for properties such as program equivalence.

MOTS CLÉS

Preuve de programmes, Sémantique Catégorique, Langages de programmation

RÉSUMÉ

Les effets de bord présent dans les languages de programmation tel que l'état mutable, la divergence ou le non déterminisme sont capturés de manière élégante par des monades. Plusieurs systèmes ont été proposés pour spécifier et prouver que des programmes manipulant une certaine combinaison d'effets respectent leur spécification. Par exemple, la logique de Hoare permet de vérifier la correction de programmes manipulant la mémoire en stipulant des prédicats sur les états initiaux et finaux. Le but de cette thèse est de définir un cadre sémantique générique pour vérifier que des programmes avec des effets monadique arbitraire respectent de telles spécifications. Les interprétations diverses des effets tel que la correction totale ou partielle, ou encore le non-déterminisme angélique ou démonique, introduisent un défi supplémentaire. Ce cadre sémantique devra aussi considérer la vérification de propriétés relationnelles, par exemple la simulation ou l'équivalence de programmes.

KEYWORDS

Proof of programs, Categorical semantics, Programming languages