我正在尝试使用 GHC API 动态编译和加载 Haskell 模块。我知道 API 从一个版本到另一个版本波动很大,所以我专门谈论 GHC 7.6.*。
我尝试在 MacOS 和 Linux 上运行相同的代码。在这两种情况下,插件模块都可以正常编译,但在加载时会出现以下错误:Cannot add module Plugin to context: not interpreted
问题类似于this https://stackoverflow.com/questions/12790341/haskell-ghc-dynamic-compliation-only-works-on-first-compile其中,只有在主机程序的同一运行中编译该模块时,才会加载该模块。
-- Host.hs: compile with ghc-7.6.*
-- $ ghc -package ghc -package ghc-paths Host.hs
-- Needs Plugin.hs in the same directory.
module Main where
import GHC
import GHC.Paths ( libdir )
import DynFlags
import Unsafe.Coerce
main :: IO ()
main =
defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
result <- runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
target <- guessTarget "Plugin.hs" Nothing
setTargets [target]
r <- load LoadAllTargets
case r of
Failed -> error "Compilation failed"
Succeeded -> do
setContext [IIModule (mkModuleName "Plugin")]
result <- compileExpr ("Plugin.getInt")
let result' = unsafeCoerce result :: Int
return result'
print result
和插件:
-- Plugin.hs
module Plugin where
getInt :: Int
getInt = 33
问题是你正在使用IIModule
。这表明您希望将模块及其中的所有内容(包括未导出的内容)引入上下文中。它本质上是一样的:load
GHCi 中带有星号。正如您所注意到的,这仅适用于解释代码,因为它可以让您“查看”模块内部。
但这不是您在这里需要的。你想要的是加载它,就像你使用过一样:module
or an import
声明,适用于已编译的模块。为此,您使用IIDecl
您可以使用它进行进口申报simpleImportDecl
:
setContext [IIDecl $ simpleImportDecl (mkModuleName "Plugin")]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)