[Git][ghc/ghc][wip/fendor/one-shot-no-eps] 2 commits: Make Haddock avoid the PIT
Hannes Siebenhandl pushed to branch wip/fendor/one-shot-no-eps at Glasgow Haskell Compiler / GHC Commits: c18b3e6f by Wolfgang Jeltsch at 2026-11-20T16:06:07+01: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. - - - - - 56cd7264 by Hannes Siebenhandl at 2026-11-20T16:06:07+01:00 WIP: one-shot uses home loader state - - - - - 21 changed files: - compiler/GHC/Core/Opt/Monad.hs - compiler/GHC/Core/Opt/Pipeline.hs - compiler/GHC/Core/Opt/Simplify.hs - compiler/GHC/Core/Opt/Specialise.hs - compiler/GHC/Core/Rules.hs - compiler/GHC/Driver/Env.hs - compiler/GHC/Driver/Main/Passes.hs - compiler/GHC/HsToCore/Monad.hs - compiler/GHC/Iface/Load.hs - compiler/GHC/Iface/Recomp.hs - compiler/GHC/IfaceToCore.hs - compiler/GHC/Linker/Deps.hs - compiler/GHC/Tc/Instance/Family.hs - compiler/GHC/Tc/Module.hs - compiler/GHC/Tc/Utils/Env.hs - compiler/GHC/Tc/Utils/Instantiate.hs - compiler/GHC/Tc/Utils/Monad.hs - compiler/GHC/Unit/External.hs - compiler/GHC/Unit/Home/PackageTable.hs - compiler/GHC/Unit/Module/Env.hs - utils/haddock/haddock-api/src/Haddock/Interface.hs Changes: ===================================== compiler/GHC/Core/Opt/Monad.hs ===================================== @@ -16,8 +16,8 @@ module GHC.Core.Opt.Monad ( -- ** Reading from the monad getModule, - initRuleEnv, getExternalRuleBase, - getDynFlags, getPackageFamInstEnv, + initRuleEnv, getExternalRuleBase, getLazyHomeRuleBase, + getDynFlags, getPackageFamInstEnv, getLazyHomeFamInstEnv, getInteractiveContext, getUniqTag, getNamePprCtx, getSrcSpanM, @@ -44,7 +44,7 @@ import GHC.Driver.Errors ( reportDiagnostic, reportError ) import GHC.Driver.Config.Diagnostic ( initDiagOpts ) import GHC.Driver.Env -import GHC.Core.Rules ( RuleBase, RuleEnv, mkRuleEnv ) +import GHC.Core.Rules ( RuleBase, RuleEnv, mkRuleEnv, unionRuleBase ) import GHC.Core.Opt.Stats ( SimplCount, zeroSimplCount, plusSimplCount ) import GHC.Types.Annotations @@ -73,6 +73,9 @@ import Data.Dynamic import Data.Maybe (listToMaybe) import Control.Monad import Control.Applicative ( Alternative(..) ) +import GHC.Unit.Home.PackageTable (HomePackageTable) +import qualified GHC.Unit.Home.PackageTable as HomePackageTable +import GHC.Core.FamInstEnv data FloatOutSwitches = FloatOutSwitches { floatOutLambdas :: Maybe Int -- ^ Just n <=> float lambdas to top level, if @@ -248,7 +251,10 @@ instance HasHscEnv CoreM where getHscEnv = read cr_hsc_env getHomeRuleBase :: CoreM RuleBase -getHomeRuleBase = read cr_rule_base +getHomeRuleBase = do + hptRules <- read cr_rule_base + extraRules <- getLazyHomeRuleBase + pure $ hptRules `unionRuleBase` extraRules initRuleEnv :: ModGuts -> CoreM RuleEnv initRuleEnv guts @@ -259,6 +265,9 @@ initRuleEnv guts getExternalRuleBase :: CoreM RuleBase getExternalRuleBase = eps_rule_base <$> get_eps +getLazyHomeRuleBase :: CoreM RuleBase +getLazyHomeRuleBase = get_hpt HomePackageTable.hptLoadedRuleBase + getNamePprCtx :: CoreM NamePprCtx getNamePprCtx = read cr_name_ppr_ctx @@ -302,11 +311,20 @@ getInteractiveContext = hsc_IC <$> getHscEnv getPackageFamInstEnv :: CoreM PackageFamInstEnv getPackageFamInstEnv = eps_fam_inst_env <$> get_eps +getLazyHomeFamInstEnv :: CoreM FamInstEnv +getLazyHomeFamInstEnv = get_hpt HomePackageTable.hptLoadedFamInstEnv + get_eps :: CoreM ExternalPackageState get_eps = do hsc_env <- getHscEnv liftIO $ hscEPS hsc_env +get_hpt :: (HomePackageTable -> IO a) -> CoreM a +get_hpt f = do + hsc_env <- getHscEnv + a <- liftIO $ f $ hsc_HPT hsc_env + pure a + {- ************************************************************************ * * ===================================== compiler/GHC/Core/Opt/Pipeline.hs ===================================== @@ -449,8 +449,9 @@ doCorePass pass guts = do dflags <- getDynFlags us <- getUniqueSupplyM p_fam_env <- getPackageFamInstEnv + l_fam_env <- getLazyHomeFamInstEnv let platform = targetPlatform dflags - let fam_envs = (p_fam_env, mg_fam_inst_env guts) + let fam_envs = (p_fam_env `unionFamInstEnv` l_fam_env, mg_fam_inst_env guts) let updateBinds f = return $ guts { mg_binds = f (mg_binds guts) } let updateBindsM f = f (mg_binds guts) >>= \b' -> return $ guts { mg_binds = b' } let updateBindsAndRulesM f = f (mg_binds guts) (mg_rules guts) >>= \(b',r') -> return $ guts { mg_binds = b', mg_rules = r' } ===================================== compiler/GHC/Core/Opt/Simplify.hs ===================================== @@ -30,7 +30,7 @@ import GHC.Utils.Logger as Logger import GHC.Utils.Outputable import GHC.Utils.Constants (debugIsOn) -import GHC.Unit.Env ( UnitEnv, ueEPS ) +import GHC.Unit.Env ( UnitEnv, ueEPS, ue_hpt ) import GHC.Unit.External import GHC.Unit.Module.ModGuts @@ -44,6 +44,7 @@ import GHC.Types.Unique.FM import Control.Monad import Data.Foldable ( for_ ) +import GHC.Unit.Home.PackageTable (hptLoadedRuleBase, HomePackageTable) {- ************************************************************************ @@ -63,13 +64,14 @@ data SimplifyExprOpts = SimplifyExprOpts simplifyExpr :: Logger -> ExternalUnitCache + -> HomePackageTable -> SimplifyExprOpts -> CoreExpr -> IO CoreExpr -- ^ Simplify an expression using 'simplExprGently'. -- -- See 'simplExprGently' for details. -simplifyExpr logger euc opts expr +simplifyExpr logger euc hpt opts expr = withTiming logger (text "Simplify [expr]") (const ()) $ do { eps <- eucEPS euc ; ; let fam_envs = ( eps_fam_inst_env eps @@ -81,7 +83,8 @@ simplifyExpr logger euc opts expr base_env = mkSimplEnv (se_mode opts) fam_envs top_env_cfg = se_top_env_cfg opts read_eps_rules = eps_rule_base <$> eucEPS euc - read_ruleenv = updExternalPackageRules emptyRuleEnv <$> read_eps_rules + read_home_rules = hptLoadedRuleBase hpt + read_ruleenv = (\ home_rules eps_rules -> updExternalPackageRules (updHomePackageRules emptyRuleEnv home_rules) eps_rules) <$> read_home_rules <*> read_eps_rules ; let sz = exprSize expr @@ -285,8 +288,11 @@ simplifyPgm logger unit_env name_ppr_ctx opts ; read_eps_rules :: IO PackageRuleBase ; read_eps_rules = eps_rule_base <$> ueEPS unit_env + ; read_home_rules :: IO RuleBase + ; read_home_rules = hptLoadedRuleBase (ue_hpt unit_env) + ; read_rule_env :: IO RuleEnv - ; read_rule_env = updExternalPackageRules base_rule_env <$> read_eps_rules + ; read_rule_env = (\ home_rules eps_rules -> updExternalPackageRules (updHomePackageRules base_rule_env home_rules) eps_rules) <$> read_home_rules <*> read_eps_rules ; fam_envs = (eps_fam_inst_env eps, fam_inst_env) ; simpl_env = mkSimplEnv mode fam_envs } ; ===================================== compiler/GHC/Core/Opt/Specialise.hs ===================================== @@ -854,7 +854,8 @@ spec_import env callers dict_binds cis@(CIS fn _) -- We keep doing this in case we "page-fault in" -- more rules as we go along ; eps_rules <- getExternalRuleBase - ; let rule_env = se_rules env `updExternalPackageRules` eps_rules + ; home_rules <- getLazyHomeRuleBase + ; let rule_env = se_rules env `updHomePackageRules` home_rules `updExternalPackageRules` eps_rules -- ; debugTraceMsg (text "specImport1" <+> vcat -- [ text "function:" <+> ppr fn ===================================== compiler/GHC/Core/Rules.hs ===================================== @@ -13,8 +13,9 @@ module GHC.Core.Rules ( -- ** RuleBase, RuleEnv RuleBase, RuleEnv(..), mkRuleEnv, emptyRuleEnv, - updExternalPackageRules, addLocalRules, updLocalRules, - emptyRuleBase, mkRuleBase, extendRuleBaseList, + updExternalPackageRules, updHomePackageRules, + addLocalRules, updLocalRules, + emptyRuleBase, mkRuleBase, extendRuleBaseList, unionRuleBase, pprRuleBase, -- ** Checking rule applications @@ -398,6 +399,10 @@ extendRuleBase rule_base rule lookupRuleBase :: RuleBase -> Unique -> Maybe [CoreRule] lookupRuleBase = lookupUFM +unionRuleBase :: RuleBase -> RuleBase -> RuleBase +unionRuleBase + = plusUFM + pprRuleBase :: RuleBase -> SDoc pprRuleBase rules = pprUFM rules $ \rss -> vcat [ pprRules (tidyRules emptyTidyEnv rs) @@ -433,6 +438,10 @@ updExternalPackageRules :: RuleEnv -> RuleBase -> RuleEnv updExternalPackageRules rule_env eps_rules = rule_env { re_eps_rules = eps_rules } +updHomePackageRules :: RuleEnv -> RuleBase -> RuleEnv +updHomePackageRules rule_env eps_rules + = rule_env { re_home_rules = (re_home_rules rule_env ) `unionRuleBase` eps_rules } + updLocalRules :: RuleEnv -> [CoreRule] -> RuleEnv -- Completely over-ride the local rules in RuleEnv updLocalRules rule_env local_rules ===================================== compiler/GHC/Driver/Env.hs ===================================== @@ -98,6 +98,7 @@ import GHC.Builtin.Modules( gHC_PRIM ) import Data.IORef import qualified Data.Set as Set import GHC.Types.Name.Reader (ExactRdrName(..)) +import qualified GHC.Unit.Home.PackageTable as HomePackageTable runHsc :: HscEnv -> Hsc a -> IO a runHsc hsc_env hsc = do @@ -348,10 +349,11 @@ prepareAnnotations hsc_env mb_guts = do home_pkg_anns <- fromMaybe (hugAllAnns (hsc_unit_env hsc_env)) $ uncurry (hugAnnsBelow hsc_env) . get_mod <$> mb_guts + more_home_pkg_anns <- HomePackageTable.hptLoadedAnnEnv $ hsc_HPT hsc_env let other_pkg_anns = eps_ann_env eps !ann_env = maybe id plusAnnEnv mb_this_module_anns $! - plusAnnEnv home_pkg_anns other_pkg_anns + plusAnnEnv home_pkg_anns (plusAnnEnv more_home_pkg_anns other_pkg_anns) return ann_env -- | Find the 'TyThing' for the given 'Name' by using all the resources @@ -374,12 +376,9 @@ lookupTypeInPTE hsc_env pte name = ty then mkHomeModule (hsc_home_unit hsc_env) (moduleName (nameModule name)) else nameModule name - ty = if isOneShot (ghcMode (hsc_dflags hsc_env)) - -- in one-shot, we don't use the HPT - then return $! lookupNameEnv pte name - else HUG.lookupHugByModule mod hpt >>= \case - Just hm -> pure $! lookupNameEnv (md_types (hm_details hm)) name - Nothing -> pure $! lookupNameEnv pte name + ty = HUG.lookupHugByModule mod hpt >>= \case + Just hm -> pure $! lookupNameEnv (md_types (hm_details hm)) name + Nothing -> pure $! lookupNameEnv pte name -- | Find the 'ModIface' for a 'Module', searching in both the loaded home -- and external package module information ===================================== compiler/GHC/Driver/Main/Passes.hs ===================================== @@ -1546,7 +1546,7 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr = do let unit_env = hsc_unit_env hsc_env let simplify_expr_opts = initSimplifyExprOpts dflags ic - simpl_expr <- simplifyExpr logger (ue_eps unit_env) simplify_expr_opts ds_expr + simpl_expr <- simplifyExpr logger (ue_eps unit_env) (ue_hpt unit_env) simplify_expr_opts ds_expr -- Create a unique temporary binding -- ===================================== compiler/GHC/HsToCore/Monad.hs ===================================== @@ -131,6 +131,7 @@ import GHC.Data.OrdList import Data.IORef import GHC.IO.Unsafe (unsafeInterleaveIO) +import qualified GHC.Unit.Home.PackageTable as HomePackageTable {- ************************************************************************ @@ -385,6 +386,7 @@ mkDsEnvsFromTcGbl hsc_env msg_var tcg_env -- ToDo: what becomes of the values put into these ref-cells? ; eps <- liftIO $ hscEPS hsc_env + ; extra_matches <- liftIO $ HomePackageTable.hptLoadedCompleteMatches $ hsc_HPT hsc_env ; let unit_env = hsc_unit_env hsc_env this_mod = tcg_mod tcg_env type_env = tcg_type_env tcg_env @@ -406,7 +408,7 @@ mkDsEnvsFromTcGbl hsc_env msg_var tcg_env -- Relevant test case: MultiLayerModulesTH_Make, which regresses -- in allocations by ~5% if we don't do this. traverse (lookupCompleteMatch type_env hsc_env) =<< - localAndImportedCompleteMatches tcg_comp_env eps + localAndImportedCompleteMatches (tcg_comp_env ++ extra_matches) eps ; tcm_plugins <- liftIO $ readIORef (tcg_plugins tcg_env) -- Pass the running 'TcM' plugins to the desugarer, so that the pattern-match @@ -469,6 +471,7 @@ initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds ; statics_var <- newIORef nilOL ; known_key_maps_var <- newIORef Nothing ; eps <- liftIO $ hscEPS hsc_env + ; extra_matches <- liftIO $ HomePackageTable.hptLoadedCompleteMatches $ hsc_HPT hsc_env ; let unit_env = hsc_unit_env hsc_env type_env = typeEnvFromEntities ids tycons patsyns fam_insts ptc = initPromotionTickContext (hsc_dflags hsc_env) @@ -476,7 +479,7 @@ initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds bindsToIds (Rec binds) = map fst binds ids = concatMap bindsToIds binds ; ds_complete_matches <- traverse (lookupCompleteMatch type_env hsc_env) =<< - localAndImportedCompleteMatches local_complete_matches eps + localAndImportedCompleteMatches (local_complete_matches ++ extra_matches) eps ; let tcm_plugins = emptyTcMPluginsRun envs = mkDsEnvs unit_env this_mod rdr_env type_env @@ -842,8 +845,8 @@ dsGetFamInstEnvs :: DsM FamInstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) dsGetFamInstEnvs - = do { eps <- getEps; env <- getGblEnv - ; return (eps_fam_inst_env eps, ds_fam_inst_env env) } + = do { eps <- getEps; env <- getGblEnv; lazy_env <- queryHpt HomePackageTable.hptLoadedFamInstEnv + ; return (eps_fam_inst_env eps, ds_fam_inst_env env `unionFamInstEnv` lazy_env) } dsGetMetaEnv :: DsM (NameEnv DsMetaVal) dsGetMetaEnv = do { env <- getLclEnv; return (dsl_meta env) } ===================================== compiler/GHC/Iface/Load.hs ===================================== @@ -152,6 +152,13 @@ import Data.Function ((&)) import Data.Map ( toList ) import System.FilePath import System.Directory +import GHC.Types.DefaultEnv (DefaultEnv) +import GHC.Core (CoreRule) +import GHC.Unit.Module.ModDetails (ModDetails(..)) +import GHC.Unit.Home.ModInfo (HomeModInfo(..), emptyHomeModInfoLinkable) +import qualified Data.Set as Set +import qualified GHC.Unit.Home.PackageTable as HomePackageTable +import Control.Applicative ((<|>)) {- ********************************************************************* @@ -513,8 +520,9 @@ importDecl name ; Succeeded _ -> do -- Now look it up again; this time we should find it - { eps <- getEps - ; case lookupTypeEnv (eps_PTE eps) name of + { eps <- getEps -- @fendor: DONE + ; loaderTypeEnv <- queryHpt HomePackageTable.hptLoadedTypeEnv + ; case lookupTypeEnv loaderTypeEnv name <|> lookupTypeEnv (eps_PTE eps) name of Just thing -> return $ Succeeded thing Nothing -> return $ Failed $ Can'tFindNameInInterface name @@ -789,7 +797,9 @@ loadInterface doc_str mod from _ -> do { -- READ THE MODULE IN - ; read_result <- case wantHiBootFile mhome_unit eps mod from of + ; hpt <- getHpt + ; hls <- liftIO (hptLoaderState hpt) + ; read_result <- case wantHiBootFile mhome_unit hls mod from of Failed err -> return (Failed err) Succeeded hi_boot_file -> do hsc_env <- getTopEnv @@ -818,108 +828,37 @@ loadInterface doc_str mod from let loc_doc = text (ml_hi_file loc) in - initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $ - - dontLeakTheHUG $ do - - -- Load the new ModIface into the External Package State - -- Even home-package interfaces loaded by loadInterface - -- (which only happens in OneShot mode; in Batch/Interactive - -- mode, home-package modules are loaded one by one into the HPT) - -- are put in the EPS. - -- - -- The main thing is to add the ModIface to the PIT, but - -- we also take the - -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules, - -- out of the ModIface and put them into the big EPS pools - - -- NB: *first* we do tcIfaceDecls, so that the provenance of all the locally-defined - --- names is done correctly (notably, whether this is an .hi file or .hi-boot file). - -- If we do loadExport first the wrong info gets into the cache (unless we - -- explicitly tag each export which seems a bit of a bore) - - -- Crucial assertion that checks if you are trying to load a HPT module into the EPS. - -- If you start loading HPT modules into the EPS then you get strange errors about - -- overlapping instances. - ; massertPpr - ((isOneShot (ghcMode (hsc_dflags hsc_env))) - || moduleUnitId mod `notElem` hsc_all_home_unit_ids hsc_env - || mod == gHC_PRIM) - (text "Attempting to load home package interface into the EPS" $$ ppr (HUG.allUnits hug) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod)) - ; ignore_prags <- goptM Opt_IgnoreInterfacePragmas - ; new_eps_decls <- tcIfaceDecls ignore_prags (mi_decls iface) - ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface) - ; new_eps_defaults <- tcIfaceDefaults mod (mi_defaults iface) - ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface) - ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface) - ; new_eps_anns <- tcIfaceAnnotations (mi_anns iface) - ; 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 - && isJust (lookupKnotVars (if_rec_types gbl_env) mod) - -- Warn against an EPS-updating import - -- of one's own boot file! (one-shot only) - -- See Note [Loading your own hi-boot file] - - -- Create an IO action that loads and compiles bytecode from Core - -- bindings. + initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $ do + + ; if fromMaybe False $ fmap (`isHomeModule` mod) mhome_unit -- TODO @fendor: horrible code + then do -- TODO @fendor: document that we don't want/need 'dontLeakTheHUG' here + massertPpr (moduleUnitId mod `Set.member` hsc_all_home_unit_ids hsc_env) + (text "Attempting to non-home package interface into the Home Loader State" $$ ppr (HUG.allUnits $ hsc_HUG hsc_env) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod)) + tcParts <- tcPartsOfTheIface mod iface + addModIfacePartsToHpt gbl_env mod loc iface tcParts + else dontLeakTheHUG $ do + -- Load the new ModIface into the External Package State -- - -- See Note [Interface Files with Core Definitions] - add_bytecode old - | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls) - = extendModuleEnv old mod action - -- Don't add an entry if the iface doesn't have 'extra_decls' - -- so 'get_link_deps' knows that it should load object code. - | otherwise - = old - - ; warnPprTrace bad_boot "loadInterface" (ppr mod) $ - updateEps_ $ \ eps -> - if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface - then eps - else if bad_boot - -- See Note [Loading your own hi-boot file] - then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls } - else - eps { - eps_PIT = extendModuleEnv (eps_PIT eps) mod final_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) - new_eps_rules, - eps_complete_matches - = eps_complete_matches eps ++ new_eps_complete_matches, - eps_inst_env = extendInstEnvList (eps_inst_env eps) - new_eps_insts, - eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps) - new_eps_fam_insts, - eps_ann_env = extendAnnEnvList (eps_ann_env eps) - new_eps_anns, - eps_mod_fam_inst_env - = let - fam_inst_env = - extendFamInstEnvList emptyFamInstEnv - new_eps_fam_insts - in - extendModuleEnv (eps_mod_fam_inst_env eps) - mod - fam_inst_env, - eps_stats = addEpsInStats (eps_stats eps) - (length new_eps_decls) - (length new_eps_insts) - (length new_eps_rules), - eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults - } + -- The main thing is to add the ModIface to the PIT, but + -- we also take the + -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules, + -- out of the ModIface and put them into the big EPS pools + + -- NB: *first* we do tcIfaceDecls, so that the provenance of all the locally-defined + --- names is done correctly (notably, whether this is an .hi file or .hi-boot file). + -- If we do loadExport first the wrong info gets into the cache (unless we + -- explicitly tag each export which seems a bit of a bore) + + -- Crucial assertion that checks if you are trying to load a HPT module into the EPS. + -- If you start loading HPT modules into the EPS then you get strange errors about + -- overlapping instances. + + massertPpr + (moduleUnitId mod `Set.notMember` hsc_all_home_unit_ids hsc_env + || mod == gHC_PRIM) + (text "Attempting to load home package interface into the EPS" $$ ppr (HUG.allUnits $ hsc_HUG hsc_env) $$ doc_str $$ ppr mod $$ ppr (moduleUnitId mod)) + tcParts <- tcPartsOfTheIface mod iface + addModIfacePartsToEps gbl_env mod loc iface tcParts ; -- invoke plugins with *full* interface, not final_iface, to ensure -- that plugins have access to declarations, etc. @@ -927,6 +866,134 @@ loadInterface doc_str mod from ; return (Succeeded res) }}}} +tcPartsOfTheIface :: Module -> ModIface -> IfL ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], CompleteMatches) +tcPartsOfTheIface mod iface = do + ignore_prags <- goptM Opt_IgnoreInterfacePragmas + new_eps_decls <- tcIfaceDecls ignore_prags (mi_decls iface) + new_eps_insts <- mapM tcIfaceInst (mi_insts iface) + new_eps_defaults <- tcIfaceDefaults mod (mi_defaults iface) + new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface) + new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface) + new_eps_anns <- tcIfaceAnnotations (mi_anns iface) + new_eps_complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface) + pure + ( new_eps_decls + , new_eps_insts + , new_eps_defaults + , new_eps_fam_insts + , new_eps_rules + , new_eps_anns + , new_eps_complete_matches + ) + +addModIfacePartsToHpt :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL () +addModIfacePartsToHpt gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) = do + ; hsc_env <- getTopEnv + ; let details = ModDetails + { md_types = mkNameEnv new_eps_decls + , md_exports = mi_exports iface + , md_defaults = new_eps_defaults + , md_insts = mkInstEnv new_eps_insts + , md_fam_insts = new_eps_fam_insts + , md_rules = new_eps_rules + , md_anns = new_eps_anns + , md_complete_matches = new_eps_complete_matches + } + ; let final_iface = iface + & set_mi_decls (panic "No mi_decls in HomeLoaderState") + & set_mi_insts (panic "No mi_insts in HomeLoaderState") + & set_mi_defaults (panic "No mi_defaults in HomeLoaderState") + & set_mi_fam_insts (panic "No mi_fam_insts in HomeLoaderState") + & set_mi_rules (panic "No mi_rules in HomeLoaderState") + & set_mi_anns (panic "No mi_anns in HomeLoaderState") + & set_mi_simplified_core (panic "No mi_simplified_core in HomeLoaderState") + + bad_boot = mi_boot iface == IsBoot + && isJust (lookupKnotVars (if_rec_types gbl_env) mod) + -- Warn against an HPT-updating import + -- of one's own boot file! (one-shot only) + -- See Note [Loading your own hi-boot file] + + ; warnPprTrace bad_boot "loadInterface" (ppr mod) $ do + hpt <- getHpt + -- Create an IO action that loads and compiles bytecode from Core + -- bindings. + -- + -- See Note [Interface Files with Core Definitions] + let lazy_bytecode = loadIfaceByteCode hsc_env iface loc (mkNameEnv new_eps_decls) + liftIO $ addHomeModInfoToHpt (HomeModInfo iface details emptyHomeModInfoLinkable) hpt + liftIO $ addOnDemandHomeModule hpt mod final_iface bad_boot (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) lazy_bytecode + +addModIfacePartsToEps :: IfGblEnv -> Module -> ModLocation -> ModIface -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> IfL () +addModIfacePartsToEps gbl_env mod loc iface (new_eps_decls, new_eps_insts, new_eps_defaults, new_eps_fam_insts, new_eps_rules, new_eps_anns, new_eps_complete_matches) = do + ; 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 + && isJust (lookupKnotVars (if_rec_types gbl_env) mod) + -- Warn against an EPS-updating import + -- of one's own boot file! (one-shot only) + -- See Note [Loading your own hi-boot file] + + -- Create an IO action that loads and compiles bytecode from Core + -- bindings. + -- + -- See Note [Interface Files with Core Definitions] + add_bytecode old + | Just action <- loadIfaceByteCode purged_hsc_env iface loc (mkNameEnv new_eps_decls) + = extendModuleEnv old mod action + -- Don't add an entry if the iface doesn't have 'extra_decls' + -- so 'get_link_deps' knows that it should load object code. + | otherwise + = old + ; let mhome_unit = ue_homeUnit (hsc_unit_env purged_hsc_env) + ; warnPprTrace bad_boot "loadInterface" (ppr mod) $ + updateEps_ $ \ eps -> + if elemModuleEnv mod (eps_PIT eps) || is_external_sig mhome_unit iface + then eps + else if bad_boot + -- See Note [Loading your own hi-boot file] + then eps { eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls } + else + eps { + eps_PIT = extendModuleEnv (eps_PIT eps) mod final_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) + new_eps_rules, + eps_complete_matches + = eps_complete_matches eps ++ new_eps_complete_matches, + eps_inst_env = extendInstEnvList (eps_inst_env eps) + new_eps_insts, + eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps) + new_eps_fam_insts, + eps_ann_env = extendAnnEnvList (eps_ann_env eps) + new_eps_anns, + eps_mod_fam_inst_env + = let + fam_inst_env = + extendFamInstEnvList emptyFamInstEnv + new_eps_fam_insts + in + extendModuleEnv (eps_mod_fam_inst_env eps) + mod + fam_inst_env, + eps_stats = addEpsInStats (eps_stats eps) + (length new_eps_decls) + (length new_eps_insts) + (length new_eps_rules), + eps_defaults = extendModuleEnv (eps_defaults eps) mod new_eps_defaults + } + + {- Note [Loading your own hi-boot file] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generally speaking, when compiling module M, we should not @@ -1142,10 +1209,10 @@ moduleFreeHolesPrecise doc_str mod return (Succeeded (renameFreeHoles ifhs insts)) Failed err -> return (Failed err) -wantHiBootFile :: Maybe HomeUnit -> ExternalPackageState -> Module -> WhereFrom +wantHiBootFile :: Maybe HomeUnit -> HomeLoaderState -> Module -> WhereFrom -> MaybeErr MissingInterfaceError IsBootInterface -- Figure out whether we want Foo.hi or Foo.hi-boot -wantHiBootFile mhome_unit eps mod from +wantHiBootFile mhome_unit hls mod from = case from of ImportByUser usr_boot | usr_boot == IsBoot && notHomeModuleMaybe mhome_unit mod @@ -1164,8 +1231,8 @@ wantHiBootFile mhome_unit eps mod from -- We never import boot modules from other packages! | otherwise - -> case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of - Just (GWIB { gwib_isBoot = is_boot }) -> + -> case hlsIsBoot hls (toUnitId <$> mod) of + Just is_boot -> Succeeded is_boot Nothing -> Succeeded NotBoot ===================================== compiler/GHC/Iface/Recomp.hs ===================================== @@ -93,6 +93,7 @@ import GHC.ByteCode.Serialize (ModuleByteCode, gbc_hash) import GHC.Unit.Home.Graph (lookupHugByModule) import GHC.Unit.Home.ModInfo (HomeModLinkable(..), HomeModInfo (..)) import GHC.Linker.Types (linkableParts) +import GHC.Unit.Home.PackageTable {- ----------------------------------------------- @@ -427,7 +428,8 @@ checkVersions hsc_env mod_summary iface self_recomp -- case we'll compile the module from scratch anyhow). when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do { - ; updateEps_ $ \eps -> eps { eps_is_boot = mkModDeps $ dep_boot_mods (mi_deps iface) } + ; hpt <- getHpt + ; liftIO $ hlsSetBootInfo hpt (mkModDeps $ dep_boot_mods (mi_deps iface)) } ; recomp <- checkList [checkModUsage (hsc_FC hsc_env) u | u <- mi_sr_usages self_recomp] ===================================== compiler/GHC/IfaceToCore.hs ===================================== @@ -137,6 +137,7 @@ import Language.Haskell.Syntax.BooleanFormula (BooleanFormula) import Language.Haskell.Syntax.BooleanFormula qualified as BF(BooleanFormula(..)) import Language.Haskell.Syntax.Extension (NoExtField (NoExtField)) import GHC.Builtin.KnownKeys (ioTyConKey) +import GHC.Unit.Home.PackageTable {- This module takes @@ -631,12 +632,13 @@ tcHiBootIface hsc_src mod -- current module, which either means a module loop (not -- a SOURCE import) or that our hi-boot file has mysteriously -- disappeared. - do { eps <- getEps - ; case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of + do { hpt <- getHpt + ; hls <- liftIO $ hptLoaderState hpt + ; case hlsIsBoot hls (toUnitId <$> mod) of -- The typical case Nothing -> return NoSelfBoot -- error cases - Just (GWIB { gwib_isBoot = is_boot }) -> case is_boot of + Just is_boot -> case is_boot of IsBoot -> let diag = Can'tFindInterface err (LookingForHiBoot mod) ===================================== compiler/GHC/Linker/Deps.hs ===================================== @@ -157,8 +157,8 @@ get_link_deps opts pls maybe_normal_osuf span mods = do else homeModInfoObject hmi <|> homeModInfoByteCode hmi get_linkable osuf mod -- A home-package module - = HUG.lookupHugByModule mod (ue_home_unit_graph unit_env) >>= \case - Just mod_info -> adjust_linkable (expectJust (homeModLinkable mod_info)) + = lookupHomeLinkable mod (ue_home_unit_graph unit_env) >>= \ case + Just home_linkable -> adjust_linkable home_linkable Nothing -> do -- It's not in the HPT because we are in one shot mode, -- so use the Finder to get a ModLocation... @@ -175,6 +175,10 @@ get_link_deps opts pls maybe_normal_osuf span mods = do maybe (fallback_no_bytecode home_unit mod) pure from_bc _ -> fallback_no_bytecode home_unit mod where + lookupHomeLinkable mod hug = + HUG.lookupHugByModule mod hug >>= \case + Just mod_info -> pure $ homeModLinkable mod_info + Nothing -> pure Nothing fallback_no_bytecode home_unit mod = do let fc = ldFinderCache opts ===================================== compiler/GHC/Tc/Instance/Family.hs ===================================== @@ -57,6 +57,8 @@ import Data.Function ( on ) import qualified GHC.LanguageExtensions as LangExt import Data.List (sortOn) import qualified GHC.Unit.Home.Graph as HUG +import qualified GHC.Unit.Home.PackageTable as HomePackageTable +import Control.Applicative ((<|>)) {- Note [The type family instance consistency story] @@ -407,8 +409,9 @@ getFamInsts hpt_fam_insts mod | Just env <- lookupModuleEnv hpt_fam_insts mod = return env | otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod) ; eps <- getEps + ; hpt_extra_mod_fam_insts <- queryHpt HomePackageTable.hptLoadedModFamInstEnv ; return (expectJust $ - lookupModuleEnv (eps_mod_fam_inst_env eps) mod) } + lookupModuleEnv hpt_extra_mod_fam_insts mod <|> lookupModuleEnv (eps_mod_fam_inst_env eps) mod) } where doc = ppr mod <+> text "is a family-instance module" @@ -615,7 +618,8 @@ addLocalFamInst (home_fie, my_fis) fam_inst -- by the current module, rather than every instance -- we've ever seen. Fixing this is part of #13102. ; eps <- getEps - ; let inst_envs = (eps_fam_inst_env eps, home_fie) + ; extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv + ; let inst_envs = (eps_fam_inst_env eps `unionFamInstEnv` extra, home_fie) home_fie' = extendFamInstEnv home_fie fam_inst -- Check for conflicting instance decls and injectivity violations @@ -948,7 +952,7 @@ tcGetFamInstEnvs :: TcM FamInstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) tcGetFamInstEnvs - = do { eps <- getEps; env <- getGblEnv + = do { eps <- getEps; env <- getGblEnv; !extra <- queryHpt HomePackageTable.hptLoadedFamInstEnv ; let !pkg_env = eps_fam_inst_env eps !home_env = tcg_fam_inst_env env - ; return (pkg_env, home_env) } + ; return (pkg_env, home_env `unionFamInstEnv` extra) } ===================================== compiler/GHC/Tc/Module.hs ===================================== @@ -157,7 +157,6 @@ import GHC.Types.SourceFile import qualified GHC.LanguageExtensions as LangExt import GHC.Unit.Env as UnitEnv -import GHC.Unit.External import GHC.Unit.Types import GHC.Unit.State import GHC.Unit.Home @@ -192,6 +191,7 @@ import qualified Data.Map as M import Data.Foldable ( for_ ) import Data.Traversable ( for ) import Data.IORef( newIORef ) +import GHC.Unit.Home.PackageTable (hlsSetBootInfo) {- ************************************************************************ @@ -513,7 +513,8 @@ tcRnImports hsc_env import_decls -- visible to loadHiBootInterface in tcRnSrcDecls, -- and any other incrementally-performed imports ; when (isOneShot (ghcMode (hsc_dflags hsc_env))) $ do { - updateEps_ $ \eps -> eps { eps_is_boot = imp_boot_mods imports } + ; hpt <- getHpt + ; liftIO $ hlsSetBootInfo hpt (imp_boot_mods imports) } -- Update the gbl env ===================================== compiler/GHC/Tc/Utils/Env.hs ===================================== @@ -152,6 +152,7 @@ import Control.Monad import Data.IORef import Data.List ( intercalate ) import qualified Data.List.NonEmpty as NE +import qualified GHC.Unit.Home.PackageTable as HomePackageTable {- ********************************************************************* * * @@ -385,7 +386,8 @@ tcGetClsDefaults :: [Module] -> TcM [DefaultEnv] tcGetClsDefaults mods = do hug <- hsc_HUG <$> getTopEnv module_env_defaults <- eps_defaults <$> getEps - liftIO $ mapMaybeM (lookupClsDefault hug module_env_defaults) mods + more_env_defaults <- queryHpt HomePackageTable.hptLoadedDefaults + liftIO $ mapMaybeM (lookupClsDefault hug (module_env_defaults `plusModuleEnv` more_env_defaults)) mods lookupClsDefault :: HomeUnitGraph -> ModuleEnv DefaultEnv -> Module -> IO (Maybe DefaultEnv) lookupClsDefault hug module_env_defaults mod = @@ -398,8 +400,9 @@ tcGetInstEnvs :: TcM InstEnvs -- and the home-pkg inst env (includes module being compiled) tcGetInstEnvs = do { eps <- getEps ; env <- getGblEnv + ; extra <- queryHpt HomePackageTable.hptLoadedInstEnv ; return (InstEnvs { ie_global = eps_inst_env eps - , ie_local = tcg_inst_env env + , ie_local = tcg_inst_env env `unionInstEnv` extra , ie_visible = tcVisibleOrphanMods env }) } -- Illegal term-level use of type things ===================================== compiler/GHC/Tc/Utils/Instantiate.hs ===================================== @@ -88,6 +88,7 @@ import Data.List ( mapAccumL ) import qualified Data.List.NonEmpty as NE import Control.Monad( when, unless ) import Data.Function ( on ) +import qualified GHC.Unit.Home.PackageTable as HomePackageTable {- ************************************************************************ @@ -922,6 +923,7 @@ addLocalInst (home_ie, my_insts) ispec -- 'dups' are those 'matches' that are equal to the new one ; isGHCi <- getIsGHCi ; eps <- getEps + ; extra_inst_env <- queryHpt HomePackageTable.hptLoadedInstEnv ; tcg_env <- getGblEnv -- In GHCi, we *override* any identical instances @@ -933,7 +935,7 @@ addLocalInst (home_ie, my_insts) ispec global_ie = eps_inst_env eps inst_envs = InstEnvs { ie_global = global_ie - , ie_local = home_ie' + , ie_local = home_ie' `unionInstEnv` extra_inst_env , ie_visible = tcVisibleOrphanMods tcg_env } -- Check for inconsistent functional dependencies @@ -945,6 +947,13 @@ addLocalInst (home_ie, my_insts) ispec ; let (_tvs, cls, tys) = instanceHead ispec (matches, _, _) = lookupInstEnv False inst_envs cls tys dups = filter (identicalClsInstHead ispec) (map fst matches) + ; traceRn "addLocalInst 0" (ppr ispec) + ; traceRn "addLocalInst 1" (ppr home_ie) + ; traceRn "addLocalInst 2" (ppr my_insts) + ; traceRn "addLocalInst 3" (ppr matches) + ; traceRn "addLocalInst 4" (ppr dups) + ; traceRn "addLocalInst 5" (ppr global_ie) + ; traceRn "addLocalInst 6" (ppr extra_inst_env) ; unless (null dups) $ dupInstErr ispec (head dups) ===================================== compiler/GHC/Tc/Utils/Monad.hs ===================================== @@ -30,7 +30,7 @@ module GHC.Tc.Utils.Monad( getEpsVar, getEps, updateEps, updateEps_, - getHpt, getEpsAndHug, + getHpt, queryHpt, getEpsAndHug, -- * Initialising TcM plugins TcMPluginHandling(..), @@ -261,6 +261,7 @@ import Control.Monad.Catch ( bracket_, finally, onException, mask, mask_, MonadC import Data.Foldable (traverse_) import Data.IORef import qualified Data.Map as Map +import qualified GHC.Unit.Home.PackageTable as HomePackageTable {- ************************************************************************ @@ -740,6 +741,11 @@ updateEps_ upd_fn = updateEps (\eps -> (upd_fn eps, ())) getHpt :: TcRnIf gbl lcl HomePackageTable getHpt = do { env <- getTopEnv; return (hsc_HPT env) } +queryHpt :: (HomePackageTable -> IO a) -> TcRnIf gbl lcl a +queryHpt f = do + hpt <- getHpt + liftIO $ f hpt + getEpsAndHug :: TcRnIf gbl lcl (ExternalPackageState, HomeUnitGraph) getEpsAndHug = do { env <- getTopEnv; eps <- liftIO $ hscEPS env ; return (eps, hsc_HUG env) } @@ -2740,8 +2746,9 @@ getCompleteMatchesTcM = do { hsc_env <- getTopEnv ; eps <- liftIO $ hscEPS hsc_env ; tcg_env <- getGblEnv + ; extra_matches <- queryHpt HomePackageTable.hptLoadedCompleteMatches ; let tcg_comps = tcg_complete_match_env tcg_env - ; liftIO $ localAndImportedCompleteMatches tcg_comps eps + ; liftIO $ localAndImportedCompleteMatches (tcg_comps ++ extra_matches) eps } localAndImportedCompleteMatches :: CompleteMatches -> ExternalPackageState -> IO CompleteMatches ===================================== compiler/GHC/Unit/External.hs ===================================== @@ -71,8 +71,7 @@ eucEPS = readIORef . euc_eps initExternalPackageState :: ExternalPackageState initExternalPackageState = EPS - { eps_is_boot = emptyInstalledModuleEnv - , eps_PIT = emptyPackageIfaceTable + { eps_PIT = emptyPackageIfaceTable , eps_free_holes = emptyInstalledModuleEnv , eps_PTE = emptyTypeEnv , eps_iface_bytecode = emptyModuleEnv @@ -101,19 +100,6 @@ initExternalPackageState = EPS -- their interface files data ExternalPackageState = EPS { - eps_is_boot :: !(InstalledModuleEnv ModuleNameWithIsBoot), - -- ^ In OneShot mode (only), home-package modules - -- accumulate in the external package state, and are - -- sucked in lazily. For these home-pkg modules - -- (only) we need to record which are boot modules. - -- We set this field after loading all the - -- explicitly-imported interfaces, but before doing - -- anything else - -- - -- The 'ModuleName' part is not necessary, but it's useful for - -- debug prints, and it's convenient because this field comes - -- direct from 'GHC.Tc.Utils.imp_dep_mods' - eps_PIT :: !PackageIfaceTable, -- ^ The 'ModIface's for modules in external packages -- whose interfaces we have opened. ===================================== compiler/GHC/Unit/Home/PackageTable.hs ===================================== @@ -23,9 +23,12 @@ -- 'hptCollectObjects'... module GHC.Unit.Home.PackageTable ( - HomePackageTable(..) + HomePackageTable , emptyHomePackageTable + , HomeLoaderState -- TODO: should this be opaque? Probably + , emptyHomeLoaderState + -- * Lookups in the HPT , lookupHpt , lookupHptByModule @@ -33,6 +36,7 @@ module GHC.Unit.Home.PackageTable -- * Extending the HPT , addHomeModInfoToHpt , addHomeModInfosToHpt + , addOnDemandHomeModule -- * Restrict the HPT , restrictHpt @@ -42,6 +46,18 @@ module GHC.Unit.Home.PackageTable , hptAllInstances , hptAllFamInstances , hptAllAnnotations + , hlsIsModuleNameWithBoot + , hlsIsBoot + , hlsSetBootInfo + , hptLoadedIsBoot + , hptLoadedTypeEnv + , hptLoadedInstEnv + , hptLoadedFamInstEnv + , hptLoadedModFamInstEnv + , hptLoadedRuleBase + , hptLoadedAnnEnv + , hptLoadedCompleteMatches + , hptLoadedDefaults -- ** More Traversal-based queries , hptCollectDependencies @@ -64,7 +80,7 @@ module GHC.Unit.Home.PackageTable -- it is not sufficient to go through the intended insert-only API. , hptInternalTableRef , hptInternalTableFromRef - + , hptLoaderState -- * Legacy API -- -- | This API is deprecated and meant to be removed. @@ -80,8 +96,14 @@ import qualified Data.Set as Set import GHC.Core.FamInstEnv import GHC.Core.InstEnv +import GHC.Core.Rules (RuleBase, extendRuleBaseList, emptyRuleBase) +import GHC.Data.Word64Set qualified as W64 +import GHC.Linker.Types (Linkable) import GHC.Types.Annotations import GHC.Types.CompleteMatch +import GHC.Types.TypeEnv +import GHC.Types.TyThing +import GHC.Types.Unique (getKey, getUnique) import GHC.Types.Unique.DFM import GHC.Unit.Home.ModInfo import GHC.Unit.Module @@ -89,13 +111,15 @@ import GHC.Unit.Module.Deps import GHC.Unit.Module.ModDetails import GHC.Unit.Module.ModIface import GHC.Utils.Outputable -import GHC.Types.Unique (getUnique, getKey) -import qualified GHC.Data.Word64Set as W64 +import GHC.Types.Name +import GHC.Types.Name.Env (extendNameEnvList) +import GHC.Types.DefaultEnv (DefaultEnv) +import GHC.Core -- | Helps us find information about modules in the home package -newtype HomePackageTable = HPT { +data HomePackageTable = HPT { - table :: IORef (DModuleNameEnv HomeModInfo) + table :: IORef (DModuleNameEnv HomeModInfo), -- ^ Domain = modules in this home unit -- -- This is an IORef because we want to avoid leaking HPTs (see the particularly bad #25511). @@ -109,6 +133,7 @@ newtype HomePackageTable = HPT { -- to temporarily violate the HPT monotonicity. -- -- The elements of this table may be updated (e.g. on rehydration). + loader :: IORef HomeLoaderState } -- | Create a new 'HomePackageTable'. @@ -120,7 +145,38 @@ emptyHomePackageTable :: IO HomePackageTable -- romes:todo: use a MutableArray directly? emptyHomePackageTable = do table <- newIORef emptyUDFM - return HPT{table} + loader <- newIORef emptyHomeLoaderState + return HPT{table, loader} + +data HomeLoaderState = HomeLoaderState + { hls_is_boot :: InstalledModuleEnv ModuleNameWithIsBoot + , hls_iface_table :: ModuleEnv ModIface + , hls_type_env :: !TypeEnv + , hls_iface_bytecode :: !(ModuleEnv (IO Linkable)) + , hls_inst_env :: !InstEnv + , hls_fam_inst_env :: !FamInstEnv + , hls_mod_fam_inst_env :: !(ModuleEnv FamInstEnv) + , hls_rule_base :: !RuleBase + , hls_ann_env :: !AnnEnv + , hls_complete_matches :: !CompleteMatches + , hls_defaults :: ModuleEnv DefaultEnv + } + +emptyHomeLoaderState :: HomeLoaderState +emptyHomeLoaderState = + HomeLoaderState + { hls_is_boot = emptyInstalledModuleEnv + , hls_iface_table = emptyModuleEnv + , hls_type_env = emptyTypeEnv + , hls_iface_bytecode = emptyModuleEnv + , hls_inst_env = emptyInstEnv + , hls_fam_inst_env = emptyFamInstEnv + , hls_mod_fam_inst_env = emptyModuleEnv + , hls_rule_base = emptyRuleBase + , hls_ann_env = emptyAnnEnv + , hls_complete_matches = [] + , hls_defaults = emptyModuleEnv + } -------------------------------------------------------------------------------- -- * Lookups in the HPT @@ -139,6 +195,36 @@ lookupHptByModule hpt mod Just hm | mi_module (hm_iface hm) == mod -> Just hm _otherwise -> Nothing +hptLoaderState :: HomePackageTable -> IO HomeLoaderState +hptLoaderState = readIORef . loader + +hptLoadedIsBoot :: HomePackageTable -> IO (InstalledModuleEnv ModuleNameWithIsBoot) +hptLoadedIsBoot hpt = hls_is_boot <$> readIORef (loader hpt) + +hptLoadedTypeEnv :: HomePackageTable -> IO TypeEnv +hptLoadedTypeEnv hpt = hls_type_env <$> readIORef (loader hpt) + +hptLoadedInstEnv :: HomePackageTable -> IO InstEnv +hptLoadedInstEnv hpt = hls_inst_env <$> readIORef (loader hpt) + +hptLoadedFamInstEnv :: HomePackageTable -> IO FamInstEnv +hptLoadedFamInstEnv hpt = hls_fam_inst_env <$> readIORef (loader hpt) + +hptLoadedModFamInstEnv :: HomePackageTable -> IO (ModuleEnv FamInstEnv) +hptLoadedModFamInstEnv hpt = hls_mod_fam_inst_env <$> readIORef (loader hpt) + +hptLoadedRuleBase :: HomePackageTable -> IO RuleBase +hptLoadedRuleBase hpt = hls_rule_base <$> readIORef (loader hpt) + +hptLoadedAnnEnv :: HomePackageTable -> IO AnnEnv +hptLoadedAnnEnv hpt = hls_ann_env <$> readIORef (loader hpt) + +hptLoadedCompleteMatches :: HomePackageTable -> IO CompleteMatches +hptLoadedCompleteMatches hpt = hls_complete_matches <$> readIORef (loader hpt) + +hptLoadedDefaults :: HomePackageTable -> IO (ModuleEnv DefaultEnv) +hptLoadedDefaults hpt = hls_defaults <$> readIORef (loader hpt) + -------------------------------------------------------------------------------- -- * Extending the HPT -------------------------------------------------------------------------------- @@ -186,6 +272,56 @@ restrictHpt HPT{table=hptr} hmis = addListToHpt :: HomePackageTable -> [(ModuleName, HomeModInfo)] -> IO () addListToHpt hpt = mapM_ (uncurry (addToHpt hpt)) +addOnDemandHomeModule :: HomePackageTable -> Module -> ModIface -> Bool -> ([(Name, TyThing)], [ClsInst], DefaultEnv, [FamInst], [CoreRule], [Annotation], [CompleteMatch]) -> Maybe (IO Linkable) -> IO () +addOnDemandHomeModule hpt mn iface bad_boot (new_hls_decls, new_hls_insts, new_hls_defaults, new_hls_fam_insts, new_hls_rules, new_hls_anns, new_hls_complete_matches) bytecode = do + atomicModifyIORef (loader hpt) $ \hls -> + ( if mn `elemModuleEnv` hls_iface_table hls + then hls -- If already loaded, don't add twice + else + if bad_boot + then addHomeModTypeEnv hls + else addHomeModData hls + , () + ) + where + addHomeModTypeEnv hls = hls + { hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls + } + + addHomeModData hls = hls { + hls_iface_table = extendModuleEnv (hls_iface_table hls) mn iface, + hls_type_env = extendNameEnvList (hls_type_env hls) new_hls_decls, + hls_iface_bytecode = case bytecode of + Nothing -> hls_iface_bytecode hls + Just bc -> extendModuleEnv (hls_iface_bytecode hls) mn bc, + hls_rule_base = extendRuleBaseList (hls_rule_base hls) + new_hls_rules, + hls_complete_matches + = hls_complete_matches hls ++ new_hls_complete_matches, + hls_inst_env = extendInstEnvList (hls_inst_env hls) + new_hls_insts, + hls_fam_inst_env = extendFamInstEnvList (hls_fam_inst_env hls) + new_hls_fam_insts, + hls_ann_env = extendAnnEnvList (hls_ann_env hls) + new_hls_anns, + hls_mod_fam_inst_env + = + let + fam_inst_env = + extendFamInstEnvList emptyFamInstEnv + new_hls_fam_insts + in + extendModuleEnv (hls_mod_fam_inst_env hls) + mn + fam_inst_env, + hls_defaults = extendModuleEnv (hls_defaults hls) mn new_hls_defaults + } + +hlsSetBootInfo :: HomePackageTable -> InstalledModuleEnv ModuleNameWithIsBoot -> IO () +hlsSetBootInfo hpt is_boot_env = + atomicModifyIORef' (loader hpt) $ \ hls -> + (hls { hls_is_boot = is_boot_env }, ()) + ---------------------------------------------------------------------------------- ---- * Queries ---------------------------------------------------------------------------------- @@ -216,6 +352,11 @@ hptAllFamInstances = fmap mkModuleEnv . concatHpt (\hmi -> [(hmiModule hmi, hmiF hptAllAnnotations :: HomePackageTable -> IO AnnEnv hptAllAnnotations = fmap mkAnnEnv . concatHpt (md_anns . hm_details) +hlsIsBoot :: HomeLoaderState -> InstalledModule -> Maybe IsBootInterface +hlsIsBoot hls mn = gwib_isBoot <$> hlsIsModuleNameWithBoot hls mn + +hlsIsModuleNameWithBoot :: HomeLoaderState -> InstalledModule -> Maybe ModuleNameWithIsBoot +hlsIsModuleNameWithBoot hls mn = lookupInstalledModuleEnv (hls_is_boot hls) mn -------------------------------------------------------------------------------- -- * Traversal-based queries @@ -315,7 +456,8 @@ hptInternalTableRef = table -- Use with care, only if you can really justify going around the intended insert-only API. hptInternalTableFromRef :: IORef (DModuleNameEnv HomeModInfo) -> IO HomePackageTable hptInternalTableFromRef ref = do + loader <- newIORef emptyHomeLoaderState return HPT { - table = ref + table = ref, + loader } - ===================================== compiler/GHC/Unit/Module/Env.hs ===================================== @@ -13,7 +13,12 @@ module GHC.Unit.Module.Env , extendModuleEnvWith, filterModuleEnv, mapMaybeModuleEnv -- * ModuleName mappings - , ModuleNameEnv, DModuleNameEnv + , ModuleNameEnv + , extendModuleNameEnv + , emptyModuleNameEnv + , lookupModuleNameEnv + , unionModuleNameEnv + , DModuleNameEnv -- * Sets of Modules , ModuleSet @@ -234,6 +239,17 @@ UniqFM. -- | A map keyed off of 'ModuleName's (actually, their 'Unique's) type ModuleNameEnv elt = UniqFM ModuleName elt +extendModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> elt -> ModuleNameEnv elt +extendModuleNameEnv = addToUFM + +emptyModuleNameEnv :: ModuleNameEnv elt +emptyModuleNameEnv = emptyUFM + +lookupModuleNameEnv :: ModuleNameEnv elt -> ModuleName -> Maybe elt +lookupModuleNameEnv = lookupUFM + +unionModuleNameEnv :: ModuleNameEnv elt -> ModuleNameEnv elt -> ModuleNameEnv elt +unionModuleNameEnv = unionModuleNameEnv -- | A map keyed off of 'ModuleName's (actually, their 'Unique's) -- Has deterministic folds and can be deterministically converted to a list ===================================== 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/0f928d0a6db34470ba941f37d58ee0f... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0f928d0a6db34470ba941f37d58ee0f... 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
participants (1)
-
Hannes Siebenhandl (@fendor)