Fake GADTs in Rust

—

For those unfamiliar – the Haskell programming language (infamous for its terrible module system) has a language feature called Generalised Algebraic Data Types. We can mock a similar idea in Rust by making use of generics and uninhabited types (the never type !). To understand why we would want this and how we could achieve this we must first discuss algebraic data types and why GADTs generalise them.

Algebraic Data Types #

ADTs primarily of two things, the product type _×_\_\times\_ and the coproduct (sum) type _+_\_+\_ which both take 2 types, A and B, as arguments, and spit out A×BA \times B and A+BA + B respectively.

Unsurprisingly ∣A×B∣=∣A∣⋅∣B∣|A \times B| = |A|\cdot |B| and ∣A+B∣=∣A∣+∣B∣|A + B| = |A| + |B| where ∣_∣|\_| is the function that counts the “size” of the type (number of elements). Of course since the product and sum types are once again types, they may partake in the product type constructor as many times as you can imagine, that being A×B+C×(D×E)A\times B + C\times (D\times E) is a perfectly valid thing to do.

Wait! This is just struct (product) and enum (sum) in Rust. In Rust the “number” of possible values a type can take on is exactly the product of its fields for struct and the sum of its variants for enums. This property is what algebraic refers to in ADTs.

Generalise! #

The generalise in GADTs generalises an ADTs to a family of (general) ADTs (one more general for good measure!). What is a type family though? Without loss of generality a type family is a type function P:B−>UP: B -> \mathcal{U}, which given a term b:Bb: B, produces P(b):UP(b): \mathcal{U}. The fact that all the P(b)P(b) are related through \(B\) is what makes them a family. Instead of considering a single type we are considering an entire family of related types, but what does this look like?

Look at the following pseudo-code example

type Foo<T> = {
  foo(Int): Foo<Int>,
  bar(Int, Int): Foo<Int>,
  zoo(String): Foo<String>,
  kaboom(Explosion): Foo<Explosion>
}

We define a type Foo<T> for a generic type T, then we define all the ways to construct Foo<_>. These are also the only ways to construct a Foo<_>, making the type family closed (we can’t add more constructors, or at least I’m not letting you add more constructors).

Each constructor of Foo<_> produces a Foo<_> indexed by a completely different type, this means that if we receive a e:Foo<Int>e: Foo<Int> we know it could only have been constructed by the constructors foo and bar as only they produce terms with type Foo<Int>

Similar statements are applicable for Foo<Explosion> and Foo<String> except they only have one constructor each. This kind of looks like a generalisation of an enum as we are hiding multiple subenums in one bigger enum.

The generalisation in GADTs refer to how instead of the constructors of a type returning a ‘regular’ type, they may now return an indexed type (the index may be concrete or generic).

Rusty Rust Rust, Rust Rust Rust #

Let’s think about the properties we are hoping to obtain. We want a type Foo<T> to be different from Foo<U> when T≠UT \neq U. We want to be able to write functions that are generic over T. We want to be able to ‘specialise’ based on a specific instance of T, so naturally we come up with this

enum Foo<A = !, B = !, C = !> {
  Foo(i32, A),
  Bar(i32, i32, A),
  Zoo(String, B),
  Kaboom(Explosion, C)
}

type FooInt = Foo<(), !, !>;
type FooString = Foo<!, (), !>;
type FooExplosion = Foo<!, !, ()>;
type Foo_ = Foo<(), (), ()>;

Usually the first thing we come up with is pretty crap but this works (if we ignore the terrible ergonomics of using this)!

Each Foo* variant only allows specific enum variants to be accessed, since the other variants will have a term of ! of which no terms exists, therefore the variant cannot be constructed. As the variant can’t be construced we are free to ignore it in our match statement. Rust will optimise this out (hopefully).

Ergonomics? That’s a big word, and I can’t read! #

Defining these fake GADTs is annoying, as each output of the closed type family must be annotated in the enum definition, and added to the relevant variants. We can imagine a world where we have a proc-macro that allows us to write

#[gadt]
enum Foo {
  #[family(Int)]
  Foo(i32),
  #[family(Int)]
  Bar(i32, i32),
  #[family(String)]
  Zoo(String, B),
  #[family(Explosion)]
  Kaboom(Explosion)
}

which sets this up for us and some sort of macro that will remove the irrelevant () inhabited field for us


fn foo_handler(foo_int: FooInt) {
  match foo_int {
    happy!(Foo::Foo(i)) => todo!(),
    happy!(Foo::Bar(i, j)) => todo!(),
  }
}

Although this is is a little ugly – and we haven’t generalised this to struct variants – it could work.

It’s generics all the way down #

This technique also works recursively, taking the Haskell example

data Expr a where
  LitInt  :: Int -> Expr Int
  LitBool :: Bool -> Expr Bool
  Add     :: Expr Int -> Expr Int -> Expr Int
  IsZero  :: Expr Int -> Expr Bool

eval :: Expr a -> a
eval (LitInt n) = n
eval (LitBool b) = b
eval (Add a b) = eval a + eval b
eval (IsZero(i)) = eval i == 0

we can translate it to Rust like this

enum Expr<A = !, B = !> {
  LitInt(i32, A),
  AndBool(Box<ExprBool>, Box<ExprBool>, B),
  Add(Box<ExprInt>, Box<ExprInt>, A),
  IsZero(Box<ExprInt>, B)
}

fn int(i: i32) -> ExprInt {
    ExprInt::LitInt(i, ())
}

fn and(a: ExprBool, b: ExprBool) -> ExprBool {
    ExprBool::AndBool(Box::new(a), Box::new(b), ())
}
fn add(a: ExprInt, b: ExprInt) -> ExprInt {
    ExprInt::Add(Box::new(a), Box::new(b), ())
}
fn is_zero(a: ExprInt) -> ExprBool {
    ExprBool::IsZero(Box::new(a), ())
}

type ExprInt = Expr<(), !>;
type ExprBool = Expr<!, ()>;

trait Eval: Sized {
    type Out;
    fn eval(self) -> Self::Out; 
}

impl Eval for ExprInt {
    type Out = i32;
    fn eval(self) -> Self::Out {
        match self {
            ExprInt::LitInt(i, ()) => i,
            ExprInt::Add(a, b, ()) => a.eval() + b.eval(),
        }
    }
}

impl Eval for ExprBool {
    type Out = bool;
    fn eval(self) -> Self::Out {
        match self {
            ExprBool::IsZero(i, ()) => i.eval() == 0,
            ExprBool::AndBool(a, b, ()) => a.eval() && b.eval(),
        }
    }
}

Now actually running some code

fn main() {
    let expr = and(
                    is_zero(int(0)),
                    is_zero(add(int(4), int(-4)))
                );
    assert!(expr.eval());
}

Playground link.

We are unable to have a generic output like Expr a because our generics in Expr are ‘group’ markers rather than being the actual type we are indexing. So we are forced to resort to an Eval trait to be generic over the output.

Final words #

It’s an interesting technique, and maybe if someone made a nice crate to make the definition and application easier it would gain more traction. I’ve personally used it while writing a recursive enum where I knew the “top” term of a fresh instance of this enum would always be a particular variant (it’s deserialisation related), so I didn’t want to deal with handling the other variants.