1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! ![license: MIT](https://img.shields.io/github/license/boltlabs-inc/dialectic)
//! [![crates.io](https://img.shields.io/crates/v/dialectic)](https://crates.io/crates/dialectic)
//! [![docs.rs documentation](https://docs.rs/dialectic/badge.svg)](https://docs.rs/dialectic)
//!
//! > **dialectic (noun):** The process of arriving at the truth by stating a thesis, developing a
//! > contradictory antithesis, and combining them into a coherent synthesis.
//! >
//! > **dialectic (crate):** Transport-polymorphic session types for asynchronous Rust.
//!
//! When two concurrent processes communicate, it's good to give their messages *types*, which
//! ensure every message is of an expected form.
//!
//! - **Conventional types** merely describe **what is valid** to communicate.
//! - **Session types** describe **when it is valid** to communicate, and **in what manner**.
//!
//! This crate provides a generic wrapper around almost any type of asynchronous channel that adds
//! compile-time guarantees that a specified *session protocol* will not be violated by any code
//! using the channel. Such a wrapped channel:
//!
//! - has **almost no runtime cost** in time or memory;
//! - is **built on `async`/`.await`** to allow integration with Rust's powerful `async` ecosystem;
//! - gracefully handles runtime protocol violations, introducing **no panics**;
//! - allows for **full duplex concurrent communication**, if specified in its type, while
//!   preserving all the same session-type safety guarantees; and
//! - can even implement **context free sessions**, a more general form of session type than
//!   supported by most other session typing libraries.
//!
//! Together, these make Dialectic ideal for writing networked services that need to ensure **high
//! levels of availability** and **complex protocol correctness properties** in the real world,
//! where protocols might be violated and connections might be dropped.
//!
//! <!-- snip -->
//!
//! # What now?
//!
//! - If you are **new to session types** you might consider starting with the **[tutorial-style
//!   tour of the crate](tutorial)**.
//! - If you're **familiar with session types**, you might jump to the **[quick
//!   reference](#quick-reference)**, then read more in the [`types`](crate::types) module and the
//!   documentation for [`Chan`](crate::Chan).
//! - If you want to **integrate your own channel type** with Dialectic, you need to implement the
//!   [`Transmit`] and [`Receive`] traits from the [`backend`] module.
//! - Or, you can **[dive into the reference documentation](#modules)**...
//!
//! # Quick reference
//!
//! The **[tutorial]** covers all the constructs necessary to write session-typed programs with
//! Dialectic. A quick summary:
//!
//! - To make a pair of dual [`Chan`]s for a session type `P`: [`let (c1, c2) = P::channel(||
//!   {...})`](NewSession::channel) with some closure that builds a unidirectional underlying
//!   channel.
//! - To wrap an existing sender `tx` and receiver `rx` in a single [`Chan`] for `P`: [`let c =
//!   P::wrap(tx, rx)`](NewSession::wrap).
//! - Backend transports suitable for being wrapped in a [`Chan`] are provided in [`backend`], along
//!   with the [`Transmit`] and [`Receive`] traits necessary to implement your own.
//!
//! Once you've got a channel, here's what you can do:
//!
//! | Session Type (`S`) | Channel Operation(s) (on a channel `c: Chan<_, _, S, _>`) | Dual Type (`S::Dual`) |
//! | :----------- | :------------------- | :-------- |
//! | [`Send<T, P = Done>`](Send) | Given some `t: T`, returns a new `c`:<br>[`let c = c.send(t).await?;`](CanonicalChan::send) | [`Recv<T, P::Dual>`](Recv) |
//! | [`Recv<T, P = Done>`](Recv) | Returns some `t: T` and a new `c`:<br>[`let (t, c) = c.recv().await?;`](CanonicalChan::recv) | [`Send<T, P::Dual>`](Send) |
//! | [`Choose<Choices>`](Choose) | Given some `_N` < the length of `Choices`, returns a new `c`:<br>[`let c = c.choose(_N).await?;`](CanonicalChan::choose) | [`Offer<Choices::Dual>`](Offer) |
//! | [`Offer<Choices>`](Offer) | Given a set of labeled branches `_N => ...` in ascending order, exactly one for each option in the tuple `Choices`, returns a new `c` whose type each branch must match:<br>[`let c = offer!(c => { _0 => ..., _1 => ..., ... });`](offer!) | [`Choose<Choices::Dual>`](Choose) |
//! | [`Split<P, Q>`](Split) | Given a closure evaluating the session types `P` (send-only) and `Q` (receive-only) each to `Done` (potentially concurrently), returns a result and a channel for `Done`:<br>[<code>let (t, c) = c.split(&#124;c&#124; async move { ... }).await?;</code>](CanonicalChan::split) | [`Split<Q::Dual, P::Dual>`](Split) |
//! | [`Loop<P>`](Loop) | Whatever operations are available for `P` | [`Loop<P::Dual>`](Loop) |
//! | [`Continue<N = Z>`](Continue) | Whatever operations are available for the start of the `N`th-innermost [`Loop`] | [`Continue<N>`](Continue) |
//! | [`Break<N = Z>`](Break) | • If exiting the *outermost* [`Loop`]: Returns the underlying [`Transmit`]/[`Receive`] ends: [`let (tx, rx) = c.close();`](CanonicalChan::close)<br> • If exiting an *inner* [`Loop`]: Whatever operations are available for the start of the `(N + 1)`th-innermost [`Loop`] | [`Break<N>`](Break) |
//! | [`Seq<P, Q>`](Seq) | Given a closure evaluating the session type `P` to `Done`, returns a result and a channel for the type `Q`:<br>[<code>let (t, c) = c.seq(&#124;c&#124; async move { ... }).await?;</code>](CanonicalChan::seq) | [`Seq<P::Dual, Q::Dual>`](Seq) |
//! | [`Done`] | • If *outside* a [`Loop`]: Returns the underlying [`Transmit`]/[`Receive`] ends: [`let (tx, rx) = c.close();`](CanonicalChan::close)<br> • If *inside* a [`Loop`], equivalent to [`Continue`]: whatever operations are available for the start of the innermost [`Loop`] | [`Done`] | [`c.close()`](CanonicalChan::close) |

#![recursion_limit = "256"]
#![allow(clippy::type_complexity)]
#![warn(missing_docs)]
#![warn(missing_copy_implementations, missing_debug_implementations)]
#![warn(unused_qualifications, unused_results)]
#![warn(future_incompatible)]
#![warn(unused)]
#![forbid(broken_intra_doc_links)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::{
    marker::{self, PhantomData},
    pin::Pin,
};

