Background
I would like to implement a program in Haskell that can generate Haskell module (hs-File) dynamically and then compile, and import it into the same application that generated the code.
Therefore, I tried to understand some example code snippets in SO and documentation. But it doesn't work nor compiles.
After some modifications of one of the given examples, I created the following souce code, Main.hs:
import qualified GhcApiWrap as Ghw
main :: IO ()
main = Ghw.msLoadModuleAndExecute "../dyn/" "DynExample.hs" "nFromChar" 'A'
GhcApiWrap.hs:
module GhcApiWrap
(
msLoadModuleAndExecute
) where
import GHC
--import GHC.Paths (libdir)
msLoadModuleAndExecute :: String -> String -> String -> Char -> IO ()
msLoadModuleAndExecute _ _ _ _ = do
value' <- runGhc (Just "./src/") $ do
dflags <- getSessionDynFlags
setSessionDynFlags $ dflags {
ghcLink = LinkInMemory,
ghcMode = CompManager,
objectDir = Just "../dyn/",
hiDir = Just "../dyn/"
}
target <- guessTarget ("DynExample.hs") Nothing
setTargets [target]
ret <- load LoadAllTargets
case ret of
Succeeded -> do
importDecl_RdrName <- parseImportDecl $ "import DynExample"
setContext [IIDecl importDecl_RdrName]
value <- dynCompileExpr ("DynExample.nFromChar")
return value
_ ->
return undefined
print $ value'
DynExample.hs:
module DynExample
(
nFromChar
) where
nFromChar :: Char -> Int
nFromChar _ = 33
...which compiles but doesn't work.
Its ouput is:
ExprmntGhcApi-exe: Missing file: src/settings
As you can see, I commented out import GHC.Paths (libdir)
because it doesn't exist anymore. Therefore, as a humble guess I used (Just "./src/")
instead of (Just libdir)
.
I tried several versions that are "flying around", but none of them work with GHC 9.2.7.
Question
Is it, and how is it possible to use DynExample.nFromChar
dynamically this way using an up-to-date Haskell Stack environment, and having the following type of the function?
msLoadModuleAndExecute :: String -> String -> String -> Char -> ... Int
Environment
At the moment, I am using Stack with:
resolver:
url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/20/20.yaml
...which translates to usage of GHC 9.2.7.