Search code examples
fay

Passing records to ffi


When I pass a record to javascript, it works:

data Record = Record {
  elem :: String
}
doSomethingForeign :: Record -> Fay ()
doSomethingForeign = ffi " callJsFun(%1) "

But when the function is not monomorphical, the record is not evaluated, one needs to do it manually:

class Passable a
instance Passable Record
instance Passable Text
doSomethingForeign' :: (Passable a) => a -> Fay ()
doSomethingForeign' = ffi " callJsFun(Fay$$_(%1)) "

This is the simple case, when the extra typing of Fay$$_ isn't that annoying, but if I pass more complex structures with type parameters to js, then adding just Fay$$_ won't solve it. I'd like to know the rule, when the evaluation to native js types is applied and where not.


Solution

  • The thunks will remain and type conversions won't happen if you have a type variable or Ptr X in the FFI, in contrast to a concrete type or Automatic a where the opposite applies.

    I think what you want here is :: Passable a => Automatic a -> Fay () to force any thunks. It should be equivalent to separating this into two functions with a monomorphic argument. Using Automatic with a foreign type such as Text will only force the thunk and not do any type conversions.