packages feed

MicroHs-0.17.4.0: src/MicroHs/FFI.hs

module MicroHs.FFI(makeFFI) where
import qualified Prelude(); import MHSPrelude
import Data.Char
import Data.List
import MicroHs.Desugar(LDef)
import MicroHs.Error(mhsError)
import MicroHs.Exp
import MicroHs.Expr
import MicroHs.Flags
import MicroHs.Ident
import MicroHs.Names
--import Debug.Trace

-- The export table has (internal-name, external-name, external-type)
makeFFI :: Flags -> [(Ident, Ident, CType, IsJavascript)] -> [IdentModule ]-> [[LDef]] -> (String, String)
makeFFI _ forExps exclude dss =
  let ffiImports = nubBy eq [ (ie, n, cRep ie t, mn) | ds <- dss, (_, d) <- ds, Lit (LForImp mn ie n (CType t)) <- [get d] ]
                 where get (App _ a) = a   -- if there is no IO type, we have (App primPerform (LForImp ...))
                       get a = a
                       eq (_, n, _, _) (_, n', _, _) = n == n'
                       -- Only a call through a pointer needs the C types.
                       cRep ImpDynamic t = t
                       cRep _          t = repType t
      wrappers = [ t | (ImpWrapper, _, t, _) <- ffiImports]
      imps     = filter ((`notElem` exclude) . impModule) $ filter ((`notElem` runtimeFFI) . impName) ffiImports
      includes = jsincs ++ nub [ inc | (ImpStatic iincs _ _, _, _, _) <- imps, inc <- iincs ]
      jsincs   = if any isJS ffiImports then ["emscripten.h"] else []
        where isJS (ImpJS _, _, _, _) = True
              isJS _ = False
      mkSig (_, i, CType t, js) = let (as, ior) = getArrows t in mkExportSig js i as ior ++ ";"
      header = unlines
        ["#include <stdint.h>",
         "#if defined(__cplusplus)",
         "extern \"C\" {",
         "#endif",
         "void mhs_init(void);",
         intercalate "\n" $ map mkSig forExps,
         "#if defined(__cplusplus)",
         "}",
         "#endif"
        ]
  in
    if not (null wrappers) then mhsError "Unimplemented FFI feature: foreign import \"wrapper\"" else
    (unlines $
      map (\ fn -> "#include \"" ++ fn ++ "\"") includes ++
      (if any (\ (_, _, _, js) -> js) forExps then
         ["#if defined(__EMSCRIPTEN__)",
          "#include \"emscripten.h\"",
          "#else",
          "#define EMSCRIPTEN_KEEPALIVE",
          "#endif"]
       else []) ++
      map mkHdr imps ++
      ["static const struct ffi_entry imp_table[] = {"] ++
      map mkEntry imps ++
      ["{ 0,0 }",
       "};",
       "const struct ffi_entry *xffi_table = imp_table;"
      ] ++
      ["static struct ffe_entry exp_table[] = {"] ++
      map mkExport forExps ++
      ["  { 0,0 }",
       "};",
       "struct ffe_entry *xffe_table = exp_table;",
       "\n"
      ] ++ zipWith mkExportWrapper [0..] forExps
    , header)

mkExportSig :: IsJavascript -> Ident -> [EType] -> EType -> String
mkExportSig js n as ior =
  let outT = expTypeName js $ checkIO ior
      ins = zipWith (\ i a -> expTypeName js a ++ " _x" ++ show i) [1::Int ..] as
   in outT ++ " " ++ unIdent n ++ "(" ++ intercalate ", " ins ++ ")"

mkExport :: (Ident, Ident, CType, IsJavascript) -> String
mkExport (i, _, _, _) = "  { \"" ++ unIdent i ++ "\", 0 },"

mkExportWrapper :: Int -> (Ident, Ident, CType, IsJavascript) -> String
mkExportWrapper no (_, n, CType t, js) = unlines $
  let (as, ior) = getArrows t
      r = checkIO ior
      outT = expTypeName js r
      arg k a = "  mhs_from_" ++ expTypeHsName js a ++ "(ffe_alloc(), 0, _x" ++ show k ++ "); ffe_apply();"
      eval = if eqEType r ior then "ffe_eval()" else "ffe_exec()"
  in  [(if js then "EMSCRIPTEN_KEEPALIVE " else "") ++ mkExportSig js n as ior ++ " {",
       "  gc_check(" ++ show (2 * length as + 4) ++ ");",
       "  ffe_push(xffe_table[" ++ show no ++ "].ffe_value);" ]
      ++ zipWith arg [1::Int ..] as ++
      if isUnit r then
        [ "  (void)" ++ eval ++ ";",
          "  ffe_pop();",
          "}"
        ]
       else
        [ "  " ++ outT ++ " _res = mhs_to_" ++ expTypeHsName js r ++ "(" ++ eval ++ ", -1);",
          "  ffe_pop();",
          "  return _res;",
          "}"
        ]

impName :: (ImpEnt, String, EType, IdentModule) -> String
impName (_, s, _, _) = s

impModule :: (ImpEnt, String, EType, IdentModule) -> IdentModule
impModule (_, _, _, m) = m

mkEntry :: (ImpEnt, String, EType, IdentModule) -> String
mkEntry (ImpStatic _ IFunc  _, f, t, _) = "{ \"" ++ f ++ "\", " ++ show (arity t) ++ ", mhs_" ++ f ++ "},"
mkEntry (ImpStatic _ IPtr   _, f, _, _) = "{ \"&" ++ f ++ "\", 0, mhs_addr_" ++ f ++ "},"
mkEntry (ImpStatic _ IValue _, f, t, _) = "{ \"" ++ f ++ "\", " ++ show (arity t) ++ ", mhs_" ++ f ++ "},"
mkEntry (ImpJS _,              f, t, _) = "{ \"" ++ f ++ "\", " ++ show (arity t) ++ ", mhs_" ++ f ++ "},"
mkEntry (ImpDynamic,           f, t, _) = "{ \"" ++ f ++ "\", " ++ show (arity t) ++ ", mhs_" ++ f ++ "},"
mkEntry _ = undefined

mkMhsFun :: String -> String -> String
mkMhsFun fn body = "from_t mhs_" ++ fn ++ "(int s) { " ++ body ++ "; }"

checkIO :: EType -> EType
checkIO iot =
  case dropApp identIO iot of
    Nothing -> iot -- errorMessage (getSLoc iot) $ "foreign return type must be IO: " ++ showEType iot
    Just t  -> t

dropApp :: Ident -> EType -> Maybe EType
dropApp i (EApp (EVar i') t) | i == i' = Just t
dropApp _ _ = Nothing

isUnit :: EType -> Bool
isUnit (EVar unit) = unit == identUnit
isUnit _ = False

mkRet :: HasCallStack => EType -> Int -> String -> String
mkRet t n call = "mhs_from_" ++ cTypeHsName t ++ "(s, " ++ show n ++ ", " ++ call ++ ")"

mkArg :: EType -> Int -> String
mkArg t i = "mhs_to_" ++ cTypeHsName t ++ "(s, " ++ show i ++ ")"

mkJSArg :: EType -> Int -> String
mkJSArg t i = "mhs_to_" ++ jsTypeName t ++ "(s, " ++ show i ++ ")"

mkHdr :: (ImpEnt, String, EType, IdentModule) -> String
mkHdr (ImpStatic _ IPtr fn, f, iot, _) =
  let r = checkIO iot
      (s, _) =
        case dropApp identPtr r of
          Just t  -> ("", t)
          Nothing ->
            case dropApp identFunPtr r of
              Just t  -> ("(HsFunPtr)", t)
              Nothing -> errorMessage (getSLoc r) "foreign & must be Ptr/FunPtr"
      body = "return " ++ mkRet r 0 (s ++ "&" ++ fn)
  in  mkMhsFun ("addr_" ++ f) body
mkHdr (ImpStatic _ IFunc fn, f, t, _) =
  let (as, ior) = getArrows t
      r = checkIO ior
      len = length as
      call = fn ++ "(" ++ intercalate ", " (zipWith mkArg as [0..]) ++ ")"
      fcall =
        if isUnit r then
          call ++ "; return mhs_from_Unit(s, " ++ show len ++ ")"
        else
          "return " ++ mkRet r len call
  in  mkMhsFun f fcall
mkHdr (ImpStatic _ IValue val, f, t, _) =
  let (as, ior) = getArrows t
      r = checkIO ior
      len = length as
      call = expandArgs t len (\ i -> mkArg (as !! i) i) val
      fcall =
        if isUnit r then
          call ++ "; return mhs_from_Unit(s, " ++ show len ++ ")"
        else
          "return " ++ mkRet r len call
  in  mkMhsFun f fcall
mkHdr (ImpJS s, f, ty, _) =
  let (as, ior) = getArrows ty
      rt = checkIO ior
      jsr = jsTypeNameR rt
      n = length as
      args = concat $ zipWith arg as [0..]
      arg t i = ", " ++ mkJSArg t i
      call = "EM_ASM" ++
             (if isUnit rt then "" else '_':jsr) ++
             "({ " ++ expandArgs ty n (\ i -> '$' : show i) s ++ " }" ++ args ++ ")"  -- EM_ASM counts from $0
      fcall =
        if isUnit rt then
          call ++ "; return mhs_from_Unit(s, " ++ show n ++ ")"
        else
          "return " ++ mkRet rt n call
  in  mkMhsFun f fcall
-- Call the function pointer in the first argument with the other arguments.
-- The pointer is cast to the exact C type of the function.
mkHdr (ImpDynamic, f, t, _) =
  let (ats, ior) = getArrows t
      (fpt, as) =
        case ats of
          fp : as' | Just ft <- dropApp identFunPtr fp
                   , let (fas, fr) = getArrows ft
                   , length fas == length as' && and (zipWith eqEType fas as') && eqEType fr ior
                   -> (fp, as')
          _ -> errorMessage (getSLoc t) $ "foreign import dynamic must have type FunPtr ft -> ft: " ++ showEType t
      r = checkIO ior
      len = length ats
      cfun = cCallTypeName r ++ " (*)(" ++ (if null as then "void" else intercalate ", " (map cCallTypeName as)) ++ ")"
      call = "((" ++ cfun ++ ")" ++ mkArg fpt 0 ++ ")(" ++ intercalate ", " (zipWith mkArg (map repType as) [1..]) ++ ")"
      fcall =
        if isUnit r then
          call ++ "; return mhs_from_Unit(s, " ++ show len ++ ")"
        else
          "return " ++ mkRet (repType r) len call
  in  mkMhsFun f fcall
mkHdr _ = undefined

-- Replace $1, $2, ... (up to $9) in the code of a "value" or javascript import
-- by the arguments, numbered from 1 as in GHC.  The function gets the argument
-- number counted from 0.  Any other $k is an error.
expandArgs :: EType -> Int -> (Int -> String) -> String -> String
expandArgs t len arg = expand
  where
    expand [] = []
    expand ('$':c:cs) | isDigit c =
      let k = digitToInt c
      in  if k < 1 || k > len then
            errorMessage (getSLoc t) $ "foreign import: $" ++ show k ++ " is not an argument: " ++ argsAre ++
              (if k == 0 then " (they start at $1, not $0)" else "")
          else
            arg (k - 1) ++ expand cs
    expand (c:cs) = c : expand cs
    argsAre | len == 0  = "the import has no arguments"
            | len == 1  = "the argument is $1"
            | otherwise = "the arguments are $1 .. $" ++ show len

-- Replace the newtypes for C types by the types that represent them.
repType :: EType -> EType
repType (EApp f a) = EApp (repType f) (repType a)
repType t@(EVar i) | Just (_, r) <- lookup (unIdent i) cNewtypes = EVar (mkIdentSLoc (getSLoc i) r)
                   | otherwise = t
repType t = t

-- The C type of an argument or the result of a call through a pointer.
cCallTypeName :: EType -> String
cCallTypeName (EApp (EVar ptr) _) | ptr == identFunPtr = "HsFunPtr"
cCallTypeName (EVar i) | Just (c, _) <- lookup (unIdent i) cNewtypes = c
cCallTypeName t = cTypeName t

arity :: EType -> Int
arity = length . fst . getArrows

-- Use to construct 'foreign import/export ccall' wrapper.
cTypeHsName :: HasCallStack => EType -> String
cTypeHsName (EApp (EVar ptr) _t) | ptr == identPtr = "Ptr"
                                 | ptr == identFunPtr = "FunPtr"
cTypeHsName (EVar i) | Just c <- lookup (unIdent i) cHsTypes = c
cTypeHsName t = errorMessage (getSLoc t) $ "Not a valid C type: " ++ showEType t

cHsTypes :: [(String, String)]
cHsTypes =
  [ ("Primitives.Float",  "Float")
  , ("Primitives.Double", "Double")
  , ("Primitives.Int",    "Int")
  , ("Primitives.Int64",  "Int64")
  , ("Primitives.Word",   "Word")
  , ("Primitives.Word64", "Word64")
  , ("()",                "Unit")
  , ("System.IO.Handle",  "Ptr")
  ]

-- Foreign export type names; a javascript export also allows Bool.
expTypeName :: IsJavascript -> EType -> String
expTypeName True (EVar i) | unIdent i == "Data.Bool_Type.Bool" = "int"
expTypeName _ t = cTypeName t

expTypeHsName :: IsJavascript -> EType -> String
expTypeHsName True (EVar i) | unIdent i == "Data.Bool_Type.Bool" = "Bool"
expTypeHsName _ t = cTypeHsName t

-- Use to construct 'foreign export ccall' signature.
cTypeName :: EType -> String
cTypeName (EApp (EVar ptr) _t) | ptr == identPtr = "void*"
cTypeName (EVar i) | Just c <- lookup (unIdent i) cTypes = c
cTypeName t = errorMessage (getSLoc t) $ "Not a valid C type: " ++ showEType t

cTypes :: [(String, String)]
cTypes =
  [ ("Primitives.Float",  "float")
  , ("Primitives.Double", "double")
  , ("Primitives.Int",    "intptr_t")   -- value_t
  , ("Primitives.Int64",  "int64_t")
  , ("Primitives.Word",   "uintptr_t")  -- uvalue_t
  , ("Primitives.Word64", "uint64_t")
  , ("()",                "void")
  , ("System.IO.Handle",  "void*")
  ]

-- Use to construct 'foreign import javascript' return value wrapper.
jsTypeNameR :: EType -> String
jsTypeNameR (EApp (EVar ptr) _) | ptr == identPtr = "PTR"
jsTypeNameR (EVar i) | Just c <- lookup (unIdent i) jsTypesR = c
jsTypeNameR t = errorMessage (getSLoc t) $ "Not a valid Javascript return type: " ++ showEType t

jsTypesR :: [(String, String)]
jsTypesR =
  [ ("Primitives.Int",    "INT")
  , ("Primitives.Double", "DOUBLE")
  , ("Primitives.Float",  "DOUBLE")
  ]

-- Use to construct 'foreign import javascript' argument wrapper.
jsTypeName :: EType -> String
jsTypeName (EApp (EVar ptr) _) | ptr == identPtr = "Ptr"
jsTypeName (EVar i) | Just c <- lookup (unIdent i) jsTypes = c
jsTypeName t = errorMessage (getSLoc t) $ "Not a valid Javascript argument type: " ++ showEType t

jsTypes :: [(String, String)]
jsTypes =
  [ ("Primitives.Int",    "Int")
  , ("Primitives.Double", "Double")
  , ("Primitives.Float",  "Float")
  ]

-- These are already in the runtime
runtimeFFI :: [String]
runtimeFFI = [
  "GETRAW", "GETTIMEMICRO", "GETBOOTTIMEMICRO", "acos", "add_FILE", "add_fd", "open", "add_utf8", "add_buf", "add_crlf",
  "asin", "atan", "atan2", "calloc", "closeb",
  "cos", "exp", "flushb", "fopen", "free", "getb", "getenv", "isattyb", "filesizeb", "islinux", "ismacos", "ismingw", "iswindows", "log", "malloc",
  "md5Array", "md5BFILE", "md5String", "memcpy", "memmove", "realloc", "strlen", "strcpy",
  "putb", "putchar", "sin", "sqrt", "system", "tan", "tmpname", "ungetb", "remove",
  "acosf", "asinf", "atanf", "atan2f", "cosf", "expf", "logf", "sinf", "sqrtf", "tanf",
  "scalbn", "scalbnf", "pow", "powf",
  "js_debug", "js_eval_run", "js_eval_call", "js_set_haskellCallback",
  "readb", "writeb",
  "peekPtr", "pokePtr", "pokeWord", "peekWord",
  "add_lz77_compressor", "add_lz77_decompressor", "lz77c",
  "add_lzma_compressor", "add_lzma_decompressor",
  "add_rle_compressor", "add_rle_decompressor",
  "add_base64_encoder", "add_base64_decoder",
  "add_bwt_compressor", "add_bwt_decompressor",
  "peek_uint8", "poke_uint8", "peek_uint16", "poke_uint16", "peek_uint32", "poke_uint32", "peek_uint64", "poke_uint64",
  "peek_int8", "poke_int8", "peek_int16", "poke_int16", "peek_int32", "poke_int32", "peek_int64", "poke_int64",
  "peek_char", "poke_char", "peek_schar", "poke_schar", "peek_uchar", "poke_uchar",
  "peek_ushort", "poke_ushort", "peek_short", "poke_short",
  "peek_uint", "poke_uint", "peek_int", "poke_int",
  "peek_ulong", "poke_ulong", "peek_long", "poke_long",
  "peek_ullong", "poke_ullong", "peek_llong", "poke_llong",
  "peek_size_t", "poke_size_t",
  "peek_flt32", "poke_flt32",
  "peek_flt64", "poke_flt64",
  "sizeof_char", "sizeof_short", "sizeof_int", "sizeof_long", "sizeof_llong", "sizeof_size_t",
  "opendir", "closedir", "readdir", "c_d_name", "chdir", "mkdir", "getcwd",
  "getcpu",
  "get_mem", "openb_rd_mem", "openb_wr_mem",
  "new_mpz", "mpz_abs", "mpz_add", "mpz_and", "mpz_cmp", "mpz_get_d", "mpz_get_f",
  "mpz_get_si", "mpz_init_set_si", "mpz_init_set_ui",
  "mpz_ior",
  "mpz_mul", "mpz_mul_2exp", "mpz_neg", "mpz_popcount", "mpz_sub", "mpz_fdiv_q_2exp",
  "mpz_tdiv_qr", "mpz_tstbit", "mpz_xor",
  "mpz_get_si64", "mpz_init_set_si64", "mpz_init_set_ui64",
  "mpz_log2",
  "want_gmp",
  "want_imath",
  "gettimeofday",
  "E2BIG", "EACCES", "EADDRINUSE", "EADDRNOTAVAIL", "EADV", "EAFNOSUPPORT", "EAGAIN",
  "EALREADY", "EBADF", "EBADMSG", "EBADRPC", "EBUSY", "ECHILD", "ECOMM", "ECONNABORTED",
  "ECONNREFUSED", "ECONNRESET", "EDEADLK", "EDESTADDRREQ", "EDIRTY", "EDOM", "EDQUOT",
  "EEXIST", "EFAULT", "EFBIG", "EFTYPE", "EHOSTDOWN", "EHOSTUNREACH", "EIDRM", "EILSEQ",
  "EINPROGRESS", "EINTR", "EINVAL", "EIO", "EISCONN", "EISDIR", "ELOOP", "EMFILE", "EMLINK",
  "EMSGSIZE", "EMULTIHOP", "ENAMETOOLONG", "ENETDOWN", "ENETRESET", "ENETUNREACH",
  "ENFILE", "ENOBUFS", "ENODATA", "ENODEV", "ENOENT", "ENOEXEC", "ENOLCK", "ENOLINK",
  "ENOMEM", "ENOMSG", "ENONET", "ENOPROTOOPT", "ENOSPC", "ENOSR", "ENOSTR", "ENOSYS",
  "ENOTBLK", "ENOTCONN", "ENOTDIR", "ENOTEMPTY", "ENOTSOCK", "ENOTSUP", "ENOTTY", "ENXIO",
  "EOPNOTSUPP", "EPERM", "EPFNOSUPPORT", "EPIPE", "EPROCLIM", "EPROCUNAVAIL",
  "EPROGMISMATCH", "EPROGUNAVAIL", "EPROTO", "EPROTONOSUPPORT", "EPROTOTYPE",
  "ERANGE", "EREMCHG", "EREMOTE", "EROFS", "ERPCMISMATCH", "ERREMOTE", "ESHUTDOWN",
  "ESOCKTNOSUPPORT", "ESPIPE", "ESRCH", "ESRMNT", "ESTALE", "ETIME", "ETIMEDOUT",
  "ETOOMANYREFS", "ETXTBSY", "EUSERS", "EWOULDBLOCK", "EXDEV",
  "errno",
  "strerror_r",
  "environ",
  "get_executable_path",
  "setenv", "unsetenv",
  "set_permissions", "get_permissions", "get_file_size",
  "F_SETFL", "O_NONBLOCK", "SOL_SOCKET", "SO_DEBUG", "SO_ERROR", "SO_REUSEADDR", "SO_TYPE",
  "accept", "bind", "close", "connect", "fcntl", "getsockopt", "listen", "recv", "send", "setsockopt", "socket"
  ]

{-
-- lib/ modules that use foreign import
libImports :: [String]
libImports = [
  "Data.Integer_Type",
  "Data.Integer.Internal",
  "System.Process",
  "System.Environment",
  "System.Compress.ByteString",
  "System.Compress",
  "System.IO.TimeMilli",
  "System.IO.Open",
  "System.IO.Transducers",
  "System.IO.MD5",
  "System.IO.Base",
  "System.IO.StringHandle",
  "System.IO.Internal",
  "System.IO.Serialize",
  "System.CPUTime",
  "System.Directory",
  "System.Cmd",
  "Data.ByteString",
  "Data.Double",
  "Data.Float",
  "Foreign.Marshal.Utils",
  "Foreign.Marshal.Alloc",
  "Foreign.Storable",
  "Foreign.C.Error",
  "Primitives"
  ]
-}