Ticket #1604 (new proposed-project)

Opened 2 years ago

Embedding Haskell in C++: The FFI upside-down

Reported by: bschuur Owned by:
Priority: not yet rated Keywords: embed haskell c++ ffi
Cc: Topic: Tools
Difficulty: 1 person Summer Mentor: not-accepted

Description

The idea is to, following in the footsteps of tickets #1555 and #1564, make accessing Haskell functions from C++ as conveniently as possible by creating a tool which easily exposes Haskell functions to C++.

Why?

The main rationale behind this, is that pure code should be called from impure code. This is a paradigm already present in Haskell in the form of the IO monad. Thus Haskell should be invoked from an external (impure) language, not the other way around.

The FFI is mostly used in the opposite direction, because it is usually employed to create wrappers for external libraries.

Implementation

A big part of exposing Haskell functionality to another language is marshalling data structures between the two languages. We could use the following system to derive a c++ representation for Haskell datatypes:

To keep things initially simple one could start with mutually recursive datatypes with type parameters (no nested datatypes or functions with constructors). For these there is a straightforward (automatic) translation from Haskell types into c++ types:

  • Datatypes become virtual classes
  • Constructors become subclasses of their datatype
  • Constructor parameters become class-variables
  • Type parameters become templates

Standard Haskell types such as integers/lists/maybe/map could be treated separately to create native c++ representations.

For functions we want exposed to c++, a wrapper function is created which calls the original Haskell function (via C). This is also where the marshalling of arguments/results takes place. Initially only first-order functions will be supported. A system to support higher-order functions (which implies functions have to become first-class in c++) may be possible but this would be future work.

Use-case

A possible use-case for this system would be a code editor. The (impure) gui can be written in c++ while the text editing functions and for example parsing for code-highlighting can be provided by pure Haskell functions.

Note: See TracTickets for help on using tickets.