#[macro_use]
extern crate derivative;

use crate::backend::*;
use futures::Future;

/// The prelude module for quickly getting started with Dialectic.
///
/// This module is designed to be imported as `use dialectic::prelude::*;`, which brings into scope
/// all the bits and pieces you need to start writing programs with Dialectic.
pub mod prelude {
    #[doc(no_inline)]
    pub use crate::backend::{Choice, Receive, Transmit};
    #[doc(no_inline)]
    pub use crate::new_session::NewSession;
    pub use crate::tuple::{List, Tuple};
    pub use crate::types::unary::constants::*;
    pub use crate::types::unary::types::*;
    pub use crate::types::unary::{LessThan, Unary, S, Z};
    pub use crate::types::*;
    pub use crate::{
        canonical::{Branches, CanonicalChan},
        offer, Chan, IncompleteHalf, SessionIncomplete,
    };
    #[doc(no_inline)]
    pub use call_by::{CallBy, CallingConvention, Mut, Ref, Val};
}

pub mod backend;
pub mod tutorial;
pub mod types;

mod new_session;
pub use new_session::NewSession;

pub mod canonical;
#[doc(inline)]
pub use canonical::Branches;

use prelude::*;

/// A bidirectional communications channel using the session type `P` over the connections `Tx` and
/// `Rx`.
///
/// **[See the documentation for `CanonicalChan` for available methods and trait
/// implementations.](CanonicalChan)**
///
/// **Important: always write this type synonym ([`Chan`]) in type signatures, not️
/// [`CanonicalChan`] directly.** This is because the [`Chan`] type synonym canonicalizes its
/// session type argument, which means it can be used more flexibly. The details:
///
/// # Technical notes on canonicity: TL;DR: always write `Chan`
///
/// In Dialectic, operations are liberally available on [`Chan`]s wherever they make
/// sense. For instance, it's valid to call [`send`](CanonicalChan::send) on a channel which was
/// created using the session type `Loop<Send<String>>`, even though the type does not literally
/// begin with `Send<String>`.
///
/// A `CanonicalChan` always has a session type which is syntactically a real action: it will never
/// be [`Loop`], [`Continue`], or [`Break`] (or, when inside a [`Loop`], it will never be [`Done`]).
/// Every action available on a [`CanonicalChan`] "fast-forwards" through such control operators,
/// yielding a [`CanonicalChan`] that corresponds to the next real action available.
///
/// While this design means greater flexibility and concision in writing session-typed code, it can
/// be confusing in the case where you want to explicitly write out the session type of a channel,
/// because the automatic canonicalization can mean a [`Chan`] does not have the type
/// you might think it does.
///
/// ⚠️ **The problem:** Suppose you wanted to explicitly annotate the type of a new channel:
///
/// ```compile_fail
/// # use dialectic::prelude::*;
/// # use dialectic::backend::mpsc;
/// use dialectic::canonical::CanonicalChan;
///
/// type P = Loop<Send<String>>;
/// let (c1, c2): (CanonicalChan<_, _, P, ()>, _) = P::channel(mpsc::unbounded_channel);
/// ```
///
/// This fails to typecheck, returning several errors (abridged for clarity):
///
/// ```text
/// error[E0271]: type mismatch resolving `<Loop<Send<String>> as Actionable>::Action == Loop<Send<String>>`
///    = note: expected struct `Loop<Send<_>>`
///               found struct `Send<_>`
///
/// error[E0271]: type mismatch resolving `<Loop<Send<String>> as Actionable>::Env == ()`
///    = note: expected unit type `()`
///                    found type `(Send<String>, ())`
/// ```
///
/// These errors indicate that the returned [`CanonicalChan`] from `P::channel` *does not* have the
/// session type `P` and the initial empty environment `E = ()`, as annotated. Instead, it has the
/// session type and environment corresponding to the *inside* of the `Loop`, which are the
/// *canonical* session type and environment for `P`.
///
/// 💡 **Do this instead:** When annotating the types of channels, prefer the type synonym
/// [`Chan`], which computes the correct [`CanonicalChan`] type for a given (possibly
/// non-canonical) session type. Using [`Chan`]instead of [`CanonicalChan`], we can
/// correctly annotate a newly created channel of any session type:
///
/// ```
/// # use dialectic::prelude::*;
/// # use dialectic::backend::mpsc;
/// #
/// type P = Loop<Send<String>>;
/// let (c1, c2): (Chan<_, _, P>, Chan<_, _, <P as Session>::Dual>) =
///     P::channel(mpsc::unbounded_channel);
/// ```
pub type Chan<Tx, Rx, P, E = ()> =
    CanonicalChan<Tx, Rx, <P as Actionable<E>>::Action, <P as Actionable<E>>::Env>;

