【问题标题】:Haskell, GHC 8: dynamically load/import moduleHaskell,GHC 8:动态加载/导入模块
【发布时间】:2017-12-06 17:54:03
【问题描述】:

我需要类似的东西

-- Main.hs
module Main where

main :: IO ()
main = do
  <import Plugin>
  print Plugin.computation

使用类似插件

-- Plugin.hs
module Plugin where

computation :: Int
computation = 4

但是,我需要将插件与主应用程序一起编译。它们需要一起部署。只有模块的导入(而不是编译)应该动态发生。

我一路上找到了Dynamically loading compiled Haskell module - GHC 7.6,它在 GHC 8.0.2 上工作得很好,除了它要求插件的源文件在执行应用程序时位于当前工作目录中。


编辑 (07.12.2017)

是否可以使用 GHC API 从字符串而不是文件加载模块? http://hackage.haskell.org/package/ghc-8.2.1/docs/GHC.html#t:Target 建议这是可能的,但文档有很多漏洞,我找不到真正做到这一点的方法。如果可以做到这一点,我可以使用file-embed 将插件源文件包含到编译后的二进制文件中。 示例:

module Main where

-- Dynamic loading of modules
import GHC
import GHC.Paths ( libdir )
import DynFlags
import Unsafe.Coerce

import Data.Time.Clock (getCurrentTime)
import StringBuffer

pluginModuleNameStr :: String
pluginModuleNameStr = "MyPlugin"

pluginSourceStr :: String
pluginSourceStr = unlines
  [ "module MyPlugin where"
  , "computation :: Int"
  , "computation = 4"
  ]

pluginModuleName :: ModuleName
pluginModuleName = mkModuleName pluginModuleNameStr

pluginSource :: StringBuffer
pluginSource = stringToStringBuffer pluginSourceStr

main :: IO ()
main = do
    currentTime <- getCurrentTime
    defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
      result <- runGhc (Just libdir) $ do
        dflags <- getSessionDynFlags
        setSessionDynFlags dflags
        let target = Target { targetId = TargetModule $ pluginModuleName
                            , targetAllowObjCode = True
                            , targetContents = Just ( pluginSource
                                                    , currentTime
                                                    )
                            }
        setTargets [target]
        r <- load LoadAllTargets
        case r of
          Failed    -> error "Compilation failed"
          Succeeded -> do
            setContext [IIDecl $ simpleImportDecl pluginModuleName]
            result <- compileExpr ("MyPlugin.computation")
            let result' = unsafeCoerce result :: Int
            return result'
      print result

然而,这会导致

<command-line>: panic! (the 'impossible' happened)
  (GHC version 8.0.2 for x86_64-apple-darwin):
    module ‘MyPlugin’ is a package module

编辑 (08.12.2017)

我可以通过将源代码写入临时文件然后像链接的帖子 (Dynamically loading compiled Haskell module - GHC 7.6) 中那样加载它,将“插件”直接编译到最终的二进制文件中。但是,如果插件从 Hackage 导入包,则效果不佳:

module Main where

import Control.Monad.IO.Class (liftIO)
import DynFlags
import GHC
import GHC.Paths (libdir)
import System.Directory (getTemporaryDirectory, removePathForcibly)
import Unsafe.Coerce (unsafeCoerce)

pluginModuleNameStr :: String
pluginModuleNameStr = "MyPlugin"

pluginSourceStr :: String
pluginSourceStr = unlines
  [ "module MyPlugin where"
  , "import Data.Aeson"
  , "computation :: Int"
  , "computation = 4"
  ]

writeTempFile :: IO FilePath
writeTempFile = do
  dir <- getTemporaryDirectory
  let file = dir ++ "/" ++ pluginModuleNameStr ++ ".hs"
  writeFile file pluginSourceStr
  return file

main :: IO ()
main = do
  moduleFile <- writeTempFile
  defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
    result <- runGhc (Just libdir) $ do
      dflags <- getSessionDynFlags
      setSessionDynFlags dflags
      target <- guessTarget moduleFile Nothing
      setTargets [target]
      r <- load LoadAllTargets
      liftIO $ removePathForcibly moduleFile
      case r of
        Failed -> error "Compilation failed"
        Succeeded -> do
          setContext [IIDecl $ simpleImportDecl $ mkModuleName pluginModuleNameStr]
          result <- compileExpr "MyPlugin.computation"
          let result' = unsafeCoerce result :: Int
          return result'
    print result

MyPlugin 包含语句import Data.Aeson 时,有没有办法加载包?如果我将它添加到插件字符串,它会失败

/var/folders/t2/hp9y8x6s6rs7zg21hdzvhbf40000gn/T/MyPlugin.hs:2:1: error:
    Failed to load interface for ‘Data.Aeson’
    Perhaps you meant Data.Version (from base-4.9.1.0)
    Use -v to see a list of the files searched for.
haskell-loader-exe: panic! (the 'impossible' happened)
  (GHC version 8.0.2 for x86_64-apple-darwin):
  Compilation failed
CallStack (from HasCallStack):
  error, called at app/Main.hs:40:19 in main:Main

我请求的原因是数据库支持:我们使用 Persistent 访问数据库,需要动态导入以支持多个数据库(MySQL、PostgreSQL 和 SQLite),同时仍然允许最终用户只安装三个数据库中的一个服务器(换句话说:如果他们只使用例如 PostgreSQL,则不需要用户安装所有服务器)。只有当用户实际配置主应用程序以使用该模块时,才应加载特定于数据库的模块。

如果我不import Database.Persist.MySQL,那么应用程序不需要安装 MySQL。否则,应用程序将失败,例如,

dyld: Library not loaded: 
/usr/local/opt/mysql/lib/libmysqlclient.20.dylib

在 macOS 上。

【问题讨论】:

  • 我感觉这可能是 ghc backpack 的一个用例,但不能确定,因为我自己还没有使用它。此外,它仅在 ghc-8.2 上可用
  • 谢谢,但我不确定我们现在是否可以将项目升级到 GHC 8.2。另外,我们使用 Stack,目前与背包不兼容(尽管他们正在努力)。
  • 我编辑了帖子以展示我当前的方法。
  • 如果我确保 .hs 文件存在,则错误消息是不同的,因此 GHC make 系统中的某些内容正在检查是否存在与文档相符的文件,请注意这是一项功能对于可以存在文件但应使用一些正在进行的内容的 IDE。
  • 我的下一个错误是:“缓冲区需要预处理;禁用交互式检查”

标签: haskell ghc ghc-api


【解决方案1】:

从外观上看,具有匹配模块名称的文件必须存在 - 文件的内容是什么似乎并不重要。

在 Linux 上,我什至可以将其设为 /dev/null 的符号链接,一切正常,但自身的符号链接却不行。

【讨论】:

  • 如果有人知道强制解释模块的方法,那么可能不需要磁盘上的文件。如果是这样,请添加您的知识!
  • 即使在强制解释模块时,也需要磁盘上的文件。我寻找方法来挂钩 GHC 的 API 以访问文件系统,但看起来 GHC 使用 IO monad 并且没有可以实现的 ModuleStore 类型类。
猜你喜欢
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
相关资源
最近更新 更多