Foreign Function Interface

Compiler Pragmas

There are two backend-generic pragmas used for the FFI:

  1. {-# COMPILE <Backend> <Name> <Text> #-}
  2. {-# FOREIGN <Backend> <Text> #-}

The COMPILE pragma associates some information <Text> with a name <Name> defined in the same module, and the FOREIGN pragma associates <Text> with the current top-level module. This information is interpreted by the specific backend during compilation (see below). These pragmas were added in Agda 2.5.3.

Haskell FFI

Note

This section applies to the GHC Backend.

The FOREIGN pragma

The GHC backend interprets FOREIGN pragmas as inline Haskell code and can contain arbitrary code (including import statements) that will be added to the compiled module. For instance:

  1. {-# FOREIGN GHC import Data.Maybe #-}
  2. {-# FOREIGN GHC
  3. data Foo = Foo | Bar Foo
  4. countBars :: Foo -> Integer
  5. countBars Foo = 0
  6. countBars (Bar f) = 1 + countBars f
  7. #-}

The COMPILE pragma

There are four forms of COMPILE annotations recognized by the GHC backend

  1. {-# COMPILE GHC <Name> = <HaskellCode> #-}
  2. {-# COMPILE GHC <Name> = type <HaskellType> #-}
  3. {-# COMPILE GHC <Name> = data <HaskellData> (<HsCon1> | .. | <HsConN>) #-}
  4. {-# COMPILE GHC <Name> as <HaskellName> #-}

The first three tells the compiler how to compile a given Agda definition and the last exposes an Agda definition under a particular Haskell name allowing Agda libraries to be used from Haskell.

Using Haskell Types from Agda

In order to use a Haskell function from Agda its type must be mapped to an Agda type. This mapping can be configured using the type and data forms of the COMPILE pragma.

Opaque types

Opaque Haskell types are exposed to Agda by postulating an Agda type and associating it to the Haskell type using the type form of the COMPILE pragma:

  1. {-# FOREIGN GHC import qualified System.IO #-}
  2. postulate FileHandle : Set
  3. {-# COMPILE GHC FileHandle = type System.IO.Handle #-}

This tells the compiler that the Agda type FileHandle corresponds to the Haskell type System.IO.Handle and will enable functions using file handles to be used from Agda.

Data types

Non-opaque Haskell data types can be mapped to Agda datatypes using the data form of the COMPILED pragma:

  1. data Maybe (A : Set) : Set where
  2. nothing : Maybe A
  3. just : A Maybe A
  4. {-# COMPILE GHC Maybe = data Maybe (Nothing | Just) #-}

The compiler checks that the types of the Agda constructors match the types of the corresponding Haskell constructors and that no constructors have been left out (on either side).

Record types

The data form of the COMPILE pragma also works with Agda’s record types:

  1. import Agda.Builtin.List
  2. {-# FOREIGN GHC import Data.Tree #-}
  3. record Tree (A : Set) : Set where
  4. inductive
  5. constructor node
  6. field root-label : A
  7. field sub-forest : Agda.Builtin.List.List (Tree A)
  8. {-# COMPILE GHC Tree = data Tree (Node) #-}

Built-in Types

The GHC backend compiles certain Agda built-in types to special Haskell types. The mapping between Agda built-in types and Haskell types is as follows:

Agda Built-in

Haskell Type

NAT

Integer

INTEGER

Integer

STRING

Data.Text.Text

CHAR

Char

BOOL

Bool

FLOAT

Double

Warning

Haskell code manipulating Agda natural numbers as integers must take care to avoid negative values.

Warning

Agda FLOAT values have only one logical NaN value. At runtime, there might be multiple different NaN representations present. All such NaN values must be treated equal by FFI calls.

Using Haskell functions from Agda

Once a suitable mapping between Haskell types and Agda types has been set up, Haskell functions whose types map to Agda types can be exposed to Agda code with a COMPILE pragma:

  1. open import Agda.Builtin.IO
  2. open import Agda.Builtin.String
  3. open import Agda.Builtin.Unit
  4. {-# FOREIGN GHC
  5. import qualified Data.Text.IO as Text
  6. import qualified System.IO as IO
  7. #-}
  8. postulate
  9. stdout : FileHandle
  10. hPutStrLn : FileHandle String IO
  11. {-# COMPILE GHC stdout = IO.stdout #-}
  12. {-# COMPILE GHC hPutStrLn = Text.hPutStrLn #-}

The compiler checks that the type of the given Haskell code matches the type of the Agda function. Note that the COMPILE pragma only affects the runtime behaviour–at type-checking time the functions are treated as postulates.

Warning

It is possible to give Haskell definitions to defined (non-postulate) Agda functions. In this case the Agda definition will be used at type-checking time and the Haskell definition at runtime. However, there are no checks to ensure that the Agda code and the Haskell code behave the same and discrepancies may lead to undefined behaviour.

This feature can be used to let you reason about code involving calls to Haskell functions under the assumption that you have a correct Agda model of the behaviour of the Haskell code.

Using Agda functions from Haskell

Since Agda 2.3.4 Agda functions can be exposed to Haskell code using the as form of the COMPILE pragma:

  1. module IdAgda where
  2. idAgda : {A : Set} A A
  3. idAgda x = x
  4. {-# COMPILE GHC idAgda as idAgdaFromHs #-}

This tells the compiler that the Agda function idAgda should be compiled to a Haskell function called idAgdaFromHs. Without this pragma, functions are compiled to Haskell functions with unpredictable names and, as a result, cannot be invoked from Haskell. The type of idAgdaFromHs will be the translated type of idAgda.

The compiled and exported function idAgdaFromHs can then be imported and invoked from Haskell like this:

  1. -- file UseIdAgda.hs
  2. module UseIdAgda where
  3. import MAlonzo.Code.IdAgda (idAgdaFromHs)
  4. -- idAgdaFromHs :: () -> a -> a
  5. idAgdaApplied :: a -> a
  6. idAgdaApplied = idAgdaFromHs ()

Polymorphic functions

Agda is a monomorphic language, so polymorphic functions are modeled as functions taking types as arguments. These arguments will be present in the compiled code as well, so when calling polymorphic Haskell functions they have to be discarded explicitly. For instance,

  1. postulate
  2. ioReturn : {A : Set} A IO A
  3. {-# COMPILE GHC ioReturn = \ _ x -> return x #-}

In this case compiled calls to ioReturn will still have A as an argument, so the compiled definition ignores its first argument and then calls the polymorphic Haskell return function.

Level-polymorphic types

Level-polymorphic types face a similar problem to polymorphic functions. Since Haskell does not have universe levels the Agda type will have more arguments than the corresponding Haskell type. This can be solved by defining a Haskell type synonym with the appropriate number of phantom arguments. For instance:

  1. data Either {a b} (A : Set a) (B : Set b) : Set (a b) where
  2. left : A Either A B
  3. right : B Either A B
  4. {-# FOREIGN GHC type AgdaEither a b = Either #-}
  5. {-# COMPILE GHC Either = data AgdaEither (Left | Right) #-}

Handling typeclass constraints

There is (currently) no way to map a Haskell type with type class constraints to an Agda type. This means that functions with class constraints cannot be used from Agda. However, this can be worked around by wrapping class constraints in Haskell data types, and providing Haskell functions using explicit dictionary passing.

For instance, suppose we have a simple GUI library in Haskell:

  1. module GUILib where
  2. class Widget w
  3. setVisible :: Widget w => w -> Bool -> IO ()
  4. data Window
  5. instance Widget Window
  6. newWindow :: IO Window

To use this library from Agda we first define a Haskell type for widget dictionaries and map this to an Agda type Widget:

  1. {-# FOREIGN GHC import GUILib #-}
  2. {-# FOREIGN GHC data WidgetDict w = Widget w => WidgetDict #-}
  3. postulate
  4. Widget : Set Set
  5. {-# COMPILE GHC Widget = type WidgetDict #-}

We can then expose setVisible as an Agda function taking a Widget instance argument:

  1. postulate
  2. setVisible : {w : Set} {{_ : Widget w}} w Bool IO
  3. {-# COMPILE GHC setVisible = \ _ WidgetDict -> setVisible #-}

Note that the Agda Widget argument corresponds to a WidgetDict argument on the Haskell side. When we match on the WidgetDict constructor in the Haskell code, the packed up dictionary will become available for the call to setVisible.

The window type and functions are mapped as expected and we also add an Agda instance packing up the Widget Window Haskell instance into a WidgetDict:

  1. postulate
  2. Window : Set
  3. newWindow : IO Window
  4. instance WidgetWindow : Widget Window
  5. {-# COMPILE GHC Window = type Window #-}
  6. {-# COMPILE GHC newWindow = newWindow #-}
  7. {-# COMPILE GHC WidgetWindow = WidgetDict #-}

We can then write code like this:

  1. openWindow : IO Window
  2. openWindow = newWindow >>= λ w
  3. setVisible w true >>= λ _
  4. return w

JavaScript FFI

The JavaScript backend recognizes COMPILE pragmas of the following form:

  1. {-# COMPILE JS <Name> = <JsCode> #-}

where <Name> is a postulate, constructor, or data type. The code for a data type is used to compile pattern matching and should be a function taking a value of the data type and a table of functions (corresponding to case branches) indexed by the constructor names. For instance, this is the compiled code for the List type, compiling lists to JavaScript arrays:

  1. data List {a} (A : Set a) : Set a where
  2. [] : List A
  3. __ : (x : A) (xs : List A) List A
  4. {-# COMPILE JS List = function(x,v) {
  5. if (x.length < 1) {
  6. return v["[]"]();
  7. } else {
  8. return v["_∷_"](x[0], x.slice(1));
  9. }
  10. } #-}
  11. {-# COMPILE JS [] = Array() #-}
  12. {-# COMPILE JS __ = function (x) { return function(y) { return Array(x).concat(y); }; } #-}