我正在尝试使用GHC API动态编译和加载Haskell模块。我了解API在不同版本间有相当大的波动,因此我特别针对GHC 7.6.* 进行讨论。
我尝试在MacOS和Linux上运行相同的代码。在两种情况下,Plugin模块编译顺利,但在加载时会出现以下错误:Cannot add module Plugin to context: not interpreted
问题类似于这里的内容,其中模块仅在与主程序相同的运行中编译时才会加载。
-- 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