[Git][ghc/ghc][master] Add support for streaming `ghc -M` to stdout
by Marge Bot (@marge-bot) 17 Nov '26
by Marge Bot (@marge-bot) 17 Nov '26
17 Nov '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
cbe0a6bf by fendor at 2026-11-17T09:25:55-05:00
Add support for streaming `ghc -M` to stdout
Adds the flags `-dep-json-stdout` and `-dep-makefile-stdout` which
streams dependency information line-by-line to stdout.
Each dependency generation can be redirected to separate outputs.
Providing any extra `-dep-{json,makefile}[-stdout]` disables the default
generation of the `Makefile` file.
Allows consumers to start processing the dependency information as it
comes in and not waiting for the dependency generation to finish.
`DepStream` abstracts over the possible output handles, which is either
a file or the stdout handle.
Writing to a file requires temporary file paths, thus `DepStream` must
provide a way to perform clean up when dependency processing finished or
when an error is thrown for any reason.
We further decouple the rendering and writing of the result from the
dependency generation, localising side effects and making the code
slightly more readable.
The testsuite now also handles `ghc -M` writing to stdout.
We add a test for each combination of writing to stdout and file,
except for writing both makefile and json.
While it probably works, is really undefined behaviour.
Closes #27937
- - - - -
15 changed files:
- + changelog.d/make-depends-streaming-output
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Session.hs
- docs/users_guide/separate_compilation.rst
- testsuite/driver/my_typing.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/tests/driver/mkdepend/all.T
- testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-json → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-makefile → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
Changes:
=====================================
changelog.d/make-depends-streaming-output
=====================================
@@ -0,0 +1,16 @@
+section: compiler
+synopsis: Allow streaming `ghc -M` output to stdout
+issues: #27937
+mrs: !16830
+description: {
+ Add options `-dep-makefile-stdout` and `-dep-json-stdout` which stream the dependency generation
+ output to stdout.
+
+ The Makefile and json dependency generation can stream to separate targets, e.g. `-dep-makefile target.Makefile -dep-json-stdout`
+ streams the JSON Lines output to stdout and the Makefile to `target.Makefile`.
+
+ If `-dep-makefile-stdout`, `-dep-json` or `-dep-json-stdout` is given, we no longer generate a Makefile by default, but only
+ if the user explicitly requests the Makefile dependency generation.
+
+ The output from a particular backend can be disabled via `-no-dep-json` and `-no-dep-makefile` respectively.
+}
=====================================
compiler/GHC/Driver/DynFlags.hs
=====================================
@@ -73,6 +73,9 @@ module GHC.Driver.DynFlags (
IncludeSpecs(..), addGlobalInclude, addQuoteInclude, flattenIncludes,
addImplicitQuoteInclude,
+ -- * `ghc -M` specification
+ MkDependOutput(..),
+
-- * SDoc
initSDocContext, initDefaultSDocContext,
initPromotionTickContext,
@@ -335,8 +338,8 @@ data DynFlags = DynFlags {
-- ^ External plugins loaded from shared libraries
-- For ghc -M
- depMakefile :: Maybe FilePath,
- depJson :: Maybe FilePath,
+ depMakefile :: MkDependOutput,
+ depJson :: MkDependOutput,
depIncludePkgDeps :: Bool,
depIncludeCppDeps :: Bool,
depExcludeMods :: [ModuleName],
@@ -670,8 +673,8 @@ defaultDynFlags mySettings =
llvmOptLevel = 0,
-- ghc -M values
- depMakefile = Just "Makefile",
- depJson = Nothing,
+ depMakefile = MkDepend_Default "Makefile",
+ depJson = MkDepend_None,
depIncludePkgDeps = False,
depIncludeCppDeps = False,
depExcludeMods = [],
@@ -766,6 +769,15 @@ flattenExtensionFlags ml = foldr g defaultExtensionFlags
g (Off f) flags = EnumSet.delete f flags
defaultExtensionFlags = EnumSet.fromList (languageExtensions ml)
+-- -----------------------------------------------------------------------------
+-- -M -dep-*
+
+data MkDependOutput
+ = MkDepend_None
+ | MkDepend_Default !FilePath
+ | MkDepend_Explicit !FilePath
+ | MkDepend_StdOut
+
-- -----------------------------------------------------------------------------
-- -jN
=====================================
compiler/GHC/Driver/MakeFile.hs
=====================================
@@ -132,7 +132,7 @@ doMkDepend = do
module_graph <- GHC.depanal excl_mods True {- Allow dup roots -}
doMkDependModuleGraph dflags module_graph
-doMkDependModuleGraph :: GhcMonad m => DynFlags -> ModuleGraph -> m ()
+doMkDependModuleGraph :: GhcMonad m => DynFlags -> ModuleGraph -> m ()
doMkDependModuleGraph dflags module_graph = do
hsc_env <- getSession
logger <- getLogger
@@ -143,12 +143,14 @@ doMkDependModuleGraph dflags module_graph = do
root <- liftIO Directory.getCurrentDirectory
let
+ suffixes = fmap unsafeEncodeUtf (depSuffixes dflags)
+ tmpdir = tmpDir dflags
backends = concat
- [ [ initFileDepWriter logger root tmpfs dflags makefile_output
- | Just makefile_output <- [depMakefile dflags]
+ [ [ initFileDepWriter logger root tmpfs tmpdir suffixes makefile_output
+ | Just makefile_output <- [initDepOutput (depMakefile dflags)]
]
- , [ initJsonDepWriter logger tmpfs dflags json_output
- | Just json_output <- [depJson dflags]
+ , [ initJsonDepWriter logger tmpfs tmpdir json_output
+ | Just json_output <- [initDepOutput (depJson dflags)]
]
]
@@ -160,28 +162,20 @@ doMkDependModuleGraph dflags module_graph = do
liftIO $ do
-- Setup the writers
- writers <- sequenceA backends
-
- -- Do the actual work
- do
+ withWriters backends $ \ write_dep -> do
+ -- Do the actual work
-- Process them one by one, dumping results and complaining about cycles
forM_
sorted
(\ mod_graph_node ->
processDeps hsc_env (UniqSet.mkUniqSet excl_mods) mod_graph_node >>= \ case
Nothing -> pure ()
- Just dep_node ->
- traverse_ (\ s -> dw_writeDependency s dep_node) writers
+ Just dep_node -> write_dep dep_node
)
-- If -ddump-mod-cycles, show cycles in the module graph
liftIO $ dumpModCycles logger module_graph
- -- Tidy up
- do
- traverse_ dw_endWriter writers
-
-
-- Unconditional exiting is a bad idea. If an error occurs we'll get an
--exception; if that is not caught it's fine, but at least we have a
--chance to find out exactly what went wrong. Uncomment the following
@@ -261,11 +255,102 @@ data DependencyWriter = DependencyWriter
{ dw_writeDependency :: DepNode -> IO ()
-- ^ Serialise a 'DepNode' and write it out.
, dw_endWriter :: IO ()
- -- ^ End the serialiation of dependency information and perform
- -- final steps, such as cleaning up temporary files and copying intermediate
- -- files to their final location.
+ -- ^ We finished consuming the dependency information, perform final
+ -- tidy up operations. This may be a no-op, but could also
+ -- copy temporary files, close open handlers, etc...
+ --
+ -- If 'dw_endWriter' was called, calling 'dw_onError' is unnecessary,
+ -- but it must be safe to call 'dw_onError' any way.
+ , dw_onError :: IO ()
+ -- ^ Something crashed! Clean up any resources opened by this 'DependencyWriter'.
}
+-- | Initialise multiple backends and combine them into one output function.
+--
+-- Combines the 'DepSink' of each 'DependencyWriter' into one single consumer.
+withWriters :: [IO DependencyWriter] -> ((DepNode -> IO ()) -> IO a) -> IO a
+withWriters [] k = k (\ _ -> pure ())
+withWriters (dw : dws) k =
+ withWriter
+ dw
+ $ \s -> withWriters dws (\s' -> k (s `mappendWriter` s'))
+ where
+ mappendWriter w1 w2 = \ node -> w1 node >> w2 node
+
+-- | Initialise a single 'DependencyWriter', making sure any allocated resource
+-- get's tidied up again.
+--
+-- Accepts 'IO' 'DependencyWriter' since the initialisation may perform setup operations,
+-- such as opening file handles, or intermediate data types.
+withWriter :: IO DependencyWriter -> ((DepNode -> IO ()) -> IO r) -> IO r
+withWriter dwIO k =
+ bracketOnError dwIO dw_onError $ \ dw -> do
+ r <- k (dw_writeDependency dw)
+ -- Clean up open resources
+ dw_endWriter dw
+ pure r
+
+-- | Where should the dependency output end up?
+data DepOutput
+ = DepStreamHandle Handle
+ -- ^ The dependency information should be written to this 'Handle'.
+ | DepFileOutput FilePath
+ -- ^ The dependency information should be written to this 'FilePath'.
+
+-- | A 'DepStream' is an abstraction over how to output single elements
+-- of the dependency generation, e.g., a json object or one makefile rule.
+data DepStream = DepStream
+ { depStream_write :: String -> IO ()
+ , depStream_close :: IO ()
+ , depStream_onError :: IO ()
+ }
+
+initDepOutput :: MkDependOutput -> Maybe DepOutput
+initDepOutput = \ case
+ MkDepend_None -> Nothing
+ MkDepend_Default fp -> Just $ DepFileOutput fp
+ MkDepend_Explicit fp -> Just $ DepFileOutput fp
+ MkDepend_StdOut -> Just $ DepStreamHandle stdout
+
+initMakefileDepStream :: Logger -> TmpFs -> TempDir -> DepOutput -> IO DepStream
+initMakefileDepStream _ _ _ (DepStreamHandle h) =
+ pure $ depStreamHandle h
+initMakefileDepStream logger tmpfs tmpdir (DepFileOutput fp) = do
+ files <- beginMkDependHS logger tmpfs tmpdir fp
+ pure $
+ DepStream
+ { depStream_write = hPutStrLn (mkd_tmp_hdl files)
+ , depStream_onError = do
+ hClose $ mkd_tmp_hdl files
+ case mkd_make_hdl files of
+ Nothing -> return ()
+ Just hdl -> hClose hdl
+ , depStream_close = endMkDependHS logger files
+ }
+
+initJsonDepStream :: Logger -> TmpFs -> TempDir -> DepOutput -> IO DepStream
+initJsonDepStream _ _ _ (DepStreamHandle h) =
+ pure $ depStreamHandle h
+initJsonDepStream logger tmpfs tmpdir (DepFileOutput fp) = do
+ files <- initJsonDepFiles logger tmpfs tmpdir fp
+ pure $
+ DepStream
+ { depStream_write = hPutStrLn (json_tmp_hdl files)
+ , depStream_onError = hClose (json_tmp_hdl files)
+ , depStream_close = endJsonDepFiles logger files
+ }
+
+depStreamHandle :: Handle -> DepStream
+depStreamHandle h =
+ DepStream
+ { depStream_write =
+ \output -> do
+ hPutStrLn h output
+ hFlush h -- We flush to ensure the output is streamed per line.
+ , depStream_close = pure ()
+ , depStream_onError = pure ()
+ }
+
-----------------------------------------------------------------
--
-- processDeps
@@ -415,17 +500,16 @@ findDependency hsc_env (L srcloc imp) = do
--
-----------------------------------------------------------------
-initFileDepWriter :: Logger -> OsPath -> TmpFs -> DynFlags -> FilePath -> IO DependencyWriter
-initFileDepWriter logger root tmpfs dflags makefile = do
- files <- beginMkDependHS logger tmpfs dflags makefile
+initFileDepWriter :: Logger -> OsPath -> TmpFs -> TempDir -> [OsPath] -> DepOutput -> IO DependencyWriter
+initFileDepWriter logger root tmpfs tmpdir suffixes output = do
+ stream <- initMakefileDepStream logger tmpfs tmpdir output
pure DependencyWriter
{ dw_writeDependency = \ case
ModuleDepNode node deps -> do
- writeDependencies root (mkd_tmp_hdl files) suffixes node deps
- , dw_endWriter = endMkDependHS logger files
+ traverse_ (depStream_write stream) (dependencyRules root suffixes node deps)
+ , dw_endWriter = depStream_close stream
+ , dw_onError = depStream_onError stream
}
- where
- suffixes = map unsafeEncodeUtf (depSuffixes dflags)
data MkDepFiles
= MkDep { mkd_make_file :: FilePath, -- Name of the makefile
@@ -433,11 +517,11 @@ data MkDepFiles
mkd_tmp_file :: FilePath, -- Name of the temporary file
mkd_tmp_hdl :: Handle } -- Handle of the open temporary file
-beginMkDependHS :: Logger -> TmpFs -> DynFlags -> FilePath -> IO MkDepFiles
-beginMkDependHS logger tmpfs dflags makefile = do
+beginMkDependHS :: Logger -> TmpFs -> TempDir -> FilePath -> IO MkDepFiles
+beginMkDependHS logger tmpfs tmpdir makefile = do
-- open a new temp file in which to stuff the dependency info
-- as we go along.
- tmp_file <- newTempName logger tmpfs (tmpDir dflags) TFL_CurrentModule "dep"
+ tmp_file <- newTempName logger tmpfs tmpdir TFL_CurrentModule "dep"
tmp_hdl <- openFile tmp_file WriteMode
-- open the makefile
@@ -478,16 +562,15 @@ beginMkDependHS logger tmpfs dflags makefile = do
return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl,
mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl})
-writeDependencies ::
+dependencyRules ::
OsPath ->
- Handle ->
[OsString] ->
-- ^ Suffixes
HomeModuleNode ->
[Dep] ->
- IO ()
-writeDependencies root hdl suffixes node deps =
- traverse_ write tasks
+ [String]
+dependencyRules root suffixes node deps =
+ map rule tasks
where
tasks = source_dep : boot_dep ++ concatMap import_dep deps
@@ -514,7 +597,7 @@ writeDependencies root hdl suffixes node deps =
DepCpp {dep_path} -> [(obj_files, dep_path)]
- write (from, to) = writeDependency root hdl from to
+ rule (from, to) = dependencyRule root from to
obj_files = suffixed hmn_obj
@@ -523,18 +606,18 @@ writeDependencies root hdl suffixes node deps =
HomeModuleNode {hmn_src, hmn_obj, hmn_hi, hmn_mod, hmn_includePkgDeps} = node
-----------------------------
-writeDependency :: OsPath -> Handle -> [OsPath] -> OsPath -> IO ()
--- (writeDependency r h [t1,t2] dep) writes to handle h the dependency
+dependencyRule :: OsPath -> [OsPath] -> OsPath -> String
+-- (dependencyRule r [t1,t2] dep) renders the dependency
-- t1 t2 : dep
-writeDependency root hdl targets dep
- = do let -- We need to avoid making deps on
- -- c:/foo/...
- -- on Windows as make gets confused by the :
- -- Making relative deps avoids some instances of this.
- dep' = OsPath.makeRelative root dep
- forOutput = escapeSpaces . reslash Forwards . unsafeDecodeUtf . OsPath.normalise
- output = unwords (map forOutput targets) ++ " : " ++ forOutput dep'
- hPutStrLn hdl output
+dependencyRule root targets dep
+ = let -- We need to avoid making deps on
+ -- c:/foo/...
+ -- on Windows as make gets confused by the :
+ -- Making relative deps avoids some instances of this.
+ dep' = OsPath.makeRelative root dep
+ forOutput = escapeSpaces . reslash Forwards . unsafeDecodeUtf . OsPath.normalise
+ in
+ unwords (map forOutput targets) ++ " : " ++ forOutput dep'
-----------------------------
insertSuffixes
@@ -589,82 +672,86 @@ endMkDependHS logger
--
-----------------------------------------------------------------
-initJsonDepWriter :: Logger -> TmpFs -> DynFlags -> FilePath -> IO DependencyWriter
-initJsonDepWriter logger tmpfs dflags output = do
- json_var <- mkJsonOutput logger tmpfs dflags output initDepJson
- pure DependencyWriter
- { dw_writeDependency = \ case
- ModuleDepNode node deps ->
- writeHomeUnitDeps json_var node deps
- , dw_endWriter = do
- writeJsonOutput logger json_var
- }
+initJsonDepWriter :: Logger -> TmpFs -> TempDir -> DepOutput -> IO DependencyWriter
+initJsonDepWriter logger tmpfs tmpdir output = do
+ stream <- initJsonDepStream logger tmpfs tmpdir output
+ json_var <- mkJsonOutput
+ pure
+ DependencyWriter
+ { dw_writeDependency = \ case
+ ModuleDepNode node deps -> do
+ extUnits <- readJson json_var
+ let
+ (extUnitsDeps, payload) = homeUnitDeps node deps
+ newExtUnits = Set.difference extUnitsDeps (externalDeps extUnits)
+ -- Write new external unit deps before the module that uses them
+ for_ newExtUnits $ \extUnit -> do
+ depStream_write stream (renderJsonl extUnit)
+ depStream_write stream (renderJsonl payload)
+ -- Cache external deps we already reported in the past
+ updateJson json_var $ cacheExternalDepsJson newExtUnits
+ , dw_endWriter = depStream_close stream
+ , dw_onError = depStream_onError stream
+ }
--------------------------------------------------------------------------------
-- Output interface for json dumps
--- | Resources for a json dump option, used in "GHC.Driver.MakeFile".
--- The flag @-dep-json@ add an additional output target for dependency
--- diagnostics.
---
--- Contains temporary file locations to stream output to.
-data JsonOutput =
- JsonOutput {
- -- | @-dep-json@ specific state for json lines dependency information generation.
- json_ref :: IORef DepJson,
-
- -- | The output file path specified as argument to the flag.
- json_path :: FilePath,
- -- | Name of the temporary file
- json_tmp_file :: FilePath,
- -- | Handle of the open temporary file
- json_tmp_hdl :: Handle
+-- | State to keep track of during `-dep-json` generation.
+newtype JsonState
+ = JsonState
+ { json_ref :: IORef DepJson
+ -- ^ This ref is updated in @processDeps@ incrementally, using a
+ -- flag-specific type.
}
--- | Set up json generation for `ghc -M`.
---
--- Creates a temporary file that we write the dependency information to.
--- The temporary file is written to the final output file path in 'writeJsonOutput'.
-mkJsonOutput ::
- Logger ->
- TmpFs ->
- DynFlags ->
- FilePath ->
- IO (IORef DepJson) ->
- IO JsonOutput
-mkJsonOutput logger tmpfs dflags json_path mk_ref = do
- json_ref <- mk_ref
- -- open a new temp file in which to stuff the dependency info
+data JsonDepFiles = JsonDepFiles
+ { json_path :: FilePath
+ -- ^ The output file path specified as argument to the flag.
+ , json_tmp_file :: FilePath
+ -- ^ Name of the temporary file
+ , json_tmp_hdl :: Handle
+ -- ^ Handle of the open temporary file
+ }
+
+initJsonDepFiles :: Logger -> TmpFs -> TempDir -> FilePath -> IO JsonDepFiles
+initJsonDepFiles logger tmpfs tmpdir path = do
+ -- open a new temp file in which to stuff the dependency info into
-- as we go along.
- json_tmp_file <- newTempName logger tmpfs (tmpDir dflags) TFL_CurrentModule "dep"
+ json_tmp_file <- newTempName logger tmpfs tmpdir TFL_CurrentModule "dep-json"
json_tmp_hdl <- openFile json_tmp_file WriteMode
-
- pure JsonOutput {json_ref, json_path, json_tmp_file, json_tmp_hdl}
-
-updateJson :: JsonOutput -> (DepJson -> DepJson) -> IO ()
-updateJson JsonOutput {json_ref} f = modifyIORef' json_ref f
-
-readJson :: JsonOutput -> IO DepJson
-readJson JsonOutput {json_ref} = readIORef json_ref
+ pure $ JsonDepFiles
+ { json_path = path
+ , json_tmp_file = json_tmp_file
+ , json_tmp_hdl = json_tmp_hdl
+ }
-- | Finalise the json generation by copying the temporary file to the final destination.
-- Avoids partial writes in the case of an error.
-writeJsonOutput ::
- Logger ->
- JsonOutput ->
- IO ()
-writeJsonOutput logger JsonOutput {json_path, json_tmp_file, json_tmp_hdl} = do
+endJsonDepFiles :: Logger -> JsonDepFiles -> IO ()
+endJsonDepFiles logger JsonDepFiles {json_path, json_tmp_file, json_tmp_hdl} = do
hClose json_tmp_hdl
-- Copy the new jsonl in place
showPass logger "Installing new json output"
SysTools.copyFile json_tmp_file json_path
+-- | Set up json generation for `ghc -M`.
+mkJsonOutput :: IO JsonState
+mkJsonOutput =
+ JsonState <$> newIORef (DepJson Set.empty)
+
+updateJson :: JsonState -> (DepJson -> DepJson) -> IO ()
+updateJson JsonState {json_ref} f = modifyIORef' json_ref f
+
+readJson :: JsonState -> IO DepJson
+readJson JsonState {json_ref} = readIORef json_ref
+
--------------------------------------------------------------------------------
-- Output helpers
-writeJsonl :: ToJson a => JsonOutput -> a -> IO ()
-writeJsonl JsonOutput {json_tmp_hdl} output = do
- hPutStrLn json_tmp_hdl (showSDocUnsafe $ renderJSON $ json output)
+renderJsonl :: ToJson a => a -> String
+renderJsonl output =
+ showSDocUnsafe $ renderJSON $ json output
--------------------------------------------------------------------------------
-- Payload for -dep-json
@@ -846,9 +933,6 @@ instance ToJson ExtUnitDep where
where
showPackageId (DPackageId (PackageId pid)) = unpackFS pid
-initDepJson :: IO (IORef DepJson)
-initDepJson = newIORef $ DepJson Set.empty
-
cacheExternalDepsJson :: Set.Set ExtUnitDep -> DepJson -> DepJson
cacheExternalDepsJson extUnits (DepJson e0) =
DepJson
@@ -856,19 +940,10 @@ cacheExternalDepsJson extUnits (DepJson e0) =
Set.union e0 extUnits
}
-writeHomeUnitDeps :: JsonOutput -> HomeModuleNode -> [Dep] -> IO ()
-writeHomeUnitDeps deps_json HomeModuleNode {..} deps = do
- extUnits <- readJson deps_json
- let newExtUnits = Set.difference extUnitsDeps (externalDeps extUnits)
- -- Write new external unit deps before the module that uses them
- for_ newExtUnits $ \ extUnit -> do
- writeJsonl deps_json extUnit
- writeJsonl deps_json payload
- -- Cache external deps we already reported in the past
- updateJson deps_json $ cacheExternalDepsJson newExtUnits
+homeUnitDeps :: Foldable t => HomeModuleNode -> t Dep -> (Set.Set ExtUnitDep, HomeUnitDep)
+homeUnitDeps HomeModuleNode {..} deps =
+ foldl' go (Set.empty, initial_node_data) deps
where
- (extUnitsDeps, payload) = foldl' go (Set.empty, initial_node_data) deps
-
initial_node_data =
HomeUnitDep
{ unitId = hmn_unitId
=====================================
compiler/GHC/Driver/Session.hs
=====================================
@@ -774,16 +774,44 @@ addOptCmmP f = alterToolSettings $ \s -> s
}
setDepMakefile :: FilePath -> DynFlags -> DynFlags
-setDepMakefile f d = d { depMakefile = Just f }
+setDepMakefile f d = d { depMakefile = MkDepend_Explicit f
+ -- depJson has no default value, we add this for symmetry with `setDepJson`
+ -- and if anything changes in the future, then the code is already here :)
+ , depJson = unsetMkDependOutputIfDefault (depJson d)
+ }
+
+setDepMakefileStdout :: DynFlags -> DynFlags
+setDepMakefileStdout d = d { depMakefile = MkDepend_StdOut
+ -- depJson has no default value, we add this for symmetry with `setDepJson`
+ -- and if anything changes in the future, then the code is already here :)
+ , depJson = unsetMkDependOutputIfDefault (depJson d)
+ }
unsetDepMakefile :: DynFlags -> DynFlags
-unsetDepMakefile d = d { depMakefile = Nothing }
+unsetDepMakefile d = d { depMakefile = MkDepend_None }
setDepJson :: FilePath -> DynFlags -> DynFlags
-setDepJson f d = d { depJson = Just f }
+setDepJson f d = d { depJson = MkDepend_Explicit f
+ -- We generate a Makefile by default, but if a user requests json
+ -- output, then they most likely don't need a Makefile.
+ -- Thus, we only generate it if the user requests it.
+ , depMakefile = unsetMkDependOutputIfDefault (depMakefile d)
+ }
+
+setDepJsonStdout :: DynFlags -> DynFlags
+setDepJsonStdout d = d { depJson = MkDepend_StdOut
+ -- We generate a Makefile by default, but if a user requests json
+ -- output, then they most likely don't need a Makefile.
+ -- Thus, we only generate it if the user requests it.
+ , depMakefile = unsetMkDependOutputIfDefault (depMakefile d)
+ }
unsetDepJson :: DynFlags -> DynFlags
-unsetDepJson d = d { depJson = Nothing }
+unsetDepJson d = d { depJson = MkDepend_None }
+
+unsetMkDependOutputIfDefault :: MkDependOutput -> MkDependOutput
+unsetMkDependOutputIfDefault (MkDepend_Default _) = MkDepend_None
+unsetMkDependOutputIfDefault mkDepend_output = mkDepend_output
setDepIncludeCppDeps :: Bool -> DynFlags -> DynFlags
setDepIncludeCppDeps b d = d { depIncludeCppDeps = b }
@@ -1248,8 +1276,10 @@ dynamic_flags_deps = [
-------- ghc -M -----------------------------------------------------
, make_ord_flag defGhcFlag "dep-suffix" (hasArg addDepSuffix)
+ , make_ord_flag defGhcFlag "dep-makefile-stdout" (noArg setDepMakefileStdout)
, make_ord_flag defGhcFlag "dep-makefile" (hasArg setDepMakefile)
, make_ord_flag defGhcFlag "no-dep-makefile" (noArg unsetDepMakefile)
+ , make_ord_flag defGhcFlag "dep-json-stdout" (noArg setDepJsonStdout)
, make_ord_flag defGhcFlag "dep-json" (hasArg setDepJson)
, make_ord_flag defGhcFlag "no-dep-json" (noArg unsetDepJson)
, make_ord_flag defGhcFlag "include-cpp-deps"
=====================================
docs/users_guide/separate_compilation.rst
=====================================
@@ -1511,6 +1511,23 @@ generation are:
Introduced in GHC 10.1, ``-no-dep-makefile`` disables the generation of a Makefile altogether.
+.. ghc-flag:: -dep-makefile-stdout
+ :shortdesc: Write dependency generation to stdout using makefile format
+ :type: dynamic
+ :reverse: -no-dep-makefile
+ :category: redirect-output
+
+ :since: 10.1
+
+ Stream the dependency generation of :ghc-flag:`-dep-makefile ⟨file⟩` to stdout instead of ⟨file⟩.
+
+ Contrary to :ghc-flag:`-dep-makefile ⟨file⟩`, the markers
+
+ * "``# DO NOT DELETE: Beginning of Haskell dependencies``" and
+ * "``# DO NOT DELETE: End of Haskell dependencies``"
+
+ are not emitted.
+
.. ghc-flag:: -dep-json ⟨file⟩
:shortdesc: Write dependencies to ⟨file⟩ as a JSON Lines format
:type: dynamic
@@ -1540,8 +1557,19 @@ generation are:
``-no-dep-json`` disables the generation of the JSON file.
- By default, :ghc-flag:`-dep-makefile ⟨file⟩` is enabled even if :ghc-flag:`-dep-json ⟨file⟩` is given.
- Disable the generation of any Makefile via ``-no-dep-makefile``.
+ :ghc-flag:`-dep-json ⟨file⟩` and :ghc-flag:`-dep-json-stdout` disable the default generation of a Makefile.
+ To generate a Makefile for the dependency information, explicitly use :ghc-flag:`-dep-makefile ⟨file⟩` or
+ :ghc-flag:`-dep-makefile-stdout`.
+
+.. ghc-flag:: -dep-json-stdout
+ :shortdesc: Write dependency generation to stdout using JSON Lines format
+ :type: dynamic
+ :reverse: -no-dep-json
+ :category: redirect-output
+
+ :since: 10.1
+
+ Stream the dependency generation of :ghc-flag:`-dep-json ⟨file⟩` to stdout instead of ⟨file⟩.
.. ghc-flag:: -dep-suffix ⟨suffix⟩
:shortdesc: Make dependencies that declare that files with suffix
=====================================
testsuite/driver/my_typing.py
=====================================
@@ -10,7 +10,7 @@ The testsuite driver can be typechecked using mypy [1].
from typing import *
import typing
-
+import enum
####################################################
# Backwards compatibility shims
@@ -34,3 +34,7 @@ GitHash = NewType("GitHash", str) # a Git commit hash
GitRef = NewType("GitRef", str)
TestEnv = NewType("TestEnv", str)
MetricName = NewType("MetricName", str)
+
+# Used by `ghc -M` test mode
+DepMode = enum.Enum('DepMode', [('NONE', 0), ('FILE', 1), ('STDOUT', 2)])
+
=====================================
testsuite/driver/testglobals.py
=====================================
@@ -412,8 +412,8 @@ class TestOptions:
self.ignore_extension = False
# make_depend tests: which outputs to write and check
- self.dep_makefile = False
- self.dep_json = False
+ self.dep_makefile: DepMode = DepMode.NONE
+ self.dep_json: DepMode = DepMode.NONE
self.ignore_dep_outputs = False
# Backpack test
=====================================
testsuite/driver/testlib.py
=====================================
@@ -439,14 +439,26 @@ def dep_makefile( name, opts ):
For make_depend tests: write the -dep-makefile output and
compare it against <name>.dep-makefile.
"""
- opts.dep_makefile = True
+ opts.dep_makefile = DepMode.FILE
def dep_json( name, opts ):
"""
For make_depend tests: write the -dep-json output and
compare it against <name>.dep-json.
"""
- opts.dep_json = True
+ opts.dep_json = DepMode.FILE
+
+def dep_makefile_stdout( name, opts ):
+ """
+ For make_depend tests: add -dep-makefile-stdout flag.
+ """
+ opts.dep_makefile = DepMode.STDOUT
+
+def dep_json_stdout( name, opts ):
+ """
+ For make_depend tests: add -dep-json-stdout flag.
+ """
+ opts.dep_json = DepMode.STDOUT
def ignore_dep_outputs( name, opts ):
"""
@@ -2118,6 +2130,10 @@ async def do_make_depend(name: TestName,
against <name>.dep-makefile. Otherwise, -no-dep-makefile is passed.
* 'dep_json': write the -dep-json output and compare it
against <name>.dep-json.
+ * 'dep_json_stdout': write the -dep-json-stdout and compare it with
+ <name>.stderr
+ * 'dep_makefile_stdout': write the -dep-makefile-stdout and compare it with
+ <name>.stderr
"""
opts = getTestOpts()
@@ -2126,14 +2142,29 @@ async def do_make_depend(name: TestName,
outputs = []
output_flags = []
- if opts.dep_makefile:
+ if opts.dep_makefile == DepMode.FILE:
outputs.append(('dep-makefile', normalise_dep_makefile))
output_flags.append('-dep-makefile %s' % actual_file('dep-makefile'))
- else:
- output_flags.append('-no-dep-makefile')
- if opts.dep_json:
+ elif opts.dep_makefile == DepMode.STDOUT:
+ outputs.append(('stdout', normalise_dep_makefile))
+ output_flags.append('-dep-makefile-stdout')
+
+ if opts.dep_json == DepMode.FILE:
outputs.append(('dep-json', normalise_dep_json))
output_flags.append('-dep-json %s' % actual_file('dep-json'))
+ elif opts.dep_json == DepMode.STDOUT:
+ outputs.append(('stdout', normalise_dep_json))
+ output_flags.append('-dep-json-stdout')
+
+ # Somewhat non-sensical here, but `do_compile` outputs stdout and stderr into the same.
+ # Then, it only applies the `normalise_errmsg_fun` to the output, and compares it against
+ # <name>.stderr as the golden file.
+ #
+ # This is not really what we want in this situation, but it seems this requires more refactoring
+ # of the `do_compile` function than what fendor is ready to commit to.
+ # Thus, as a workaround, we simply add the normalisers for the stderr...
+ stdout_normalisers = [ n for (k, n) in outputs if k == 'stdout' ]
+ opts.extra_errmsg_normaliser = join_normalisers(opts.extra_errmsg_normaliser, normalise_slashes_, *stdout_normalisers)
result = await do_compile( name, way, False, None, [], units,
' '.join(output_flags + [extra_hc_opts]),
@@ -2143,9 +2174,9 @@ async def do_make_depend(name: TestName,
for (kind, normaliser) in outputs:
output_match = await compare_outputs(way, kind,
- join_normalisers(opts.extra_normaliser,
- normalise_slashes_, normaliser),
- find_expected_file(name, kind, way), actual_file(kind))
+ join_normalisers(opts.extra_normaliser, normalise_slashes_, normaliser),
+ find_expected_file(name, kind, way),
+ actual_file(kind))
if not output_match:
return failBecause(kind + ' mismatch', diff=output_match.diff)
=====================================
testsuite/tests/driver/mkdepend/all.T
=====================================
@@ -15,9 +15,20 @@ test('T24384b', [ *T24384_extras, when(opsys('mingw32'), skip), *json_normaliser
test('T24384c', [ *T24384_extras, when(opsys('mingw32'), skip), *json_normalisers ], makefile_test, [])
# Multiple home units with explicit level imports.
-test('mkdepend_mhu01',
+test('mkdepend_mhu01a',
[ extra_files(['mhu01/']), dep_makefile, dep_json ],
make_depend_multiunit, [['mhu01/unitA', 'mhu01/unitB', 'mhu01/unitC'], ''])
+# test the output streaming and writing to files
+test('mkdepend_mhu01b',
+ [ extra_files(['mhu01/']), dep_json_stdout ],
+ make_depend_multiunit, [['mhu01/unitA', 'mhu01/unitB', 'mhu01/unitC'], ''])
+test('mkdepend_mhu01c',
+ [ extra_files(['mhu01/']), dep_makefile_stdout ],
+ make_depend_multiunit, [['mhu01/unitA', 'mhu01/unitB', 'mhu01/unitC'], ''])
+test('mkdepend_mhu01d',
+ [ extra_files(['mhu01/']), dep_json_stdout, dep_makefile ],
+ make_depend_multiunit, [['mhu01/unitA', 'mhu01/unitB', 'mhu01/unitC'], ''])
+
# Preprocessor must not be inherited by default active home unit
test('mkdepend_mhu02',
[ extra_files(['mhu02/']), dep_json
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-json → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
=====================================
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu01.dep-makefile → testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
=====================================
@@ -1,23 +1,23 @@
# DO NOT DELETE: Beginning of Haskell dependencies
+mhu01/a/A/Base.o-boot : mhu01/a/A/Base.hs-boot
mhu01/a/A/Base.o : mhu01/a/A/Base.hi-boot
+mhu01/a/Util.o : mhu01/a/Util.hs
+mhu01/a/Util.o : mhu01/a/A/Base.hi-boot
mhu01/a/A/Base.o : mhu01/a/A/Base.hs
mhu01/a/A/Base.o : mhu01/a/Util.hi
-mhu01/a/A/Base.o-boot : mhu01/a/A/Base.hs-boot
-mhu01/a/A/TH.o : mhu01/a/A/Base.hi
mhu01/a/A/TH.o : mhu01/a/A/TH.hs
-mhu01/a/Util.o : mhu01/a/A/Base.hi-boot
-mhu01/a/Util.o : mhu01/a/Util.hs
-mhu01/b/B/Normal.o : mhu01/a/A/Base.hi
-mhu01/b/B/Normal.o : mhu01/b/B/Normal.hs
-mhu01/b/B/Normal.o : mhu01/b/B/Splice.hi
-mhu01/b/B/Splice.o : mhu01/a/A/Base.hi
-mhu01/b/B/Splice.o : mhu01/a/A/TH.hi
+mhu01/a/A/TH.o : mhu01/a/A/Base.hi
+mhu01/b/Util.o : mhu01/b/Util.hs
mhu01/b/B/Splice.o : mhu01/b/B/Splice.hs
mhu01/b/B/Splice.o : mhu01/b/Util.hi
-mhu01/b/Util.o : mhu01/b/Util.hs
-mhu01/c/C.o : mhu01/a/Util.hi
-mhu01/c/C.o : mhu01/b/B/Normal.hi
+mhu01/b/B/Splice.o : mhu01/a/A/Base.hi
+mhu01/b/B/Splice.o : mhu01/a/A/TH.hi
+mhu01/b/B/Normal.o : mhu01/b/B/Normal.hs
+mhu01/b/B/Normal.o : mhu01/b/B/Splice.hi
+mhu01/b/B/Normal.o : mhu01/a/A/Base.hi
+mhu01/c/C.o : mhu01/c/C.hs
mhu01/c/C.o : mhu01/b/B/Splice.hi
+mhu01/c/C.o : mhu01/b/B/Normal.hi
mhu01/c/C.o : mhu01/b/Util.hi
-mhu01/c/C.o : mhu01/c/C.hs
+mhu01/c/C.o : mhu01/a/Util.hi
# DO NOT DELETE: End of Haskell dependencies
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
=====================================
@@ -0,0 +1,8 @@
+{"module":"A.Base","unit-id":"a","boot":true,"imports":{},"package-name":"a","source":"mhu01/a/A/Base.hs-boot"}
+{"module":"Util","unit-id":"a","imports":{"a":[{"module":"A.Base","boot":true}]},"package-name":"a","source":"mhu01/a/Util.hs"}
+{"module":"A.Base","unit-id":"a","imports":{"a":["Util"]},"package-name":"a","source":"mhu01/a/A/Base.hs"}
+{"module":"A.TH","unit-id":"a","imports":{"a":["A.Base"]},"package-name":"a","source":"mhu01/a/A/TH.hs"}
+{"module":"Util","unit-id":"b","imports":{},"package-name":"b","source":"mhu01/b/Util.hs"}
+{"module":"B.Splice","unit-id":"b","imports":{"a":[{"module":"A.Base","level":"quote"},{"module":"A.TH","level":"splice"}],"b":["Util"]},"package-name":"b","source":"mhu01/b/B/Splice.hs"}
+{"module":"B.Normal","unit-id":"b","imports":{"a":["A.Base"],"b":["B.Splice"]},"package-name":"b","source":"mhu01/b/B/Normal.hs"}
+{"module":"C","unit-id":"c","imports":{"a":[{"module":"Util","level":"splice"}],"b":["B.Normal",{"module":"B.Splice","level":"splice"},{"module":"Util","level":"quote"}]},"package-name":"c","source":"mhu01/c/C.hs"}
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
=====================================
@@ -0,0 +1,21 @@
+mhu01/a/A/Base.o-boot : mhu01/a/A/Base.hs-boot
+mhu01/a/A/Base.o : mhu01/a/A/Base.hi-boot
+mhu01/a/Util.o : mhu01/a/Util.hs
+mhu01/a/Util.o : mhu01/a/A/Base.hi-boot
+mhu01/a/A/Base.o : mhu01/a/A/Base.hs
+mhu01/a/A/Base.o : mhu01/a/Util.hi
+mhu01/a/A/TH.o : mhu01/a/A/TH.hs
+mhu01/a/A/TH.o : mhu01/a/A/Base.hi
+mhu01/b/Util.o : mhu01/b/Util.hs
+mhu01/b/B/Splice.o : mhu01/b/B/Splice.hs
+mhu01/b/B/Splice.o : mhu01/b/Util.hi
+mhu01/b/B/Splice.o : mhu01/a/A/Base.hi
+mhu01/b/B/Splice.o : mhu01/a/A/TH.hi
+mhu01/b/B/Normal.o : mhu01/b/B/Normal.hs
+mhu01/b/B/Normal.o : mhu01/b/B/Splice.hi
+mhu01/b/B/Normal.o : mhu01/a/A/Base.hi
+mhu01/c/C.o : mhu01/c/C.hs
+mhu01/c/C.o : mhu01/b/B/Splice.hi
+mhu01/c/C.o : mhu01/b/B/Normal.hi
+mhu01/c/C.o : mhu01/b/Util.hi
+mhu01/c/C.o : mhu01/a/Util.hi
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
=====================================
@@ -0,0 +1,23 @@
+# DO NOT DELETE: Beginning of Haskell dependencies
+mhu01/a/A/Base.o-boot : mhu01/a/A/Base.hs-boot
+mhu01/a/A/Base.o : mhu01/a/A/Base.hi-boot
+mhu01/a/Util.o : mhu01/a/Util.hs
+mhu01/a/Util.o : mhu01/a/A/Base.hi-boot
+mhu01/a/A/Base.o : mhu01/a/A/Base.hs
+mhu01/a/A/Base.o : mhu01/a/Util.hi
+mhu01/a/A/TH.o : mhu01/a/A/TH.hs
+mhu01/a/A/TH.o : mhu01/a/A/Base.hi
+mhu01/b/Util.o : mhu01/b/Util.hs
+mhu01/b/B/Splice.o : mhu01/b/B/Splice.hs
+mhu01/b/B/Splice.o : mhu01/b/Util.hi
+mhu01/b/B/Splice.o : mhu01/a/A/Base.hi
+mhu01/b/B/Splice.o : mhu01/a/A/TH.hi
+mhu01/b/B/Normal.o : mhu01/b/B/Normal.hs
+mhu01/b/B/Normal.o : mhu01/b/B/Splice.hi
+mhu01/b/B/Normal.o : mhu01/a/A/Base.hi
+mhu01/c/C.o : mhu01/c/C.hs
+mhu01/c/C.o : mhu01/b/B/Splice.hi
+mhu01/c/C.o : mhu01/b/B/Normal.hi
+mhu01/c/C.o : mhu01/b/Util.hi
+mhu01/c/C.o : mhu01/a/Util.hi
+# DO NOT DELETE: End of Haskell dependencies
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
=====================================
@@ -0,0 +1,8 @@
+{"module":"A.Base","unit-id":"a","boot":true,"imports":{},"package-name":"a","source":"mhu01/a/A/Base.hs-boot"}
+{"module":"Util","unit-id":"a","imports":{"a":[{"module":"A.Base","boot":true}]},"package-name":"a","source":"mhu01/a/Util.hs"}
+{"module":"A.Base","unit-id":"a","imports":{"a":["Util"]},"package-name":"a","source":"mhu01/a/A/Base.hs"}
+{"module":"A.TH","unit-id":"a","imports":{"a":["A.Base"]},"package-name":"a","source":"mhu01/a/A/TH.hs"}
+{"module":"Util","unit-id":"b","imports":{},"package-name":"b","source":"mhu01/b/Util.hs"}
+{"module":"B.Splice","unit-id":"b","imports":{"a":[{"module":"A.Base","level":"quote"},{"module":"A.TH","level":"splice"}],"b":["Util"]},"package-name":"b","source":"mhu01/b/B/Splice.hs"}
+{"module":"B.Normal","unit-id":"b","imports":{"a":["A.Base"],"b":["B.Splice"]},"package-name":"b","source":"mhu01/b/B/Normal.hs"}
+{"module":"C","unit-id":"c","imports":{"a":[{"module":"Util","level":"splice"}],"b":["B.Normal",{"module":"B.Splice","level":"splice"},{"module":"Util","level":"quote"}]},"package-name":"c","source":"mhu01/c/C.hs"}
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/cbe0a6bf04f78e0c7b15b3b6b995deb…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/cbe0a6bf04f78e0c7b15b3b6b995deb…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/romes/async-rpc] 6 commits: runWithPipes: fix on Windows when without -threaded
by Andrea Vezzosi (@trac-Saizan) 17 Nov '26
by Andrea Vezzosi (@trac-Saizan) 17 Nov '26
17 Nov '26
Andrea Vezzosi pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC
Commits:
2bd5c810 by Andrea Vezzosi at 2026-11-17T13:27:47+01:00
runWithPipes: fix on Windows when without -threaded
Test 'static-plugin-interp-panic' happens to build without -threaded
and would timeout on Windows CI.
Turns out that in such a configuration the 'Handle's we get from
'System.Process.CommunicationHandle' cause the whole process to lock.
Rebuilding them with 'hANDLEToHandle' fixes it.
- - - - -
6de946f5 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
interp: close pipes more promptly
- - - - -
0b9d2cf5 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
interp: time limit closePipe in stopInterp
- - - - -
43341d18 by Andrea Vezzosi at 2026-11-17T13:28:22+01:00
runWithPipes: avoid race to close their end on windows
`closeCommunicationHandle` will query info about the raw handle, using windows
primitives that block while a ReadFile is pending. We call it right after
createProcess for `iserv`, but `iserv` might still start reading from the pipe
first. If that happens then there's a deadlock, because we won't write anything
for iserv to read until we are done closing its read end in our process.
The fix is to use `closeHandle` directly, as that won't block for pending reads.
- - - - -
5fbd333c by Andrea Vezzosi at 2026-11-17T13:30:00+01:00
interp: cleanup with stopInterp outside interpLoader lock
On a PipeClosedException we want to stop the running external interpreter and
reset the state of the `Interp`, which includes the loader state.
So, to avoid deadlocks, we now have the PipeClosedException handler outside of places
where we take the loader state lock.
A new `SafeInterp` type is introduced to aid with this discipline: functions
that take a bare `Interp` must not take the loader state lock themselves.
We also fix a race between restarting the interpreter and the
PipeClosedException cleanup: if an interpreter's Pipe is open we don't terminate
it, as it must be a new instance.
- - - - -
abdfbbf3 by Andrea Vezzosi at 2026-11-17T14:34:55+01:00
interp: test concurrent use of one external interpreter
Threads share a GHC session: concurrent requests, killing waiting threads,
cancelling a running splice, and restarting after the interpreter dies.
- - - - -
18 changed files:
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Env/Types.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Runtime/Interpreter/Init.hs
- compiler/GHC/Runtime/Interpreter/Types.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Runtime/Utils.hs
- compiler/GHC/Tc/Gen/Splice.hs
- ghc/GHCi/UI/Monad.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Message/Async.hs
- testsuite/tests/ghci/interp-cancellation/all.T
- + testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs
- + testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout
Changes:
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -56,7 +56,7 @@ import GHC.Driver.Config.Diagnostic (initDiagOpts, initPrintConfig)
import GHC.Driver.Env.Types ( Hsc(..), HscEnv(..), HasHscEnv (..) )
import GHC.Runtime.Context
-import GHC.Runtime.Interpreter.Types (Interp)
+import GHC.Runtime.Interpreter.Types (SafeInterp)
import GHC.Unit
import GHC.Unit.External.Database
@@ -410,7 +410,7 @@ mainModIs hue = mkHomeModule (expectJust $ homeUnitEnv_home_unit hue) (mainModul
-- | Retrieve the target code interpreter
--
-- Fails if no target code interpreter is available
-hscInterp :: HscEnv -> Interp
+hscInterp :: HscEnv -> SafeInterp
hscInterp hsc_env = case hsc_interp hsc_env of
Nothing -> throw (InstallationError "Couldn't find a target code interpreter. Try with -fexternal-interpreter")
Just i -> i
=====================================
compiler/GHC/Driver/Env/Types.hs
=====================================
@@ -14,7 +14,7 @@ import GHC.Driver.LlvmConfigCache (LlvmConfigCache)
import GHC.Prelude
import GHC.Runtime.Context
-import GHC.Runtime.Interpreter.Types ( Interp )
+import GHC.Runtime.Interpreter.Types ( SafeInterp )
import GHC.Types.Error ( Messages )
import GHC.Types.Name.Cache
import GHC.Types.Target
@@ -88,7 +88,7 @@ data HscEnv
-- the 'IfGblEnv'. See 'tcg_knot_vars' in 'GHC.Tc.Utils.TcGblEnv'.
-- See also Note [hsc_type_env_var hack]
- , hsc_interp :: Maybe Interp
+ , hsc_interp :: Maybe SafeInterp
-- ^ target code interpreter (if any) to use for TH and GHCi.
-- See Note [Target code interpreter]
=====================================
compiler/GHC/Driver/Main/Passes.hs
=====================================
@@ -1604,10 +1604,9 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do
let (stg_binds, _stg_deps) = unzip stg_binds_with_deps
let interp = hscInterp hsc_env
-
- case interp of
+ case interpInstance interp of
-- always generate JS code for the JS interpreter (no bytecode!)
- Interp { interpInstance = ExternalInterp (ExtJS i) } ->
+ ExternalInterp (ExtJS i) ->
jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id
_ -> do
@@ -1645,7 +1644,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
let logger = hsc_logger hsc_env
tmpfs = hsc_tmpfs hsc_env
dflags = hsc_dflags hsc_env
- interp = hscInterp hsc_env
+ interp0 = hscInterp hsc_env
tmp_dir = tmpDir dflags
unit_env = hsc_unit_env hsc_env
js_config = initStgToJSConfig dflags
@@ -1671,10 +1670,10 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
-- by default, so we can safely ignore them here.
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
-- Take lock for the actual work.
- (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp $ \pls -> do
+ (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp0 $ \interp pls -> do
let link_opts = initLinkDepsOpts hsc_env
-- Find what packages and linkables are required
@@ -1715,7 +1714,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
jsLinkObject logger tmpfs tmp_dir js_config unit_env (hsc_FC hsc_env) inst out_obj roots needed_units
-- look up "id_sym" closure and create a StablePtr (HValue) from it
- binding_fref <- lookupClosure interp (IFaststringSymbol id_sym) >>= \case
+ binding_fref <- withInterp interp0 $ \interp -> lookupClosure interp (IFaststringSymbol id_sym) >>= \case
Nothing -> pprPanic "Couldn't find just linked TH closure" (ppr id_sym)
Just r -> pure r
=====================================
compiler/GHC/Driver/Make.hs
=====================================
@@ -837,7 +837,7 @@ pruneCache hpt summ
-- ---------------------------------------------------------------------------
--
-- | Unloading
-unload :: Interp -> HscEnv -> IO ()
+unload :: SafeInterp -> HscEnv -> IO ()
unload interp hsc_env
= case ghcLink (hsc_dflags hsc_env) of
LinkInMemory -> Linker.unload interp hsc_env
=====================================
compiler/GHC/Linker/Loader.hs
=====================================
@@ -170,19 +170,19 @@ import Foreign.Ptr (nullPtr)
uninitialised :: a
uninitialised = panic "Loader not initialised"
-modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()
-modifyLoaderState_ interp f =
+modifyLoaderState_ :: SafeInterp -> (Interp -> LoaderState -> IO LoaderState) -> IO ()
+modifyLoaderState_ interp0 f = withInterp interp0 $ \ interp ->
modifyMVar_ (loader_state (interpLoader interp))
- (fmap pure . f . fromMaybe uninitialised)
+ (fmap pure . f interp . fromMaybe uninitialised)
-modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
-modifyLoaderState interp f =
+modifyLoaderState :: SafeInterp -> (Interp -> LoaderState -> IO (LoaderState, a)) -> IO a
+modifyLoaderState interp0 f = withInterp interp0 $ \ interp ->
modifyMVar (loader_state (interpLoader interp))
- (fmapFst pure . f . fromMaybe uninitialised)
+ (fmapFst pure . f interp . fromMaybe uninitialised)
where fmapFst f = fmap (\(x, y) -> (f x, y))
-getLoaderState :: Interp -> IO (Maybe LoaderState)
-getLoaderState interp = readMVar (loader_state (interpLoader interp))
+getLoaderState :: SafeInterp -> IO (Maybe LoaderState)
+getLoaderState (SafeInterp interp) = readMVar (loader_state (interpLoader interp))
emptyLoaderState :: UnitEnv -> LoaderState
@@ -206,21 +206,21 @@ emptyLoaderState unit_env = LoaderState
pkg_to_dfm rtsUnitId
] ++ fmap pkg_to_dfm deps
-extendLoadedEnv :: Interp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
+extendLoadedEnv :: SafeInterp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
extendLoadedEnv interp modify_bytecode_loader_state new_bindings =
- modifyLoaderState_ interp $ \pls -> do
+ modifyLoaderState_ interp $ \_ pls -> do
return $! modifyBytecodeLoaderState modify_bytecode_loader_state pls $ \bco_loader_state ->
modifyClosureEnv bco_loader_state $ \ce -> extendClosureEnv ce new_bindings
-- strictness is important for not retaining old copies of the pls
-deleteFromLoadedHomeEnv :: Interp -> [Name] -> IO ()
+deleteFromLoadedHomeEnv :: SafeInterp -> [Name] -> IO ()
deleteFromLoadedHomeEnv interp to_remove =
- modifyLoaderState_ interp $ \pls -> do
+ modifyLoaderState_ interp $ \_ pls -> do
return $ modifyBytecodeLoaderState modifyHomePackageBytecodeState pls $ \bco_state ->
modifyClosureEnv bco_state $ \ce -> delListFromNameEnv ce to_remove
-- | Have we already loaded a name into the interpreter?
-lookupFromLoadedEnv :: Interp -> Name -> IO (Maybe ForeignHValue)
+lookupFromLoadedEnv :: SafeInterp -> Name -> IO (Maybe ForeignHValue)
lookupFromLoadedEnv interp name = do
mstate <- getLoaderState interp
return $ do
@@ -231,10 +231,10 @@ lookupFromLoadedEnv interp name = do
-- | Load the module containing the given Name and get its associated 'HValue'.
--
-- Throws a 'ProgramError' if loading fails or the name cannot be found.
-loadName :: Interp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
-loadName interp hsc_env name = do
- initLoaderState interp hsc_env
- modifyLoaderState interp $ \pls0 -> do
+loadName :: SafeInterp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
+loadName interp0 hsc_env name = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState interp0 $ \interp pls0 -> do
(pls, links, pkgs) <- if not (isExternalName name)
then return (pls0, [], emptyUDFM)
else do
@@ -248,6 +248,7 @@ loadName interp hsc_env name = do
Just (_,aa) -> return (pls,(aa, links, pkgs))
Nothing -> assertPpr (isExternalName name) (ppr name) $
do let sym_to_find = IClosureSymbol name
+ -- TODO: does not take loader state lock
m <- lookupClosure interp sym_to_find
r <- case m of
Just fhv -> return fhv
@@ -295,7 +296,7 @@ loadDependencies interp hsc_env pls span needed_mods = do
-- | Temporarily extend the loaded env.
withExtendedLoadedEnv
:: (ExceptionMonad m)
- => Interp
+ => SafeInterp
-> [(Name,ForeignHValue)]
-> m a
-> m a
@@ -314,9 +315,9 @@ withExtendedLoadedEnv interp new_env action
-- | Display the loader state.
-showLoaderState :: Interp -> IO SDoc
+showLoaderState :: SafeInterp -> IO SDoc
showLoaderState interp = do
- ls <- readMVar (loader_state (interpLoader interp))
+ ls <- getLoaderState interp
let docs = case ls of
Nothing -> [ text "Loader not initialised"]
Just pls -> [ text "Pkgs:" <+> ppr (map loaded_pkg_uid $ eltsUDFM $ pkgs_loaded pls)
@@ -352,8 +353,8 @@ showLoaderState interp = do
-- nothing. This is useful in Template Haskell, where we call it before
-- trying to link.
--
-initLoaderState :: Interp -> HscEnv -> IO ()
-initLoaderState interp hsc_env = do
+initLoaderState :: SafeInterp -> HscEnv -> IO ()
+initLoaderState interp0 hsc_env = withInterp interp0 $ \ interp -> do
modifyMVar_ (loader_state (interpLoader interp)) $ \pls -> do
case pls of
Just _ -> return pls
@@ -382,10 +383,10 @@ reallyInitLoaderState interp hsc_env = do
loadCmdLineLibs' interp hsc_env pls
-loadCmdLineLibs :: Interp -> HscEnv -> IO ()
-loadCmdLineLibs interp hsc_env = do
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls ->
+loadCmdLineLibs :: SafeInterp -> HscEnv -> IO ()
+loadCmdLineLibs interp0 hsc_env = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls ->
loadCmdLineLibs' interp hsc_env pls
@@ -730,13 +731,13 @@ get_reachable_nodes hsc_env mods
********************************************************************* -}
-- | Load the dependencies of a linkable, and then load the linkable itself.
-loadDecls :: Interp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
-loadDecls interp hsc_env span linkable = do
+loadDecls :: SafeInterp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
+loadDecls interp0 hsc_env span linkable = do
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
-- Take lock for the actual work.
- modifyLoaderState interp $ \pls0 -> do
+ modifyLoaderState interp0 $ \interp pls0 -> do
-- Link the packages and modules required
(pls, ok, links_needed, units_needed) <- loadDependencies interp hsc_env pls0 span needed_mods
if failed ok
@@ -770,10 +771,10 @@ loadDecls interp hsc_env span linkable = do
********************************************************************* -}
-loadModule :: Interp -> HscEnv -> Module -> IO ()
-loadModule interp hsc_env mod = do
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls -> do
+loadModule :: SafeInterp -> HscEnv -> Module -> IO ()
+loadModule interp0 hsc_env mod = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls -> do
(pls', ok, _, _) <- loadDependencies interp hsc_env pls noSrcSpan [mod]
if failed ok
then throwGhcExceptionIO (ProgramError "could not load module")
@@ -1158,16 +1159,16 @@ gets actually written to the loader state, the failure to do so is tracked by
-- * we also implicitly unload all temporary bindings at this point.
--
unload
- :: Interp
+ :: SafeInterp
-> HscEnv
-> IO ()
-unload interp hsc_env
+unload interp0 hsc_env
= mask_ $ do -- mask, so we're safe from Ctrl-C in here
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
- _new_pls <- modifyLoaderState interp $ \pls -> do
+ _new_pls <- modifyLoaderState interp0 $ \interp pls -> do
pls1 <- unload_wkr interp pls
return (pls1, pls1)
@@ -1234,7 +1235,7 @@ showLS (BytecodeLibrary nm) = "(bytecode) " ++ nm
-- automatically, and it doesn't matter what order you specify the input
-- packages.
--
-loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
+loadPackages :: SafeInterp -> HscEnv -> [UnitId] -> IO ()
-- NOTE: in fact, since each module tracks all the packages it depends on,
-- we don't really need to use the package-config dependencies.
--
@@ -1243,11 +1244,11 @@ loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
-- perhaps makes the error message a bit more localised if we get a link
-- failure. So the dependency walking code is still here.
-loadPackages interp hsc_env new_pkgs = do
+loadPackages interp0 hsc_env new_pkgs = do
-- It's probably not safe to try to load packages concurrently, so we take
-- a lock.
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls ->
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls ->
loadPackages' interp hsc_env new_pkgs pls
-- | Compute 'LoadedPkgInfo' metadata (with transitive deps) for new packages,
=====================================
compiler/GHC/Runtime/Eval.hs
=====================================
@@ -468,7 +468,7 @@ resumeExec step mbCnt r = do
| otherwise -> pure prevHistoryLst
handleRunStatus step eval_opts expr bindings final_ids status =<< hist'
-setupBreakpoint :: GhcMonad m => Interp -> InternalBreakpointId -> Int -> m () -- #19157
+setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157
setupBreakpoint interp ibi cnt = do
hug <- hsc_HUG <$> getSession
liftIO $ do
@@ -476,18 +476,18 @@ setupBreakpoint interp ibi cnt = do
breakArray <- getBreakArray interp ibi modBreaks
GHCi.storeBreakpoint interp breakArray (ibi_info_index ibi) cnt
-getBreakArray :: Interp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
+getBreakArray :: SafeInterp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
getBreakArray interp InternalBreakpointId{ibi_info_mod} imbs = do
breaks0 <- bco_linked_breaks . homePackage_loaded . bco_loader_state . fromMaybe (panic "Loader not initialised") <$> getLoaderState interp
case lookupModuleEnv (breakarray_env breaks0) ibi_info_mod of
Just ba -> return ba
Nothing -> do
- modifyLoaderState interp $ \ld_st -> do
+ modifyLoaderState interp $ \interp' ld_st -> do
let lb = bco_linked_breaks . homePackage_loaded . bco_loader_state $ ld_st
-- Recall that BreakArrays are allocated only at BCO link time, so if we
-- haven't linked the BCOs we intend to break at yet, we allocate the arrays here.
- ba_env <- allocateBreakArrays interp (breakarray_env lb) [imbs]
+ ba_env <- allocateBreakArrays interp' (breakarray_env lb) [imbs]
let ld_st' = modifyBytecodeLoaderState modifyHomePackageBytecodeState ld_st $ \bco_state -> bco_state { bco_linked_breaks = (bco_linked_breaks bco_state) { breakarray_env = ba_env } }
let ba = expectJust {- just computed -} $ lookupModuleEnv ba_env ibi_info_mod
=====================================
compiler/GHC/Runtime/Interpreter.hs
=====================================
@@ -64,6 +64,9 @@ module GHC.Runtime.Interpreter
-- * Reexport for convenience
, Message (..)
, module GHC.Runtime.Interpreter.Process
+
+ -- * High-level interface to the interpreter
+ , withInterp
) where
import GHC.Prelude
@@ -107,6 +110,7 @@ import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Catch as MC (mask, handle, MonadThrow (..))
+import Control.Monad.STM
import Data.Binary
import Data.ByteString (ByteString)
import qualified Data.ByteString.Short as SBS
@@ -198,7 +202,7 @@ interpCmd interp msg = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> run msg -- Just run it directly
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst ->
+ ExternalInterp ext -> withExtInterp ext $ \inst ->
sendMessage inst msg
-- | Calls `interpCmd` and the continuation while masked.
@@ -208,13 +212,22 @@ interpCmd interp msg = case interpInstance interp of
withInterpCmdMasked :: Binary a => Interp -> Message a -> (a -> IO b) -> IO b
withInterpCmdMasked interp msg own = mask_ $ interpCmd interp msg >>= own
-withExtInterp :: ExceptionMonad m => Interp -> ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
-withExtInterp interp ext action = stopInterpOnPipeClosed $ case ext of
+-- | Passes the `Interp` to the continuation while setting up a
+-- 'PipeClosedException' handler that calls 'stopInterp'.
+--
+-- Will take the 'interpLoader' lock on a 'PipeClosedException'.
+withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
+withInterp interp0@(SafeInterp interp) k = stopInterpOnPipeClosed $ k interp
+ where
+ stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> do
+ liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0
+ MC.throwM e
+
+withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
+withExtInterp ext action = case ext of
ExtJS i -> withJSInterp i action
ExtWasm i -> withWasmInterp i action
ExtIServ i -> withIServ i action
- where
- stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> liftIO (stopInterp interp) >> MC.throwM e
withExtInterpStatus :: ExtInterp -> (forall d. ExtInterpStatusVar d -> m a) -> m a
withExtInterpStatus ext action = case ext of
@@ -294,11 +307,11 @@ withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do
-- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for
-- each of the results.
evalStmt
- :: Interp
+ :: SafeInterp
-> EvalOpts
-> EvalExpr ForeignHValue
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
-evalStmt interp opts foreign_expr = do
+evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do
status <- withExpr foreign_expr $ \expr ->
interpCmd interp (EvalStmt opts expr)
handleEvalStatus interp status
@@ -312,17 +325,17 @@ evalStmt interp opts foreign_expr = do
cont (EvalApp fl' fr')
resumeStmt
- :: Interp
+ :: SafeInterp
-> EvalOpts
-> ForeignRef (ResumeContext [HValueRef])
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
-resumeStmt interp opts resume_ctxt = do
+resumeStmt interp0 opts resume_ctxt = withInterp interp0 $ \interp -> do
status <- withForeignRef resume_ctxt $ \rhv ->
interpCmd interp (ResumeStmt opts rhv)
handleEvalStatus interp status
-abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
-abandonStmt interp resume_ctxt =
+abandonStmt :: SafeInterp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
+abandonStmt interp0 resume_ctxt = withInterp interp0 $ \ interp ->
withForeignRef resume_ctxt $ \rhv ->
interpCmd interp (AbandonStmt rhv)
@@ -341,20 +354,20 @@ handleEvalStatus interp status =
EvalSuccess <$> mapM (mkFinalizedHValue interp) rs
-- | Execute an action of type @IO ()@
-evalIO :: Interp -> ForeignHValue -> IO ()
-evalIO interp fhv =
+evalIO :: SafeInterp -> ForeignHValue -> IO ()
+evalIO interp0 fhv = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalIO fhv) >>= fromEvalResult
-- | Execute an action of type @IO String@
-evalString :: Interp -> ForeignHValue -> IO String
-evalString interp fhv =
+evalString :: SafeInterp -> ForeignHValue -> IO String
+evalString interp0 fhv = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalString fhv) >>= fromEvalResult
-- | Execute an action of type @String -> IO String@
-evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String
-evalStringToIOString interp fhv str =
+evalStringToIOString :: SafeInterp -> ForeignHValue -> String -> IO String
+evalStringToIOString interp0 fhv str = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalStringToString fhv str) >>= fromEvalResult
@@ -388,44 +401,44 @@ addHpcModule :: Interp -> SBS.ShortByteString -> Int -> Int -> SBS.ShortByteStri
addHpcModule interp modLabel tickNo hash tickboxes =
interpCmd interp (AddHpcModule modLabel tickNo hash tickboxes)
-costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String]
-costCentreStackInfo interp ccs =
+costCentreStackInfo :: SafeInterp -> RemotePtr CostCentreStack -> IO [String]
+costCentreStackInfo interp0 ccs = withInterp interp0 $ \interp ->
interpCmd interp (CostCentreStackInfo ccs)
newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray)
newBreakArray interp size =
withInterpCmdMasked interp (NewBreakArray size) (mkFinalizedHValue interp)
-storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO ()
-storeBreakpoint interp ref ix cnt = do -- #19157
+storeBreakpoint :: SafeInterp -> ForeignRef BreakArray -> Int -> Int -> IO ()
+storeBreakpoint interp0 ref ix cnt = withInterp interp0 $ \ interp -> do -- #19157
withForeignRef ref $ \breakarray ->
interpCmd interp (SetupBreakpoint breakarray ix cnt)
-breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool
-breakpointStatus interp ref ix =
+breakpointStatus :: SafeInterp -> ForeignRef BreakArray -> Int -> IO Bool
+breakpointStatus interp0 ref ix = withInterp interp0 $ \ interp ->
withForeignRef ref $ \breakarray ->
interpCmd interp (BreakpointStatus breakarray ix)
-getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
-getBreakpointVar interp ref ix =
+getBreakpointVar :: SafeInterp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
+getBreakpointVar interp0 ref ix = withInterp interp0 $ \ interp ->
withForeignRef ref $ \apStack ->
withInterpCmdMasked interp (GetBreakpointVar apStack ix)
(mapM (mkFinalizedHValue interp))
-getClosure :: Interp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
-getClosure interp ref =
+getClosure :: SafeInterp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
+getClosure interp0 ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval ->
withInterpCmdMasked interp (GetClosure hval) $
mapM (mkFinalizedHValue interp)
-whereFrom :: Interp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
-whereFrom interp ref =
+whereFrom :: SafeInterp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
+whereFrom interp0 ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
interpCmd interp (WhereFrom hval)
-- | Send a Seq message to the iserv process to force a value #2950
-seqHValue :: Interp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
-seqHValue interp unit_env logger ref =
+seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
+seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
status <- interpCmd interp (Seq hval)
handleSeqHValueStatus interp unit_env logger status
@@ -649,26 +662,38 @@ spawnIServ conf = do
pure inst
-- | Stop the interpreter
-stopInterp :: Interp -> IO ()
-stopInterp interp = case interpInstance interp of
+stopInterp :: SafeInterp -> IO ()
+stopInterp = stopInterpWhen (const $ pure True)
+
+-- | Stop the interpreter if predicate returns 'True'.
+stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO ()
+stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> pure ()
#endif
- ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> do
- MC.mask $ \restore -> modifyMVar mstate $ \state -> do
+ ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do
+ -- takes interpLoader lock before ExternalInterp lock to avoid deadlocks.
+ -- commits emptied values before 'gracefulShutdown' so we don't hold locks
+ -- more than necessary.
+ mi <- modifyMVar (loader_state (interpLoader interp)) $ \l_st -> do
+ modifyMVar mstate $ \state -> do
case state of
- InterpPending -> pure (state, Nothing) -- already stopped
- InterpRunning i -> do
- e <- getProcessExitCode (interpHandle (instProcess i)) >>= \case
- Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
- Nothing -> gracefulShutdown i restore
- modifyMVar_ (loader_state (interpLoader interp)) (const $ pure Nothing)
- purgeInterpSymbolCache (interpSymbolCache interp)
- modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
- pure (InterpPending,e)
+ InterpPending -> pure (state, (l_st, Nothing)) -- already stopped
+ InterpRunning i -> shouldStop (instProcess i) >>= \case
+ False -> pure (state, (l_st, Nothing))
+ True -> do
+ purgeInterpSymbolCache (interpSymbolCache interp)
+ modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
+ pure (InterpPending,(Nothing,Just i))
+ case mi of
+ Nothing -> pure Nothing
+ Just i -> getProcessExitCode (interpHandle (instProcess i)) >>= \case
+ Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
+ Nothing -> gracefulShutdown i restore
+
where
gracefulShutdown i restore = do
- x <- try (timeLimited restore $ sendMessage i Shutdown `finally` closePipe (interpPipe (instProcess i)))
+ x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i)))))
let ph = interpHandle (instProcess i)
e <- case x of
-- happy path: ext. interp. should be shutting down of its own accord.
@@ -731,7 +756,7 @@ principle it would probably be ok, but it seems less hairy this way.
-- | Creates a 'ForeignRef' that will automatically release the
-- 'RemoteRef' when it is no longer referenced.
-mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a)
+mkFinalizedHValue :: HasInterpInstance i => i -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue interp rref = do
case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
@@ -754,13 +779,13 @@ freeHValueRefs interp refs = interpCmd interp (FreeHValueRefs refs)
-- | Convert a 'ForeignRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
-wormhole :: Interp -> ForeignRef a -> IO a
+wormhole :: SafeInterp -> ForeignRef a -> IO a
wormhole interp r = wormholeRef interp (unsafeForeignRefToRemoteRef r)
-- | Convert an 'RemoteRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
-wormholeRef :: Interp -> RemoteRef a -> IO a
+wormholeRef :: SafeInterp -> RemoteRef a -> IO a
wormholeRef interp _r = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> localRef _r
=====================================
compiler/GHC/Runtime/Interpreter/Init.hs
=====================================
@@ -29,7 +29,9 @@ import GHC.Utils.Monad
import GHC.Utils.Outputable
import GHC.Utils.Logger
import GHC.Utils.Error
+
import Control.Concurrent
+import Data.Coerce
import System.Process
data InterpOpts = InterpOpts
@@ -67,8 +69,8 @@ initInterpreter
-> FinderCache
-> UnitEnv
-> InterpOpts
- -> IO (Maybe Interp)
-initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = do
+ -> IO (Maybe SafeInterp)
+initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = coerce $ do
lookup_cache <- liftIO $ mkInterpSymbolCache
=====================================
compiler/GHC/Runtime/Interpreter/Types.hs
=====================================
@@ -4,6 +4,8 @@
-- | Types used by the runtime interpreter
module GHC.Runtime.Interpreter.Types
( Interp(..)
+ , SafeInterp(..)
+ , HasInterpInstance(..)
, InterpInstance(..)
, InterpProcess (..)
, ExtInterp (..)
@@ -66,9 +68,36 @@ import System.Process ( ProcessHandle, CreateProcess )
import System.IO
import GHC.Unit.Finder.Types (FinderCache, FinderOpts)
+{-
+Note [Interpreter locks order]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To avoid deadlocks, the 'interpLoader' lock should be taken before the lock that
+contains the 'InterpStatus'.
+
+Further, you should wrap the code that takes the 'interpLoader' lock with
+'withInterp', as it will cleanup the whole interpreter state in case the
+external interpreter pipe died:
+```
+withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
+```
+
+'SafeInterp' is a newtype introduced to aid with the discipline: only code that
+has ownership over a 'SafeInterp' should take its 'interpLoader' lock.
+
+-}
+
+
+
+
+-- | An 'Interp' where we have not taken the 'interpLoader' lock in this thread.
+--
+-- See Note [Interpreter locks order]
+newtype SafeInterp = SafeInterp Interp
+
-- | Interpreter
data Interp = Interp
- { interpInstance :: !InterpInstance
+ { _interpInstance :: !InterpInstance
-- ^ Interpreter instance (internal, external)
, interpLoader :: !Loader
@@ -81,6 +110,13 @@ data Interp = Interp
-- ^ MallocStrings cache
}
+class HasInterpInstance a where
+ interpInstance :: a -> InterpInstance
+instance HasInterpInstance SafeInterp where
+ interpInstance (SafeInterp interp) = interpInstance interp
+instance HasInterpInstance Interp where
+ interpInstance = _interpInstance
+
data InterpInstance
= ExternalInterp !ExtInterp -- ^ External interpreter
#if defined(HAVE_INTERNAL_INTERPRETER)
@@ -143,7 +179,7 @@ data ExtInterpInstance c = ExtInterpInstance
}
-- | Interpreter uses Profiling way
-interpreterProfiled :: Interp -> Bool
+interpreterProfiled :: HasInterpInstance a => a -> Bool
interpreterProfiled interp = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> hostIsProfiled
@@ -154,7 +190,7 @@ interpreterProfiled interp = case interpInstance interp of
ExtWasm i -> wasmInterpProfiled $ interpConfig i
-- | Interpreter uses Dynamic way
-interpreterDynamic :: Interp -> Bool
+interpreterDynamic :: HasInterpInstance a => a -> Bool
interpreterDynamic interp = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> hostIsDynamic
=====================================
compiler/GHC/Runtime/Loader.hs
=====================================
@@ -283,7 +283,7 @@ getValueSafely hsc_env val_name expected_type = do
logger = hsc_logger hsc_env
hooks = hsc_hooks hsc_env
-getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
+getHValueSafely :: SafeInterp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
getHValueSafely interp hsc_env val_name expected_type = do
forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name
-- Now look up the names for the value and type constructor in the type environment
=====================================
compiler/GHC/Runtime/Utils.hs
=====================================
@@ -1,3 +1,5 @@
+{-# LANGUAGE CPP #-}
+
module GHC.Runtime.Utils
( runWithPipes
)
@@ -10,6 +12,14 @@ import System.Process
import System.Process.CommunicationHandle
import System.IO
+#if defined(mingw32_HOST_OS)
+import Control.Concurrent (rtsSupportsBoundThreads)
+import GHC.IO.Handle.Windows (handleToHANDLE)
+import GHC.IO.SubSystem (isWindowsNativeIO)
+import System.Process.CommunicationHandle.Internal (CommunicationHandle(..))
+import qualified System.Win32 as Win32
+#endif
+
-- | Spawn a process connected to us by two pipes. Important to close our copy
-- of the endpoints passed to the child so each side only keeps open copies it
-- needs. If we don't do that, then closing one end wouldn't interrupt reads on
@@ -17,14 +27,64 @@ import System.IO
runWithPipes :: (CreateProcess -> IO ProcessHandle)
-> FilePath -> [String] -> [String] -> IO (ProcessHandle, Handle, Handle)
runWithPipes createProc prog pre_opts opts = do
- (rh, chTheyWrite) <- createWeReadTheyWritePipe
- (chTheyRead, wh) <- createTheyReadWeWritePipe
+ (rh, chTheyWrite) <- fixedCreateWeReadTheyWritePipe
+ (chTheyRead, wh) <- fixedCreateTheyReadWeWritePipe
let args = pre_opts ++ (show chTheyWrite : show chTheyRead : opts)
closeTheirs = do
- closeCommunicationHandle chTheyWrite
- closeCommunicationHandle chTheyRead
+ closeTheirEnd chTheyWrite
+ closeTheirEnd chTheyRead
-- These handles have no finalizers, so close them ourselves if the spawn fails.
ph <- createProc (proc prog args)
`onException` (closeTheirs >> hClose rh >> hClose wh)
closeTheirs
return (ph, rh, wh)
+
+-- | 'createWeReadTheyWritePipe', except in a non-threaded runtime on Windows
+-- without WinIO. There process gives us a synchronous native 'Handle', and
+-- reading from it is a safe call to @ReadFile@, which blocks every Haskell
+-- thread until data arrives. As 'GHCi.Message.Async' always has a thread
+-- waiting to read the pipe, no other thread would get to run. So in that case
+-- we swap our end for a file descriptor 'Handle', whose reads only block the
+-- reading thread.
+fixedCreateWeReadTheyWritePipe :: IO (Handle, CommunicationHandle)
+fixedCreateWeReadTheyWritePipe = do
+ (h, ch) <- createWeReadTheyWritePipe
+ h' <- toFdHandleIfNeeded h
+ return (h', ch)
+
+-- | 'createTheyReadWeWritePipe', with the same exception as
+-- 'fixedCreateWeReadTheyWritePipe'.
+fixedCreateTheyReadWeWritePipe :: IO (CommunicationHandle, Handle)
+fixedCreateTheyReadWeWritePipe = do
+ (ch, h) <- createTheyReadWeWritePipe
+ h' <- toFdHandleIfNeeded h
+ return (ch, h')
+
+toFdHandleIfNeeded :: Handle -> IO Handle
+#if defined(mingw32_HOST_OS)
+-- The native 'Handle' has a finalizer that closes its @HANDLE@, so we wrap a
+-- duplicate and close the original.
+toFdHandleIfNeeded h
+ | not rtsSupportsBoundThreads && not isWindowsNativeIO = do
+ me <- Win32.getCurrentProcess
+ hh <- handleToHANDLE h
+ dup <- Win32.duplicateHandle me hh me 0 False Win32.dUPLICATE_SAME_ACCESS
+ hClose h
+ Win32.hANDLEToHandle dup
+ | otherwise = return h
+#else
+toFdHandleIfNeeded = return
+#endif
+
+-- | Workaround for locking prone closeCommunicationHandle on windows
+--
+-- Called after a createProcess: the subprocess might start reading from the
+-- inherited raw handle before this close is scheduled, and, on windows,
+-- closeCommunicationHandle will block on a pending read during its conversion
+-- to Handle. Calling Win32.closeHandle directly avoids the blocking.
+closeTheirEnd :: CommunicationHandle -> IO ()
+#if defined(mingw32_HOST_OS)
+closeTheirEnd (CommunicationHandle h) = Win32.closeHandle h
+#else
+closeTheirEnd = closeCommunicationHandle
+#endif
=====================================
compiler/GHC/Tc/Gen/Splice.hs
=====================================
@@ -1151,16 +1151,16 @@ runRemoteModFinalizers (ThModFinalizers finRefs) = do
let withForeignRefs [] f = f []
withForeignRefs (x : xs) f = withForeignRef x $ \r ->
withForeignRefs xs $ \rs -> f (r : rs)
- interp <- tcGetInterp
+ interp0 <- tcGetInterp
- case interpInstance interp of
+ withInterp interp0 $ \interp -> case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> do
qs <- liftIO (withForeignRefs finRefs $ mapM localRef)
runQinTcM $ sequence_ qs
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
+ ExternalInterp ext -> withExtInterp ext $ \inst -> do
tcg <- getGblEnv
th_state <- readTcRef (tcg_th_remote_state tcg)
case th_state of
@@ -1807,17 +1807,17 @@ runTHDec = runTH THDec
runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
runTH ty fhv = do
- interp <- tcGetInterp
- case interpInstance interp of
+ interp0 <- tcGetInterp
+ withInterp interp0 $ \ interp -> case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> do
-- Run it in the local TcM
- hv <- liftIO $ wormhole interp fhv
+ hv <- liftIO $ wormhole interp0 fhv
r <- runQinTcM (unsafeCoerce hv :: TH.Q a)
return r
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
+ ExternalInterp ext -> withExtInterp ext $ \inst -> do
-- Run it on the server. For an overview of how TH works with
-- Remote GHCi, see Note [Remote Template Haskell] in
-- libraries/ghci/GHCi/TH.hs.
@@ -3031,7 +3031,7 @@ mkThAppTs fun_ty arg_tys = foldl' TH.AppT fun_ty arg_tys
noTH :: UnrepresentableTypeDescr -> Type -> TcM a
noTH s d = failWithTc $ TcRnTHError $ THReifyError $ CannotRepresentType s d
-tcGetInterp :: TcM Interp
+tcGetInterp :: TcM SafeInterp
tcGetInterp = do
hsc_env <- getTopEnv
case hsc_interp hsc_env of
=====================================
ghc/GHCi/UI/Monad.hs
=====================================
@@ -475,8 +475,8 @@ printStats dflags ActionStats{actionAllocs = mallocs, actionElapsedTime = secs}
revertCAFs :: GhciMonad m => m ()
revertCAFs = do
- interp <- hscInterp <$> GHC.getSession
- liftIO $ interpCmd interp RtsRevertCAFs
+ interp0 <- hscInterp <$> GHC.getSession
+ liftIO $ withInterp interp0 $ \interp -> interpCmd interp RtsRevertCAFs
s <- getGHCiState
when (not (ghc_e s)) turnOffBuffering
-- Have to turn off buffering again, because we just
=====================================
libraries/ghci/GHCi/Message.hs
=====================================
@@ -27,7 +27,7 @@ module GHCi.Message
, QState(..)
, getMessage, putMessage, getTHMessage, putTHMessage
- , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe
+ , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe, isPipeOpen
, remoteCall, remoteCallInterleaving, remoteTHCall
, handleRemoteCall, handleRemoteTHCall, writeReply
, RemoteProcessException(..), PipeClosedException(..)
=====================================
libraries/ghci/GHCi/Message/Async.hs
=====================================
@@ -8,6 +8,7 @@ module GHCi.Message.Async
-- * Pipes
Pipe(..), mkPipeFromHandles, mkPipeFromContinuations
, closePipe, PipeClosedException(..)
+ , closingPipe, isPipeOpen
-- * Interface for async bidirectional RPC
, remoteAsyncReq, handleAsyncReq
@@ -31,7 +32,7 @@ module GHCi.Message.Async
-- * Serializable exceptions
, SerializableException(..)
- , toSerializableException, fromSerializableException, closingPipe
+ , toSerializableException, fromSerializableException
) where
import Prelude -- See note [Why do we import Prelude here?]
@@ -159,6 +160,11 @@ closePipe Pipe{..} = do
throwTo (asyncFillTid pipeAsyncMngr) PipeWriteClosedException
`finally` throwTo (asyncDrainTid pipeAsyncMngr) PipeReadClosedException
+isPipeOpen :: Pipe -> STM Bool
+isPipeOpen pipe = liftM2 (&&)
+ (isOpen <$> readTVar (pipeReadStatus pipe))
+ (isOpen <$> readTVar (pipeWriteStatus pipe))
+
closingPipeEnd :: TVar PipeEndStatus -> STM PipeEndStatus
closingPipeEnd v = readTVar v >>= \ s -> do
case s of
@@ -598,9 +604,8 @@ drainPipe p unmask = catch loop (void . replyToPendings) where
Just q -> writeTQueue q (uq,bs)
Cancel uq -> cancelRequest am uq
- replyToPendings e = do
- atomically $ failPendingReplies p e
- pipeCloseRead p `catch` \(_ :: IOException) -> pure ()
+ replyToPendings e = finally (pipeCloseRead p `catch` \(_ :: IOException) -> pure ()) -- TODO: log with verbose.
+ . atomically $ failPendingReplies p e
am = pipeAsyncMngr p
@@ -669,8 +674,8 @@ fillPipe p unmask = loop `catch` cleanup Nothing where
am = pipeAsyncMngr p
- cleanup last_write e0 = do
- atomically $ do
+ cleanup last_write e0 = finally (pipeCloseWrite p `catch` \(_ :: IOException) -> pure ()) -- TODO: log with verbose
+ . atomically $ do
-- deactivate here too so we keep track of the exception if end still 'Open'.
s <- deactivatePipeEnd (pipeWriteStatus p) (Just e0)
case last_write of
@@ -680,7 +685,6 @@ fillPipe p unmask = loop `catch` cleanup Nothing where
putTMVar var . Left $ if isOpen s then e0 else toException PipeWriteClosedException
-- real exception already reported once
failPendingWrites p $ toException PipeWriteClosedException
- pipeCloseWrite p `catch` \(_ :: IOException) -> pure ()
failPendingWrites :: Pipe -> SomeException -> STM ()
failPendingWrites p e = do
=====================================
testsuite/tests/ghci/interp-cancellation/all.T
=====================================
@@ -8,3 +8,14 @@ test('interp-cancellation',
],
multimod_compile_and_run,
['Main.hs', '-package ghc -package ghci'])
+
+test('interp-concurrent',
+ [ extra_run_opts(f'"{config.libdir}"')
+ , windows_skip
+ , when(config.cross, skip)
+ , req_th
+ , unless(config.have_ext_interp, skip)
+ , only_ways(['normal'])
+ ],
+ compile_and_run,
+ ['-package ghc -threaded'])
=====================================
testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs
=====================================
@@ -0,0 +1,265 @@
+{-# LANGUAGE LambdaCase, ScopedTypeVariables #-}
+
+-- | Several threads share one GHC session, and so one external interpreter.
+--
+-- Checks that concurrent requests get their own replies, that killing threads
+-- waiting on the interpreter leaves it usable, that killing a thread running a
+-- splice cancels the splice in the interpreter, and that when the interpreter
+-- dies it is stopped and the next request starts a new one.
+module Main (main) where
+
+import Control.Concurrent
+import Control.Exception
+import Control.Monad
+import Control.Monad.IO.Class (liftIO)
+import Data.Either (isLeft)
+import Data.Maybe (isJust, isNothing)
+import System.Directory (doesFileExist, removeFile)
+import System.Environment (getArgs)
+import System.Exit (exitFailure)
+import System.IO
+import System.Posix.Signals (sigKILL, signalProcess)
+import System.Process (ProcessHandle, getPid, getProcessExitCode)
+import System.Timeout (timeout)
+
+import GHC
+import GHC.Driver.Env (hscInterp)
+import GHC.Driver.Monad (Session, reflectGhc, reifyGhc)
+import GHC.Driver.Session (gopt_set, xopt_set)
+import qualified GHC.LanguageExtensions as LangExt
+import GHC.Runtime.Interpreter (evalString, evalStringToIOString)
+import GHC.Runtime.Interpreter.Types
+import GHCi.Message (PipeClosedException)
+
+main :: IO ()
+main = do
+ hSetBuffering stdout LineBuffering
+ [libdir] <- getArgs
+ mapM_ removeIfExists markers
+ runGhc (Just libdir) $ do
+ let withTH fs = foldl xopt_set fs
+ [LangExt.TemplateHaskell, LangExt.TemplateHaskellQuotes]
+ dflags <- getSessionDynFlags
+ _ <- setSessionDynFlags (withTH (gopt_set dflags Opt_ExternalInterpreter))
+ { ghcLink = LinkInMemory }
+ setContext [ IIDecl (simpleImportDecl (mkModuleName m))
+ | m <- [ "Prelude", "Control.Concurrent", "Control.Exception"
+ , "System.IO", "System.IO.Error", "Language.Haskell.TH" ] ]
+ reifyGhc $ \s -> do
+ concurrentReplies s
+ killWaiting s
+ killSplice s
+ interpreterDies s
+
+--------------------------------------------------------------------------------
+-- Scenarios
+
+concurrentReplies :: Session -> IO ()
+concurrentReplies s = do
+ echo <- compile s echoExpr
+ ws <- forM [1 .. 16 :: Int] $ \n -> async $
+ forM [1 .. 50 :: Int] $ \k -> do
+ let x = show (n, k)
+ (== x) <$> evalEcho s echo x
+ rs <- mapM (waiting "concurrent requests" . readMVar . snd) ws
+ check "concurrent requests each get their own reply"
+ (all (either (const False) and) rs)
+
+-- | Kill threads waiting on two gated requests, and check a third request
+-- made alongside them still gets its reply.
+killWaiting :: Session -> IO ()
+killWaiting s = do
+ echo <- compile s echoExpr
+ -- Compiled up front: compiling needs the interpreter, which 'a' may hold up.
+ bAct <- compile s (gated "b.started" "b.gate" "pure \"b\"")
+ (a, aRes) <- async $ inSession s $
+ execStmt (gated "a.started" "a.gate" "pure ()") execOptions
+ awaitFileUntil "the statement to start" "a.started" aRes
+ (b, bRes) <- async $ evalFHV s bAct
+ (_, cRes) <- async $ evalEcho s echo "c"
+ threadDelay 100000 -- let b and c send their requests
+ waiting "killing the thread waiting on the statement" (killThread a)
+ waiting "killing the thread waiting on the other one" (killThread b)
+ aR <- waiting "the killed statement thread to finish" (readMVar aRes)
+ bR <- waiting "the other killed thread to finish" (readMVar bRes)
+ check "killed threads stop waiting for their replies"
+ (isKilled aR && isKilled bR)
+ -- Let the server side evaluation of 'a' and 'b' go through, since eval
+ -- requests ignore canceling atm.
+ mapM_ (`writeFile` "") ["a.gate", "b.gate"]
+ cR <- waiting "the remaining request's reply" (readMVar cRes)
+ check "a request made alongside cancelled ones gets its reply"
+ (either (const False) (== "c") cR)
+ stillAnswers s echo
+
+-- | Splices run in their own thread in the interpreter, so they don't hold up
+-- other requests, and can be cancelled there.
+killSplice :: Session -> IO ()
+killSplice s = do
+ echo <- compile s echoExpr
+ (t, tRes) <- async $ inSession s $
+ compileExprRemote (blockingSplice "th.started" "th.cancelled")
+ awaitFileUntil "the splice to start" "th.started" tRes
+ r <- waiting "a request while a splice runs" (evalEcho s echo "during splice")
+ check "a running splice does not hold up other requests"
+ (r == "during splice")
+ waiting "killing the thread running the splice" (killThread t)
+ tR <- waiting "the killed splice thread to finish" (readMVar tRes)
+ check "the thread running the splice is killed" (isKilled tR)
+ awaitFile "the splice to be cancelled in the interpreter" "th.cancelled"
+ -- just printing what we can infer from the previous line.
+ check "the splice is cancelled in the interpreter" True
+ stillAnswers s echo
+
+-- | Kill the interpreter while one thread waits on a statement and another
+-- runs a splice.
+interpreterDies :: Session -> IO ()
+interpreterDies s = do
+ _ <- compile s echoExpr
+ ph <- runningInterp s >>= maybe (failWith "no interpreter running") pure
+ pid <- getPid ph >>= maybe (failWith "interpreter has no pid") pure
+
+ -- Splice first: compiling it needs the interpreter, which the statement
+ -- may hold up.
+ (_, fRes) <- async $ inSession s $
+ compileExprRemote (blockingSplice "f.started" "f.cancelled")
+ awaitFileUntil "the splice to start" "f.started" fRes
+ (_, dRes) <- async $ evalIn s (gated "d.started" "d.gate" "pure \"d\"")
+ awaitFileUntil "the statement to start" "d.started" dRes
+
+ signalProcess sigKILL pid
+ dR <- waiting "the statement thread to fail" (readMVar dRes)
+ check "a thread waiting on a dead interpreter gets PipeClosedException"
+ (isPipeClosed dR)
+ fR <- waiting "the splice thread to fail" (readMVar fRes)
+ check "a thread running a splice in a dead interpreter fails" (isLeft fR)
+
+ st <- runningInterp s
+ check "the dead interpreter is stopped" (isNothing st)
+ ex <- getProcessExitCode ph
+ check "its process is reaped" (isJust ex)
+
+ r <- waiting "a request after the interpreter died"
+ (evalIn s "pure \"alive\" :: IO String")
+ check "the next request starts a new interpreter" (r == "alive")
+ ph' <- runningInterp s >>= maybe (failWith "no interpreter running") pure
+ pid' <- getPid ph'
+ check "the new interpreter is a different process" (pid' /= Just pid)
+
+--------------------------------------------------------------------------------
+-- Talking to the interpreter through the session
+
+inSession :: Session -> Ghc a -> IO a
+inSession = flip reflectGhc
+
+compile :: Session -> String -> IO ForeignHValue
+compile s e = inSession s (compileExprRemote e)
+
+-- | Compile an @IO String@ and run it.
+evalIn :: Session -> String -> IO String
+evalIn s e = compile s e >>= evalFHV s
+
+-- | Run a compiled @IO String@.
+evalFHV :: Session -> ForeignHValue -> IO String
+evalFHV s fhv = inSession s $ do
+ hsc_env <- getSession
+ liftIO (evalString (hscInterp hsc_env) fhv)
+
+evalEcho :: Session -> ForeignHValue -> String -> IO String
+evalEcho s echo x = inSession s $ do
+ hsc_env <- getSession
+ liftIO (evalStringToIOString (hscInterp hsc_env) echo x)
+
+stillAnswers :: Session -> ForeignHValue -> IO ()
+stillAnswers s echo = do
+ r <- waiting "a request after the cancellations" (evalEcho s echo "after")
+ check "the interpreter still answers" (r == "after")
+
+runningInterp :: Session -> IO (Maybe ProcessHandle)
+runningInterp s = do
+ interp <- inSession s (hscInterp <$> getSession)
+ case interpInstance interp of
+ ExternalInterp (ExtIServ st) -> readMVar (interpStatus st) >>= \case
+ InterpRunning inst -> pure (Just (interpHandle (instProcess inst)))
+ InterpPending -> pure Nothing
+ _ -> failWith "not using an external interpreter"
+
+--------------------------------------------------------------------------------
+-- Interpreted code
+
+echoExpr :: String
+echoExpr = "(\\x -> pure x) :: String -> IO String"
+
+-- | Creates @started@, waits for @gate@ to exist, then runs @k@.
+gated :: FilePath -> FilePath -> String -> String
+gated started gate k = concat
+ [ "let { waitFor p = catchIOError (withFile p ReadMode (\\_ -> pure ()))"
+ , " (\\_ -> threadDelay 10000 >> waitFor p) }"
+ , " in writeFile ", show started, " \"\" >> waitFor ", show gate, " >> ", k ]
+
+-- | Creates @started@, then blocks. Creates @cancelled@ if interrupted.
+blockingSplice :: FilePath -> FilePath -> String
+blockingSplice started cancelled = concat
+ [ "$(runIO (writeFile ", show started, " \"\""
+ , " >> (threadDelay maxBound `onException` writeFile ", show cancelled, " \"\"))"
+ , " >> [| () |])" ]
+
+markers :: [FilePath]
+markers = [ "a.started", "a.gate", "b.started", "b.gate"
+ , "th.started", "th.cancelled"
+ , "d.started", "d.gate", "f.started", "f.cancelled" ]
+
+--------------------------------------------------------------------------------
+-- Utilities
+
+async :: IO a -> IO (ThreadId, MVar (Either SomeException a))
+async act = do
+ v <- newEmptyMVar
+ t <- forkFinally act (putMVar v)
+ pure (t, v)
+
+awaitFile :: String -> FilePath -> IO ()
+awaitFile what p = waiting what loop
+ where
+ loop = doesFileExist p >>= \b -> unless b (threadDelay 10000 >> loop)
+
+-- | Like 'awaitFile', but fails straight away if the thread that should
+-- create the file ends first.
+awaitFileUntil :: String -> FilePath -> MVar (Either SomeException a) -> IO ()
+awaitFileUntil what p res = waiting what loop
+ where
+ loop = do
+ b <- doesFileExist p
+ unless b $ tryReadMVar res >>= \case
+ Just r -> failWith ("waiting for " ++ what ++ ", the thread ended: "
+ ++ either show (const "no exception") r)
+ Nothing -> threadDelay 10000 >> loop
+
+removeIfExists :: FilePath -> IO ()
+removeIfExists p = removeFile p `catch` \(_ :: IOException) -> pure ()
+
+isKilled :: Either SomeException a -> Bool
+isKilled = \case
+ Left e | Just ThreadKilled <- fromException e -> True
+ _ -> False
+
+isPipeClosed :: Either SomeException a -> Bool
+isPipeClosed = \case
+ Left e | Just (_ :: PipeClosedException) <- fromException e -> True
+ _ -> False
+
+-- | Adds a timeout so we fail with a message rather than hang the whole test.
+waiting :: String -> IO a -> IO a
+waiting what act =
+ timeout (60 * 1000000) act >>= maybe (failWith ("timed out waiting for " ++ what)) pure
+
+failWith :: String -> IO a
+failWith what = do
+ hPutStrLn stderr ("FAILED: " ++ what)
+ hFlush stderr
+ exitFailure
+
+check :: String -> Bool -> IO ()
+check what ok
+ | ok = putStrLn ("ok: " ++ what)
+ | otherwise = void (failWith what)
=====================================
testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout
=====================================
@@ -0,0 +1,14 @@
+ok: concurrent requests each get their own reply
+ok: killed threads stop waiting for their replies
+ok: a request made alongside cancelled ones gets its reply
+ok: the interpreter still answers
+ok: a running splice does not hold up other requests
+ok: the thread running the splice is killed
+ok: the splice is cancelled in the interpreter
+ok: the interpreter still answers
+ok: a thread waiting on a dead interpreter gets PipeClosedException
+ok: a thread running a splice in a dead interpreter fails
+ok: the dead interpreter is stopped
+ok: its process is reaped
+ok: the next request starts a new interpreter
+ok: the new interpreter is a different process
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/000d737cb934a9c0d0da206d23eb87…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/000d737cb934a9c0d0da206d23eb87…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/andrea/async-rpc] 3 commits: interp: cleanup with stopInterp outside interpLoader lock
by Andrea Vezzosi (@trac-Saizan) 17 Nov '26
by Andrea Vezzosi (@trac-Saizan) 17 Nov '26
17 Nov '26
Andrea Vezzosi pushed to branch wip/andrea/async-rpc at Glasgow Haskell Compiler / GHC
Commits:
000d737c by Andrea Vezzosi at 2026-11-16T17:27:25+01:00
interp: cleanup with stopInterp outside interpLoader lock
- - - - -
4691cfdb by Andrea Vezzosi at 2026-11-17T13:05:22+01:00
interp: fix race between stopInterp and starting a new instance.
On a PipeClosedException we stop the external interpreter and cleanup its state.
With multiple threads sharing the same ghc session we could have had two threads
getting the exception, one of them cleanup and start a new instance before
the second thread gets to do its cleanup, which would then stop the new
instance which is working fine.
Now we check whether the 'Pipe' of the interpreter we are about to cleanup is
closed, otherwise it must be a new one and we leave it be.
- - - - -
5c310af6 by Andrea Vezzosi at 2026-11-17T13:16:12+01:00
interp: test concurrent use of one external interpreter
Threads share a GHC session: concurrent requests, killing waiting threads,
cancelling a running splice, and restarting after the interpreter dies.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
17 changed files:
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Env/Types.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Runtime/Interpreter/Init.hs
- compiler/GHC/Runtime/Interpreter/Types.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Tc/Gen/Splice.hs
- ghc/GHCi/UI/Monad.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Message/Async.hs
- testsuite/tests/ghci/interp-cancellation/all.T
- + testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs
- + testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout
Changes:
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -56,7 +56,7 @@ import GHC.Driver.Config.Diagnostic (initDiagOpts, initPrintConfig)
import GHC.Driver.Env.Types ( Hsc(..), HscEnv(..), HasHscEnv (..) )
import GHC.Runtime.Context
-import GHC.Runtime.Interpreter.Types (Interp)
+import GHC.Runtime.Interpreter.Types (SafeInterp)
import GHC.Unit
import GHC.Unit.External.Database
@@ -410,7 +410,7 @@ mainModIs hue = mkHomeModule (expectJust $ homeUnitEnv_home_unit hue) (mainModul
-- | Retrieve the target code interpreter
--
-- Fails if no target code interpreter is available
-hscInterp :: HscEnv -> Interp
+hscInterp :: HscEnv -> SafeInterp
hscInterp hsc_env = case hsc_interp hsc_env of
Nothing -> throw (InstallationError "Couldn't find a target code interpreter. Try with -fexternal-interpreter")
Just i -> i
=====================================
compiler/GHC/Driver/Env/Types.hs
=====================================
@@ -14,7 +14,7 @@ import GHC.Driver.LlvmConfigCache (LlvmConfigCache)
import GHC.Prelude
import GHC.Runtime.Context
-import GHC.Runtime.Interpreter.Types ( Interp )
+import GHC.Runtime.Interpreter.Types ( SafeInterp )
import GHC.Types.Error ( Messages )
import GHC.Types.Name.Cache
import GHC.Types.Target
@@ -88,7 +88,7 @@ data HscEnv
-- the 'IfGblEnv'. See 'tcg_knot_vars' in 'GHC.Tc.Utils.TcGblEnv'.
-- See also Note [hsc_type_env_var hack]
- , hsc_interp :: Maybe Interp
+ , hsc_interp :: Maybe SafeInterp
-- ^ target code interpreter (if any) to use for TH and GHCi.
-- See Note [Target code interpreter]
=====================================
compiler/GHC/Driver/Main/Passes.hs
=====================================
@@ -1604,10 +1604,9 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do
let (stg_binds, _stg_deps) = unzip stg_binds_with_deps
let interp = hscInterp hsc_env
-
- case interp of
+ case interpInstance interp of
-- always generate JS code for the JS interpreter (no bytecode!)
- Interp { interpInstance = ExternalInterp (ExtJS i) } ->
+ ExternalInterp (ExtJS i) ->
jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id
_ -> do
@@ -1645,7 +1644,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
let logger = hsc_logger hsc_env
tmpfs = hsc_tmpfs hsc_env
dflags = hsc_dflags hsc_env
- interp = hscInterp hsc_env
+ interp0 = hscInterp hsc_env
tmp_dir = tmpDir dflags
unit_env = hsc_unit_env hsc_env
js_config = initStgToJSConfig dflags
@@ -1671,10 +1670,10 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
-- by default, so we can safely ignore them here.
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
-- Take lock for the actual work.
- (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp $ \pls -> do
+ (dep_linkables, needed_units, this_pkgs_loaded) <- modifyLoaderState interp0 $ \interp pls -> do
let link_opts = initLinkDepsOpts hsc_env
-- Find what packages and linkables are required
@@ -1715,7 +1714,7 @@ jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id = do
jsLinkObject logger tmpfs tmp_dir js_config unit_env (hsc_FC hsc_env) inst out_obj roots needed_units
-- look up "id_sym" closure and create a StablePtr (HValue) from it
- binding_fref <- lookupClosure interp (IFaststringSymbol id_sym) >>= \case
+ binding_fref <- withInterp interp0 $ \interp -> lookupClosure interp (IFaststringSymbol id_sym) >>= \case
Nothing -> pprPanic "Couldn't find just linked TH closure" (ppr id_sym)
Just r -> pure r
=====================================
compiler/GHC/Driver/Make.hs
=====================================
@@ -837,7 +837,7 @@ pruneCache hpt summ
-- ---------------------------------------------------------------------------
--
-- | Unloading
-unload :: Interp -> HscEnv -> IO ()
+unload :: SafeInterp -> HscEnv -> IO ()
unload interp hsc_env
= case ghcLink (hsc_dflags hsc_env) of
LinkInMemory -> Linker.unload interp hsc_env
=====================================
compiler/GHC/Linker/Loader.hs
=====================================
@@ -170,19 +170,19 @@ import Foreign.Ptr (nullPtr)
uninitialised :: a
uninitialised = panic "Loader not initialised"
-modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()
-modifyLoaderState_ interp f =
+modifyLoaderState_ :: SafeInterp -> (Interp -> LoaderState -> IO LoaderState) -> IO ()
+modifyLoaderState_ interp0 f = withInterp interp0 $ \ interp ->
modifyMVar_ (loader_state (interpLoader interp))
- (fmap pure . f . fromMaybe uninitialised)
+ (fmap pure . f interp . fromMaybe uninitialised)
-modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a
-modifyLoaderState interp f =
+modifyLoaderState :: SafeInterp -> (Interp -> LoaderState -> IO (LoaderState, a)) -> IO a
+modifyLoaderState interp0 f = withInterp interp0 $ \ interp ->
modifyMVar (loader_state (interpLoader interp))
- (fmapFst pure . f . fromMaybe uninitialised)
+ (fmapFst pure . f interp . fromMaybe uninitialised)
where fmapFst f = fmap (\(x, y) -> (f x, y))
-getLoaderState :: Interp -> IO (Maybe LoaderState)
-getLoaderState interp = readMVar (loader_state (interpLoader interp))
+getLoaderState :: SafeInterp -> IO (Maybe LoaderState)
+getLoaderState (SafeInterp interp) = readMVar (loader_state (interpLoader interp))
emptyLoaderState :: UnitEnv -> LoaderState
@@ -206,21 +206,21 @@ emptyLoaderState unit_env = LoaderState
pkg_to_dfm rtsUnitId
] ++ fmap pkg_to_dfm deps
-extendLoadedEnv :: Interp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
+extendLoadedEnv :: SafeInterp -> BytecodeLoaderStateModifier -> [(Name,ForeignHValue)] -> IO ()
extendLoadedEnv interp modify_bytecode_loader_state new_bindings =
- modifyLoaderState_ interp $ \pls -> do
+ modifyLoaderState_ interp $ \_ pls -> do
return $! modifyBytecodeLoaderState modify_bytecode_loader_state pls $ \bco_loader_state ->
modifyClosureEnv bco_loader_state $ \ce -> extendClosureEnv ce new_bindings
-- strictness is important for not retaining old copies of the pls
-deleteFromLoadedHomeEnv :: Interp -> [Name] -> IO ()
+deleteFromLoadedHomeEnv :: SafeInterp -> [Name] -> IO ()
deleteFromLoadedHomeEnv interp to_remove =
- modifyLoaderState_ interp $ \pls -> do
+ modifyLoaderState_ interp $ \_ pls -> do
return $ modifyBytecodeLoaderState modifyHomePackageBytecodeState pls $ \bco_state ->
modifyClosureEnv bco_state $ \ce -> delListFromNameEnv ce to_remove
-- | Have we already loaded a name into the interpreter?
-lookupFromLoadedEnv :: Interp -> Name -> IO (Maybe ForeignHValue)
+lookupFromLoadedEnv :: SafeInterp -> Name -> IO (Maybe ForeignHValue)
lookupFromLoadedEnv interp name = do
mstate <- getLoaderState interp
return $ do
@@ -231,10 +231,10 @@ lookupFromLoadedEnv interp name = do
-- | Load the module containing the given Name and get its associated 'HValue'.
--
-- Throws a 'ProgramError' if loading fails or the name cannot be found.
-loadName :: Interp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
-loadName interp hsc_env name = do
- initLoaderState interp hsc_env
- modifyLoaderState interp $ \pls0 -> do
+loadName :: SafeInterp -> HscEnv -> Name -> IO (ForeignHValue, [LinkableUsage], PkgsLoaded)
+loadName interp0 hsc_env name = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState interp0 $ \interp pls0 -> do
(pls, links, pkgs) <- if not (isExternalName name)
then return (pls0, [], emptyUDFM)
else do
@@ -248,6 +248,7 @@ loadName interp hsc_env name = do
Just (_,aa) -> return (pls,(aa, links, pkgs))
Nothing -> assertPpr (isExternalName name) (ppr name) $
do let sym_to_find = IClosureSymbol name
+ -- TODO: does not take loader state lock
m <- lookupClosure interp sym_to_find
r <- case m of
Just fhv -> return fhv
@@ -295,7 +296,7 @@ loadDependencies interp hsc_env pls span needed_mods = do
-- | Temporarily extend the loaded env.
withExtendedLoadedEnv
:: (ExceptionMonad m)
- => Interp
+ => SafeInterp
-> [(Name,ForeignHValue)]
-> m a
-> m a
@@ -314,9 +315,9 @@ withExtendedLoadedEnv interp new_env action
-- | Display the loader state.
-showLoaderState :: Interp -> IO SDoc
+showLoaderState :: SafeInterp -> IO SDoc
showLoaderState interp = do
- ls <- readMVar (loader_state (interpLoader interp))
+ ls <- getLoaderState interp
let docs = case ls of
Nothing -> [ text "Loader not initialised"]
Just pls -> [ text "Pkgs:" <+> ppr (map loaded_pkg_uid $ eltsUDFM $ pkgs_loaded pls)
@@ -352,8 +353,8 @@ showLoaderState interp = do
-- nothing. This is useful in Template Haskell, where we call it before
-- trying to link.
--
-initLoaderState :: Interp -> HscEnv -> IO ()
-initLoaderState interp hsc_env = do
+initLoaderState :: SafeInterp -> HscEnv -> IO ()
+initLoaderState interp0 hsc_env = withInterp interp0 $ \ interp -> do
modifyMVar_ (loader_state (interpLoader interp)) $ \pls -> do
case pls of
Just _ -> return pls
@@ -382,10 +383,10 @@ reallyInitLoaderState interp hsc_env = do
loadCmdLineLibs' interp hsc_env pls
-loadCmdLineLibs :: Interp -> HscEnv -> IO ()
-loadCmdLineLibs interp hsc_env = do
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls ->
+loadCmdLineLibs :: SafeInterp -> HscEnv -> IO ()
+loadCmdLineLibs interp0 hsc_env = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls ->
loadCmdLineLibs' interp hsc_env pls
@@ -730,13 +731,13 @@ get_reachable_nodes hsc_env mods
********************************************************************* -}
-- | Load the dependencies of a linkable, and then load the linkable itself.
-loadDecls :: Interp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
-loadDecls interp hsc_env span linkable = do
+loadDecls :: SafeInterp -> HscEnv -> SrcSpan -> Linkable -> IO ([LinkableUsage], PkgsLoaded)
+loadDecls interp0 hsc_env span linkable = do
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
-- Take lock for the actual work.
- modifyLoaderState interp $ \pls0 -> do
+ modifyLoaderState interp0 $ \interp pls0 -> do
-- Link the packages and modules required
(pls, ok, links_needed, units_needed) <- loadDependencies interp hsc_env pls0 span needed_mods
if failed ok
@@ -770,10 +771,10 @@ loadDecls interp hsc_env span linkable = do
********************************************************************* -}
-loadModule :: Interp -> HscEnv -> Module -> IO ()
-loadModule interp hsc_env mod = do
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls -> do
+loadModule :: SafeInterp -> HscEnv -> Module -> IO ()
+loadModule interp0 hsc_env mod = do
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls -> do
(pls', ok, _, _) <- loadDependencies interp hsc_env pls noSrcSpan [mod]
if failed ok
then throwGhcExceptionIO (ProgramError "could not load module")
@@ -1158,16 +1159,16 @@ gets actually written to the loader state, the failure to do so is tracked by
-- * we also implicitly unload all temporary bindings at this point.
--
unload
- :: Interp
+ :: SafeInterp
-> HscEnv
-> IO ()
-unload interp hsc_env
+unload interp0 hsc_env
= mask_ $ do -- mask, so we're safe from Ctrl-C in here
-- Initialise the linker (if it's not been done already)
- initLoaderState interp hsc_env
+ initLoaderState interp0 hsc_env
- _new_pls <- modifyLoaderState interp $ \pls -> do
+ _new_pls <- modifyLoaderState interp0 $ \interp pls -> do
pls1 <- unload_wkr interp pls
return (pls1, pls1)
@@ -1234,7 +1235,7 @@ showLS (BytecodeLibrary nm) = "(bytecode) " ++ nm
-- automatically, and it doesn't matter what order you specify the input
-- packages.
--
-loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
+loadPackages :: SafeInterp -> HscEnv -> [UnitId] -> IO ()
-- NOTE: in fact, since each module tracks all the packages it depends on,
-- we don't really need to use the package-config dependencies.
--
@@ -1243,11 +1244,11 @@ loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
-- perhaps makes the error message a bit more localised if we get a link
-- failure. So the dependency walking code is still here.
-loadPackages interp hsc_env new_pkgs = do
+loadPackages interp0 hsc_env new_pkgs = do
-- It's probably not safe to try to load packages concurrently, so we take
-- a lock.
- initLoaderState interp hsc_env
- modifyLoaderState_ interp $ \pls ->
+ initLoaderState interp0 hsc_env
+ modifyLoaderState_ interp0 $ \interp pls ->
loadPackages' interp hsc_env new_pkgs pls
-- | Compute 'LoadedPkgInfo' metadata (with transitive deps) for new packages,
=====================================
compiler/GHC/Runtime/Eval.hs
=====================================
@@ -468,7 +468,7 @@ resumeExec step mbCnt r = do
| otherwise -> pure prevHistoryLst
handleRunStatus step eval_opts expr bindings final_ids status =<< hist'
-setupBreakpoint :: GhcMonad m => Interp -> InternalBreakpointId -> Int -> m () -- #19157
+setupBreakpoint :: GhcMonad m => SafeInterp -> InternalBreakpointId -> Int -> m () -- #19157
setupBreakpoint interp ibi cnt = do
hug <- hsc_HUG <$> getSession
liftIO $ do
@@ -476,18 +476,18 @@ setupBreakpoint interp ibi cnt = do
breakArray <- getBreakArray interp ibi modBreaks
GHCi.storeBreakpoint interp breakArray (ibi_info_index ibi) cnt
-getBreakArray :: Interp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
+getBreakArray :: SafeInterp -> InternalBreakpointId -> InternalModBreaks -> IO (ForeignRef BreakArray)
getBreakArray interp InternalBreakpointId{ibi_info_mod} imbs = do
breaks0 <- bco_linked_breaks . homePackage_loaded . bco_loader_state . fromMaybe (panic "Loader not initialised") <$> getLoaderState interp
case lookupModuleEnv (breakarray_env breaks0) ibi_info_mod of
Just ba -> return ba
Nothing -> do
- modifyLoaderState interp $ \ld_st -> do
+ modifyLoaderState interp $ \interp' ld_st -> do
let lb = bco_linked_breaks . homePackage_loaded . bco_loader_state $ ld_st
-- Recall that BreakArrays are allocated only at BCO link time, so if we
-- haven't linked the BCOs we intend to break at yet, we allocate the arrays here.
- ba_env <- allocateBreakArrays interp (breakarray_env lb) [imbs]
+ ba_env <- allocateBreakArrays interp' (breakarray_env lb) [imbs]
let ld_st' = modifyBytecodeLoaderState modifyHomePackageBytecodeState ld_st $ \bco_state -> bco_state { bco_linked_breaks = (bco_linked_breaks bco_state) { breakarray_env = ba_env } }
let ba = expectJust {- just computed -} $ lookupModuleEnv ba_env ibi_info_mod
=====================================
compiler/GHC/Runtime/Interpreter.hs
=====================================
@@ -64,6 +64,9 @@ module GHC.Runtime.Interpreter
-- * Reexport for convenience
, Message (..)
, module GHC.Runtime.Interpreter.Process
+
+ -- * High-level interface to the interpreter
+ , withInterp
) where
import GHC.Prelude
@@ -107,6 +110,7 @@ import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Catch as MC (mask, handle, MonadThrow (..))
+import Control.Monad.STM
import Data.Binary
import Data.ByteString (ByteString)
import qualified Data.ByteString.Short as SBS
@@ -198,7 +202,7 @@ interpCmd interp msg = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> run msg -- Just run it directly
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst ->
+ ExternalInterp ext -> withExtInterp ext $ \inst ->
sendMessage inst msg
-- | Calls `interpCmd` and the continuation while masked.
@@ -208,13 +212,22 @@ interpCmd interp msg = case interpInstance interp of
withInterpCmdMasked :: Binary a => Interp -> Message a -> (a -> IO b) -> IO b
withInterpCmdMasked interp msg own = mask_ $ interpCmd interp msg >>= own
-withExtInterp :: ExceptionMonad m => Interp -> ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
-withExtInterp interp ext action = stopInterpOnPipeClosed $ case ext of
+-- | Passes the `Interp` to the continuation while setting up a
+-- 'PipeClosedException' handler that calls 'stopInterp'.
+--
+-- Will take the 'interpLoader' lock on a 'PipeClosedException'.
+withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
+withInterp interp0@(SafeInterp interp) k = stopInterpOnPipeClosed $ k interp
+ where
+ stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> do
+ liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0
+ MC.throwM e
+
+withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
+withExtInterp ext action = case ext of
ExtJS i -> withJSInterp i action
ExtWasm i -> withWasmInterp i action
ExtIServ i -> withIServ i action
- where
- stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> liftIO (stopInterp interp) >> MC.throwM e
withExtInterpStatus :: ExtInterp -> (forall d. ExtInterpStatusVar d -> m a) -> m a
withExtInterpStatus ext action = case ext of
@@ -294,11 +307,11 @@ withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do
-- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for
-- each of the results.
evalStmt
- :: Interp
+ :: SafeInterp
-> EvalOpts
-> EvalExpr ForeignHValue
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
-evalStmt interp opts foreign_expr = do
+evalStmt interp0 opts foreign_expr = withInterp interp0 $ \ interp -> do
status <- withExpr foreign_expr $ \expr ->
interpCmd interp (EvalStmt opts expr)
handleEvalStatus interp status
@@ -312,17 +325,17 @@ evalStmt interp opts foreign_expr = do
cont (EvalApp fl' fr')
resumeStmt
- :: Interp
+ :: SafeInterp
-> EvalOpts
-> ForeignRef (ResumeContext [HValueRef])
-> IO (EvalStatus_ [ForeignHValue] [HValueRef])
-resumeStmt interp opts resume_ctxt = do
+resumeStmt interp0 opts resume_ctxt = withInterp interp0 $ \interp -> do
status <- withForeignRef resume_ctxt $ \rhv ->
interpCmd interp (ResumeStmt opts rhv)
handleEvalStatus interp status
-abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
-abandonStmt interp resume_ctxt =
+abandonStmt :: SafeInterp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
+abandonStmt interp0 resume_ctxt = withInterp interp0 $ \ interp ->
withForeignRef resume_ctxt $ \rhv ->
interpCmd interp (AbandonStmt rhv)
@@ -341,20 +354,20 @@ handleEvalStatus interp status =
EvalSuccess <$> mapM (mkFinalizedHValue interp) rs
-- | Execute an action of type @IO ()@
-evalIO :: Interp -> ForeignHValue -> IO ()
-evalIO interp fhv =
+evalIO :: SafeInterp -> ForeignHValue -> IO ()
+evalIO interp0 fhv = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalIO fhv) >>= fromEvalResult
-- | Execute an action of type @IO String@
-evalString :: Interp -> ForeignHValue -> IO String
-evalString interp fhv =
+evalString :: SafeInterp -> ForeignHValue -> IO String
+evalString interp0 fhv = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalString fhv) >>= fromEvalResult
-- | Execute an action of type @String -> IO String@
-evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String
-evalStringToIOString interp fhv str =
+evalStringToIOString :: SafeInterp -> ForeignHValue -> String -> IO String
+evalStringToIOString interp0 fhv str = withInterp interp0 $ \ interp ->
liftIO $ withForeignRef fhv $ \fhv ->
interpCmd interp (EvalStringToString fhv str) >>= fromEvalResult
@@ -388,44 +401,44 @@ addHpcModule :: Interp -> SBS.ShortByteString -> Int -> Int -> SBS.ShortByteStri
addHpcModule interp modLabel tickNo hash tickboxes =
interpCmd interp (AddHpcModule modLabel tickNo hash tickboxes)
-costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String]
-costCentreStackInfo interp ccs =
+costCentreStackInfo :: SafeInterp -> RemotePtr CostCentreStack -> IO [String]
+costCentreStackInfo interp0 ccs = withInterp interp0 $ \interp ->
interpCmd interp (CostCentreStackInfo ccs)
newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray)
newBreakArray interp size =
withInterpCmdMasked interp (NewBreakArray size) (mkFinalizedHValue interp)
-storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO ()
-storeBreakpoint interp ref ix cnt = do -- #19157
+storeBreakpoint :: SafeInterp -> ForeignRef BreakArray -> Int -> Int -> IO ()
+storeBreakpoint interp0 ref ix cnt = withInterp interp0 $ \ interp -> do -- #19157
withForeignRef ref $ \breakarray ->
interpCmd interp (SetupBreakpoint breakarray ix cnt)
-breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool
-breakpointStatus interp ref ix =
+breakpointStatus :: SafeInterp -> ForeignRef BreakArray -> Int -> IO Bool
+breakpointStatus interp0 ref ix = withInterp interp0 $ \ interp ->
withForeignRef ref $ \breakarray ->
interpCmd interp (BreakpointStatus breakarray ix)
-getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
-getBreakpointVar interp ref ix =
+getBreakpointVar :: SafeInterp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
+getBreakpointVar interp0 ref ix = withInterp interp0 $ \ interp ->
withForeignRef ref $ \apStack ->
withInterpCmdMasked interp (GetBreakpointVar apStack ix)
(mapM (mkFinalizedHValue interp))
-getClosure :: Interp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
-getClosure interp ref =
+getClosure :: SafeInterp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)
+getClosure interp0 ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval ->
withInterpCmdMasked interp (GetClosure hval) $
mapM (mkFinalizedHValue interp)
-whereFrom :: Interp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
-whereFrom interp ref =
+whereFrom :: SafeInterp -> ForeignHValue -> IO (Maybe InfoProv.InfoProv)
+whereFrom interp0 ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
interpCmd interp (WhereFrom hval)
-- | Send a Seq message to the iserv process to force a value #2950
-seqHValue :: Interp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
-seqHValue interp unit_env logger ref =
+seqHValue :: SafeInterp -> UnitEnv -> Logger -> ForeignHValue -> IO (EvalResult ())
+seqHValue interp0 unit_env logger ref = withInterp interp0 $ \ interp ->
withForeignRef ref $ \hval -> do
status <- interpCmd interp (Seq hval)
handleSeqHValueStatus interp unit_env logger status
@@ -649,23 +662,35 @@ spawnIServ conf = do
pure inst
-- | Stop the interpreter
-stopInterp :: Interp -> IO ()
-stopInterp interp = case interpInstance interp of
+stopInterp :: SafeInterp -> IO ()
+stopInterp = stopInterpWhen (const $ pure True)
+
+-- | Stop the interpreter if predicate returns 'True'.
+stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO ()
+stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> pure ()
#endif
- ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> do
- MC.mask $ \restore -> modifyMVar mstate $ \state -> do
+ ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do
+ -- takes interpLoader lock before ExternalInterp lock to avoid deadlocks.
+ -- commits emptied values before 'gracefulShutdown' so we don't hold locks
+ -- more than necessary.
+ mi <- modifyMVar (loader_state (interpLoader interp)) $ \l_st -> do
+ modifyMVar mstate $ \state -> do
case state of
- InterpPending -> pure (state, Nothing) -- already stopped
- InterpRunning i -> do
- e <- getProcessExitCode (interpHandle (instProcess i)) >>= \case
- Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
- Nothing -> gracefulShutdown i restore
- modifyMVar_ (loader_state (interpLoader interp)) (const $ pure Nothing)
- purgeInterpSymbolCache (interpSymbolCache interp)
- modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
- pure (InterpPending,e)
+ InterpPending -> pure (state, (l_st, Nothing)) -- already stopped
+ InterpRunning i -> shouldStop (instProcess i) >>= \case
+ False -> pure (state, (l_st, Nothing))
+ True -> do
+ purgeInterpSymbolCache (interpSymbolCache interp)
+ modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
+ pure (InterpPending,(Nothing,Just i))
+ case mi of
+ Nothing -> pure Nothing
+ Just i -> getProcessExitCode (interpHandle (instProcess i)) >>= \case
+ Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
+ Nothing -> gracefulShutdown i restore
+
where
gracefulShutdown i restore = do
x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i)))))
@@ -731,7 +756,7 @@ principle it would probably be ok, but it seems less hairy this way.
-- | Creates a 'ForeignRef' that will automatically release the
-- 'RemoteRef' when it is no longer referenced.
-mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a)
+mkFinalizedHValue :: HasInterpInstance i => i -> RemoteRef a -> IO (ForeignRef a)
mkFinalizedHValue interp rref = do
case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
@@ -754,13 +779,13 @@ freeHValueRefs interp refs = interpCmd interp (FreeHValueRefs refs)
-- | Convert a 'ForeignRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
-wormhole :: Interp -> ForeignRef a -> IO a
+wormhole :: SafeInterp -> ForeignRef a -> IO a
wormhole interp r = wormholeRef interp (unsafeForeignRefToRemoteRef r)
-- | Convert an 'RemoteRef' to the value it references directly. This
-- only works when the interpreter is running in the same process as
-- the compiler, so it fails when @-fexternal-interpreter@ is on.
-wormholeRef :: Interp -> RemoteRef a -> IO a
+wormholeRef :: SafeInterp -> RemoteRef a -> IO a
wormholeRef interp _r = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> localRef _r
=====================================
compiler/GHC/Runtime/Interpreter/Init.hs
=====================================
@@ -29,7 +29,9 @@ import GHC.Utils.Monad
import GHC.Utils.Outputable
import GHC.Utils.Logger
import GHC.Utils.Error
+
import Control.Concurrent
+import Data.Coerce
import System.Process
data InterpOpts = InterpOpts
@@ -67,8 +69,8 @@ initInterpreter
-> FinderCache
-> UnitEnv
-> InterpOpts
- -> IO (Maybe Interp)
-initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = do
+ -> IO (Maybe SafeInterp)
+initInterpreter dflags tmpfs logger platform finder_cache unit_env opts = coerce $ do
lookup_cache <- liftIO $ mkInterpSymbolCache
=====================================
compiler/GHC/Runtime/Interpreter/Types.hs
=====================================
@@ -4,6 +4,8 @@
-- | Types used by the runtime interpreter
module GHC.Runtime.Interpreter.Types
( Interp(..)
+ , SafeInterp(..)
+ , HasInterpInstance(..)
, InterpInstance(..)
, InterpProcess (..)
, ExtInterp (..)
@@ -66,9 +68,36 @@ import System.Process ( ProcessHandle, CreateProcess )
import System.IO
import GHC.Unit.Finder.Types (FinderCache, FinderOpts)
+{-
+Note [Interpreter locks order]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+To avoid deadlocks, the 'interpLoader' lock should be taken before the lock that
+contains the 'InterpStatus'.
+
+Further, you should wrap the code that takes the 'interpLoader' lock with
+'withInterp', as it will cleanup the whole interpreter state in case the
+external interpreter pipe died:
+```
+withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
+```
+
+'SafeInterp' is a newtype introduced to aid with the discipline: only code that
+has ownership over a 'SafeInterp' should take its 'interpLoader' lock.
+
+-}
+
+
+
+
+-- | An 'Interp' where we have not taken the 'interpLoader' lock in this thread.
+--
+-- See Note [Interpreter locks order]
+newtype SafeInterp = SafeInterp Interp
+
-- | Interpreter
data Interp = Interp
- { interpInstance :: !InterpInstance
+ { _interpInstance :: !InterpInstance
-- ^ Interpreter instance (internal, external)
, interpLoader :: !Loader
@@ -81,6 +110,13 @@ data Interp = Interp
-- ^ MallocStrings cache
}
+class HasInterpInstance a where
+ interpInstance :: a -> InterpInstance
+instance HasInterpInstance SafeInterp where
+ interpInstance (SafeInterp interp) = interpInstance interp
+instance HasInterpInstance Interp where
+ interpInstance = _interpInstance
+
data InterpInstance
= ExternalInterp !ExtInterp -- ^ External interpreter
#if defined(HAVE_INTERNAL_INTERPRETER)
@@ -143,7 +179,7 @@ data ExtInterpInstance c = ExtInterpInstance
}
-- | Interpreter uses Profiling way
-interpreterProfiled :: Interp -> Bool
+interpreterProfiled :: HasInterpInstance a => a -> Bool
interpreterProfiled interp = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> hostIsProfiled
@@ -154,7 +190,7 @@ interpreterProfiled interp = case interpInstance interp of
ExtWasm i -> wasmInterpProfiled $ interpConfig i
-- | Interpreter uses Dynamic way
-interpreterDynamic :: Interp -> Bool
+interpreterDynamic :: HasInterpInstance a => a -> Bool
interpreterDynamic interp = case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> hostIsDynamic
=====================================
compiler/GHC/Runtime/Loader.hs
=====================================
@@ -283,7 +283,7 @@ getValueSafely hsc_env val_name expected_type = do
logger = hsc_logger hsc_env
hooks = hsc_hooks hsc_env
-getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
+getHValueSafely :: SafeInterp -> HscEnv -> Name -> Type -> IO (Either Type (HValue, [LinkableUsage], PkgsLoaded))
getHValueSafely interp hsc_env val_name expected_type = do
forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name
-- Now look up the names for the value and type constructor in the type environment
=====================================
compiler/GHC/Tc/Gen/Splice.hs
=====================================
@@ -1151,16 +1151,16 @@ runRemoteModFinalizers (ThModFinalizers finRefs) = do
let withForeignRefs [] f = f []
withForeignRefs (x : xs) f = withForeignRef x $ \r ->
withForeignRefs xs $ \rs -> f (r : rs)
- interp <- tcGetInterp
+ interp0 <- tcGetInterp
- case interpInstance interp of
+ withInterp interp0 $ \interp -> case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> do
qs <- liftIO (withForeignRefs finRefs $ mapM localRef)
runQinTcM $ sequence_ qs
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
+ ExternalInterp ext -> withExtInterp ext $ \inst -> do
tcg <- getGblEnv
th_state <- readTcRef (tcg_th_remote_state tcg)
case th_state of
@@ -1807,17 +1807,17 @@ runTHDec = runTH THDec
runTH :: Binary a => THResultType -> ForeignHValue -> TcM a
runTH ty fhv = do
- interp <- tcGetInterp
- case interpInstance interp of
+ interp0 <- tcGetInterp
+ withInterp interp0 $ \ interp -> case interpInstance interp of
#if defined(HAVE_INTERNAL_INTERPRETER)
InternalInterp -> do
-- Run it in the local TcM
- hv <- liftIO $ wormhole interp fhv
+ hv <- liftIO $ wormhole interp0 fhv
r <- runQinTcM (unsafeCoerce hv :: TH.Q a)
return r
#endif
- ExternalInterp ext -> withExtInterp interp ext $ \inst -> do
+ ExternalInterp ext -> withExtInterp ext $ \inst -> do
-- Run it on the server. For an overview of how TH works with
-- Remote GHCi, see Note [Remote Template Haskell] in
-- libraries/ghci/GHCi/TH.hs.
@@ -3031,7 +3031,7 @@ mkThAppTs fun_ty arg_tys = foldl' TH.AppT fun_ty arg_tys
noTH :: UnrepresentableTypeDescr -> Type -> TcM a
noTH s d = failWithTc $ TcRnTHError $ THReifyError $ CannotRepresentType s d
-tcGetInterp :: TcM Interp
+tcGetInterp :: TcM SafeInterp
tcGetInterp = do
hsc_env <- getTopEnv
case hsc_interp hsc_env of
=====================================
ghc/GHCi/UI/Monad.hs
=====================================
@@ -475,8 +475,8 @@ printStats dflags ActionStats{actionAllocs = mallocs, actionElapsedTime = secs}
revertCAFs :: GhciMonad m => m ()
revertCAFs = do
- interp <- hscInterp <$> GHC.getSession
- liftIO $ interpCmd interp RtsRevertCAFs
+ interp0 <- hscInterp <$> GHC.getSession
+ liftIO $ withInterp interp0 $ \interp -> interpCmd interp RtsRevertCAFs
s <- getGHCiState
when (not (ghc_e s)) turnOffBuffering
-- Have to turn off buffering again, because we just
=====================================
libraries/ghci/GHCi/Message.hs
=====================================
@@ -27,7 +27,7 @@ module GHCi.Message
, QState(..)
, getMessage, putMessage, getTHMessage, putTHMessage
- , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe
+ , Pipe(..), mkPipeFromHandles, mkPipeFromContinuations, closePipe, isPipeOpen
, remoteCall, remoteCallInterleaving, remoteTHCall
, handleRemoteCall, handleRemoteTHCall, writeReply
, RemoteProcessException(..), PipeClosedException(..)
=====================================
libraries/ghci/GHCi/Message/Async.hs
=====================================
@@ -8,6 +8,7 @@ module GHCi.Message.Async
-- * Pipes
Pipe(..), mkPipeFromHandles, mkPipeFromContinuations
, closePipe, PipeClosedException(..)
+ , closingPipe, isPipeOpen
-- * Interface for async bidirectional RPC
, remoteAsyncReq, handleAsyncReq
@@ -31,7 +32,7 @@ module GHCi.Message.Async
-- * Serializable exceptions
, SerializableException(..)
- , toSerializableException, fromSerializableException, closingPipe
+ , toSerializableException, fromSerializableException
) where
import Prelude -- See note [Why do we import Prelude here?]
@@ -159,6 +160,11 @@ closePipe Pipe{..} = do
throwTo (asyncFillTid pipeAsyncMngr) PipeWriteClosedException
`finally` throwTo (asyncDrainTid pipeAsyncMngr) PipeReadClosedException
+isPipeOpen :: Pipe -> STM Bool
+isPipeOpen pipe = liftM2 (&&)
+ (isOpen <$> readTVar (pipeReadStatus pipe))
+ (isOpen <$> readTVar (pipeWriteStatus pipe))
+
closingPipeEnd :: TVar PipeEndStatus -> STM PipeEndStatus
closingPipeEnd v = readTVar v >>= \ s -> do
case s of
=====================================
testsuite/tests/ghci/interp-cancellation/all.T
=====================================
@@ -8,3 +8,14 @@ test('interp-cancellation',
],
multimod_compile_and_run,
['Main.hs', '-package ghc -package ghci'])
+
+test('interp-concurrent',
+ [ extra_run_opts(f'"{config.libdir}"')
+ , windows_skip
+ , when(config.cross, skip)
+ , req_th
+ , unless(config.have_ext_interp, skip)
+ , only_ways(['normal'])
+ ],
+ compile_and_run,
+ ['-package ghc -threaded'])
=====================================
testsuite/tests/ghci/interp-cancellation/interp-concurrent.hs
=====================================
@@ -0,0 +1,271 @@
+{-# LANGUAGE LambdaCase, ScopedTypeVariables #-}
+
+-- | Several threads share one GHC session, and so one external interpreter.
+--
+-- Checks that concurrent requests get their own replies, that killing threads
+-- waiting on the interpreter leaves it usable, that killing a thread running a
+-- splice cancels the splice in the interpreter, and that when the interpreter
+-- dies it is stopped and the next request starts a new one.
+module Main (main) where
+
+import Control.Concurrent
+import Control.Exception
+import Control.Monad
+import Control.Monad.IO.Class (liftIO)
+import Data.Either (isLeft)
+import Data.Maybe (isJust, isNothing)
+import System.Directory (doesFileExist, removeFile)
+import System.Environment (getArgs)
+import System.Exit (exitFailure)
+import System.IO
+import System.Posix.Signals (sigKILL, signalProcess)
+import System.Process (ProcessHandle, getPid, getProcessExitCode)
+import System.Timeout (timeout)
+
+import GHC
+import GHC.Driver.Env (hscInterp)
+import GHC.Driver.Monad (Session, reflectGhc, reifyGhc)
+import GHC.Driver.Session (gopt_set, xopt_set)
+import qualified GHC.LanguageExtensions as LangExt
+import GHC.Runtime.Interpreter (evalString, evalStringToIOString)
+import GHC.Runtime.Interpreter.Types
+import GHCi.Message (PipeClosedException)
+
+main :: IO ()
+main = do
+ hSetBuffering stdout LineBuffering
+ [libdir] <- getArgs
+ mapM_ removeIfExists markers
+ runGhc (Just libdir) $ do
+ -- compileExprRemote parses with the interactive flags but typechecks with
+ -- the session ones, so TH goes in both. xopt_set doesn't add implied
+ -- extensions, so the quotes one is set too.
+ let withTH fs = foldl xopt_set fs
+ [LangExt.TemplateHaskell, LangExt.TemplateHaskellQuotes]
+ dflags <- getSessionDynFlags
+ _ <- setSessionDynFlags (withTH (gopt_set dflags Opt_ExternalInterpreter))
+ { ghcLink = LinkInMemory }
+ getInteractiveDynFlags >>= setInteractiveDynFlags . withTH
+ setContext [ IIDecl (simpleImportDecl (mkModuleName m))
+ | m <- [ "Prelude", "Control.Concurrent", "Control.Exception"
+ , "System.IO", "System.IO.Error", "Language.Haskell.TH" ] ]
+ reifyGhc $ \s -> do
+ concurrentReplies s
+ killWaiting s
+ killSplice s
+ interpreterDies s
+
+--------------------------------------------------------------------------------
+-- Scenarios
+
+concurrentReplies :: Session -> IO ()
+concurrentReplies s = do
+ echo <- compile s echoExpr
+ ws <- forM [1 .. 16 :: Int] $ \n -> async $
+ forM [1 .. 50 :: Int] $ \k -> do
+ let x = show (n, k)
+ (== reverse x) <$> evalEcho s echo x
+ rs <- mapM (within "concurrent requests" . readMVar . snd) ws
+ check "concurrent requests each get their own reply"
+ (all (either (const False) and) rs)
+
+-- | Kill threads waiting on two gated requests, and check a third request
+-- made alongside them still gets its reply.
+--
+-- Whether the interpreter runs b behind a or alongside it, and whether it
+-- interrupts a cancelled one, b is still waiting when killed. The gates only
+-- open after the kills, so whatever is still running in the interpreter can
+-- finish and let c through.
+killWaiting :: Session -> IO ()
+killWaiting s = do
+ echo <- compile s echoExpr
+ -- Compiled up front: compiling needs the interpreter, which a may hold up.
+ bAct <- compile s (gated "b.started" "b.gate" "pure \"b\"")
+ (a, aRes) <- async $ inSession s $
+ execStmt (gated "a.started" "a.gate" "pure ()") execOptions
+ awaitStarted "the statement to start" "a.started" aRes
+ (b, bRes) <- async $ evalFHV s bAct
+ (_, cRes) <- async $ evalEcho s echo "c"
+ threadDelay 100000 -- let b and c send their requests
+ within "killing the thread waiting on the statement" (killThread a)
+ within "killing the thread waiting on the other one" (killThread b)
+ aR <- within "the killed statement thread to finish" (readMVar aRes)
+ bR <- within "the other killed thread to finish" (readMVar bRes)
+ check "killed threads stop waiting for their replies"
+ (isKilled aR && isKilled bR)
+ mapM_ (`writeFile` "") ["a.gate", "b.gate"]
+ cR <- within "the remaining request's reply" (readMVar cRes)
+ check "a request made alongside cancelled ones gets its reply"
+ (either (const False) (== reverse "c") cR)
+ stillAnswers s echo
+
+-- | Splices run in their own thread in the interpreter, so they don't hold up
+-- other requests, and can be cancelled there.
+killSplice :: Session -> IO ()
+killSplice s = do
+ echo <- compile s echoExpr
+ (t, tRes) <- async $ inSession s $
+ compileExprRemote (blockingSplice "th.started" "th.cancelled")
+ awaitStarted "the splice to start" "th.started" tRes
+ r <- within "a request while a splice runs" (evalEcho s echo "during splice")
+ check "a running splice does not hold up other requests"
+ (r == reverse "during splice")
+ within "killing the thread running the splice" (killThread t)
+ tR <- within "the killed splice thread to finish" (readMVar tRes)
+ check "the thread running the splice is killed" (isKilled tR)
+ awaitFile "the splice to be cancelled in the interpreter" "th.cancelled"
+ check "the splice is cancelled in the interpreter" True
+ stillAnswers s echo
+
+-- | Kill the interpreter while one thread waits on a statement and another
+-- runs a splice.
+interpreterDies :: Session -> IO ()
+interpreterDies s = do
+ _ <- compile s echoExpr
+ ph <- runningInterp s >>= maybe (failWith "no interpreter running") pure
+ pid <- getPid ph >>= maybe (failWith "interpreter has no pid") pure
+
+ -- Splice first: compiling it needs the interpreter, which the statement
+ -- may hold up.
+ (_, fRes) <- async $ inSession s $
+ compileExprRemote (blockingSplice "f.started" "f.cancelled")
+ awaitStarted "the splice to start" "f.started" fRes
+ (_, dRes) <- async $ evalIn s (gated "d.started" "d.gate" "pure \"d\"")
+ awaitStarted "the statement to start" "d.started" dRes
+
+ signalProcess sigKILL pid
+ dR <- within "the statement thread to fail" (readMVar dRes)
+ check "a thread waiting on a dead interpreter gets PipeClosedException"
+ (isPipeClosed dR)
+ fR <- within "the splice thread to fail" (readMVar fRes)
+ check "a thread running a splice in a dead interpreter fails" (isLeft fR)
+
+ st <- runningInterp s
+ check "the dead interpreter is stopped" (isNothing st)
+ ex <- getProcessExitCode ph
+ check "its process is reaped" (isJust ex)
+
+ r <- within "a request after the interpreter died"
+ (evalIn s "pure \"alive\" :: IO String")
+ check "the next request starts a new interpreter" (r == "alive")
+ ph' <- runningInterp s >>= maybe (failWith "no interpreter running") pure
+ pid' <- getPid ph'
+ check "the new interpreter is a different process" (pid' /= Just pid)
+
+--------------------------------------------------------------------------------
+-- Talking to the interpreter through the session
+
+inSession :: Session -> Ghc a -> IO a
+inSession = flip reflectGhc
+
+compile :: Session -> String -> IO ForeignHValue
+compile s e = inSession s (compileExprRemote e)
+
+-- | Compile an @IO String@ and run it.
+evalIn :: Session -> String -> IO String
+evalIn s e = compile s e >>= evalFHV s
+
+-- | Run a compiled @IO String@.
+evalFHV :: Session -> ForeignHValue -> IO String
+evalFHV s fhv = inSession s $ do
+ hsc_env <- getSession
+ liftIO (evalString (hscInterp hsc_env) fhv)
+
+evalEcho :: Session -> ForeignHValue -> String -> IO String
+evalEcho s echo x = inSession s $ do
+ hsc_env <- getSession
+ liftIO (evalStringToIOString (hscInterp hsc_env) echo x)
+
+stillAnswers :: Session -> ForeignHValue -> IO ()
+stillAnswers s echo = do
+ r <- within "a request after the cancellations" (evalEcho s echo "after")
+ check "the interpreter still answers" (r == reverse "after")
+
+runningInterp :: Session -> IO (Maybe ProcessHandle)
+runningInterp s = do
+ interp <- inSession s (hscInterp <$> getSession)
+ case interpInstance interp of
+ ExternalInterp (ExtIServ st) -> readMVar (interpStatus st) >>= \case
+ InterpRunning inst -> pure (Just (interpHandle (instProcess inst)))
+ InterpPending -> pure Nothing
+ _ -> failWith "not using an external interpreter"
+
+--------------------------------------------------------------------------------
+-- Interpreted code
+
+echoExpr :: String
+echoExpr = "(\\x -> pure (reverse x)) :: String -> IO String"
+
+-- | Creates @started@, waits for @gate@ to exist, then runs @k@.
+gated :: FilePath -> FilePath -> String -> String
+gated started gate k = concat
+ [ "let { waitFor p = catchIOError (withFile p ReadMode (\\_ -> pure ()))"
+ , " (\\_ -> threadDelay 10000 >> waitFor p) }"
+ , " in writeFile ", show started, " \"\" >> waitFor ", show gate, " >> ", k ]
+
+-- | Creates @started@, then blocks. Creates @cancelled@ if interrupted.
+blockingSplice :: FilePath -> FilePath -> String
+blockingSplice started cancelled = concat
+ [ "$(runIO (writeFile ", show started, " \"\""
+ , " >> (threadDelay 100000000 `onException` writeFile ", show cancelled, " \"\"))"
+ , " >> [| () |])" ]
+
+markers :: [FilePath]
+markers = [ "a.started", "a.gate", "b.started", "b.gate"
+ , "th.started", "th.cancelled"
+ , "d.started", "d.gate", "f.started", "f.cancelled" ]
+
+--------------------------------------------------------------------------------
+-- Utilities
+
+async :: IO a -> IO (ThreadId, MVar (Either SomeException a))
+async act = do
+ v <- newEmptyMVar
+ t <- forkFinally act (putMVar v)
+ pure (t, v)
+
+awaitFile :: String -> FilePath -> IO ()
+awaitFile what p = within what loop
+ where
+ loop = doesFileExist p >>= \b -> unless b (threadDelay 10000 >> loop)
+
+-- | Like 'awaitFile', but fails straight away if the thread that should
+-- create the file ends first.
+awaitStarted :: String -> FilePath -> MVar (Either SomeException a) -> IO ()
+awaitStarted what p res = within what loop
+ where
+ loop = do
+ b <- doesFileExist p
+ unless b $ tryReadMVar res >>= \case
+ Just r -> failWith ("waiting for " ++ what ++ ", the thread ended: "
+ ++ either show (const "no exception") r)
+ Nothing -> threadDelay 10000 >> loop
+
+removeIfExists :: FilePath -> IO ()
+removeIfExists p = removeFile p `catch` \(_ :: IOException) -> pure ()
+
+isKilled :: Either SomeException a -> Bool
+isKilled = \case
+ Left e | Just ThreadKilled <- fromException e -> True
+ _ -> False
+
+isPipeClosed :: Either SomeException a -> Bool
+isPipeClosed = \case
+ Left e | Just (_ :: PipeClosedException) <- fromException e -> True
+ _ -> False
+
+-- | Fail rather than hang.
+within :: String -> IO a -> IO a
+within what act =
+ timeout (60 * 1000000) act >>= maybe (failWith ("timed out waiting for " ++ what)) pure
+
+failWith :: String -> IO a
+failWith what = do
+ hPutStrLn stderr ("FAILED: " ++ what)
+ hFlush stderr
+ exitFailure
+
+check :: String -> Bool -> IO ()
+check what ok
+ | ok = putStrLn ("ok: " ++ what)
+ | otherwise = void (failWith what)
=====================================
testsuite/tests/ghci/interp-cancellation/interp-concurrent.stdout
=====================================
@@ -0,0 +1,14 @@
+ok: concurrent requests each get their own reply
+ok: killed threads stop waiting for their replies
+ok: a request made alongside cancelled ones gets its reply
+ok: the interpreter still answers
+ok: a running splice does not hold up other requests
+ok: the thread running the splice is killed
+ok: the splice is cancelled in the interpreter
+ok: the interpreter still answers
+ok: a thread waiting on a dead interpreter gets PipeClosedException
+ok: a thread running a splice in a dead interpreter fails
+ok: the dead interpreter is stopped
+ok: its process is reaped
+ok: the next request starts a new interpreter
+ok: the new interpreter is a different process
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/a30a4599674b3609cc5701cb17247e…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/a30a4599674b3609cc5701cb17247e…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/andreask/cfg-fix] 2 commits: x86 ncg: Track the current block in NatM to keep the CFG in sync
by Sylvain Henry (@hsyl20) 17 Nov '26
by Sylvain Henry (@hsyl20) 17 Nov '26
17 Nov '26
Sylvain Henry pushed to branch wip/andreask/cfg-fix at Glasgow Haskell Compiler / GHC
Commits:
1540fd6b by Andreas Klebinger at 2026-11-17T12:15:21+01:00
x86 ncg: Track the current block in NatM to keep the CFG in sync
The x86 NCG uses a CFG for code layout. When instruction selection
makes new blocks (word2Float#, cmpxchg loops, 64-bit shifts on i386),
it must add them to the CFG. Some sites did not. The CFG went out of
sync, the layout was bad, and the register allocator panicked when it
added fixup blocks (#27694, #27915).
NatM now keeps the current block in its state. Combinators update the
CFG and the current block together. See Note [Updating the CFG during
CodeGen] in GHC.CmmToAsm.Monad.
Other changes:
* -dasm-lint checks that the jumps in the code and the edges in the
CFG agree in both directions. This found a second desync: the CFG
did not follow the jumps that allocMoreStack retargets. The new
addPreentryBlock fixes it.
* The code must be emitted in generation order, because the CFG
records new blocks in that order. A store now generates the code of
its value before the code of its address, in the order it emits
them. Atomic operations take their address from the new
getNonClobberedAmode, so the code of their other operands cannot
clobber it.
Fixes #27694, #27915
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
e07bdf0b by Sylvain Henry at 2026-11-17T12:15:21+01:00
x86 ncg: Maintain the CFG on i386
The i386 NCG now keeps its CFG in sync with the code (see the previous
commit), so backendMaintainsCfg is now True for i386. i386 gets the
CFG based code layout, dead code elimination and the -dasm-lint check,
like x86-64.
The compiler allocates more on i386: the CFG now goes through the
register allocator, branch shortcutting and optimizeCFG, which i386
skipped before. x86-64 already does this work.
Metric Increase:
CoOpt_Read
ManyAlternatives
T10421
T12425
T12707
T13056
T13253
T13253-spj
T13960
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T19695
T20049
T21839c
T24471
T26425
T26989
T5642
T6048
T783
T9233
T9630
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
17 changed files:
- + changelog.d/27694
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- + testsuite/tests/codeGen/should_compile/T27694.hs
- + testsuite/tests/codeGen/should_compile/T27694d.hs
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_run/T27694b.hs
- + testsuite/tests/codeGen/should_run/T27694b.stdout
- + testsuite/tests/codeGen/should_run/T27915.hs
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-32
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-64
- testsuite/tests/codeGen/should_run/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1d72b2358d7022970ee1aceb9c85a0…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1d72b2358d7022970ee1aceb9c85a0…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
Simon Peyton Jones pushed to branch wip/T28135 at Glasgow Haskell Compiler / GHC
Commits:
15ab4a00 by Simon Peyton Jones at 2026-11-17T11:15:51+00:00
Fix a zonking bug
As #28135 showed, we were failing to zonk some type-variable
binders before doing scoped-sort dependency analysis, resulting
in chaos.
The fix is easy.
- - - - -
6 changed files:
- + changelog.d/T28135
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/TyCl.hs
- + testsuite/tests/typecheck/should_compile/T28135.hs
- testsuite/tests/typecheck/should_compile/all.T
Changes:
=====================================
changelog.d/T28135
=====================================
@@ -0,0 +1,8 @@
+section: compiler
+issues: #28135
+mrs: !17006
+synopsis:
+ Fix a bug in kind inference in data constructors
+description:
+ This bug affected only data constructors using kind polymorphism,
+ and declared in GADT style.
=====================================
compiler/GHC/Tc/Gen/HsType.hs
=====================================
@@ -29,7 +29,6 @@ module GHC.Tc.Gen.HsType (
bindOuterFamEqnTKBndrs_Q_Tv, bindOuterFamEqnTKBndrs,
tcOuterTKBndrs, scopedSortOuter, outerTyVars, outerTyVarBndrs,
- tcGadtConTyVarBndrs,
bindOuterSigTKBndrs_Tv,
tcExplicitTKBndrs,
bindNamedWildCardBinders,
@@ -3545,20 +3544,6 @@ tcOuterTKBndrsX skol_mode skol_info outer_bndrs thing_inside
, hso_bndrs = exp_bndrs }
, thing) }
----------------
-tcGadtConTyVarBndrs :: SkolemInfo
- -> HsOuterSigTyVarBndrs GhcRn
- -> [LHsGadtTelescope GhcRn]
- -> TcM a -> TcM ([TcTyVarBinder], a)
-tcGadtConTyVarBndrs skol_info outer inner thing_inside
- = do { (outer_bndrs, (inner_tvbs, a)) <-
- tcOuterTKBndrs skol_info outer $
- tcExplicitTKBndrs skol_info (gadtTelescopeBndrs inner) $
- thing_inside
- ; outer_bndrs <- scopedSortOuter outer_bndrs
- ; let outer_tvbs = tyVarSpecToBinders (outerTyVarBndrs outer_bndrs)
- ; return (outer_tvbs ++ inner_tvbs, a) }
-
--------------------------------------
-- Explicit tyvar binders
--------------------------------------
=====================================
compiler/GHC/Tc/Solver.hs
=====================================
@@ -187,7 +187,7 @@ pushLevelAndSolveEqualitiesX callsite thing_inside
do { (res, wanted) <- captureConstraints thing_inside
; wanted <- runTcSEqualities (simplifyTopWanteds wanted)
; return (wanted,res) }
- ; traceTc "pushLevelAndSolveEqualities }" (vcat [ text "Residual:" <+> ppr wanted
+ ; traceTc "pushLevelAndSolveEqualitiesX }" (vcat [ text "Residual:" <+> ppr wanted
, text "Level:" <+> ppr tclvl ])
; return (tclvl, wanted, res) }
=====================================
compiler/GHC/Tc/TyCl.hs
=====================================
@@ -4185,12 +4185,16 @@ tcConDecl new_or_data dd_info rep_tycon tc_bndrs _res_kind tag_map
, con_cxts = cxts, con_g_args = hs_args
, con_res_ty = hs_res_ty })
= addErrCtxt (DataConDefCtxt names) $
- do { traceTc "tcConDecl 1 gadt" (ppr names)
+ do { traceTc "tcConDecl 1 gadt" $
+ vcat [ text "data con names:" <+> ppr names
+ , text "outer_bndrs:" <+> ppr outer_bndrs
+ , text "inner_bndrs:" <+> ppr inner_bndrs ]
; let L _ name :| _ = names
; skol_info <- mkSkolemInfo (DataConSkol name)
- ; (tclvl, wanted, (tvbs, (ctxt, arg_tys, res_ty, field_lbls, stricts)))
- <- pushLevelAndSolveEqualitiesX "tcConDecl:GADT" $
- tcGadtConTyVarBndrs skol_info outer_bndrs inner_bndrs $
+ ; (tclvl, wanted, (tc_outer, (inner_tvbs, (ctxt, arg_tys, res_ty, field_lbls, stricts))))
+ <- pushLevelAndSolveEqualitiesX "tcConDecl:GADT" $
+ tcOuterTKBndrs skol_info outer_bndrs $
+ tcExplicitTKBndrs skol_info (gadtTelescopeBndrs inner_bndrs) $
do { ctxt <- tcHsContext cxts
; (res_ty, res_kind) <- tcInferLHsTypeKind hs_res_ty
-- See Note [GADT return kinds]
@@ -4217,11 +4221,16 @@ tcConDecl new_or_data dd_info rep_tycon tc_bndrs _res_kind tag_map
; return (ctxt, arg_tys, res_ty, field_lbls, stricts)
}
+ -- Must do this scopedSortOut /after/ solving the equalities (#28135)
+ ; tc_outer <- scopedSortOuter tc_outer
+ ; let outer_tvbs = tyVarSpecToBinders (outerTyVarBndrs tc_outer)
+ tvbs = outer_tvbs ++ inner_tvbs
+
; inf_tkvs <- kindGeneralizeAll skol_info
- (mkForAllTys tvbs $
- tcMkPhiTy ctxt $
- tcMkScaledFunTys arg_tys $
- res_ty)
+ (mkForAllTys tvbs $
+ tcMkPhiTy ctxt $
+ tcMkScaledFunTys arg_tys $
+ res_ty)
; traceTc "tcConDecl:GADT" (ppr names $$ ppr res_ty $$ ppr inf_tkvs)
; reportUnsolvedEqualities skol_info inf_tkvs tclvl wanted
=====================================
testsuite/tests/typecheck/should_compile/T28135.hs
=====================================
@@ -0,0 +1,10 @@
+{-# LANGUAGE GADTs, TypeFamilies #-}
+
+-- GHC 9.14.1 panics with "updateRole" when compiling this module.
+-- Compiles fine with GHC 9.12 (but by a fluke)
+module T28135 where
+
+data S t where
+ W :: C f => (forall (a :: k). S (t a)) -> S (t f)
+
+class C f
=====================================
testsuite/tests/typecheck/should_compile/all.T
=====================================
@@ -975,3 +975,4 @@ test('T26543_orig', normal, compile, [''])
test('T27994', normal, compile, [''])
test('T27994a', normal, compile, [''])
test('T27994b', normal, compile, [''])
+test('T28135', normal, compile, [''])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/15ab4a00d4ae11d9f56594d50ccd3f6…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/15ab4a00d4ae11d9f56594d50ccd3f6…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
Simon Peyton Jones pushed new branch wip/T28135 at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/T28135
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/mangoiv/ghc-9.12-adjustments] release 9.12.5: adjust release notes
by Magnus (@MangoIV) 17 Nov '26
by Magnus (@MangoIV) 17 Nov '26
17 Nov '26
Magnus pushed to branch wip/mangoiv/ghc-9.12-adjustments at Glasgow Haskell Compiler / GHC
Commits:
ac26fea3 by mangoiv at 2026-11-17T11:43:55+01:00
release 9.12.5: adjust release notes
- - - - -
1 changed file:
- docs/users_guide/9.12.5-notes.rst
Changes:
=====================================
docs/users_guide/9.12.5-notes.rst
=====================================
@@ -23,7 +23,12 @@ This release of GHC supports LLVM versions 13 through 19.
- ffi: collapse void pointer chains in capi wrappers (:ghc-ticket:`26852`)
- aarch64: fix ``MOVK reguUsageOfInstr`` to mark dst as both read and written (:ghc-ticket:`26980`)
- Fix ``dsuppress-uniques`` for free variables in demand signatures (:ghc-ticket:`27106`)
-- demand analysis: take stable unfoldings into account when determining argument demands (:ghc-ticket:`26416`)
+- Fix multiple demand analysis bugs (:ghc-ticket:`26416`, :ghc-ticket:`27845`, :ghc-ticket: `27626`)
+- Fix multiple tag inference bugs: (:ghc-ticket:`27831`, :ghc-ticket:`27841`, :ghc-ticket:`27842`, :ghc-ticket:`27005`)
+- Fix a scoping error in specialise (:ghc-ticket:`27766`)
+- Fix multiple specialiser bugs related to absent fillers (:ghc-ticket: `27717`, :ghc-ticket: `27703`, :ghc-ticket: `27704`, :ghc-ticket: `27627`, :ghc-ticket: `25924`)
+- Desugar a ``case`` scrutinee only once (:ghc-ticket:`27383`, :ghc-ticket:`20251`)
+- Fix missing handling of CmmUnsafeForeignCall node in LayoutStack (:ghc-ticket:`27447)
Runtime System
~~~~~~~~~~~~~~
@@ -34,11 +39,12 @@ Runtime System
- add a few missing i386 relocations in the rts linker
- handle heap allocation failures in I/O primops (:ghc-ticket:`24105`)
- small fixes to allow more configurations to succesfully build (debugging RTS with optimizations)
-- fix race conditions between ``flushEventLog`` acquiring/releasing the ``state_change`` mutex
+- Fix race conditions between ``flushEventLog`` acquiring/releasing the ``state_change`` mutex
- align stack to 64-byte boundary in StgRun on x65 (:ghc-ticket:`26595`, ghc-ticket:`26822`)
- carefully SLIDE off the end of a stack chunk (:ghc-ticket:`27001`)
- Fix missing profiling header for origin_thunk frame (:ghc-ticket:`27007`)
-
+- move stack check to the start of the stg_unpack_cstring thunks (:ghc-ticket: `27272`)
+- Fix missing memory barrier in ``eval_thunk_selector`` (:ghc-ticket: `27477`)
Code Generation
~~~~~~~~~~~~~~~
@@ -52,6 +58,8 @@ Bytecode Compiler
``base`` library
~~~~~~~~~~~~~~~~
+- don't drop exception context in ``SomeException``
+
``ghc-internal`` library
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -75,6 +83,7 @@ Packaging and Build System
- accept ``happy`` version 2.2
- hadrian: don't include package hash in haddock library
- configure: fix check for ``--target`` support in stage0 ``CC`` (:ghc-ticket:`26999`)
+- fix build error with glibc 2.43 (:ghc-ticket:`27076`)
Wasm Backend
~~~~~~~~~~~~
@@ -103,6 +112,7 @@ for further change information.
libraries/exceptions/exceptions.cabal: Dependency of ``ghc`` and ``haskeline`` library
libraries/file-io/file-io.cabal: Dependency of ``directory`` library
libraries/filepath/filepath.cabal: Dependency of ``ghc`` library
+ libraries/ghc-bignum/ghc-bignum.cabal: Internal compiler library
libraries/ghc-boot/ghc-boot.cabal: Internal compiler library
libraries/ghc-boot-th/ghc-boot-th.cabal: Internal compiler library
libraries/ghc-compact/ghc-compact.cabal: Core library
@@ -132,3 +142,5 @@ for further change information.
libraries/xhtml/xhtml.cabal: Dependency of ``haddock`` executable
utils/haddock/haddock-api/haddock-api.cabal: Dependency of ``haddock`` executable
utils/haddock/haddock-library/haddock-library.cabal: Dependency of ``haddock`` executable
+ utils/ghc-toolchain/ghc-toolchain.cabal: Dependency of ``ghc-toolchain`` executable and ``ghc`` library
+ mk/system-cxx-std-lib-1.0.conf.in: Core library
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/ac26fea3c56e458f1e5cfb1837b43ad…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/ac26fea3c56e458f1e5cfb1837b43ad…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/dcoutts/posix-time] 8 commits: Improve win32 implementation of getMonotonicNSec
by Duncan Coutts (@dcoutts) 17 Nov '26
by Duncan Coutts (@dcoutts) 17 Nov '26
17 Nov '26
Duncan Coutts pushed to branch wip/dcoutts/posix-time at Glasgow Haskell Compiler / GHC
Commits:
af5f4fc8 by Duncan Coutts at 2026-11-16T20:56:59+00:00
Improve win32 implementation of getMonotonicNSec
We don't need the fallback GetTickCount method.
Fixes #14233
- - - - -
4873d4f5 by Duncan Coutts at 2026-11-16T20:56:59+00:00
Improve win32 implementation of getUnixEpochTime
We can now use GetSystemTimePreciseAsFileTime, which is supported from
Windows 8 onwards. This is the recommendation from MS.
- - - - -
310d9b3c by Duncan Coutts at 2026-11-16T20:56:59+00:00
Remove initializeTimer
It is now a no-op on all platforms.
- - - - -
0c2d6a5c by Duncan Coutts at 2026-11-16T20:56:59+00:00
Refine the meaning of the main monotonic clock and add a high-res clock
We now define the monotonic clock to prioritise accuracy, and to be
steady: which implies it must count time while the system is suspended.
In particular this means that on Linux we must use CLOCK_BOOTTIME.
Since different use cases want different trade-offs (where such
trade-offs are necessary on some platforms) we also add support for a
high resolution clock. This is defined to be as precise as possible, but
not necessarily steady or accurate over long timer periods. This is the
appropriate choice for measuring the time of short-running actions. We
don't get use this one, but will do in susbequent changes.
- - - - -
ddb48e75 by Duncan Coutts at 2026-11-16T20:56:59+00:00
Switch some RTS uses from getMonotonicTime to getHighResolutionTime
Wherever we want to measure the duration of relatively short time
intervals then we want getHighResolutionTime rather than
getMonotonicTime. In particular this is appropriate for RTS stats,
profiling and the eventlog timestamps.
In practice this is hardly a change in behaviour compared to the prior
implementation of getMonotonicNSec/getProcessElapsedTime. On Linux and
FreeBSD it used CLOCK_MONOTONIC, and still does (or the more-or-less
equivalent CLOCK_BOOTTIME on Linux). On macOS it used the low-level
mach_absolute_time and now uses the equivalent CLOCK_UPTIME_RAW for
getHighResolutionTime. While on Windows getHighResolutionTime uses
QueryPerformanceCounter, the same as previously.
- - - - -
284f4572 by Duncan Coutts at 2026-11-16T20:56:59+00:00
Add support for macOS non-standard clock_gettime_nsec_np
It's a way to get what we want with fewer conversions, so plausibly
faster.
- - - - -
c478085d by Duncan Coutts at 2026-11-16T20:56:59+00:00
Remove unused rtsSleep utility
- - - - -
fa788650 by Duncan Coutts at 2026-11-16T20:56:59+00:00
Add a changelog entry for the clock_gettime changes
- - - - -
12 changed files:
- + changelog.d/clock_gettime
- rts/GetTime.h
- rts/RtsStartup.c
- rts/RtsUtils.c
- rts/Stats.c
- rts/configure.ac
- rts/posix/Clock.h
- rts/posix/GetTime.c
- rts/sm/GC.c
- rts/wasm/GetTime.c
- rts/win32/GetTime.c
- testsuite/tests/rts/TimeoutQueue.c
Changes:
=====================================
changelog.d/clock_gettime
=====================================
@@ -0,0 +1,18 @@
+section: rts
+synopsis: The RTS now uses the `clock_gettime` monotonic clock on all POSIX platforms.
+issues: #28119 #14233
+mrs: !16968
+description:
+ Having a good monotonic clock source is vital for concurrent programming.
+ Historically platform APIs for high precision monotonic time have not been
+ widely available in a consistent standard form, and GHC was forced to depend
+ on a hodge podge of different APIs (some of which did not even provide
+ monotonic time). POSIX.1-2008 mandated the `clock_gettime` API, and this is
+ now old enough and widely supported enough that the RTS can now use this
+ with the `CLOCK_MONOTONIC` and `CLOCK_REALTIME` clocks for all of its internal
+ timing needs on all POSIX platforms.
+
+ The compatibility implication is that some older POSIX platforms that do not
+ support the POSIX.1-2008 standard will no longer be supported. To the best of
+ our knowledge the main platforms impacted are versions of macOS prior to
+ version 10.12 (released 2016, EOL 2019).
=====================================
rts/GetTime.h
=====================================
@@ -11,18 +11,76 @@
#include "BeginPrivate.h"
-void initializeTimer (void);
+/* Note [Meaning of clocks]
+ * ~~~~~~~~~~~~~~~~~~~~~~~~
+ *
+ * Clock terminology
+ *
+ * 1. monotonic time: non-decreasing. This is for measuring intervals, not
+ * subject to time jumps (e.g. due to NTP or user fixing the time).
+ * 2. real / wall clock time: corresponding to real world UTC time.
+ * 3. CPU time: time spent by threads/processes running on a CPU.
+ * 4. steady clock: (following the C++11 library definition): the time
+ * between ticks of this clock is constant. In particular this implies it
+ * _does_ keep time even when the system is suspended/hibernated. Note that
+ * a wall clock must be steady, whereas a monotonic clock need not be.
+ *
+ * An ideal clock would be:
+ * 1. accurate: able to keep time over long periods;
+ * 2. precise: a high resolution of clock measurement;
+ * 3. fast: the time duration to measure the clock.
+ *
+ * Real clocks available on platforms must make compromises.
+ *
+ * We provide a choice of clocks that pick the best platform clocks given
+ * different priorities between these desires.
+ *
+ * 1. A monotonic, steady, accurate clock: getMonotonicTime
+ * 2. A precise monotonic clock: getHighResolutionTime
+ * 3. An accurate real time clock: getWallClockTime
+ *
+ * We could also (but do not currently) provide:
+ * 4. A fast monotonic clock (but not comparable to the accurate clock)
+ * 5. A fast real time clock (a less precise real time clock, and comparable)
+ *
+ * In general these clocks are _not_ comparable. The only ones that _could_ be
+ * comparable (if we were to need and provide them) are low res clocks that are
+ * (guaranteed) to be low resolution measures of the same clock.
+ */
-/* Get the current time in a monotonic clock.
+/* Get the current time in a monotonic, steady, accurate clock.
+ * See Note [Meaning of clocks].
*
* The time is represented as nanoseconds since an arbitrary epoch.
+ *
+ * This is the clock used for user timeouts like threadDelay.
*/
Time getMonotonicTime(void);
-/* Get the current wall clock time.
+/* Get the time in a monotonic, high resolution clock.
+ * See Note [Meaning of clocks].
+ *
+ * This is intended to be the most high resolution / precise clock available on
+ * the platform. It is suitable for timing operations with maximum available
+ * precision.
+ *
+ * It is not necessarily accurate at keeping time over long time periods (i.e.
+ * may be subject to time drift). It is not necessarily steady: it may or may
+ * not include time while the system is suspend.
+ *
+ * This is the clock used for measuring timing of activities within the RTS:
+ * RTS stats, profiling and eventlog timestamps.
+ */
+Time getHighResolutionTime(void);
+
+/* Get the time in a real time, accurate clock.
+ * See Note [Meaning of clocks].
*
* The time is represented as nanoseconds since the Unix epoch
* (1970-01-01 00:00).
+ *
+ * This clock is not used much, but is emitted into eventlogs on start to
+ * enable matching the eventlog timestamps with wall clock time.
*/
Time getWallClockTime(void);
=====================================
rts/RtsStartup.c
=====================================
@@ -360,9 +360,6 @@ hs_init_ghc(int *argc, char **argv[], RtsConfig rts_config)
/* Initialise the stats department, phase 0 */
initStats0();
- /* Initialize system timer before starting to collect stats */
- initializeTimer();
-
/* Next we do is grab the start time...just in case we're
* collecting timing statistics.
*/
=====================================
rts/RtsUtils.c
=====================================
@@ -31,10 +31,6 @@ extern char *ctime_r(const time_t *, char *);
#include <fcntl.h>
#endif
-#if defined(HAVE_GETTIMEOFDAY)
-#include <sys/time.h>
-#endif
-
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
@@ -207,31 +203,6 @@ exitHeapOverflow(void)
stg_exit(EXIT_HEAPOVERFLOW);
}
-/* -----------------------------------------------------------------------------
- Sleep for the given period of time.
- -------------------------------------------------------------------------- */
-
-/* Returns -1 on failure but handles EINTR internally. On Windows this will
- * only have millisecond precision. */
-int rtsSleep(Time t)
-{
-#if defined(_WIN32)
- // N.B. we can't use nanosleep on Windows as it would incur a pthreads
- // dependency. See #18272.
- Sleep(TimeToMS(t));
- return 0;
-#else
- struct timespec req;
- req.tv_sec = TimeToSeconds(t);
- req.tv_nsec = TimeToNS(t - req.tv_sec * TIME_RESOLUTION);
- int ret;
- do {
- ret = nanosleep(&req, &req);
- } while (ret == -1 && errno == EINTR);
- return ret;
-#endif /* _WIN32 */
-}
-
/* -----------------------------------------------------------------------------
Get the current time as a string. Used in profiling reports.
-------------------------------------------------------------------------- */
=====================================
rts/Stats.c
=====================================
@@ -75,18 +75,22 @@ static void statsFlush( void );
static void statsClose( void );
/* -----------------------------------------------------------------------------
- Current elapsed time
+ Current time
+
+ We use the high resolution clock, not the accurate steady clock.
+ This is for measuring how long things take over relatively short intervals.
------------------------------------------------------------------------- */
+/* Used for eventlog timestamps, and matching census->rtime */
Time stat_getElapsedTime(void)
{
- return getMonotonicTime() - start_init_elapsed;
+ return getHighResolutionTime() - start_init_elapsed;
}
static void getProcessTimes(Time *user, Time *elapsed)
{
*user = getProcessCPUTime();
- *elapsed = getMonotonicTime();
+ *elapsed = getHighResolutionTime();
}
/* ---------------------------------------------------------------------------
@@ -301,7 +305,7 @@ stat_endExit(void)
void
stat_startGCSync (gc_thread *gct)
{
- gct->gc_sync_start_elapsed = getMonotonicTime();
+ gct->gc_sync_start_elapsed = getHighResolutionTime();
}
void
@@ -309,7 +313,7 @@ stat_startNonmovingGc (void)
{
ACQUIRE_LOCK(&stats_mutex);
start_nonmoving_gc_cpu = getCurrentThreadCPUTime();
- start_nonmoving_gc_elapsed = getMonotonicTime();
+ start_nonmoving_gc_elapsed = getHighResolutionTime();
RELEASE_LOCK(&stats_mutex);
}
@@ -317,7 +321,7 @@ void
stat_endNonmovingGc (void)
{
Time cpu = getCurrentThreadCPUTime();
- Time elapsed = getMonotonicTime();
+ Time elapsed = getHighResolutionTime();
ACQUIRE_LOCK(&stats_mutex);
stats.gc.nonmoving_gc_elapsed_ns = elapsed - start_nonmoving_gc_elapsed;
@@ -336,7 +340,7 @@ void
stat_startNonmovingGcSync (void)
{
ACQUIRE_LOCK(&stats_mutex);
- start_nonmoving_gc_sync_elapsed = getMonotonicTime();
+ start_nonmoving_gc_sync_elapsed = getHighResolutionTime();
RELEASE_LOCK(&stats_mutex);
traceConcSyncBegin();
}
@@ -344,7 +348,7 @@ stat_startNonmovingGcSync (void)
void
stat_endNonmovingGcSync (void)
{
- Time end_elapsed = getMonotonicTime();
+ Time end_elapsed = getHighResolutionTime();
ACQUIRE_LOCK(&stats_mutex);
stats.gc.nonmoving_gc_sync_elapsed_ns = end_elapsed - start_nonmoving_gc_sync_elapsed;
stats.nonmoving_gc_sync_elapsed_ns += stats.gc.nonmoving_gc_sync_elapsed_ns;
@@ -451,7 +455,7 @@ stat_startGC (Capability *cap, gc_thread *gct)
gct->gc_start_cpu = getCurrentThreadCPUTime();
}
- gct->gc_start_elapsed = getMonotonicTime();
+ gct->gc_start_elapsed = getHighResolutionTime();
#if !defined(THREADED_RTS)
// Non-threaded RTS has no sync phase. Initializing in this way makes the
// calculated statistics correctly read zero.
=====================================
rts/configure.ac
=====================================
@@ -206,6 +206,7 @@ dnl ** We now require clock_gettime for our monotonic clock.
if test "$ghc_host_os" != "mingw32" ; then
AC_CHECK_FUNCS([clock_gettime], [],
AC_MSG_ERROR([The POSIX.1-2008 function 'clock_gettime' is required but is not available]))
+ AC_CHECK_FUNCS([clock_gettime_nsec_np])
fi
dnl ** check for Apple's "interesting" long double compatibility scheme
=====================================
rts/posix/Clock.h
=====================================
@@ -8,7 +8,43 @@
#pragma once
+
+#if defined(linux_HOST_OS) || defined(linux_android_HOST_OS)
+/* On Linux the CLOCK_MONOTONIC does not count time while the machine is
+ * suspend. We have defined getMonotonicTime to be a steady clock (which does
+ * count time while suspend). So on Linux we use CLOCK_BOOTTIME:
+ *
+ * > A nonsettable system-wide clock that is identical to CLOCK_MONOTONIC,
+ * > except that it also includes any time that the system is suspended.
+ *
+ * The only downside is that there is no CLOCK_BOOTTIME_COARSE, only
+ * CLOCK_MONOTONIC_COARSE.
+ */
+#define RTS_CLOCK_MONOTONIC CLOCK_BOOTTIME
+
+#else
+/* On (most?) other POSIX platforms the CLOCK_MONOTONIC counts time while the
+ * machine is suspend. In particular this is true on FreeBSD and macOS.
+ */
#define RTS_CLOCK_MONOTONIC CLOCK_MONOTONIC
+#endif
+
+
+#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
+/* On macOS CLOCK_UPTIME_RAW is fast, and precise but not steady */
+#define RTS_CLOCK_HIGHRES CLOCK_UPTIME_RAW
+
+#elif defined(linux_HOST_OS) || defined(linux_android_HOST_OS)
+/* On Linux CLOCK_MONOTONIC and CLOCK_BOOTTIME are precise. We use
+ * CLOCK_BOOTTIME for consistency with RTS_CLOCK_MONOTONIC above.
+ */
+#define RTS_CLOCK_HIGHRES CLOCK_BOOTTIME
+
+#else
+#define RTS_CLOCK_HIGHRES CLOCK_MONOTONIC
+#endif
+
+
#define RTS_CLOCK_REALTIME CLOCK_REALTIME
#define RTS_CLOCK_CPUTIME_THREAD CLOCK_THREAD_CPUTIME_ID
#define RTS_CLOCK_CPUTIME_PROCESS CLOCK_PROCESS_CPUTIME_ID
=====================================
rts/posix/GetTime.c
=====================================
@@ -28,12 +28,18 @@
#warning _POSIX_MONOTONIC_CLOCK not defined, which is likely to be a problem.
#endif
-void initializeTimer(void)
-{
-}
-
static Time getClockTime(clockid_t clock)
{
+#if defined(HAVE_CLOCK_GETTIME_NSEC_NP)
+ /* Non-standard extension on macOS, allowing fewer conversions. */
+ uint64_t nsec = clock_gettime_nsec_np(clock);
+ if (RTS_LIKELY(nsec)) {
+ return (Time)nsec;
+ } else {
+ sysErrorBelch("clock_gettime_nsec_np");
+ stg_exit(EXIT_FAILURE);
+ }
+#else
struct timespec ts;
int res = clock_gettime(clock, &ts);
if (RTS_LIKELY(res == 0)) {
@@ -42,6 +48,7 @@ static Time getClockTime(clockid_t clock)
sysErrorBelch("clock_gettime");
stg_exit(EXIT_FAILURE);
}
+#endif
}
Time getCurrentThreadCPUTime(void)
@@ -67,6 +74,11 @@ Time getMonotonicTime(void)
return getClockTime(RTS_CLOCK_MONOTONIC);
}
+Time getHighResolutionTime(void)
+{
+ return getClockTime(RTS_CLOCK_HIGHRES);
+}
+
Time getWallClockTime(void)
{
return getClockTime(RTS_CLOCK_REALTIME);
=====================================
rts/sm/GC.c
=====================================
@@ -1525,7 +1525,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[])
uint32_t i, cur_n_gc_entered;
Time t0, t1, t2;
- t0 = t1 = t2 = getMonotonicTime();
+ t0 = t1 = t2 = getHighResolutionTime();
for(i = 0; i < getNumCapabilities(); ++i) {
if (i == me || idle_cap[i]) {
@@ -1549,7 +1549,7 @@ waitForGcThreads (Capability *cap, bool idle_cap[])
// this 1ms timeout is not well justified. It's the shortest timeout we
// can use on windows. It seems to work well for me.
timedWaitCondition(&gc_entry_arrived_cv, &gc_entry_mutex, USToTime(1000));
- t2 = getMonotonicTime();
+ t2 = getHighResolutionTime();
if (RtsFlags.GcFlags.longGCSync != 0 &&
t2 - t1 > RtsFlags.GcFlags.longGCSync) {
// best not to hold the mutex while we call a hook function
=====================================
rts/wasm/GetTime.c
=====================================
@@ -13,10 +13,6 @@
#include <time.h>
#include <sys/time.h>
-void initializeTimer(void)
-{
-}
-
static Time getClockTime(clockid_t clock)
{
struct timespec ts;
@@ -44,6 +40,11 @@ Time getMonotonicTime(void)
return getClockTime(CLOCK_MONOTONIC);
}
+Time getHighResolutionTime(void)
+{
+ return getClockTime(CLOCK_MONOTONIC);
+}
+
Time getWallClockTime(void)
{
struct timeval tv;
=====================================
rts/win32/GetTime.c
=====================================
@@ -10,6 +10,7 @@
#include "GetTime.h"
#include <windows.h>
+#include <realtimeapiset.h>
#include <time.h>
@@ -48,55 +49,93 @@ Time getProcessCPUTime(void)
return fileTimeToRtsTime(userTime);
}
-// Number of ticks per second used by the QueryPerformanceFrequency
-// implementation, represented by a 64-bit union type.
-static LARGE_INTEGER qpc_frequency = {.QuadPart = 0};
-
-// Initialize qpc_frequency. This function should be called before any call to
-// getMonotonicNSec. If QPC is not supported on this system, qpc_frequency is
-// set to 0.
-void initializeTimer(void)
+/* Note [Windows time/clock functions]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A couple useful references for time/clocks:
+https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps
+https://devblogs.microsoft.com/oldnewthing/20170921-00/?p=97057/
+
+The advice in the first article is plainly to use QueryPerformanceCounter. It
+says this is now always supported in Windows XP and later, and reliable from
+Vista, and fast from Windows 7 and 8 (relying on reliably TSCs). The internet
+is full of reports that QPC is unreliable, but these do all seem to be from
+older Windows versions (or folk lore based on earlier Windows versions or older
+hardware).
+
+Now on the other hand it is worth noting that the article is about the use
+cases of high resolution timestamps or measuring time intervals. It's not
+really clear that it means its ideal for a monotonic clock, which should be
+accurate (not just precise) over longer periods of time.
+
+In the second article, Raymond notes:
+
+> And then there are the so-called precise variants of the system timer
+> functions. These take the system timer value and combine it with the
+> system performance counter to get a high-accuracy timestamp. [...]
+>
+> + GetSystemTimePreciseAsFileTime
+> + QueryInterruptTimePrecise, QueryUnbiasedInterruptTimePrecise
+>
+> These high-accuracy functions give you the best of both worlds: Time
+> correlated with real-world clocks, but with the accuracy of the system
+> performance counter. But as noted, it comes at a performance cost.
+
+The idea here is that the system timer is very accurate (over long time
+periods), but is (very) coarse grained, while the TSC is very high frequency
+but (at least historically) has been subject to drift over longer periods,
+so by combining the two one can get the best of both worlds.
+
+This makes the "Precise" functions seem like a good choice for a monotonic
+clock. Also, they have the benefit of having correspond not-precise ones that
+are comparable time sources but coarse and faster. It may well be useful to
+have fast coarse clocks, but only if they are coarse measures of the same clock
+rather than unrelated clocks.
+
+Finally, the difference between QueryUnbiasedInterruptTimePrecise and
+QueryInterruptTimePrecise is that the "unbiased" clock does not count time when
+the system is suspended. We're following the "steady clock" semantics, so we do
+want to include suspended time, hence we use QueryInterruptTimePrecise.
+*/
+Time getMonotonicTime(void)
{
- BOOL qpc_supported = QueryPerformanceFrequency(&qpc_frequency);
- if (!qpc_supported)
- {
- qpc_frequency.QuadPart = 0;
- }
+ long long interrupt_time;
+ /* See Note [Windows time/clock functions]
+ * The "interrupt time" count is units of 100 nanoseconds.
+ */
+ QueryInterruptTimePrecise(&time);
+ Time time = interrupt_time * 100ll; /* Convert to nanoseconds */
+ return time;
}
-Time getMonotonicTime(void)
+Time getHighResolutionTime(void)
{
- if (qpc_frequency.QuadPart)
- {
- // system_time is a 64-bit union type used to represent the
- // tick count returned by QueryPerformanceCounter
- LARGE_INTEGER system_time;
-
- // get the tick count.
- QueryPerformanceCounter(&system_time);
+ /* Number of ticks per second, provided by QueryPerformanceFrequency */
+ static uint64_t ticks_per_sec = 0;
+
+ /* Initialize ticks_per_sec on the first call. It should not matter if two
+ threads race to do this. The result should be the same. */
+ if (RTS_UNLIKELY(RELAXED_LOAD_ALWAYS(&ticks_per_sec) == 0)) {
+ LARGE_INTEGER qpc_frequency; // a 64-bit union type
+ if (QueryPerformanceFrequency(&qpc_frequency)) {
+ RELAXED_STORE_ALWAYS(&ticks_per_sec, qpc_frequency.QuadPart);
+ } else {
+ /* This should be impossible now. */
+ sysErrorBelch("getMonotonicNSec: high res timestamps not available");
+ stg_exit(EXIT_FAILURE);
+ }
+ }
- // compute elapsed seconds as double
- double secs = (double)system_time.QuadPart /
- (double)qpc_frequency.QuadPart;
+ /* Get the tick count. */
+ LARGE_INTEGER tick_count;
+ QueryPerformanceCounter(&tick_count);
- // return elapsed time in nanoseconds
- return (Time)(secs * 1e9);
- }
- else // fallback to GetTickCount
- {
- // TODO: Remove this code path, it cannot be taken because
- // `QueryPerformanceFrequency` cannot fail on Windows >= XP
- // and GHC no longer supports Windows <= XP.
- // See https://gitlab.haskell.org/ghc/ghc/issues/14233
-
- // NOTE: GetTickCount is a 32-bit millisecond value, so it wraps around
- // every 49 days.
- DWORD count = GetTickCount();
-
- // getTickCount is in milliseconds, so multiply it by 1000000 to get
- // nanoseconds.
- return (Time)count * 1000000;
- }
+ /* Compute elapsed time in nanoseconds. If avoiding float, we must multiply
+ * by nanoseconds first (1e9) and then divide by ticks per sec. The
+ * intermediate result can overflow a 64bit integer. So we use 128bit.
+ */
+ return ((__uint128_t)tick_count.QuadPart * (__uint128_t)1000000000ull)
+ / (__uint128_t)ticks_per_sec;
}
Time getWallClockTime(void)
@@ -104,17 +143,14 @@ Time getWallClockTime(void)
/* Windows has a bunch of time APIs but none that directly give
us unix epoch time, so we have to do a little dance. */
- SYSTEMTIME systime;
FILETIME filetime;
ULARGE_INTEGER unixtime;
- /* Windows SYSTEMTIME is a big struct with fields for
- year, month, day, hour, minute, second, millisecond. */
- GetSystemTime(&systime);
- /* Windows FILETIME timestamps use an epoch-based time,
+ /* See Note [Windows time/clock functions]
+ Windows FILETIME timestamps use an epoch-based time,
using a 64bit unsigned word. The time is measured in
units of 100 nanoseconds since an epoch of 1601. */
- SystemTimeToFileTime(&systime, &filetime);
+ GetSystemTimePreciseAsFileTime(&filetime);
/* FILETIME isn't directly a 64bit word, but a struct with
a pair of 32bit words, so we have to convert via a
=====================================
testsuite/tests/rts/TimeoutQueue.c
=====================================
@@ -227,7 +227,6 @@ int main_bench (bool showtiming)
StgTimeoutQueue *root = EMPTY;
Time before, after;
- initializeTimer();
/* Init */
StgTimeoutQueue *elems = calloc(N, sizeof(StgTimeoutQueue));
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1f64668d5dd34d61c3a249aee04a4d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1f64668d5dd34d61c3a249aee04a4d…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/T27862] 4 commits: CoreMap: look up a non-recursive let with the key order of the store
by Simon Peyton Jones (@simonpj) 17 Nov '26
by Simon Peyton Jones (@simonpj) 17 Nov '26
17 Nov '26
Simon Peyton Jones pushed to branch wip/T27862 at Glasgow Haskell Compiler / GHC
Commits:
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
a251280b by Simon Peyton Jones at 2026-11-17T00:06:58+00:00
Better desugaring for bang patterns
Ticket #27862 showed that we were desugaring bang patterns in a
silly way, which led to bad code. This small fix makes it much
better.
I ended up refactoring `decomposeFirstPat` to be of type
(LPat -> LPat) instead of (Pat -> Pat)
which made it much easier to keep the locations correct.
On the way I also fixed #28137, a missing warning.
See Note [Tidying patterns] which has new (TP1) and (TP2)
and Note [Grouping equations] especially (GE1)
- - - - -
39 changed files:
- + changelog.d/27892
- + changelog.d/T27137
- + changelog.d/T27862
- + changelog.d/T28123
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- testsuite/tests/ado/T22483.stderr
- + testsuite/tests/deSugar/should_compile/T27862.hs
- + testsuite/tests/deSugar/should_compile/T27862.stderr
- + testsuite/tests/deSugar/should_compile/T27862a.hs
- + testsuite/tests/deSugar/should_compile/T27862a.stderr
- + testsuite/tests/deSugar/should_compile/T27862b.hs
- + testsuite/tests/deSugar/should_compile/T27862b.stderr
- + testsuite/tests/deSugar/should_compile/T27862c.hs
- + testsuite/tests/deSugar/should_compile/T27862c.stderr
- + testsuite/tests/deSugar/should_compile/T27862d.hs
- + testsuite/tests/deSugar/should_compile/T27862d.stderr
- + testsuite/tests/deSugar/should_compile/T28137.hs
- + testsuite/tests/deSugar/should_compile/T28137.stderr
- testsuite/tests/deSugar/should_compile/all.T
- testsuite/tests/deSugar/should_run/dsrun008.stderr
- testsuite/tests/pmcheck/should_compile/T24234.stderr
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- testsuite/tests/simplCore/should_compile/all.T
- testsuite/tests/typecheck/should_fail/tcfail203a.stderr
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/b158922b0ca34529a1e6d120f49e51…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/b158922b0ca34529a1e6d120f49e51…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0
[Git][ghc/ghc][wip/jeltsch/smaller-pit] 6 commits: Make Haddock avoid the PIT
by Wolfgang Jeltsch (@jeltsch) 16 Nov '26
by Wolfgang Jeltsch (@jeltsch) 16 Nov '26
16 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/smaller-pit at Glasgow Haskell Compiler / GHC
Commits:
eb4871bd by Wolfgang Jeltsch at 2026-11-16T23:35:58+02:00
Make Haddock avoid the PIT
To this end, Haddock has been using `loadSysInterface` to fetch module
interfaces. The `loadSysInterface` operation is very complex, containing
many bits that do not seem to be needed by Haddock. In particular,
storing interface data in and potentially retrieving it from the PIT
seems to be superfluous. This interaction with the PIT limits how much
we can statically shrink the amount of information that is stored in the
PIT. Therefore, we drop the use of `loadSysInterface` and implement the
necessary bits of interface fetching directly in `loadHiFile`, where
`loadSysInterface` used to be invoked.
- - - - -
5b041e93 by Wolfgang Jeltsch at 2026-11-16T23:39:09+02:00
Statically enforce module interface reduction for the PIT
`GHC.Iface.Load.loadInterface` used to replace certain fields of each
fetched module interface by `panic` applications before storing it in
the PIT. With the present change, the absence of those fields in the PIT
is guaranteed statically.
See #27044 for the bigger picture.
- - - - -
13adc58b by Wolfgang Jeltsch at 2026-11-16T23:39:09+02:00
Make `IfaceBinHandle` a type synonym family
This brings the handling of `IfaceBinHandle` somewhat in line with how
other phase-dependent data is handled. Note that `mi_hi_bytes_` now
includes the `Strict.Maybe` layer itself, independently of the phase.
This is necessary, because with a type family instead of a GADT
`clear_mi_hi_bytes` cannot determine the phase at runtime anymore and
thus has to set `mi_hi_bytes_` to `Strict.Nothing` for every phase.
Metric Decrease:
T15164
T19695
T21839c
WWRec
- - - - -
a0ef274d by Wolfgang Jeltsch at 2026-11-16T23:39:09+02:00
Streamline the construction of empty module interfaces
- - - - -
8e0c2697 by Wolfgang Jeltsch at 2026-11-16T23:39:09+02:00
Shift the creation of `ModIface` caches to later phases
- - - - -
0e011f24 by Wolfgang Jeltsch at 2026-11-16T23:39:09+02:00
Restrict storage of interface hashes to the `Final` phase
- - - - -
25 changed files:
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/Env.hs
- compiler/GHC/Driver/Main/Interactive.hs
- compiler/GHC/Driver/Main/Passes.hs
- compiler/GHC/Driver/Plugins.hs
- compiler/GHC/Driver/Session/Inspect.hs
- compiler/GHC/HsToCore/Usage.hs
- compiler/GHC/Iface/Binary.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Load.hs-boot
- compiler/GHC/Iface/Make.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Rename/Names.hs
- compiler/GHC/Rename/Utils.hs
- compiler/GHC/Runtime/Loader.hs
- compiler/GHC/Tc/Errors/Ppr.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/Splice.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Unit/External.hs
- compiler/GHC/Unit/Module/ModIface.hs
- ghc/Main.hs
- utils/count-deps/Main.hs
- utils/haddock/haddock-api/src/Haddock/Interface.hs
Changes:
=====================================
compiler/GHC/Driver/Downsweep.hs
=====================================
@@ -898,7 +898,8 @@ readFixedModule (DownsweepEnv { ds_hsc_env = hsc_env }) key =
-- part of the compiler.
lookupIfaceByModuleHsc hsc_env (mnkToModule key) >>= \case
Just iface -> return (MaybeErr.Succeeded iface)
- Nothing -> readIface (hsc_hooks hsc_env) (hsc_logger hsc_env) (hsc_dflags hsc_env) (hsc_NC hsc_env) (mnkToModule key) (ml_hi_file loc)
+ Nothing -> fmap retainedModIface <$>
+ readIface (hsc_hooks hsc_env) (hsc_logger hsc_env) (hsc_dflags hsc_env) (hsc_NC hsc_env) (mnkToModule key) (ml_hi_file loc)
return $ case read_result of
MaybeErr.Succeeded iface -> Just (FixedModule loc (ifaceEdges (mi_deps iface)))
-- Skip any failure, we might try to read a .hi-boot file for
=====================================
compiler/GHC/Driver/Env.hs
=====================================
@@ -387,10 +387,10 @@ lookupIfaceByModule
:: HomeUnitGraph
-> PackageIfaceTable
-> Module
- -> IO (Maybe ModIface)
+ -> IO (Maybe RetainedModIface)
lookupIfaceByModule hug pit mod
= HUG.lookupHugByModule mod hug >>= pure . \case
- Just hm -> Just (hm_iface hm)
+ Just hm -> Just (retainedModIface (hm_iface hm))
Nothing -> lookupModuleEnv pit mod
-- If the module does come from the home package, why do we look in the PIT as well?
-- (a) In OneShot mode, even home-package modules accumulate in the PIT
@@ -399,7 +399,7 @@ lookupIfaceByModule hug pit mod
-- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
-- of its own, but it doesn't seem worth the bother.
-lookupIfaceByModuleHsc :: HscEnv -> Module -> IO (Maybe ModIface)
+lookupIfaceByModuleHsc :: HscEnv -> Module -> IO (Maybe RetainedModIface)
lookupIfaceByModuleHsc hsc_env mod = do
eps <- hscEPS hsc_env
lookupIfaceByModule (hsc_HUG hsc_env) (eps_PIT eps) mod
=====================================
compiler/GHC/Driver/Main/Interactive.hs
=====================================
@@ -148,7 +148,7 @@ hscIsGHCiMonad :: HscEnv -> String -> IO Name
hscIsGHCiMonad hsc_env name
= runHsc hsc_env $ ioMsgMaybe $ hoistTcRnMessage $ isGHCiMonad hsc_env name
-hscGetModuleInterface :: HscEnv -> Module -> IO ModIface
+hscGetModuleInterface :: HscEnv -> Module -> IO RetainedModIface
hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ioMsgMaybe $ hoistTcRnMessage $ getModuleInterface hsc_env mod
@@ -270,7 +270,7 @@ hscCheckSafe' m l = do
_ | isHomeModule home_unit mod -> True
_ -> isUnitTrusted unit_state (moduleUnit m)
- lookup' :: Module -> Hsc (Maybe ModIface)
+ lookup' :: Module -> Hsc (Maybe RetainedModIface)
lookup' m = do
hsc_env <- getHscEnv
iface <- liftIO $ lookupIfaceByModuleHsc hsc_env m
=====================================
compiler/GHC/Driver/Main/Passes.hs
=====================================
@@ -1335,7 +1335,7 @@ hscCheckSafe' m l = do
_ | isHomeModule home_unit mod -> True
_ -> isUnitTrusted unit_state (moduleUnit m)
- lookup' :: Module -> Hsc (Maybe ModIface)
+ lookup' :: Module -> Hsc (Maybe RetainedModIface)
lookup' m = do
hsc_env <- getHscEnv
iface <- liftIO $ lookupIfaceByModuleHsc hsc_env m
=====================================
compiler/GHC/Driver/Plugins.hs
=====================================
@@ -224,7 +224,7 @@ data PluginWithArgs = PluginWithArgs
data LoadedPlugin = LoadedPlugin
{ lpPlugin :: PluginWithArgs
-- ^ the actual plugin together with its commandline arguments
- , lpModule :: ModIface
+ , lpModule :: RetainedModIface
-- ^ the module containing the plugin
}
=====================================
compiler/GHC/Driver/Session/Inspect.hs
=====================================
@@ -87,7 +87,7 @@ data ModuleInfo = ModuleInfo {
minf_type_env :: TypeEnv,
minf_exports :: [AvailInfo],
minf_instances :: [ClsInst],
- minf_iface :: Maybe ModIface,
+ minf_iface :: Maybe RetainedModIface,
minf_safe :: SafeHaskellMode,
minf_modBreaks :: Maybe InternalModBreaks
}
@@ -140,7 +140,7 @@ getHomeModuleInfo hsc_env mdl =
Nothing -> return Nothing
Just hmi -> do
let details = hm_details hmi
- iface = hm_iface hmi
+ iface = retainedModIface (hm_iface hmi)
return (Just (ModuleInfo {
minf_type_env = md_types details,
minf_exports = md_exports details,
@@ -187,7 +187,7 @@ modInfoLookupName minf name = withSession $ \hsc_env -> do
Just tyThing -> return (Just tyThing)
Nothing -> liftIO (lookupType hsc_env name)
-modInfoIface :: ModuleInfo -> Maybe ModIface
+modInfoIface :: ModuleInfo -> Maybe RetainedModIface
modInfoIface = minf_iface
-- | Retrieve module safe haskell mode
=====================================
compiler/GHC/HsToCore/Usage.hs
=====================================
@@ -276,7 +276,7 @@ mk_mod_usage_info uc home_unit home_unit_ids this_mod direct_imports imp_decls u
-- a) we used something from it; has something in used_names
-- b) we imported it, even if we used nothing from it
-- (need to recompile if its export list changes: export_fprint)
- mkUsage :: Module -> ModIface -> Maybe Usage
+ mkUsage :: Module -> RetainedModIface -> Maybe Usage
mkUsage mod iface
| toUnitId (moduleUnit mod) `Set.notMember` home_unit_ids
= Just $ UsagePackageModule{ usg_mod = mod,
@@ -302,9 +302,9 @@ mk_mod_usage_info uc home_unit home_unit_ids this_mod direct_imports imp_decls u
usg_entities = Map.toList ent_hashs,
usg_safe = imp_safe }
where
- finsts_mod = mi_finsts iface
+ finsts_mod = mi_abi_finsts (mi_abi_hashes iface)
hash_env = mi_hash_fn iface
- mod_hash = mi_mod_hash iface
+ mod_hash = mi_abi_mod_hash (mi_abi_hashes iface)
imported_exports
= if not depend_on_exports
then Nothing
@@ -312,9 +312,9 @@ mk_mod_usage_info uc home_unit home_unit_ids this_mod direct_imports imp_decls u
Just $
HomeModImport
{ hmiu_orphanLikeHash
- = mi_orphan_like_hash iface
+ = mi_abi_orphan_like_hash (mi_abi_hashes iface)
, hmiu_importedAvails
- = moduleImportedAvails mod (mi_export_avails_hash iface) imp_decls
+ = moduleImportedAvails mod (mi_abi_export_avails_hash (mi_abi_hashes iface)) imp_decls
}
by_is_safe (ImportedByUser imv) = imv_is_safe imv
=====================================
compiler/GHC/Iface/Binary.hs
=====================================
@@ -197,7 +197,7 @@ getIfaceWithExtFields name_cache bh = do
modIfaceBinData <- freezeBinHandle bh start
pure $ mod_iface
& set_mi_ext_fields extFields
- & set_mi_hi_bytes (FullIfaceBinHandle $ Strict.Just modIfaceBinData)
+ & set_mi_hi_bytes (Strict.Just modIfaceBinData)
-- | This performs a get action after reading the dictionary and symbol
-- table. It is necessary to run this before trying to deserialise any
@@ -276,10 +276,10 @@ writeBinIface profile traceBinIface compressionLevel hi_path mod_iface = do
putIfaceWithExtFields :: TraceBinIFace -> CompressionIFace -> WriteBinHandle -> ModIface -> IO ()
putIfaceWithExtFields traceBinIface compressionLevel bh mod_iface =
case mi_hi_bytes mod_iface of
- FullIfaceBinHandle Strict.Nothing -> do
+ Strict.Nothing -> do
forwardPutRel_ bh (\_ -> put_ bh (mi_ext_fields mod_iface)) $ do
putWithUserData traceBinIface compressionLevel bh mod_iface
- FullIfaceBinHandle (Strict.Just binData) -> putFullBinData bh binData
+ Strict.Just binData -> putFullBinData bh binData
-- | Put a piece of data with an initialised `UserData` field. This
-- is necessary if you want to serialise Names or FastStrings.
=====================================
compiler/GHC/Iface/Load.hs
=====================================
@@ -308,7 +308,7 @@ loadKnownKeyOccMaps
known_key_maps :: Module -> IfM lcl KnownKeyNameMaps
known_key_maps mod
= do { iface <- loadInterfaceWithException doc mod ImportBySystem
- ; let !abi_hash = mi_mod_hash iface
+ ; let !abi_hash = mi_abi_mod_hash (mi_abi_hashes iface)
; eps <- getEps
; case lookupModuleEnv (eps_known_keys eps) mod of
Just (cached_hash, kk_maps)
@@ -321,7 +321,7 @@ loadKnownKeyOccMaps
(abi_hash, kk_maps) }
; return kk_maps } }
- build_maps :: ModIface -> KnownKeyNameMaps
+ build_maps :: RetainedModIface -> KnownKeyNameMaps
build_maps iface = (kk_map, occ_map)
where
kk_map :: UniqFM KnownKey Name
@@ -628,7 +628,7 @@ loadSrcInterface :: SDoc
-> ModuleName
-> IsBootInterface -- {-# SOURCE #-} ?
-> PkgQual -- "package", if any
- -> RnM ModIface
+ -> RnM RetainedModIface
loadSrcInterface doc scope mod want_boot maybe_pkg
= do { res <- loadSrcInterface_maybe doc scope mod want_boot maybe_pkg
@@ -648,7 +648,7 @@ loadSrcInterface_maybe :: SDoc
-> ModuleName
-> IsBootInterface -- {-# SOURCE #-} ?
-> PkgQual -- "package", if any
- -> RnM (MaybeErr MissingInterfaceError ModIface)
+ -> RnM (MaybeErr MissingInterfaceError RetainedModIface)
loadSrcInterface_maybe doc scope mod want_boot maybe_pkg
-- We must first find which Module this import refers to. This involves
@@ -667,7 +667,7 @@ loadSrcInterface_maybe doc scope mod want_boot maybe_pkg
-- rare operation, but in particular it is used to load orphan modules
-- in order to pull their instances into the global package table and to
-- handle some operations in GHCi).
-loadModuleInterface :: SDoc -> Module -> TcM ModIface
+loadModuleInterface :: SDoc -> Module -> TcM RetainedModIface
loadModuleInterface doc mod = initIfaceTcRn (loadSysInterface doc mod)
-- | Load interfaces for a collection of modules.
@@ -681,7 +681,7 @@ loadModuleInterfaces doc mods
-- | Loads the interface for a given Name.
-- Should only be called for an imported name;
-- otherwise loadSysInterface may not find the interface
-loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
+loadInterfaceForName :: SDoc -> Name -> TcRn RetainedModIface
loadInterfaceForName doc name
= do { when debugIsOn $ -- Check pre-condition
do { this_mod <- getModule
@@ -690,7 +690,7 @@ loadInterfaceForName doc name
initIfaceTcRn $ loadSysInterface doc (nameModule name) }
-- | Loads the interface for a given Module.
-loadInterfaceForModule :: SDoc -> Module -> TcRn ModIface
+loadInterfaceForModule :: SDoc -> Module -> TcRn RetainedModIface
loadInterfaceForModule doc m
= do
-- Should not be called with this module
@@ -724,23 +724,23 @@ loadWiredInHomeIface name
------------------
-- | Loads a system interface and throws an exception if it fails
-loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
+loadSysInterface :: SDoc -> Module -> IfM lcl RetainedModIface
loadSysInterface doc mod_name = loadInterfaceWithException doc mod_name ImportBySystem
------------------
-- | Loads a user interface and throws an exception if it fails. The first parameter indicates
-- whether we should import the boot variant of the module
-loadUserInterface :: IsBootInterface -> SDoc -> Module -> IfM lcl ModIface
+loadUserInterface :: IsBootInterface -> SDoc -> Module -> IfM lcl RetainedModIface
loadUserInterface is_boot doc mod_name
= loadInterfaceWithException doc mod_name (ImportByUser is_boot)
-loadPluginInterface :: SDoc -> Module -> IfM lcl ModIface
+loadPluginInterface :: SDoc -> Module -> IfM lcl RetainedModIface
loadPluginInterface doc mod_name
= loadInterfaceWithException doc mod_name ImportByPlugin
------------------
-- | A wrapper for 'loadInterface' that throws an exception if it fails
-loadInterfaceWithException :: SDoc -> Module -> WhereFrom -> IfM lcl ModIface
+loadInterfaceWithException :: SDoc -> Module -> WhereFrom -> IfM lcl RetainedModIface
loadInterfaceWithException doc mod_name where_from
= do
dflags <- getDynFlags
@@ -749,7 +749,7 @@ loadInterfaceWithException doc mod_name where_from
------------------
loadInterface :: SDoc -> Module -> WhereFrom
- -> IfM lcl (MaybeErr MissingInterfaceError ModIface)
+ -> IfM lcl (MaybeErr MissingInterfaceError RetainedModIface)
-- loadInterface looks in both the HPT and PIT for the required interface
-- If not found, it loads it, and puts it in the PIT (always).
@@ -796,7 +796,7 @@ loadInterface doc_str mod from
liftIO $ computeInterface hsc_env doc_str hi_boot_file mod
; case read_result of {
Failed err -> do
- { let fake_iface = emptyFullModIface mod
+ { let fake_iface = emptyRetainedModIface mod
; updateEps_ $ \eps ->
eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
@@ -856,16 +856,7 @@ loadInterface doc_str mod from
; new_eps_complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
; purged_hsc_env <- getTopEnv
- ; let final_iface = iface
- & set_mi_decls (panic "No mi_decls in PIT")
- & set_mi_insts (panic "No mi_insts in PIT")
- & set_mi_defaults (panic "No mi_defaults in PIT")
- & set_mi_fam_insts (panic "No mi_fam_insts in PIT")
- & set_mi_rules (panic "No mi_rules in PIT")
- & set_mi_anns (panic "No mi_anns in PIT")
- & set_mi_simplified_core (panic "No mi_simplified_core in PIT")
-
- bad_boot = mi_boot iface == IsBoot
+ ; let bad_boot = mi_boot iface == IsBoot
&& isJust (lookupKnotVars (if_rec_types gbl_env) mod)
-- Warn against an EPS-updating import
-- of one's own boot file! (one-shot only)
@@ -892,7 +883,7 @@ loadInterface doc_str mod from
then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls }
else
eps {
- eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
+ eps_PIT = extendModuleEnv (eps_PIT eps) mod (retainedModIface iface),
eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
eps_iface_bytecode = add_bytecode (eps_iface_bytecode eps),
eps_rule_base = extendRuleBaseList (eps_rule_base eps)
@@ -921,10 +912,8 @@ loadInterface doc_str mod from
eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults
}
- ; -- invoke plugins with *full* interface, not final_iface, to ensure
- -- that plugins have access to declarations, etc.
- res <- withPlugins (hsc_plugins hsc_env) (\p -> interfaceLoadAction p) iface
- ; return (Succeeded res)
+ ; res <- withPlugins (hsc_plugins hsc_env) (\p -> interfaceLoadAction p) iface
+ ; return (Succeeded (retainedModIface res))
}}}}
{- Note [Loading your own hi-boot file]
@@ -1389,14 +1378,11 @@ ghcPrimIface
& set_mi_decls []
& set_mi_fixities ghcPrimFixities
& set_mi_fix_fn (mkIfaceFixCache ghcPrimFixities)
- & set_mi_decl_warn_fn (mkIfaceDeclWarnCache ghcPrimWarns)
- & set_mi_export_warn_fn (mkIfaceExportWarnCache ghcPrimWarns)
- & set_mi_fix_fn (mkIfaceFixCache ghcPrimFixities)
& set_mi_docs (Just ghcPrimDeclDocs) -- See Note [GHC.Prim Docs] in GHC.Builtin
& set_mi_warns (toIfaceWarnings ghcPrimWarns) -- See Note [GHC.Prim Deprecations] in GHC.Builtin
where
- empty_iface = emptyFullModIface gHC_PRIM
+ empty_iface = emptyModIface gHC_PRIM
-- | Get gHC_PRIM interface file
--
=====================================
compiler/GHC/Iface/Load.hs-boot
=====================================
@@ -2,7 +2,7 @@ module GHC.Iface.Load where
import GHC.Unit.Module (Module)
import GHC.Tc.Utils.Monad (IfM)
-import GHC.Unit.Module.ModIface (ModIface)
+import GHC.Unit.Module.ModIface (RetainedModIface)
import GHC.Utils.Outputable (SDoc)
-loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
+loadSysInterface :: SDoc -> Module -> IfM lcl RetainedModIface
=====================================
compiler/GHC/Iface/Make.hs
=====================================
@@ -77,6 +77,7 @@ import GHC.Iface.Binary
import GHC.Data.FastString
import GHC.Data.Maybe
+import qualified GHC.Data.Strict as Strict
import GHC.HsToCore.Docs
import GHC.HsToCore.Usage
@@ -394,7 +395,7 @@ mkIface_ hsc_env
& set_mi_docs docs
& set_mi_abi_hashes ()
& set_mi_ext_fields emptyExtensibleFields
- & set_mi_hi_bytes PartialIfaceBinHandle
+ & set_mi_hi_bytes Strict.Nothing
where
cmp_rule = lexicalCompareFS `on` ifRuleName
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -68,7 +68,6 @@ import GHC.Unit.Home
import GHC.Unit.Module
import GHC.Unit.Module.ModIface
import GHC.Unit.Module.ModSummary
-import GHC.Unit.Module.Warnings
import GHC.Unit.Module.Deps
import Control.Monad
@@ -707,7 +706,7 @@ checkDependencies hsc_env summary iface
return $ needsRecompileBecause $ ModulePackageChanged new_name
-needInterface :: Module -> (ModIface -> IO RecompileRequired)
+needInterface :: Module -> (RetainedModIface -> IO RecompileRequired)
-> IfG RecompileRequired
needInterface mod continue
= do
@@ -727,7 +726,7 @@ needBytecode mod continue
Nothing -> return $ NeedsRecompile MustCompile
Just mbc -> liftIO $ continue mbc
-tryGetModIface :: String -> Module -> IfG (Maybe ModIface)
+tryGetModIface :: String -> Module -> IfG (Maybe RetainedModIface)
tryGetModIface doc_msg mod
= do -- Load the imported interface if possible
logger <- getLogger
@@ -779,7 +778,7 @@ checkModUsage _ UsagePackageModule{
logger <- getLogger
needInterface mod $ \iface -> do
let reason = ModuleChanged (moduleName mod)
- checkModuleFingerprint logger reason old_mod_hash (mi_mod_hash iface)
+ checkModuleFingerprint logger reason old_mod_hash (mi_abi_mod_hash (mi_abi_hashes iface))
-- We only track the ABI hash of package modules, rather than
-- individual entity usages, so if the ABI hash changes we must
-- recompile. This is safe but may entail more recompilation when
@@ -789,7 +788,7 @@ checkModUsage _ UsageMergedRequirement{ usg_mod = mod, usg_mod_hash = old_mod_ha
logger <- getLogger
needInterface mod $ \iface -> do
let reason = ModuleChangedRaw (moduleName mod)
- checkModuleFingerprint logger reason old_mod_hash (mi_mod_hash iface)
+ checkModuleFingerprint logger reason old_mod_hash (mi_abi_mod_hash (mi_abi_hashes iface))
checkModUsage _ UsageHomeModuleBytecode{ usg_mod_name = mod_name
, usg_unit_id = uid
, usg_bytecode_hash = old_bytecode_hash } = do
@@ -810,7 +809,7 @@ checkModUsage _ UsageHomeModule{
logger <- getLogger
needInterface mod $ \iface -> do
let
- new_mod_hash = mi_mod_hash iface
+ new_mod_hash = mi_abi_mod_hash (mi_abi_hashes iface)
new_decl_hash = mi_hash_fn iface
reason = ModuleChanged (moduleName mod)
@@ -864,7 +863,7 @@ checkModUsage fc UsageDirectory{ usg_dir_path = dir,
-- Does this require recompilation?
--
-- See Note [When to recompile when export lists change?]
-checkHomeModImport :: Logger -> RecompReason -> Maybe HomeModImport -> ModIface -> IO RecompileRequired
+checkHomeModImport :: Logger -> RecompReason -> Maybe HomeModImport -> RetainedModIface -> IO RecompileRequired
checkHomeModImport _ _ Nothing _ = return UpToDate
checkHomeModImport logger reason
(Just (HomeModImport old_orphan_like_hash old_avails))
@@ -901,8 +900,8 @@ checkHomeModImport logger reason
2 (ppr changes)
return $ needsRecompileBecause reason
where
- new_orphan_like_hash = mi_orphan_like_hash iface
- new_avails_hash = mi_export_avails_hash iface
+ new_orphan_like_hash = mi_abi_orphan_like_hash (mi_abi_hashes iface)
+ new_avails_hash = mi_abi_export_avails_hash (mi_abi_hashes iface)
new_exports = mi_exports iface
-- | The exported avails of a module have changed. Should this cause recompilation
@@ -1299,8 +1298,6 @@ addAbiHashes hsc_env info
= iface_public
-- And these fields of deps should be in IfacePublic, but in good time.
Dependencies _ _ _ sig_mods trusted_pkgs boot_mods orph_mods fis_mods = deps
- decl_warn_fn = mkIfaceDeclWarnCache (fromIfaceWarnings warns)
- export_warn_fn = mkIfaceExportWarnCache (fromIfaceWarnings $ warns)
fix_fn = mkIfaceFixCache fixities
this_mod = mi_mod_info_module info
@@ -1535,10 +1532,10 @@ addAbiHashes hsc_env info
}
caches = IfaceCache
- { mi_cache_decl_warn_fn = decl_warn_fn
- , mi_cache_export_warn_fn = export_warn_fn
+ { mi_cache_decl_warn_fn = ()
+ , mi_cache_export_warn_fn = ()
, mi_cache_fix_fn = fix_fn
- , mi_cache_hash_fn = lookupOccEnv local_env
+ , mi_cache_hash_fn = ()
}
return (final_iface_exts, caches, decls_w_hashes)
where
@@ -1617,7 +1614,7 @@ getOrphanHashes hsc_env mods = do
get_orph_hash mod = do
iface <- initIfaceLoad hsc_env . withIfaceErr ctx
$ loadInterface (text "getOrphanHashes") mod ImportBySystem
- return (mi_orphan_hash iface)
+ return (mi_abi_orphan_hash (mi_abi_hashes iface))
mapM get_orph_hash mods
=====================================
compiler/GHC/Rename/Names.hs
=====================================
@@ -517,7 +517,7 @@ renamePkgQual unit_env mn mb_pkg = case mb_pkg of
-- interface, but without 'imp_mods'.
calculateAvails :: HomeUnit
-> S.Set UnitId
- -> ModIface
+ -> RetainedModIface
-> IsSafeImport
-> IsBootInterface
-> ImportedBy
@@ -525,8 +525,8 @@ calculateAvails :: HomeUnit
calculateAvails home_unit other_home_units iface mod_safe' want_boot imported_by =
let imp_mod = mi_module iface
imp_sem_mod= mi_semantic_module iface
- orph_iface = mi_orphan iface
- has_finsts = mi_finsts iface
+ orph_iface = mi_abi_orphan (mi_abi_hashes iface)
+ has_finsts = mi_abi_finsts (mi_abi_hashes iface)
deps = mi_deps iface
trust = getSafeMode $ mi_trust iface
trust_pkg = mi_trust_pkg iface
@@ -1209,7 +1209,7 @@ gresFromAvail hsc_env prov avail =
gresFromAvails :: HscEnv -> Maybe ImportSpec -> [AvailInfo] -> [GlobalRdrElt]
gresFromAvails hsc_env prov = concatMap (gresFromAvail hsc_env prov)
-importsFromIface :: HscEnv -> ModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv
+importsFromIface :: HscEnv -> RetainedModIface -> ImpDeclSpec -> Maybe NameSet -> GlobalRdrEnv
importsFromIface hsc_env iface decl_spec hidden = mkGlobalRdrEnv $ case hidden of
Nothing -> all_gres
Just hidden_names -> filter (not . (`elemNameSet` hidden_names) . greName) all_gres
@@ -1225,7 +1225,7 @@ rnNamespaceSpecifier (DataNamespaceSpecifier x) = DataNamespaceSpecifier x
filterImports
:: HasDebugCallStack
=> HscEnv
- -> ModIface
+ -> RetainedModIface
-> ImpDeclSpec
-- ^ Import spec
-> Maybe (ImportListInterpretation, [LIE GhcPs])
@@ -2327,7 +2327,7 @@ getMinimalImports ie_decls
where
doc = text "Compute minimal imports for" <+> ppr decl
- to_ie :: GlobalRdrEnv -> ModIface -> AvailInfo -> RnM [IE GhcRn]
+ to_ie :: GlobalRdrEnv -> RetainedModIface -> AvailInfo -> RnM [IE GhcRn]
-- The main trick here is that if we're importing all the constructors
-- we want to say "T(..)", but if we're importing only a subset we want
-- to say "T(A,B,C)". So we have to find out what the module exports.
@@ -2529,7 +2529,7 @@ DRFPatSynExport for a test of this.
-}
badImportItemErr
- :: ModIface -> ImpDeclSpec -> IE GhcPs
+ :: RetainedModIface -> ImpDeclSpec -> IE GhcPs
-> IsSubordinateError
-> [AvailInfo]
-> TcRn (NonEmpty ImportLookupReason)
=====================================
compiler/GHC/Rename/Utils.hs
=====================================
@@ -534,7 +534,7 @@ warnIfDeclDeprecated gre@(GRE { gre_imp = iss })
definedMod = moduleName $ assertPpr (isExternalName name) (ppr name) (nameModule name)
doc = text "The name" <+> quotes (ppr occ) <+> text "is mentioned explicitly"
-lookupImpDeclDeprec :: ModIface -> GlobalRdrElt -> Maybe (WarningTxt GhcRn)
+lookupImpDeclDeprec :: RetainedModIface -> GlobalRdrElt -> Maybe (WarningTxt GhcRn)
lookupImpDeclDeprec iface gre
-- Bleat if the thing, or its parent, is warn'd
= mi_decl_warn_fn iface (greOccName gre) `mplus`
=====================================
compiler/GHC/Runtime/Loader.hs
=====================================
@@ -190,7 +190,7 @@ checkExternalInterpreter hsc_env = case interpInstance <$> hsc_interp hsc_env of
-> throwIO (InstallationError "Plugins require -fno-external-interpreter")
_ -> pure ()
-loadPlugin' :: OccName -> Name -> HscEnv -> ModuleName -> IO (a, ModIface, [LinkableUsage], PkgsLoaded)
+loadPlugin' :: OccName -> Name -> HscEnv -> ModuleName -> IO (a, RetainedModIface, [LinkableUsage], PkgsLoaded)
loadPlugin' occ_name plugin_name hsc_env mod_name
= do { let plugin_rdr_name = mkRdrQual mod_name occ_name
dflags = hsc_dflags hsc_env
@@ -341,7 +341,7 @@ lessUnsafeCoerce logger context what = do
-- Need the module as well to record information in the interface file
lookupRdrNameInModuleForPlugins :: HasDebugCallStack
=> HscEnv -> ModuleName -> RdrName
- -> IO (Maybe (Name, ModIface))
+ -> IO (Maybe (Name, RetainedModIface))
lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do
let dflags = hsc_dflags hsc_env
-- First find the unit the module resides in by searching exposed units and home modules
=====================================
compiler/GHC/Tc/Errors/Ppr.hs
=====================================
@@ -6400,7 +6400,7 @@ pprImportLookup :: ImportLookupReason -> SDoc
pprImportLookup = \case
ImportLookupBad k iface decl_spec ie _exts ->
let
- pprImpDeclSpec :: ModIface -> ImpDeclSpec -> SDoc
+ pprImpDeclSpec :: RetainedModIface -> ImpDeclSpec -> SDoc
pprImpDeclSpec iface decl_spec =
quotes (ppr (moduleName $ is_mod decl_spec)) <+> case mi_boot iface of
IsBoot -> text "(hi-boot interface)"
=====================================
compiler/GHC/Tc/Errors/Types.hs
=====================================
@@ -216,7 +216,7 @@ import GHC.Types.DefaultEnv (ClassDefaults)
import GHC.Unit.Types (Module, ModuleName)
import GHC.Unit.State (UnitState)
-import GHC.Unit.Module.ModIface (ModIface)
+import GHC.Unit.Module.ModIface (RetainedModIface)
import GHC.Utils.Outputable
@@ -6650,7 +6650,7 @@ data ImportLookupReason where
T9006, T11071, T9905fail2, T5385, T10668
-}
ImportLookupBad :: BadImportKind
- -> ModIface
+ -> RetainedModIface
-> ImpDeclSpec
-> IE GhcPs
-> ImportLookupExtensions
=====================================
compiler/GHC/Tc/Gen/Splice.hs
=====================================
@@ -1693,7 +1693,7 @@ lookupArgDoc i nm = do
_ -> pure Nothing
-- | Returns the module a Name belongs to, if it is isn't local.
-getExternalModIface :: Name -> TcM (Maybe ModIface)
+getExternalModIface :: Name -> TcM (Maybe RetainedModIface)
getExternalModIface nm = do
isLocal <- nameIsLocalOrFrom <$> getModule <*> pure nm
if isLocal
=====================================
compiler/GHC/Tc/Instance/Family.hs
=====================================
@@ -309,7 +309,7 @@ checkFamInstConsistency directlyImpMods
ifc <- modIface mod
deps <- dep_finsts . mi_deps <$> modIface mod
pure $
- if mi_finsts ifc
+ if mi_abi_finsts (mi_abi_hashes ifc)
then mod:deps
else deps
=====================================
compiler/GHC/Tc/Module.hs
=====================================
@@ -2968,7 +2968,7 @@ externaliseAndTidyId this_mod id
-- a package module with an interface on disk. If neither of these is
-- true, then the result will be an error indicating the interface
-- could not be found.
-getModuleInterface :: HscEnv -> Module -> IO (Messages TcRnMessage, Maybe ModIface)
+getModuleInterface :: HscEnv -> Module -> IO (Messages TcRnMessage, Maybe RetainedModIface)
getModuleInterface hsc_env mod
= runTcInteractive NoTcMPlugins hsc_env $
loadModuleInterface (text "getModuleInterface") mod
=====================================
compiler/GHC/Unit/External.hs
=====================================
@@ -49,7 +49,7 @@ type PackageAnnEnv = AnnEnv
type PackageCompleteMatches = CompleteMatches
-- | Helps us find information about modules in the imported packages
-type PackageIfaceTable = ModuleEnv ModIface
+type PackageIfaceTable = ModuleEnv RetainedModIface
-- Domain = modules in the imported packages
-- | Constructs an empty PackageIfaceTable
=====================================
compiler/GHC/Unit/Module/ModIface.hs
=====================================
@@ -2,6 +2,7 @@
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE RecordWildCards #-}
module GHC.Unit.Module.ModIface
( ModIface
@@ -68,19 +69,35 @@ module GHC.Unit.Module.ModIface
, set_mi_fix_fn
, set_mi_hash_fn
, completePartialModIface
- , IfaceBinHandle(..)
+ , retainedModIface
+ , IfaceBinHandle
, PartialModIface
+ , RetainedModIface
, IfaceAbiHashes (..)
, IfaceSelfRecomp (..)
- , IfaceCache (..)
+ , IfaceCache_ (..)
, IfaceSimplifiedCore (..)
, withSelfRecomp
- , IfaceDeclExts
- , IfaceAbiHashesExts
+ , IfaceHashData
+ , IfaceSelfRecompData
+ , IfaceSimplifiedCoreData
+ , IfaceExtFieldsData
+ , IfaceAnnotationsData
+ , IfaceDeclsData
+ , IfaceDefaultsData
+ , IfaceClsInstsData
+ , IfaceFamInstsData
+ , IfaceRulesData
+ , IfaceCompleteMatchesData
+ , IfaceAbiHashesData
, IfaceExport
, IfacePublic_(..)
, IfacePublic
, PartialIfacePublic
+ , RetainedIfacePublic
+ , IfaceCache
+ , PartialIfaceCache
+ , RetainedIfaceCache
, IfaceModInfo(..)
, WhetherHasOrphans
, WhetherHasFamInst
@@ -106,7 +123,9 @@ module GHC.Unit.Module.ModIface
, mi_orphan_hash
, renameFreeHoles
, emptyPartialModIface
+ , emptyModIface
, emptyFullModIface
+ , emptyRetainedModIface
, mkIfaceHashCache
, emptyIfaceHashCache
, forceModIface
@@ -147,16 +166,18 @@ import GHC.Utils.Binary
import Control.DeepSeq
import Control.Exception
+import Data.Void (Void)
{- Note [Interface file stages]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Interface files have two possible stages.
+Interface files have three possible stages.
* A partial stage built from the result of the core pipeline.
-* A fully instantiated form. Which also includes fingerprints and
+* A fully instantiated form, which also includes fingerprints and
potentially information provided by backends.
+* A form for retention in the EPS.
We can build a full interface file two ways:
* Directly from a partial one:
@@ -167,9 +188,15 @@ We can build a full interface file two ways:
type PartialModIface = ModIface_ 'ModIfaceCore
type ModIface = ModIface_ 'ModIfaceFinal
+type RetainedModIface = ModIface_ 'ModIfaceRetained
type PartialIfacePublic = IfacePublic_ 'ModIfaceCore
type IfacePublic = IfacePublic_ 'ModIfaceFinal
+type RetainedIfacePublic = IfacePublic_ 'ModIfaceRetained
+
+type PartialIfaceCache = IfaceCache_ 'ModIfaceCore
+type IfaceCache = IfaceCache_ 'ModIfaceFinal
+type RetainedIfaceCache = IfaceCache_ 'ModIfaceRetained
-- | Extends a PartialModIface with hashes of the ABI.
--
@@ -196,14 +223,14 @@ data IfaceAbiHashes = IfaceAbiHashes
-- NOT transitive
}
-data IfaceCache = IfaceCache
- { mi_cache_decl_warn_fn :: !(OccName -> Maybe (WarningTxt GhcRn))
+data IfaceCache_ phase = IfaceCache
+ { mi_cache_decl_warn_fn :: !(IfaceDeclWarningCacheData phase)
-- ^ Cached lookup for 'mi_warns' for declaration deprecations
- , mi_cache_export_warn_fn :: !(Name -> Maybe (WarningTxt GhcRn))
+ , mi_cache_export_warn_fn :: !(IfaceExportWarningCacheData phase)
-- ^ Cached lookup for 'mi_warns' for export deprecations
- , mi_cache_fix_fn :: !(OccName -> Maybe Fixity)
+ , mi_cache_fix_fn :: !(IfaceFixityCacheData phase)
-- ^ Cached lookup for 'mi_fixities'
- , mi_cache_hash_fn :: !(OccName -> Maybe (OccName, Fingerprint))
+ , mi_cache_hash_fn :: !(IfaceHashCacheData phase)
-- ^ Cached lookup for 'mi_decls'. The @Nothing@ in 'mi_hash_fn' means that
-- the thing isn't in decls. It's useful to know that when seeing if we are
-- up to date wrt. the old interface. The 'OccName' is the parent of the
@@ -212,34 +239,103 @@ data IfaceCache = IfaceCache
data ModIfacePhase
= ModIfaceCore
- -- ^ Partial interface built based on output of core pipeline.
+ -- ^ Partial interface built from the output of the core pipeline
| ModIfaceFinal
-
--- | Selects a IfaceDecl representation.
--- For fully instantiated interfaces we also maintain
--- a fingerprint, which is used for recompilation checks.
-type family IfaceDeclExts (phase :: ModIfacePhase) = decl | decl -> phase where
- IfaceDeclExts 'ModIfaceCore = IfaceDecl
- IfaceDeclExts 'ModIfaceFinal = (Fingerprint, IfaceDecl)
-
-type family IfaceAbiHashesExts (phase :: ModIfacePhase) = bk | bk -> phase where
- IfaceAbiHashesExts 'ModIfaceCore = ()
- IfaceAbiHashesExts 'ModIfaceFinal = IfaceAbiHashes
+ -- ^ Complete interface
+ | ModIfaceRetained
+ -- ^ Interface shrunk to the parts that may be retained
-- | In-memory byte array representation of a 'ModIface'.
--
-- See Note [Sharing of ModIface] for why we need this.
-data IfaceBinHandle (phase :: ModIfacePhase) where
- -- | A partial 'ModIface' cannot be serialised to disk.
- PartialIfaceBinHandle :: IfaceBinHandle 'ModIfaceCore
- -- | Optional 'FullBinData' that can be serialised to disk directly.
- --
- -- See Note [Private fields in ModIface] for when this fields needs to be cleared
- -- (e.g., set to 'Nothing').
- FullIfaceBinHandle :: !(Strict.Maybe FullBinData) -> IfaceBinHandle 'ModIfaceFinal
-
-
-withSelfRecomp :: ModIface_ phase -> r -> (IfaceSelfRecomp -> r) -> r
+type family IfaceBinHandle (phase :: ModIfacePhase) where
+ IfaceBinHandle 'ModIfaceCore = Void
+ IfaceBinHandle 'ModIfaceFinal = FullBinData
+ IfaceBinHandle 'ModIfaceRetained = Void
+
+type family IfaceHashData (phase :: ModIfacePhase) where
+ IfaceHashData 'ModIfaceCore = ()
+ IfaceHashData 'ModIfaceFinal = Fingerprint
+ IfaceHashData 'ModIfaceRetained = ()
+
+type family IfaceSelfRecompData (phase :: ModIfacePhase) where
+ IfaceSelfRecompData 'ModIfaceCore = Maybe IfaceSelfRecomp
+ IfaceSelfRecompData 'ModIfaceFinal = Maybe IfaceSelfRecomp
+ IfaceSelfRecompData 'ModIfaceRetained = ()
+
+type family IfaceSimplifiedCoreData (phase :: ModIfacePhase) where
+ IfaceSimplifiedCoreData 'ModIfaceCore = Maybe IfaceSimplifiedCore
+ IfaceSimplifiedCoreData 'ModIfaceFinal = Maybe IfaceSimplifiedCore
+ IfaceSimplifiedCoreData 'ModIfaceRetained = ()
+
+type family IfaceExtFieldsData (phase :: ModIfacePhase) where
+ IfaceExtFieldsData 'ModIfaceCore = ExtensibleFields
+ IfaceExtFieldsData 'ModIfaceFinal = ExtensibleFields
+ IfaceExtFieldsData 'ModIfaceRetained = ()
+
+type family IfaceAnnotationsData (phase :: ModIfacePhase) where
+ IfaceAnnotationsData 'ModIfaceCore = [IfaceAnnotation]
+ IfaceAnnotationsData 'ModIfaceFinal = [IfaceAnnotation]
+ IfaceAnnotationsData 'ModIfaceRetained = ()
+
+-- | The fingerprint in the 'ModIfaceFinal' case is used for recompilation
+-- checks.
+type family IfaceDeclsData (phase :: ModIfacePhase) where
+ IfaceDeclsData 'ModIfaceCore = [IfaceDecl]
+ IfaceDeclsData 'ModIfaceFinal = [(Fingerprint, IfaceDecl)]
+ IfaceDeclsData 'ModIfaceRetained = ()
+
+type family IfaceDefaultsData (phase :: ModIfacePhase) where
+ IfaceDefaultsData 'ModIfaceCore = [IfaceDefault]
+ IfaceDefaultsData 'ModIfaceFinal = [IfaceDefault]
+ IfaceDefaultsData 'ModIfaceRetained = ()
+
+type family IfaceClsInstsData (phase :: ModIfacePhase) where
+ IfaceClsInstsData 'ModIfaceCore = [IfaceClsInst]
+ IfaceClsInstsData 'ModIfaceFinal = [IfaceClsInst]
+ IfaceClsInstsData 'ModIfaceRetained = ()
+
+type family IfaceFamInstsData (phase :: ModIfacePhase) where
+ IfaceFamInstsData 'ModIfaceCore = [IfaceFamInst]
+ IfaceFamInstsData 'ModIfaceFinal = [IfaceFamInst]
+ IfaceFamInstsData 'ModIfaceRetained = ()
+
+type family IfaceRulesData (phase :: ModIfacePhase) where
+ IfaceRulesData 'ModIfaceCore = [IfaceRule]
+ IfaceRulesData 'ModIfaceFinal = [IfaceRule]
+ IfaceRulesData 'ModIfaceRetained = ()
+
+type family IfaceCompleteMatchesData (phase :: ModIfacePhase) where
+ IfaceCompleteMatchesData 'ModIfaceCore = [IfaceCompleteMatch]
+ IfaceCompleteMatchesData 'ModIfaceFinal = [IfaceCompleteMatch]
+ IfaceCompleteMatchesData 'ModIfaceRetained = ()
+
+type family IfaceAbiHashesData (phase :: ModIfacePhase) where
+ IfaceAbiHashesData 'ModIfaceCore = ()
+ IfaceAbiHashesData 'ModIfaceFinal = IfaceAbiHashes
+ IfaceAbiHashesData 'ModIfaceRetained = IfaceAbiHashes
+
+type family IfaceDeclWarningCacheData (phase :: ModIfacePhase) where
+ IfaceDeclWarningCacheData 'ModIfaceCore = ()
+ IfaceDeclWarningCacheData 'ModIfaceFinal = ()
+ IfaceDeclWarningCacheData 'ModIfaceRetained = OccName -> Maybe (WarningTxt GhcRn)
+
+type family IfaceExportWarningCacheData (phase :: ModIfacePhase) where
+ IfaceExportWarningCacheData 'ModIfaceCore = ()
+ IfaceExportWarningCacheData 'ModIfaceFinal = ()
+ IfaceExportWarningCacheData 'ModIfaceRetained = Name -> Maybe (WarningTxt GhcRn)
+
+type family IfaceFixityCacheData (phase :: ModIfacePhase) where
+ IfaceFixityCacheData 'ModIfaceCore = ()
+ IfaceFixityCacheData 'ModIfaceFinal = OccName -> Maybe Fixity
+ IfaceFixityCacheData 'ModIfaceRetained = OccName -> Maybe Fixity
+
+type family IfaceHashCacheData (phase :: ModIfacePhase) where
+ IfaceHashCacheData 'ModIfaceCore = ()
+ IfaceHashCacheData 'ModIfaceFinal = ()
+ IfaceHashCacheData 'ModIfaceRetained = OccName -> Maybe (OccName, Fingerprint)
+
+withSelfRecomp :: ModIface -> r -> (IfaceSelfRecomp -> r) -> r
withSelfRecomp iface nk jk =
case mi_self_recomp_info iface of
Nothing -> nk
@@ -258,12 +354,23 @@ withSelfRecomp iface nk jk =
-- fields.
data ModIface_ (phase :: ModIfacePhase)
= PrivateModIface {
- mi_hi_bytes_ :: !(IfaceBinHandle phase),
- -- ^ A serialised in-memory buffer of this 'ModIface'.
- -- If this handle is given, we can avoid serialising the 'ModIface'
- -- when writing this 'ModIface' to disk, and write this buffer to disk instead.
- -- See Note [Sharing of ModIface].
- mi_iface_hash_ :: Fingerprint, -- A hash of the whole interface
+ mi_hi_bytes_ :: !(Strict.Maybe (IfaceBinHandle phase)),
+ -- ^ Optionally an in-memory buffer that contains the
+ -- serialization of this 'ModIface'. If such a buffer is
+ -- present, we can avoid serialising the 'ModIface' when
+ -- writing it to disk and write this buffer instead. See
+ -- Note [Sharing of ModIface] and
+ -- Note [Private fields in ModIface].
+ --
+ -- Only in the 'ModIfaceFinal' phase, there can be a buffer
+ -- with the serialization. Both @IfaceBinHandle 'ModIfaceCore@
+ -- and @IfaceBinHandle 'ModIfaceRetained@ are defined to be
+ -- 'Void', so that the 'mi_hi_bytes' field gets the type
+ -- @Strict.Maybe Void@. This type is isomorphic to '()', even
+ -- when taking partially defined values into account, because
+ -- @Strict.Just undefined@ is @undefined@ and so @Nothing@ and
+ -- @undefined@ are the only inhabitants of that type.
+ mi_iface_hash_ :: IfaceHashData phase, -- A hash of the whole interface
mi_mod_info_ :: IfaceModInfo,
-- ^ Meta information about the module the interface file is for
@@ -279,11 +386,11 @@ data ModIface_ (phase :: ModIfacePhase)
-- importing this module. The main, original part of an interface.
- mi_self_recomp_ :: Maybe IfaceSelfRecomp,
+ mi_self_recomp_ :: IfaceSelfRecompData phase,
-- ^ Information needed for checking self-recompilation.
-- See Note [Self recompilation information in interface files]
- mi_simplified_core_ :: Maybe IfaceSimplifiedCore,
+ mi_simplified_core_ :: IfaceSimplifiedCoreData phase,
-- ^ The part of the interface written when `-fwrite-if-simplified-core` is enabled.
-- These parts are used to restart bytecode generation.
@@ -301,7 +408,7 @@ data ModIface_ (phase :: ModIfacePhase)
-- defined by the user). Used for GHCi and for inspecting
-- the contents of modules via the GHC API only.
- mi_ext_fields_ :: ExtensibleFields
+ mi_ext_fields_ :: IfaceExtFieldsData phase
-- ^ Additional optional fields, where the Map key represents
-- the field name, resulting in a (size, serialized data) pair.
-- Because the data is intended to be serialized through the
@@ -334,12 +441,12 @@ data IfacePublic_ phase = IfacePublic {
-- ^ Warnings
-- NOT STRICT! we read this field lazily from the interface file
- mi_anns_ :: [IfaceAnnotation],
+ mi_anns_ :: IfaceAnnotationsData phase,
-- ^ Annotations
-- NOT STRICT! we read this field lazily from the interface file
- mi_decls_ :: [IfaceDeclExts phase],
+ mi_decls_ :: IfaceDeclsData phase,
-- ^ Type, class and variable declarations
-- The hash of an Id changes if its fixity or deprecations change
-- (as well as its type of course)
@@ -347,14 +454,14 @@ data IfacePublic_ phase = IfacePublic {
-- the hash of the parent class/tycon changes
- mi_defaults_ :: [IfaceDefault],
+ mi_defaults_ :: IfaceDefaultsData phase,
-- ^ default declarations exported by the module
-- Instance declarations and rules
- mi_insts_ :: [IfaceClsInst], -- ^ Sorted class instance
- mi_fam_insts_ :: [IfaceFamInst], -- ^ Sorted family instances
- mi_rules_ :: [IfaceRule], -- ^ Sorted rules
+ mi_insts_ :: IfaceClsInstsData phase, -- ^ Sorted class instance
+ mi_fam_insts_ :: IfaceFamInstsData phase, -- ^ Sorted family instances
+ mi_rules_ :: IfaceRulesData phase, -- ^ Sorted rules
mi_trust_ :: IfaceTrustInfo,
@@ -367,20 +474,20 @@ data IfacePublic_ phase = IfacePublic {
-- itself) but imports some trustworthy modules from its own
-- package (which does require its own package be trusted).
-- See Note [Trust Own Package] in GHC.Rename.Names
- mi_complete_matches_ :: [IfaceCompleteMatch],
+ mi_complete_matches_ :: IfaceCompleteMatchesData phase,
-- ^ {-# COMPLETE #-} declarations
- mi_caches_ :: IfaceCache,
+ mi_caches_ :: IfaceCache_ phase,
-- ^ Cached lookups of some parts of mi_public
- mi_abi_hashes_ :: (IfaceAbiHashesExts phase)
+ mi_abi_hashes_ :: IfaceAbiHashesData phase
-- ^ Either `()` or `IfaceAbiHashes` for
-- a fully instantiated interface.
-- These fields are hashes of different parts of the public interface.
}
mkIfacePublic :: [IfaceExport]
- -> [IfaceDeclExts 'ModIfaceFinal]
+ -> [(Fingerprint, IfaceDecl)]
-> [(OccName, Fixity)]
-> IfaceWarnings
-> [IfaceAnnotation]
@@ -407,10 +514,10 @@ mkIfacePublic exports decls fixities warns anns defaults insts fam_insts rules t
mi_trust_pkg_ = trust_pkg,
mi_complete_matches_ = complete_matches,
mi_caches_ = IfaceCache {
- mi_cache_decl_warn_fn = mkIfaceDeclWarnCache $ fromIfaceWarnings warns,
- mi_cache_export_warn_fn = mkIfaceExportWarnCache $ fromIfaceWarnings warns,
+ mi_cache_decl_warn_fn = (),
+ mi_cache_export_warn_fn = (),
mi_cache_fix_fn = mkIfaceFixCache fixities,
- mi_cache_hash_fn = mkIfaceHashCache decls
+ mi_cache_hash_fn = ()
},
mi_abi_hashes_ = abi_hashes
}
@@ -501,22 +608,22 @@ That's why in GHC.Driver.Main.hscMaybeWriteIface there is the call to
forceModIface.
-}
-mi_flag_hash :: ModIface_ phase -> Maybe (FingerprintWithValue IfaceDynFlags)
+mi_flag_hash :: ModIface -> Maybe (FingerprintWithValue IfaceDynFlags)
mi_flag_hash = fmap mi_sr_flag_hash . mi_self_recomp_
-mi_opt_hash :: ModIface_ phase -> Maybe Fingerprint
+mi_opt_hash :: ModIface -> Maybe Fingerprint
mi_opt_hash = fmap mi_sr_opt_hash . mi_self_recomp_
-mi_hpc_hash :: ModIface_ phase -> Maybe Fingerprint
+mi_hpc_hash :: ModIface -> Maybe Fingerprint
mi_hpc_hash = fmap mi_sr_hpc_hash . mi_self_recomp_
-mi_src_hash :: ModIface_ phase -> Maybe Fingerprint
+mi_src_hash :: ModIface -> Maybe Fingerprint
mi_src_hash = fmap mi_sr_src_hash . mi_self_recomp_
-mi_usages :: ModIface_ phase -> Maybe [Usage]
+mi_usages :: ModIface -> Maybe [Usage]
mi_usages = fmap mi_sr_usages . mi_self_recomp_
-mi_plugin_hash :: ModIface_ phase -> Maybe Fingerprint
+mi_plugin_hash :: ModIface -> Maybe Fingerprint
mi_plugin_hash = fmap mi_sr_plugin_hash . mi_self_recomp_
-- | Accessor for the module hash of the ABI from a ModIface.
@@ -547,7 +654,7 @@ mi_orphan_hash iface = mi_abi_orphan_hash (mi_abi_hashes iface)
-- | Old-style accessor for whether or not the ModIface came from an hs-boot
-- file.
-mi_boot :: ModIface -> IsBootInterface
+mi_boot :: ModIface_ phase -> IsBootInterface
mi_boot iface = if mi_hsc_src iface == HsBootFile
then IsBoot
else NotBoot
@@ -557,7 +664,7 @@ mi_mnwib iface = GWIB (moduleName $ mi_module iface) (mi_boot iface)
-- | Lookups up a (possibly cached) fixity from a 'ModIface'. If one cannot be
-- found, 'defaultFixity' is returned instead.
-mi_fix :: ModIface -> OccName -> Fixity
+mi_fix :: RetainedModIface -> OccName -> Fixity
mi_fix iface name = mi_fix_fn iface name `orElse` defaultFixity
-- | The semantic module for this interface; e.g., if it's a interface
@@ -573,7 +680,7 @@ mi_semantic_module iface = mi_mod_info_semantic_module (mi_mod_info iface)
-- | The "precise" free holes, e.g., the signatures that this
-- 'ModIface' depends on.
-mi_free_holes :: ModIface -> UniqDSet ModuleName
+mi_free_holes :: ModIface_ phase -> UniqDSet ModuleName
mi_free_holes iface =
case getModuleInstantiation (mi_module iface) of
(_, Just indef)
@@ -654,7 +761,7 @@ instance Binary ModIface where
-- We can't populate this field here, as we are
-- missing the 'mi_ext_fields_' field, which is
-- handled in 'getIfaceWithExtFields'.
- mi_hi_bytes_ = FullIfaceBinHandle Strict.Nothing
+ mi_hi_bytes_ = Strict.Nothing
})
instance Binary IfaceModInfo where
@@ -767,70 +874,109 @@ instance Binary IfaceSimplifiedCore where
emptyPartialModIface :: Module -> PartialModIface
emptyPartialModIface mod
= PrivateModIface
- { mi_mod_info_ = emptyIfaceModInfo mod,
- mi_iface_hash_ = fingerprint0,
- mi_hi_bytes_ = PartialIfaceBinHandle,
- mi_deps_ = noDependencies,
- mi_public_ = emptyPublicModIface (),
- mi_simplified_core_ = Nothing,
- mi_top_env_ = IfaceTopEnv emptyDetOrdAvails [] ,
- mi_docs_ = Nothing,
- mi_self_recomp_ = Nothing,
- mi_ext_fields_ = emptyExtensibleFields
+ {
+ mi_hi_bytes_ = Strict.Nothing,
+ mi_iface_hash_ = (),
+ mi_mod_info_ = emptyIfaceModInfo mod,
+ mi_deps_ = noDependencies,
+ mi_public_ = emptyPartialIfacePublic,
+ mi_self_recomp_ = Nothing,
+ mi_simplified_core_ = Nothing,
+ mi_docs_ = Nothing,
+ mi_top_env_ = IfaceTopEnv emptyDetOrdAvails [],
+ mi_ext_fields_ = emptyExtensibleFields
+ }
+ where
+ emptyIfaceModInfo :: Module -> IfaceModInfo
+ emptyIfaceModInfo mod
+ = IfaceModInfo
+ {
+ mi_mod_info_module = mod,
+ mi_mod_info_sig_of = Nothing,
+ mi_mod_info_hsc_src = HsSrcFile
}
-emptyIfaceModInfo :: Module -> IfaceModInfo
-emptyIfaceModInfo mod = IfaceModInfo
- { mi_mod_info_module = mod
- , mi_mod_info_sig_of = Nothing
- , mi_mod_info_hsc_src = HsSrcFile
- }
-
+ emptyPartialIfacePublic :: PartialIfacePublic
+ emptyPartialIfacePublic
+ = IfacePublic
+ {
+ mi_exports_ = [],
+ mi_fixities_ = [],
+ mi_warns_ = IfWarnSome [] [],
+ mi_anns_ = [],
+ mi_decls_ = [],
+ mi_defaults_ = [],
+ mi_insts_ = [],
+ mi_fam_insts_ = [],
+ mi_rules_ = [],
+ mi_trust_ = noIfaceTrustInfo,
+ mi_trust_pkg_ = False,
+ mi_complete_matches_ = [],
+ mi_caches_ = emptyPartialIfaceCache,
+ mi_abi_hashes_ = ()
+ }
+ where
+
+ emptyPartialIfaceCache :: PartialIfaceCache
+ emptyPartialIfaceCache
+ = IfaceCache
+ {
+ mi_cache_decl_warn_fn = (),
+ mi_cache_export_warn_fn = (),
+ mi_cache_fix_fn = (),
+ mi_cache_hash_fn = ()
+ }
-emptyPublicModIface :: IfaceAbiHashesExts phase -> IfacePublic_ phase
-emptyPublicModIface abi_hashes = IfacePublic
- { mi_exports_ = []
- , mi_decls_ = []
- , mi_fixities_ = []
- , mi_warns_ = IfWarnSome [] []
- , mi_anns_ = []
- , mi_defaults_ = []
- , mi_insts_ = []
- , mi_fam_insts_ = []
- , mi_rules_ = []
- , mi_abi_hashes_ = abi_hashes
- , mi_trust_ = noIfaceTrustInfo
- , mi_trust_pkg_ = False
- , mi_caches_ = emptyModIfaceCache
- , mi_complete_matches_ = []
- }
+emptyModIface :: Module -> ModIface
+emptyModIface mod
+ | PrivateModIface {..} <- emptyPartialModIface mod
+ = PrivateModIface
+ {
+ mi_hi_bytes_ = Strict.Nothing,
+ mi_iface_hash_ = fingerprint0,
+ mi_public_ = convertIfacePublic mi_public_,
+ ..
+ }
+ where
-emptyModIfaceCache :: IfaceCache
-emptyModIfaceCache = IfaceCache {
- mi_cache_decl_warn_fn = emptyIfaceWarnCache,
- mi_cache_export_warn_fn = emptyIfaceWarnCache,
- mi_cache_fix_fn = emptyIfaceFixCache,
- mi_cache_hash_fn = emptyIfaceHashCache
-}
+ convertIfacePublic :: PartialIfacePublic -> IfacePublic
+ convertIfacePublic IfacePublic {..}
+ = IfacePublic
+ {
+ mi_decls_ = [],
+ mi_caches_ = convertIfaceCache mi_caches_,
+ mi_abi_hashes_ = emptyIfaceAbiHashes,
+ ..
+ }
+ where
+
+ convertIfaceCache :: PartialIfaceCache -> IfaceCache
+ convertIfaceCache IfaceCache {..}
+ = IfaceCache
+ {
+ mi_cache_fix_fn = emptyIfaceFixCache,
+ ..
+ }
-emptyIfaceBackend :: IfaceAbiHashes
-emptyIfaceBackend = IfaceAbiHashes
- { mi_abi_mod_hash = fingerprint0,
- mi_abi_orphan = False,
- mi_abi_finsts = False,
+ emptyIfaceAbiHashes :: IfaceAbiHashes
+ emptyIfaceAbiHashes
+ = IfaceAbiHashes
+ {
+ mi_abi_mod_hash = fingerprint0,
+ mi_abi_orphan = False,
+ mi_abi_finsts = False,
mi_abi_export_avails_hash = fingerprint0,
- mi_abi_orphan_like_hash = fingerprint0,
- mi_abi_orphan_hash = fingerprint0
+ mi_abi_orphan_like_hash = fingerprint0,
+ mi_abi_orphan_hash = fingerprint0
}
+{-# DEPRECATED emptyFullModIface "Use the equivalent emptyModIface instead." #-}
emptyFullModIface :: Module -> ModIface
-emptyFullModIface mod =
- (emptyPartialModIface mod)
- { mi_public_ = emptyPublicModIface emptyIfaceBackend
- , mi_hi_bytes_ = FullIfaceBinHandle Strict.Nothing
- }
+emptyFullModIface = emptyModIface
+emptyRetainedModIface :: Module -> RetainedModIface
+emptyRetainedModIface = retainedModIface . emptyModIface
-- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
@@ -848,11 +994,21 @@ emptyIfaceHashCache _occ = Nothing
-- ModIface is completely forced since it will live in memory for a long time.
-- If forcing it uses a lot of memory, then store less things in ModIface.
-instance ( NFData (IfaceAbiHashesExts (phase :: ModIfacePhase))
- , NFData (IfaceDeclExts (phase :: ModIfacePhase))
+instance ( NFData (IfaceHashData phase)
+ , NFData (IfaceSelfRecompData phase)
+ , NFData (IfaceSimplifiedCoreData phase)
+ , NFData (IfaceExtFieldsData phase)
+ , NFData (IfaceAnnotationsData phase)
+ , NFData (IfaceDeclsData phase)
+ , NFData (IfaceDefaultsData phase)
+ , NFData (IfaceClsInstsData phase)
+ , NFData (IfaceFamInstsData phase)
+ , NFData (IfaceRulesData phase)
+ , NFData (IfaceCompleteMatchesData phase)
+ , NFData (IfaceAbiHashesData phase)
) => NFData (ModIface_ phase) where
rnf (PrivateModIface a1 a2 a3 a4 a5 a6 a7 a8 a9 a10)
- = (a1 :: IfaceBinHandle phase)
+ = a1
`seq` rnf a2
`seq` rnf a3
`seq` rnf a4
@@ -882,7 +1038,15 @@ instance NFData IfaceAbiHashes where
`seq` rnf a5
`seq` rnf a6
-instance (NFData (IfaceAbiHashesExts phase), NFData (IfaceDeclExts phase)) => NFData (IfacePublic_ phase) where
+instance ( NFData (IfaceAnnotationsData phase)
+ , NFData (IfaceDeclsData phase)
+ , NFData (IfaceDefaultsData phase)
+ , NFData (IfaceClsInstsData phase)
+ , NFData (IfaceFamInstsData phase)
+ , NFData (IfaceRulesData phase)
+ , NFData (IfaceCompleteMatchesData phase)
+ , NFData (IfaceAbiHashesData phase)
+ ) => NFData (IfacePublic_ phase) where
rnf (IfacePublic a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14)
= rnf a1
`seq` rnf a2
@@ -899,7 +1063,7 @@ instance (NFData (IfaceAbiHashesExts phase), NFData (IfaceDeclExts phase)) => NF
`seq` rnf a13
`seq` rnf a14
-instance NFData IfaceCache where
+instance NFData (IfaceCache_ phase) where
rnf = rwhnf
forceModIface :: ModIface -> IO ()
@@ -955,10 +1119,9 @@ completePartialModIface :: PartialModIface
completePartialModIface partial iface_hash decls extra_decls final_exts cache = partial
{ mi_public_ = completePublicModIface decls final_exts cache (mi_public_ partial)
, mi_simplified_core_ = extra_decls
- , mi_hi_bytes_ = FullIfaceBinHandle Strict.Nothing
+ , mi_hi_bytes_ = Strict.Nothing
, mi_iface_hash_ = iface_hash
}
- where
-- | Given a 'PartialIfacePublic', turn it into an 'IfacePublic' by completing
-- missing fields.
@@ -973,13 +1136,57 @@ completePublicModIface decls abi_hashes cache partial = partial
, mi_caches_ = cache
}
+retainedModIface :: ModIface -> RetainedModIface
+retainedModIface PrivateModIface {..}
+ = PrivateModIface
+ {
+ mi_hi_bytes_ = Strict.Nothing,
+ mi_iface_hash_ = (),
+ mi_public_ = retainedIfacePublic mi_public_,
+ mi_self_recomp_ = (),
+ mi_simplified_core_ = (),
+ mi_ext_fields_ = (),
+ ..
+ }
+ where
+
+ retainedIfacePublic :: IfacePublic -> RetainedIfacePublic
+ retainedIfacePublic IfacePublic {..}
+ = IfacePublic
+ {
+ mi_anns_ = (),
+ mi_decls_ = (),
+ mi_defaults_ = (),
+ mi_insts_ = (),
+ mi_fam_insts_ = (),
+ mi_rules_ = (),
+ mi_complete_matches_ = (),
+ mi_caches_ = retainedIfaceCache mi_caches_,
+ ..
+ }
+ where
+
+ retainedIfaceCache :: IfaceCache -> RetainedIfaceCache
+ retainedIfaceCache IfaceCache {..}
+ = IfaceCache
+ {
+ mi_cache_decl_warn_fn = mkIfaceDeclWarnCache bare_warnings,
+ mi_cache_export_warn_fn = mkIfaceExportWarnCache bare_warnings,
+ mi_cache_hash_fn = mkIfaceHashCache mi_decls_,
+ ..
+ }
+ where
+
+ bare_warnings :: Warnings GhcRn
+ bare_warnings = fromIfaceWarnings mi_warns_
+
set_mi_mod_info :: IfaceModInfo -> ModIface_ phase -> ModIface_ phase
set_mi_mod_info val iface = clear_mi_hi_bytes $ iface { mi_mod_info_ = val }
-set_mi_self_recomp :: Maybe IfaceSelfRecomp-> ModIface_ phase -> ModIface_ phase
+set_mi_self_recomp :: IfaceSelfRecompData phase -> ModIface_ phase -> ModIface_ phase
set_mi_self_recomp val iface = clear_mi_hi_bytes $ iface { mi_self_recomp_ = val }
-set_mi_hi_bytes :: IfaceBinHandle phase -> ModIface_ phase -> ModIface_ phase
+set_mi_hi_bytes :: Strict.Maybe (IfaceBinHandle phase) -> ModIface_ phase -> ModIface_ phase
set_mi_hi_bytes val iface = iface { mi_hi_bytes_ = val }
set_mi_deps :: Dependencies -> ModIface_ phase -> ModIface_ phase
@@ -988,7 +1195,7 @@ set_mi_deps val iface = clear_mi_hi_bytes $ iface { mi_deps_ = val }
set_mi_public :: (IfacePublic_ phase -> IfacePublic_ phase) -> ModIface_ phase -> ModIface_ phase
set_mi_public f iface = clear_mi_hi_bytes $ iface { mi_public_ = f (mi_public_ iface) }
-set_mi_simplified_core :: Maybe IfaceSimplifiedCore -> ModIface_ phase -> ModIface_ phase
+set_mi_simplified_core :: IfaceSimplifiedCoreData phase -> ModIface_ phase -> ModIface_ phase
set_mi_simplified_core val iface = clear_mi_hi_bytes $ iface { mi_simplified_core_ = val }
set_mi_top_env :: IfaceTopEnv -> ModIface_ phase -> ModIface_ phase
@@ -997,7 +1204,7 @@ set_mi_top_env val iface = clear_mi_hi_bytes $ iface { mi_top_env_ = val }
set_mi_docs :: Maybe Docs -> ModIface_ phase -> ModIface_ phase
set_mi_docs val iface = clear_mi_hi_bytes $ iface { mi_docs_ = val }
-set_mi_ext_fields :: ExtensibleFields -> ModIface_ phase -> ModIface_ phase
+set_mi_ext_fields :: IfaceExtFieldsData phase -> ModIface_ phase -> ModIface_ phase
set_mi_ext_fields val iface = clear_mi_hi_bytes $ iface { mi_ext_fields_ = val }
{- Settings for mi_public interface fields -}
@@ -1011,22 +1218,22 @@ set_mi_fixities val = set_mi_public (\iface -> iface { mi_fixities_ = val })
set_mi_warns :: IfaceWarnings -> ModIface_ phase -> ModIface_ phase
set_mi_warns val = set_mi_public (\iface -> iface { mi_warns_ = val })
-set_mi_anns :: [IfaceAnnotation] -> ModIface_ phase -> ModIface_ phase
+set_mi_anns :: IfaceAnnotationsData phase -> ModIface_ phase -> ModIface_ phase
set_mi_anns val = set_mi_public (\iface -> iface { mi_anns_ = val })
-set_mi_insts :: [IfaceClsInst] -> ModIface_ phase -> ModIface_ phase
+set_mi_insts :: IfaceClsInstsData phase -> ModIface_ phase -> ModIface_ phase
set_mi_insts val = set_mi_public (\iface -> iface { mi_insts_ = val })
-set_mi_fam_insts :: [IfaceFamInst] -> ModIface_ phase -> ModIface_ phase
+set_mi_fam_insts :: IfaceFamInstsData phase -> ModIface_ phase -> ModIface_ phase
set_mi_fam_insts val = set_mi_public (\iface -> iface { mi_fam_insts_ = val })
-set_mi_rules :: [IfaceRule] -> ModIface_ phase -> ModIface_ phase
+set_mi_rules :: IfaceRulesData phase -> ModIface_ phase -> ModIface_ phase
set_mi_rules val = set_mi_public (\iface -> iface { mi_rules_ = val })
-set_mi_decls :: [IfaceDeclExts phase] -> ModIface_ phase -> ModIface_ phase
+set_mi_decls :: IfaceDeclsData phase -> ModIface_ phase -> ModIface_ phase
set_mi_decls val = set_mi_public (\iface -> iface { mi_decls_ = val })
-set_mi_defaults :: [IfaceDefault] -> ModIface_ phase -> ModIface_ phase
+set_mi_defaults :: IfaceDefaultsData phase -> ModIface_ phase -> ModIface_ phase
set_mi_defaults val = set_mi_public (\iface -> iface { mi_defaults_ = val })
set_mi_trust :: IfaceTrustInfo -> ModIface_ phase -> ModIface_ phase
@@ -1035,27 +1242,27 @@ set_mi_trust val = set_mi_public (\iface -> iface { mi_trust_ = val })
set_mi_trust_pkg :: Bool -> ModIface_ phase -> ModIface_ phase
set_mi_trust_pkg val = set_mi_public (\iface -> iface { mi_trust_pkg_ = val })
-set_mi_complete_matches :: [IfaceCompleteMatch] -> ModIface_ phase -> ModIface_ phase
+set_mi_complete_matches :: IfaceCompleteMatchesData phase -> ModIface_ phase -> ModIface_ phase
set_mi_complete_matches val = set_mi_public (\iface -> iface { mi_complete_matches_ = val })
-set_mi_abi_hashes :: IfaceAbiHashesExts phase -> ModIface_ phase -> ModIface_ phase
+set_mi_abi_hashes :: IfaceAbiHashesData phase -> ModIface_ phase -> ModIface_ phase
set_mi_abi_hashes val = set_mi_public (\iface -> iface { mi_abi_hashes_ = val })
{- Setters for mi_caches interface fields -}
-set_mi_decl_warn_fn :: (OccName -> Maybe (WarningTxt GhcRn)) -> ModIface_ phase -> ModIface_ phase
+set_mi_decl_warn_fn :: IfaceDeclWarningCacheData phase -> ModIface_ phase -> ModIface_ phase
set_mi_decl_warn_fn val = set_mi_public (\iface -> iface { mi_caches_ = (mi_caches_ iface) { mi_cache_decl_warn_fn = val } })
-set_mi_export_warn_fn :: (Name -> Maybe (WarningTxt GhcRn)) -> ModIface_ phase -> ModIface_ phase
+set_mi_export_warn_fn :: IfaceExportWarningCacheData phase -> ModIface_ phase -> ModIface_ phase
set_mi_export_warn_fn val = set_mi_public (\iface -> iface { mi_caches_ = (mi_caches_ iface) { mi_cache_export_warn_fn = val } })
-set_mi_fix_fn :: (OccName -> Maybe Fixity) -> ModIface_ phase -> ModIface_ phase
+set_mi_fix_fn :: IfaceFixityCacheData phase -> ModIface_ phase -> ModIface_ phase
set_mi_fix_fn val = set_mi_public (\iface -> iface { mi_caches_ = (mi_caches_ iface) { mi_cache_fix_fn = val } })
-set_mi_hash_fn :: (OccName -> Maybe (OccName, Fingerprint)) -> ModIface_ phase -> ModIface_ phase
+set_mi_hash_fn :: IfaceHashCacheData phase -> ModIface_ phase -> ModIface_ phase
set_mi_hash_fn val = set_mi_public (\iface -> iface { mi_caches_ = (mi_caches_ iface) { mi_cache_hash_fn = val } })
-set_mi_caches :: IfaceCache -> ModIface_ phase -> ModIface_ phase
+set_mi_caches :: IfaceCache_ phase -> ModIface_ phase -> ModIface_ phase
set_mi_caches val = set_mi_public (\iface -> iface { mi_caches_ = val })
{-
@@ -1082,11 +1289,7 @@ set_mi_mod_info_field f iface = clear_mi_hi_bytes $ iface { mi_mod_info_ = f (mi
-- | Invalidate any byte array buffer we might have.
clear_mi_hi_bytes :: ModIface_ phase -> ModIface_ phase
-clear_mi_hi_bytes iface = iface
- { mi_hi_bytes_ = case mi_hi_bytes iface of
- PartialIfaceBinHandle -> PartialIfaceBinHandle
- FullIfaceBinHandle _ -> FullIfaceBinHandle Strict.Nothing
- }
+clear_mi_hi_bytes iface = iface { mi_hi_bytes_ = Strict.Nothing }
-- ----------------------------------------------------------------------------
-- 'ModIface' pattern synonyms to keep breakage low.
@@ -1177,33 +1380,33 @@ pattern ModIface ::
-> Module
-> Maybe Module
-> HscSource
- -> Fingerprint
+ -> IfaceHashData phase
-> Dependencies
-> IfacePublic_ phase
-> [IfaceExport]
-> [(OccName, Fixity)]
-> IfaceWarnings
- -> [IfaceAnnotation]
- -> [IfaceDeclExts phase]
- -> Maybe IfaceSimplifiedCore
- -> [IfaceDefault]
+ -> IfaceAnnotationsData phase
+ -> IfaceDeclsData phase
+ -> IfaceSimplifiedCoreData phase
+ -> IfaceDefaultsData phase
-> IfaceTopEnv
- -> [IfaceClsInst]
- -> [IfaceFamInst]
- -> [IfaceRule]
+ -> IfaceClsInstsData phase
+ -> IfaceFamInstsData phase
+ -> IfaceRulesData phase
-> IfaceTrustInfo
-> Bool
- -> [IfaceCompleteMatch]
+ -> IfaceCompleteMatchesData phase
-> Maybe Docs
- -> IfaceAbiHashesExts phase
- -> ExtensibleFields
- -> IfaceBinHandle phase
- -> Maybe IfaceSelfRecomp
- -> (OccName -> Maybe Fixity)
- -> (OccName -> Maybe (OccName, Fingerprint))
- -> (OccName -> Maybe (WarningTxt GhcRn))
- -> (Name -> Maybe (WarningTxt GhcRn)) ->
- ModIface_ phase
+ -> IfaceAbiHashesData phase
+ -> IfaceExtFieldsData phase
+ -> Strict.Maybe (IfaceBinHandle phase)
+ -> IfaceSelfRecompData phase
+ -> IfaceFixityCacheData phase
+ -> IfaceHashCacheData phase
+ -> IfaceDeclWarningCacheData phase
+ -> IfaceExportWarningCacheData phase
+ -> ModIface_ phase
pattern ModIface
{ mi_mod_info
, mi_module
=====================================
ghc/Main.hs
=====================================
@@ -515,7 +515,7 @@ abiHash strs = do
put_ bh hiVersion
-- package hashes change when the compiler version changes (for now)
-- see #5328
- mapM_ (put_ bh . mi_mod_hash) ifaces
+ mapM_ (put_ bh . mi_abi_mod_hash . mi_abi_hashes) ifaces
f <- fingerprintBinMem bh
putStrLn (showPpr dflags f)
=====================================
utils/count-deps/Main.hs
=====================================
@@ -79,5 +79,5 @@ calcDeps modName libdir =
mkModule :: String -> ModuleName -> Module
mkModule ghcUnitId = Module (stringToUnit ghcUnitId)
- modDeps :: ModIface -> [ModuleName]
+ modDeps :: ModIface_ phase -> [ModuleName]
modDeps mi = map (gwib_mod . (\(_, _, mn) -> mn)) $ Set.toList $ dep_direct_mods (mi_deps mi)
=====================================
utils/haddock/haddock-api/src/Haddock/Interface.hs
=====================================
@@ -56,21 +56,25 @@ import GHC.Driver.Monad
import GHC.Driver.Make
import GHC.Driver.Main
import GHC.Core.InstEnv
+import GHC.Core.FamInstEnv
import qualified GHC.Driver.DynFlags as DynFlags
import qualified GHC.Utils.Outputable as Outputable
import GHC.Driver.Session hiding (verbosity)
import GHC.Driver.Phases
import GHC.Driver.Pipeline (compileFile)
import GHC.HsToCore.Docs (getMainDeclBinder)
-import GHC.Iface.Load (loadSysInterface)
-import GHC.IfaceToCore (tcIfaceInst, tcIfaceFamInst)
-import GHC.Tc.Utils.Monad (initIfaceLoad, initIfaceLcl)
+import GHC.Iface.Load (findAndReadIface)
+import GHC.IfaceToCore (tcIfaceDecls, tcIfaceInst, tcIfaceFamInst)
+import GHC.Tc.Utils.Monad (goptM, updateEps_, initIfaceLoad, initIfaceLcl)
import GHC.Tc.Utils.Env (lookupGlobal_maybe)
import GHC.Types.Error (mkUnknownDiagnostic)
import GHC.Types.Name.Occurrence (emptyOccEnv)
+import GHC.Types.Name.Env (extendNameEnvList)
import GHC.Unit.Finder (findImportedModule, runFinderM, ModuleLookupScope(..), FindResult(Found))
import GHC.Unit.Home.ModInfo
import GHC.Unit.Home.PackageTable
+import GHC.Unit.External (eps_PTE, eps_inst_env, eps_fam_inst_env)
+import GHC.Unit.Module (getModuleInstantiation)
import GHC.Unit.Module.Graph (ModuleGraphNode (..), ModuleNodeInfo(..))
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface (mi_semantic_module, mi_boot)
@@ -254,19 +258,29 @@ dropErr :: MaybeErr e a -> Maybe a
dropErr (Succeeded a) = Just a
dropErr (Failed _) = Nothing
-loadHiFile :: HscEnv -> Outputable.SDoc -> Module -> IO (ModIface, ([ClsInst], [FamInst]))
-loadHiFile hsc_env doc theModule = initIfaceLoad hsc_env $ do
-
- mod_iface <- loadSysInterface doc theModule
-
- insts <- initIfaceLcl (mi_semantic_module mod_iface) doc (mi_boot mod_iface) $ do
-
- new_eps_insts <- mapM tcIfaceInst (mi_insts mod_iface)
- new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts mod_iface)
-
- pure (new_eps_insts, new_eps_fam_insts)
-
- pure (mod_iface, insts)
+loadHiFile :: Verbosity -> HscEnv -> Outputable.SDoc -> Module -> IO (ModIface, ([ClsInst], [FamInst]))
+loadHiFile verbosity hsc_env doc requested = initIfaceLoad hsc_env $ do
+ let installed = fst (getModuleInstantiation requested)
+ iface_fetch_result <- liftIO $ findAndReadIface hsc_env doc installed requested NotBoot
+ case iface_fetch_result of
+ Failed _ -> do
+ out verbosity normal $ "Loading interface for " ++
+ moduleNameString (moduleName requested) ++
+ " failed"
+ liftIO exitFailure
+ Succeeded (mod_iface, _) -> do
+ all_insts <- initIfaceLcl (mi_semantic_module mod_iface) doc (mi_boot mod_iface) $ do
+ ignore_iface_pragmas <- goptM Opt_IgnoreInterfacePragmas
+ decls <- tcIfaceDecls ignore_iface_pragmas (mi_decls mod_iface)
+ insts <- mapM tcIfaceInst (mi_insts mod_iface)
+ fam_insts <- mapM tcIfaceFamInst (mi_fam_insts mod_iface)
+ updateEps_ $ \ eps -> eps {
+ eps_PTE = extendNameEnvList (eps_PTE eps) decls,
+ eps_inst_env = extendInstEnvList (eps_inst_env eps) insts,
+ eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps) fam_insts
+ }
+ pure (insts, fam_insts)
+ pure (mod_iface, all_insts)
processModule :: Verbosity -> ModSummary -> [Flag] -> IfaceMap -> InstIfaceMap -> WarningMap -> Ghc (Maybe Interface)
processModule verbosity modSummary flags ifaceMap instIfaceMap warningMap = do
@@ -279,7 +293,7 @@ processModule verbosity modSummary flags ifaceMap instIfaceMap warningMap = do
unit_state = hsc_units hsc_env
(mod_iface, insts) <- if Flag_NoCompilation `elem` flags
- then liftIO $ loadHiFile hsc_env doc $ ms_mod modSummary
+ then liftIO $ loadHiFile verbosity hsc_env doc $ ms_mod modSummary
else do
hmi <- liftIO $ lookupHpt (hsc_HPT hsc_env) (moduleName $ ms_mod modSummary) >>= \case
Nothing -> error "processModule: All modules should be loaded into the HPT by this point"
@@ -376,7 +390,7 @@ createOneShotIface verbosity flags instIfaceMap moduleNameStr = do
let oneShotUnit = stringToUnit (unitIdString (homeUnitId_ dflags))
- (iface, insts) <- liftIO $ loadHiFile hsc_env doc $ mkModule oneShotUnit moduleNm
+ (iface, insts) <- liftIO $ loadHiFile verbosity hsc_env doc $ mkModule oneShotUnit moduleNm
-- Update the DynFlags with the extensions from the source file (as stored in the interface file)
-- This is instead of ms_hspp_opts from ModSummary, which is not available in one-shot mode.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1e837e6428ca976e0e04057858d7d0…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1e837e6428ca976e0e04057858d7d0…
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
1
0