typelead / eta

The Eta Programming Language, a dialect of Haskell on the JVM
https://eta-lang.org
BSD 3-Clause "New" or "Revised" License
2.61k stars 141 forks source link

FFI export extension - pass state between Eta and Java #666

Open jarekratajski opened 6 years ago

jarekratajski commented 6 years ago

I have couple of scenarios where I need to pass state from Eta to Java and back. If I have in Eta some data/ type: T - I would like be able to pass instances of T to java and then be able to call eta from Java with a same T.

foreign export java "[export-string]" [eta-identifier]
  :: T -> [arg-type-2] -> .. -> T

Where T is any eta Type. (not JWT).

For instance if I build Conway's Game Of Life I would like to have in Eta. This will let me to build interactive Game of life with all logic in Eta.

data GameOfLifeState = ....

nextStep::GameOfLifeState ->GameOfLifeState 

foreign export java "life.Life.nextStepo" nextStep
  :: GameOfLifeState  -> GameOfLifeState 

From java side this object might be encapsulating Closure (and context?). It does not have to expose any properties.

At the moment my workaround is to model all types in Java and import them to eta, so that Eta works on Java Types. This is however very tedious (and probably affects poerformance).

rahulmutt commented 6 years ago

This can be done using the StablePtr's which are hard references to an Eta value, represented as an int on the Java side.

foreign export java "life.Life.nextStepo" nextStep
  :: StablePtr GameOfLifeState  -> IO (StablePtr GameOfLifeState)

The above would generate:

package life;

public class Life {
    public int nextStep(int gameStatePtr) {
        ....
   }
}

For working with StablePtr's, you can check out the API: https://hackage.haskell.org/package/base-4.10.1.0/docs/Foreign-StablePtr.html

jarekratajski commented 6 years ago

Comfirmed. It works and solves my problem.

Suggestion: Maybe would be good to put this explicitly in documentation of FFI.

Issue may be closed.

rahulmutt commented 6 years ago

I'll leave this open to track that we need to document it.