/// Offer a set of different protocols, allowing the other side of the channel to choose with which
/// one to proceed. This macro only works in a `Try` context, i.e. somewhere the `?` operator would
/// make sense to use.
///
/// # Notes
///
/// - You must specify exactly as many branches as there are options in the type of the
///   [`Offer`](crate::types::Offer) to which this expression corresponds, and they must be in the
///   same order as the choices are in the tuple [`Offer`](crate::types::Offer)ed.
/// - In the body of each branch, the identifier for the channel is rebound to have the session type
///   corresponding to that branch.
/// - To use `offer!` as an expression, ensure the type of every branch matches.
///
/// # Examples
///
/// ```
/// use dialectic::prelude::*;
/// use dialectic::backend::mpsc;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// type GiveOrTake = Choose<(Send<i64>, Recv<String>)>;
///
/// let (c1, c2) = GiveOrTake::channel(|| mpsc::channel(1));
///
/// // Spawn a thread to offer a choice
/// let t1 = tokio::spawn(async move {
///     offer!(c2 => {
///         _0 => { c2.recv().await?; },
///         _1 => { c2.send("Hello!".to_string()).await?; },
///     });
///     Ok::<_, mpsc::Error>(())
/// });
///
/// // Choose to send an integer
/// c1.choose(_0).await?.send(42).await?;
///
/// // Wait for the offering thread to finish
/// t1.await??;
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! offer {
    (
        $chan:ident => { $($t:tt)* }
    ) => (
        {
            match $crate::canonical::CanonicalChan::offer($chan).await {
                Ok(b) => $crate::offer!{@branches b, $chan, $crate::types::unary::Z, $($t)* },
                Err(e) => Err(e)?,
            }
        }
    );
    (
        @branches $branch:ident, $chan:ident, $n:ty, $(,)?
    ) => (
        $crate::Branches::empty_case($branch),
    );
    (
        @branches $branch:ident, $chan:ident, $n:ty, $label:expr => $code:expr $(,)?
    ) =>
    (
        match $crate::Branches::case($branch) {
            std::result::Result::Ok($chan) => {
                let _: $n = $label;
                $code
            },
            std::result::Result::Err($branch) => $crate::Branches::empty_case($branch),
        }
    );
    (
        @branches $branch:ident, $chan:ident, $n:ty, $label:expr => $code:expr, $($t:tt)+
    ) => (
        match $crate::Branches::case($branch) {
            std::result::Result::Ok($chan) => {
                let _: $n = $label;
                $code
            },
            std::result::Result::Err($branch) => {
                $crate::offer!{@branches $branch, $chan, $crate::types::unary::S<$n>, $($t)+ }
            },
        }
    );
}

