Skip to content

Compiling modules in memory fails when file does not exist

Summary

Using the GHC API to compile a module in memory fails if the module for that file does not exist on the filesystem. When the (empty) file exists, the compilation from memory succeeds and top level values can be extracted.

Steps to reproduce

Compile and run the following:

module Lib
    ( someFunc
    ) where

import Data.Dynamic
import DynFlags
import GHC
import GHC.Paths (libdir)
import StringBuffer

import Data.Time.Clock

someFunc :: IO ()
someFunc = do
    now <- getCurrentTime

    res <- defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
        runGhcT (Just libdir) $ do
            dfs <- getSessionDynFlags
            setSessionDynFlags dfs {
              ghcLink = LinkInMemory
            , hscTarget = HscInterpreted
            }

            let target = Target (TargetModule modName) False $ Just (content, now)
            addTarget target

            res <- load LoadAllTargets
            case res of
                Failed -> return (Nothing :: Maybe Int)
                Succeeded -> do
                    setContext [IIDecl $ simpleImportDecl modName]

                    result <- dynCompileExpr "MyModule.myValue"

                    return $ fromDynamic result

    print res

    where
          content = stringToStringBuffer "module MyModule where\n\
\\n\
\myValue :: Int\n\
\myValue = 63\n\
\ "

          modName = mkModuleName "MyModule"

Outputs:

$ stack build && stack exec test-exe
test-exe: panic! (the 'impossible' happened)
  (GHC version 8.6.5 for x86_64-apple-darwin):
        module ‘MyModule’ cannot be found locally


Please report this as a GHC bug:  http://www.haskell.org/ghc/reportabug
$ touch MyModule.hs
$ stack build && stack exec test-exe
Just 63

Expected behavior

Should print Just 63 even when MyModule.hs does not exist.

Environment

  • GHC version used: GHC 8.6.5 and 8.4.4

Optional:

  • Operating System: OS X
  • System Architecture:
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information