LogicChains
LogicChains

Reputation: 4412

Using GHC.runGhc fails with error: "Failed to load interface for ‘GHC.Types’ no unit id matching ‘ghc-prim’ was found"

I have the following code, which tries to compile and print a simple expression at runtime by calling the GHC API:

module Main where

import GHC
import GHC.Paths as GHP
import GHC.Types
import GHC.Prim

main :: IO ()
main = do
  val <- GHC.runGhc (Just GHP.libdir) $ GHC.compileExpr "HelloWorld"
  putStrLn $ show val

When I try to run it, either via first compiling or directly in GHCI, it fails with a runtime error:

Failed to load interface for ‘GHC.Types’

no unit id matching ‘ghc-prim’ was found

What do I need to do to avoid this error?

I've tried with GHC 8.6 and 8.8, and both encounter the problem. I'm running it in a new stack project with only ghc, ghc-prim and ghc-paths installed.

Upvotes: 1

Views: 385

Answers (1)

K. A. Buhr
K. A. Buhr

Reputation: 51109

You need to call setSessionDynFlags to read the package database. If you modify your definition of main to read:

main = do
  val <- GHC.runGhc (Just GHP.libdir) $ do
    setSessionDynFlags =<< getSessionDynFlags
    GHC.compileExpr "HelloWorld"
  putStrLn $ show val

then it generates the exception:

Data constructor not in scope: HelloWorld

which, I suppose, is what you'd expect trying to compile the expression HelloWorld.

Upvotes: 1

Related Questions