/// A placeholder for a missing [`Transmit`] or [`Receive`] end of a connection.
///
/// When using [`split`](CanonicalChan::split), the resultant two channels can only send or only
/// receive, respectively. This is reflected at the type level by the presence of [`Unavailable`] on
/// the type of the connection which *is not* present for each part of the split, and [`Available`]
/// on the type of the connection which *is*.
#[derive(Debug)]
pub struct Unavailable<T>(PhantomData<T>);

impl<T> Unavailable<T> {
    /// Make a new `Unavailable`.
    fn new() -> Self {
        Unavailable(PhantomData)
    }
}

/// An available [`Transmit`] or [`Receive`] end of a connection.
///
/// When using [`split`](CanonicalChan::split), the resultant two channels can only send or only
/// receive, respectively. This is reflected at the type level by the presence of [`Available`] on
/// the type of the connection which *is* present for each part of the split, and [`Unavailable`] on
/// the type of the connection which *is not*.
///
/// Whenever `C` implements [`Transmit`] or [`Receive`], so does `Available<C>`.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Hash, Default)]
pub struct Available<C>(C);

impl<C> Available<C> {
    /// Retrieve the inner `C` connection.
    pub fn into_inner(self) -> C {
        self.0
    }
}

impl<C> AsRef<C> for Available<C> {
    fn as_ref(&self) -> &C {
        &self.0
    }
}

impl<C> AsMut<C> for Available<C> {
    fn as_mut(&mut self) -> &mut C {
        &mut self.0
    }
}

impl<T, Convention: CallingConvention, C> Transmit<T, Convention> for Available<C>
where
    C: Transmit<T, Convention>,
{
    type Error = C::Error;

    fn send<'a, 'async_lifetime>(
        &'async_lifetime mut self,
        message: <T as CallBy<'a, Convention>>::Type,
    ) -> Pin<Box<dyn Future<Output = Result<(), Self::Error>> + marker::Send + 'async_lifetime>>
    where
        T: CallBy<'a, Convention>,
        <T as CallBy<'a, Convention>>::Type: marker::Send,
        'a: 'async_lifetime,
    {
        self.0.send(message)
    }
}

impl<T, C> Receive<T> for Available<C>
where
    C: Receive<T>,
{
    type Error = C::Error;

    fn recv<'async_lifetime>(
        &'async_lifetime mut self,
    ) -> Pin<Box<dyn Future<Output = Result<T, Self::Error>> + marker::Send + 'async_lifetime>>
    {
        self.0.recv()
    }
}

/// The error returned when a closure which is expected to complete a channel's session fails to
/// finish the session of the channel it is given.
///
/// This error can arise either if the channel is dropped *before* its session is completed, or if
/// it is stored somewhere and is dropped *after* the closure's future is finished. The best way to
/// ensure this error does not occur is to call [`close`](CanonicalChan::close) on the channel,
/// which statically ensures it is dropped exactly when the session is complete.
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub enum SessionIncomplete<Tx, Rx> {
    /// Both the sending half `Tx` and the receiving half `Rx` did not complete the session
    /// correctly.
    BothHalves {
        /// The incomplete sending half: [`Unfinished`](IncompleteHalf::Unfinished) if dropped
        /// before the end of the session, [`Unclosed`](IncompleteHalf::Unclosed) if not dropped
        /// after the end of the session.
        tx: IncompleteHalf<Tx>,
        /// The incomplete receiving half: [`Unfinished`](IncompleteHalf::Unfinished) if dropped
        /// before the end of the session, [`Unclosed`](IncompleteHalf::Unclosed) if not dropped
        /// after the end of the session.
        rx: IncompleteHalf<Rx>,
    },
    /// Only the sending half `Tx` did not complete the session correctly, but the receiving half
    /// `Rx` did complete it correctly.
    TxHalf {
        /// The incomplete sending half: [`Unfinished`](IncompleteHalf::Unfinished) if dropped
        /// before the end of the session, [`Unclosed`](IncompleteHalf::Unclosed) if not dropped
        /// after the end of the session.
        tx: IncompleteHalf<Tx>,
        /// The receiving half, whose session was completed.
        #[derivative(Debug = "ignore")]
        rx: Rx,
    },
    /// Only the receiving half `Rx` did not complete the session correctly, but the sending half
    /// `Tx` did complete it correctly.
    RxHalf {
        /// The sending half, whose session was completed.
        #[derivative(Debug = "ignore")]
        tx: Tx,
        /// The incomplete receiving half: [`Unfinished`](IncompleteHalf::Unfinished) if dropped
        /// before the end of the session, [`Unclosed`](IncompleteHalf::Unclosed) if not dropped
        /// after the end of the session.
        rx: IncompleteHalf<Rx>,
    },
}

/// A representation of what has gone wrong when a connection half `Tx` or `Rx` is incomplete.
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub enum IncompleteHalf<T> {
    /// The underlying channel was dropped before the session was `Done`.
    Unfinished(#[derivative(Debug = "ignore")] T),
    /// The underlying channel was not dropped or [`close`](CanonicalChan::close)d after the session
    /// was `Done`.
    Unclosed,
}

impl<T> std::error::Error for IncompleteHalf<T> {}

impl<T> std::fmt::Display for IncompleteHalf<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "incomplete session or sub-session: channel half ")?;
        write!(
            f,
            "{}",
            match self {
                IncompleteHalf::Unfinished(_) => "was dropped before the session was `Done`",
                IncompleteHalf::Unclosed => "was not closed after the session was `Done`",
            }
        )
    }
}

impl<Tx, Rx> SessionIncomplete<Tx, Rx> {
    /// Extract the send and receive halves `Tx` and `Rx`, if they are present, from this
    /// `SessionIncomplete` error.
    pub fn into_halves(
        self,
    ) -> (
        Result<Tx, IncompleteHalf<Tx>>,
        Result<Rx, IncompleteHalf<Rx>>,
    ) {
        match self {
            SessionIncomplete::BothHalves { tx, rx } => (Err(tx), Err(rx)),
            SessionIncomplete::TxHalf { tx, rx } => (Err(tx), Ok(rx)),
            SessionIncomplete::RxHalf { tx, rx } => (Ok(tx), Err(rx)),
        }
    }
}

impl<Tx, Rx> std::error::Error for SessionIncomplete<Tx, Rx> {}

impl<Tx, Rx> std::fmt::Display for SessionIncomplete<Tx, Rx> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use IncompleteHalf::*;
        write!(f, "incomplete session or sub-session: channel")?;
        let reason = match self {
            SessionIncomplete::BothHalves { tx, rx } => match (tx, rx) {
                (Unclosed, Unclosed) => " was not closed after the session was `Done`",
                (Unclosed, Unfinished(_)) => {
                    "'s sending half was not closed after the session was `Done` \
                    and its receiving half was dropped before the session was `Done`"
                }
                (Unfinished(_), Unclosed) => {
                    "'s sending half was dropped before the session was `Done` \
                    and its receiving half was not closed after the session was `Done`"
                }
                (Unfinished(_), Unfinished(_)) => " was dropped before the session was `Done`",
            },
            SessionIncomplete::TxHalf { tx, .. } => match tx {
                Unfinished(_) => "'s sending half was dropped before the session was `Done`",
                Unclosed => "'s sending half was not closed after the session was `Done`",
            },
            SessionIncomplete::RxHalf { rx, .. } => match rx {
                Unfinished(_) => "'s receiving half was dropped before the session was `Done`",
                Unclosed => "'s receiving half was not closed after the session was `Done`",
            },
        };
        write!(f, "{}", reason)
    }
}