module DriverBkp (doBackpack) where
#include "HsVersions.h"
import BkpSyn
import GHC hiding (Failed, Succeeded)
import Packages
import Parser
import Lexer
import GhcMonad
import DynFlags
import TcRnMonad
import TcRnDriver
import Module
import HscTypes
import StringBuffer
import FastString
import ErrUtils
import SrcLoc
import HscMain
import UniqFM
import UniqDFM
import Outputable
import Maybes
import HeaderInfo
import MkIface
import GhcMake
import UniqDSet
import PrelNames
import BasicTypes hiding (SuccessFlag(..))
import Finder
import Util
import qualified GHC.LanguageExtensions as LangExt
import Panic
import Data.List
import System.Exit
import Control.Monad
import System.FilePath
import Data.Version
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as Map
doBackpack :: [FilePath] -> Ghc ()
doBackpack [src_filename] = do
dflags0 <- getDynFlags
let dflags1 = dflags0
src_opts <- liftIO $ getOptionsFromFile dflags1 src_filename
(dflags, unhandled_flags, warns) <- liftIO $ parseDynamicFilePragma dflags1 src_opts
modifySession (\hsc_env -> hsc_env {hsc_dflags = dflags})
liftIO $ checkProcessArgsResult dflags unhandled_flags
liftIO $ handleFlagWarnings dflags warns
buf <- liftIO $ hGetStringBuffer src_filename
let loc = mkRealSrcLoc (mkFastString src_filename) 1 1
case unP parseBackpack (mkPState dflags buf loc) of
PFailed span err -> do
liftIO $ throwOneError (mkPlainErrMsg dflags span err)
POk _ pkgname_bkp -> do
let bkp = renameHsUnits dflags (packageNameMap pkgname_bkp) pkgname_bkp
initBkpM src_filename bkp $
forM_ (zip [1..] bkp) $ \(i, lunit) -> do
let comp_name = unLoc (hsunitName (unLoc lunit))
msgTopPackage (i,length bkp) comp_name
innerBkpM $ do
let (cid, insts) = computeUnitId lunit
if null insts
then if cid == ComponentId (fsLit "main")
then compileExe lunit
else compileUnit cid []
else typecheckUnit cid insts
doBackpack _ =
throwGhcException (CmdLineError "--backpack can only process a single file")
computeUnitId :: LHsUnit HsComponentId -> (ComponentId, [(ModuleName, Module)])
computeUnitId (L _ unit) = (cid, [ (r, mkHoleModule r) | r <- reqs ])
where
cid = hsComponentId (unLoc (hsunitName unit))
reqs = uniqDSetToList (unionManyUniqDSets (map (get_reqs . unLoc) (hsunitBody unit)))
get_reqs (DeclD SignatureD (L _ modname) _) = unitUniqDSet modname
get_reqs (DeclD ModuleD _ _) = emptyUniqDSet
get_reqs (IncludeD (IncludeDecl (L _ hsuid) _ _)) =
unitIdFreeHoles (convertHsUnitId hsuid)
data SessionType
= ExeSession
| TcSession
| CompSession
deriving (Eq)
withBkpSession :: ComponentId
-> [(ModuleName, Module)]
-> [(UnitId, ModRenaming)]
-> SessionType
-> BkpM a
-> BkpM a
withBkpSession cid insts deps session_type do_this = do
dflags <- getDynFlags
let (ComponentId cid_fs) = cid
is_primary = False
uid_str = unpackFS (hashUnitId cid insts)
cid_str = unpackFS cid_fs
key_base p | Just f <- p dflags = f
| otherwise = "."
sub_comp p | is_primary = p
| otherwise = p </> cid_str
outdir p | CompSession <- session_type
, not (null insts) = sub_comp (key_base p) </> uid_str
| otherwise = sub_comp (key_base p)
withTempSession (overHscDynFlags (\dflags ->
(case session_type of
TcSession | hscTarget dflags /= HscNothing
-> flip gopt_set Opt_WriteInterface
| otherwise -> id
CompSession -> id
ExeSession -> id) $
dflags {
hscTarget = case session_type of
TcSession -> HscNothing
_ -> hscTarget dflags,
thisUnitIdInsts_ = Just insts,
thisComponentId_ = Just cid,
thisInstalledUnitId =
case session_type of
TcSession -> newInstalledUnitId cid Nothing
_ | null insts -> newInstalledUnitId cid Nothing
| otherwise -> newInstalledUnitId cid (Just (hashUnitId cid insts)),
objectDir = Just (outdir objectDir),
hiDir = Just (outdir hiDir),
stubDir = Just (outdir stubDir),
outputFile = if session_type == ExeSession
then outputFile dflags
else Nothing,
importPaths = [],
packageFlags = packageFlags dflags ++ map (\(uid0, rn) ->
let uid = unwireUnitId dflags (improveUnitId (getPackageConfigMap dflags) $ renameHoleUnitId dflags (listToUFM insts) uid0)
in ExposePackage
(showSDoc dflags
(text "-unit-id" <+> ppr uid <+> ppr rn))
(UnitIdArg uid) rn) deps
} )) $ do
dflags <- getSessionDynFlags
_ <- setSessionDynFlags dflags
do_this
withBkpExeSession :: [(UnitId, ModRenaming)] -> BkpM a -> BkpM a
withBkpExeSession deps do_this = do
withBkpSession (ComponentId (fsLit "main")) [] deps ExeSession do_this
getSource :: ComponentId -> BkpM (LHsUnit HsComponentId)
getSource cid = do
bkp_env <- getBkpEnv
case Map.lookup cid (bkp_table bkp_env) of
Nothing -> pprPanic "missing needed dependency" (ppr cid)
Just lunit -> return lunit
typecheckUnit :: ComponentId -> [(ModuleName, Module)] -> BkpM ()
typecheckUnit cid insts = do
lunit <- getSource cid
buildUnit TcSession cid insts lunit
compileUnit :: ComponentId -> [(ModuleName, Module)] -> BkpM ()
compileUnit cid insts = do
msgUnitId (newUnitId cid insts)
lunit <- getSource cid
buildUnit CompSession cid insts lunit
hsunitDeps :: Bool -> HsUnit HsComponentId -> [(UnitId, ModRenaming)]
hsunitDeps include_sigs unit = concatMap get_dep (hsunitBody unit)
where
get_dep (L _ (IncludeD (IncludeDecl (L _ hsuid) mb_lrn is_sig)))
| include_sigs || not is_sig = [(convertHsUnitId hsuid, go mb_lrn)]
| otherwise = []
where
go Nothing = ModRenaming True []
go (Just lrns) = ModRenaming False (map convRn lrns)
where
convRn (L _ (Renaming (L _ from) Nothing)) = (from, from)
convRn (L _ (Renaming (L _ from) (Just (L _ to)))) = (from, to)
get_dep _ = []
buildUnit :: SessionType -> ComponentId -> [(ModuleName, Module)] -> LHsUnit HsComponentId -> BkpM ()
buildUnit session cid insts lunit = do
let deps_w_rns = hsunitDeps (session == TcSession) (unLoc lunit)
raw_deps = map fst deps_w_rns
dflags <- getDynFlags
let hsubst = listToUFM insts
deps0 = map (renameHoleUnitId dflags hsubst) raw_deps
forM_ (zip [1..] deps0) $ \(i, dep) ->
case session of
TcSession -> return ()
_ -> compileInclude (length deps0) (i, dep)
dflags <- getDynFlags
let deps = map (improveUnitId (getPackageConfigMap dflags)) deps0
mb_old_eps <- case session of
TcSession -> fmap Just getEpsGhc
_ -> return Nothing
conf <- withBkpSession cid insts deps_w_rns session $ do
dflags <- getDynFlags
mod_graph <- hsunitModuleGraph dflags (unLoc lunit)
msg <- mkBackpackMsg
ok <- load' LoadAllTargets (Just msg) mod_graph
when (failed ok) (liftIO $ exitWith (ExitFailure 1))
let hi_dir = expectJust (panic "hiDir Backpack") $ hiDir dflags
export_mod ms = (ms_mod_name ms, ms_mod ms)
mods = [ export_mod ms | ms <- mod_graph, ms_hsc_src ms == HsSrcFile ]
hsc_env <- getSession
let home_mod_infos = eltsUDFM (hsc_HPT hsc_env)
linkables = map (expectJust "bkp link" . hm_linkable)
. filter ((==HsSrcFile) . mi_hsc_src . hm_iface)
$ home_mod_infos
getOfiles (LM _ _ us) = map nameOfObject (filter isObject us)
obj_files = concatMap getOfiles linkables
let compat_fs = (case cid of ComponentId fs -> fs)
compat_pn = PackageName compat_fs
return InstalledPackageInfo {
abiHash = "",
sourcePackageId = SourcePackageId compat_fs,
packageName = compat_pn,
packageVersion = makeVersion [0],
unitId = toInstalledUnitId (thisPackage dflags),
mungedPackageName = Nothing,
libName = Nothing,
componentId = cid,
instantiatedWith = insts,
exposedModules = map (\(m,n) -> (m,Just n)) mods,
hiddenModules = [],
depends = case session of
TcSession -> []
_ -> map (toInstalledUnitId . unwireUnitId dflags)
$ deps ++ [ moduleUnitId mod
| (_, mod) <- insts
, not (isHoleModule mod) ],
abiDepends = [],
ldOptions = case session of
TcSession -> []
_ -> obj_files,
importDirs = [ hi_dir ],
exposed = False,
indefinite = case session of
TcSession -> True
_ -> False,
hsLibraries = [],
extraLibraries = [],
extraGHCiLibraries = [],
libraryDynDirs = [],
libraryDirs = [],
frameworks = [],
frameworkDirs = [],
ccOptions = [],
includes = [],
includeDirs = [],
haddockInterfaces = [],
haddockHTMLs = [],
trusted = False
}
addPackage conf
case mb_old_eps of
Just old_eps -> updateEpsGhc_ (const old_eps)
_ -> return ()
compileExe :: LHsUnit HsComponentId -> BkpM ()
compileExe lunit = do
msgUnitId mainUnitId
let deps_w_rns = hsunitDeps False (unLoc lunit)
deps = map fst deps_w_rns
forM_ (zip [1..] deps) $ \(i, dep) ->
compileInclude (length deps) (i, dep)
withBkpExeSession deps_w_rns $ do
dflags <- getDynFlags
mod_graph <- hsunitModuleGraph dflags (unLoc lunit)
msg <- mkBackpackMsg
ok <- load' LoadAllTargets (Just msg) mod_graph
when (failed ok) (liftIO $ exitWith (ExitFailure 1))
addPackage :: GhcMonad m => PackageConfig -> m ()
addPackage pkg = do
dflags0 <- GHC.getSessionDynFlags
case pkgDatabase dflags0 of
Nothing -> panic "addPackage: called too early"
Just pkgs -> do let dflags = dflags0 { pkgDatabase =
Just (pkgs ++ [("(in memory " ++ showSDoc dflags0 (ppr (unitId pkg)) ++ ")", [pkg])]) }
_ <- GHC.setSessionDynFlags dflags
return ()
compileInclude :: Int -> (Int, UnitId) -> BkpM ()
compileInclude n (i, uid) = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
msgInclude (i, n) uid
case lookupPackage dflags uid of
Nothing -> do
case splitUnitIdInsts uid of
(_, Just indef) ->
innerBkpM $ compileUnit (indefUnitIdComponentId indef)
(indefUnitIdInsts indef)
_ -> return ()
Just _ -> return ()
type BkpM = IOEnv BkpEnv
data BkpEnv
= BkpEnv {
bkp_session :: Session,
bkp_filename :: FilePath,
bkp_table :: Map ComponentId (LHsUnit HsComponentId),
bkp_level :: Int
}
instance HasDynFlags BkpM where
getDynFlags = fmap hsc_dflags getSession
instance GhcMonad BkpM where
getSession = do
Session s <- fmap bkp_session getEnv
readMutVar s
setSession hsc_env = do
Session s <- fmap bkp_session getEnv
writeMutVar s hsc_env
getBkpEnv :: BkpM BkpEnv
getBkpEnv = getEnv
getBkpLevel :: BkpM Int
getBkpLevel = bkp_level `fmap` getBkpEnv
overHscDynFlags :: (DynFlags -> DynFlags) -> HscEnv -> HscEnv
overHscDynFlags f hsc_env = hsc_env { hsc_dflags = f (hsc_dflags hsc_env) }
innerBkpM :: BkpM a -> BkpM a
innerBkpM do_this = do
updEnv (\env -> env { bkp_level = bkp_level env + 1 }) do_this
updateEpsGhc_ :: GhcMonad m => (ExternalPackageState -> ExternalPackageState) -> m ()
updateEpsGhc_ f = do
hsc_env <- getSession
liftIO $ atomicModifyIORef' (hsc_EPS hsc_env) (\x -> (f x, ()))
getEpsGhc :: GhcMonad m => m ExternalPackageState
getEpsGhc = do
hsc_env <- getSession
liftIO $ readIORef (hsc_EPS hsc_env)
initBkpM :: FilePath -> [LHsUnit HsComponentId] -> BkpM a -> Ghc a
initBkpM file bkp m = do
reifyGhc $ \session -> do
let env = BkpEnv {
bkp_session = session,
bkp_table = Map.fromList [(hsComponentId (unLoc (hsunitName (unLoc u))), u) | u <- bkp],
bkp_filename = file,
bkp_level = 0
}
runIOEnv env m
backpackProgressMsg :: Int -> DynFlags -> String -> IO ()
backpackProgressMsg level dflags msg =
compilationProgressMsg dflags $ replicate (level * 2) ' ' ++ msg
mkBackpackMsg :: BkpM Messager
mkBackpackMsg = do
level <- getBkpLevel
return $ \hsc_env mod_index recomp mod_summary ->
let dflags = hsc_dflags hsc_env
showMsg msg reason =
backpackProgressMsg level dflags $
showModuleIndex mod_index ++
msg ++ showModMsg dflags (hscTarget dflags)
(recompileRequired recomp) mod_summary
++ reason
in case recomp of
MustCompile -> showMsg "Compiling " ""
UpToDate
| verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " ""
| otherwise -> return ()
RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]")
backpackStyle :: DynFlags -> PprStyle
backpackStyle dflags =
mkUserStyle dflags
(QueryQualify neverQualifyNames
alwaysQualifyModules
neverQualifyPackages) AllTheWay
msgTopPackage :: (Int,Int) -> HsComponentId -> BkpM ()
msgTopPackage (i,n) (HsComponentId (PackageName fs_pn) _) = do
dflags <- getDynFlags
level <- getBkpLevel
liftIO . backpackProgressMsg level dflags
$ showModuleIndex (i, n) ++ "Processing " ++ unpackFS fs_pn
msgUnitId :: UnitId -> BkpM ()
msgUnitId pk = do
dflags <- getDynFlags
level <- getBkpLevel
liftIO . backpackProgressMsg level dflags
$ "Instantiating " ++ renderWithStyle dflags (ppr pk)
(backpackStyle dflags)
msgInclude :: (Int,Int) -> UnitId -> BkpM ()
msgInclude (i,n) uid = do
dflags <- getDynFlags
level <- getBkpLevel
liftIO . backpackProgressMsg level dflags
$ showModuleIndex (i, n) ++ "Including " ++
renderWithStyle dflags (ppr uid) (backpackStyle dflags)
type PackageNameMap a = Map PackageName a
unitDefines :: LHsUnit PackageName -> (PackageName, HsComponentId)
unitDefines (L _ HsUnit{ hsunitName = L _ pn@(PackageName fs) })
= (pn, HsComponentId pn (ComponentId fs))
packageNameMap :: [LHsUnit PackageName] -> PackageNameMap HsComponentId
packageNameMap units = Map.fromList (map unitDefines units)
renameHsUnits :: DynFlags -> PackageNameMap HsComponentId -> [LHsUnit PackageName] -> [LHsUnit HsComponentId]
renameHsUnits dflags m units = map (fmap renameHsUnit) units
where
renamePackageName :: PackageName -> HsComponentId
renamePackageName pn =
case Map.lookup pn m of
Nothing ->
case lookupPackageName dflags pn of
Nothing -> error "no package name"
Just cid -> HsComponentId pn cid
Just hscid -> hscid
renameHsUnit :: HsUnit PackageName -> HsUnit HsComponentId
renameHsUnit u =
HsUnit {
hsunitName = fmap renamePackageName (hsunitName u),
hsunitBody = map (fmap renameHsUnitDecl) (hsunitBody u)
}
renameHsUnitDecl :: HsUnitDecl PackageName -> HsUnitDecl HsComponentId
renameHsUnitDecl (DeclD a b c) = DeclD a b c
renameHsUnitDecl (IncludeD idecl) =
IncludeD IncludeDecl {
idUnitId = fmap renameHsUnitId (idUnitId idecl),
idModRenaming = idModRenaming idecl,
idSignatureInclude = idSignatureInclude idecl
}
renameHsUnitId :: HsUnitId PackageName -> HsUnitId HsComponentId
renameHsUnitId (HsUnitId ln subst)
= HsUnitId (fmap renamePackageName ln) (map (fmap renameHsModuleSubst) subst)
renameHsModuleSubst :: HsModuleSubst PackageName -> HsModuleSubst HsComponentId
renameHsModuleSubst (lk, lm)
= (lk, fmap renameHsModuleId lm)
renameHsModuleId :: HsModuleId PackageName -> HsModuleId HsComponentId
renameHsModuleId (HsModuleVar lm) = HsModuleVar lm
renameHsModuleId (HsModuleId luid lm) = HsModuleId (fmap renameHsUnitId luid) lm
convertHsUnitId :: HsUnitId HsComponentId -> UnitId
convertHsUnitId (HsUnitId (L _ hscid) subst)
= newUnitId (hsComponentId hscid) (map (convertHsModuleSubst . unLoc) subst)
convertHsModuleSubst :: HsModuleSubst HsComponentId -> (ModuleName, Module)
convertHsModuleSubst (L _ modname, L _ m) = (modname, convertHsModuleId m)
convertHsModuleId :: HsModuleId HsComponentId -> Module
convertHsModuleId (HsModuleVar (L _ modname)) = mkHoleModule modname
convertHsModuleId (HsModuleId (L _ hsuid) (L _ modname)) = mkModule (convertHsUnitId hsuid) modname
hsunitModuleGraph :: DynFlags -> HsUnit HsComponentId -> BkpM ModuleGraph
hsunitModuleGraph dflags unit = do
let decls = hsunitBody unit
pn = hsPackageName (unLoc (hsunitName unit))
let get_decl (L _ (DeclD dt lmodname mb_hsmod)) = do
let hsc_src = case dt of
ModuleD -> HsSrcFile
SignatureD -> HsigFile
Just `fmap` summariseDecl pn hsc_src lmodname mb_hsmod
get_decl _ = return Nothing
nodes <- catMaybes `fmap` mapM get_decl decls
let node_map = Map.fromList [ ((ms_mod_name n, ms_hsc_src n == HsigFile), n)
| n <- nodes ]
req_nodes <- fmap catMaybes . forM (thisUnitIdInsts dflags) $ \(mod_name, _) ->
let has_local = Map.member (mod_name, True) node_map
in if has_local
then return Nothing
else fmap Just $ summariseRequirement pn mod_name
return (nodes ++ req_nodes)
summariseRequirement :: PackageName -> ModuleName -> BkpM ModSummary
summariseRequirement pn mod_name = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
let PackageName pn_fs = pn
location <- liftIO $ mkHomeModLocation2 dflags mod_name
(unpackFS pn_fs </> moduleNameSlashes mod_name) "hsig"
env <- getBkpEnv
time <- liftIO $ getModificationUTCTime (bkp_filename env)
hi_timestamp <- liftIO $ modificationTimeIfExists (ml_hi_file location)
let loc = srcLocSpan (mkSrcLoc (mkFastString (bkp_filename env)) 1 1)
mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
extra_sig_imports <- liftIO $ findExtraSigImports hsc_env HsigFile mod_name
return ModSummary {
ms_mod = mod,
ms_hsc_src = HsigFile,
ms_location = location,
ms_hs_date = time,
ms_obj_date = Nothing,
ms_iface_date = hi_timestamp,
ms_srcimps = [],
ms_textual_imps = extra_sig_imports,
ms_parsed_mod = Just (HsParsedModule {
hpm_module = L loc (HsModule {
hsmodName = Just (L loc mod_name),
hsmodExports = Nothing,
hsmodImports = [],
hsmodDecls = [],
hsmodDeprecMessage = Nothing,
hsmodHaddockModHeader = Nothing
}),
hpm_src_files = [],
hpm_annotations = (Map.empty, Map.empty)
}),
ms_hspp_file = "",
ms_hspp_opts = dflags,
ms_hspp_buf = Nothing
}
summariseDecl :: PackageName
-> HscSource
-> Located ModuleName
-> Maybe (Located (HsModule RdrName))
-> BkpM ModSummary
summariseDecl pn hsc_src (L _ modname) (Just hsmod) = hsModuleToModSummary pn hsc_src modname hsmod
summariseDecl _pn hsc_src lmodname@(L loc modname) Nothing
= do hsc_env <- getSession
let dflags = hsc_dflags hsc_env
r <- liftIO $ summariseModule hsc_env
Map.empty
(hscSourceToIsBoot hsc_src)
lmodname
True
Nothing
[]
case r of
Nothing -> throwOneError (mkPlainErrMsg dflags loc (text "module" <+> ppr modname <+> text "was not found"))
Just (Left err) -> throwOneError err
Just (Right summary) -> return summary
hsModuleToModSummary :: PackageName
-> HscSource
-> ModuleName
-> Located (HsModule RdrName)
-> BkpM ModSummary
hsModuleToModSummary pn hsc_src modname
hsmod = do
let imps = hsmodImports (unLoc hsmod)
loc = getLoc hsmod
hsc_env <- getSession
let PackageName unit_fs = pn
dflags = hsc_dflags hsc_env
location0 <- liftIO $ mkHomeModLocation2 dflags modname
(unpackFS unit_fs </>
moduleNameSlashes modname)
(case hsc_src of
HsigFile -> "hsig"
HsBootFile -> "hs-boot"
HsSrcFile -> "hs")
let location = case hsc_src of
HsBootFile -> addBootSuffixLocn location0
_ -> location0
env <- getBkpEnv
time <- liftIO $ getModificationUTCTime (bkp_filename env)
hi_timestamp <- liftIO $ modificationTimeIfExists (ml_hi_file location)
let (src_idecls, ord_idecls) = partition (ideclSource.unLoc) imps
ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc)
ord_idecls
implicit_prelude = xopt LangExt.ImplicitPrelude dflags
implicit_imports = mkPrelImports modname loc
implicit_prelude imps
convImport (L _ i) = (fmap sl_fs (ideclPkgQual i), ideclName i)
extra_sig_imports <- liftIO $ findExtraSigImports hsc_env hsc_src modname
let normal_imports = map convImport (implicit_imports ++ ordinary_imps)
required_by_imports <- liftIO $ implicitRequirements hsc_env normal_imports
this_mod <- liftIO $ addHomeModuleToFinder hsc_env modname location
return ModSummary {
ms_mod = this_mod,
ms_hsc_src = hsc_src,
ms_location = location,
ms_hspp_file = (case hiDir dflags of
Nothing -> ""
Just d -> d) </> ".." </> moduleNameSlashes modname <.> "hi",
ms_hspp_opts = dflags,
ms_hspp_buf = Nothing,
ms_srcimps = map convImport src_idecls,
ms_textual_imps = normal_imports
++ extra_sig_imports
++ required_by_imports,
ms_parsed_mod = Just (HsParsedModule {
hpm_module = hsmod,
hpm_src_files = [],
hpm_annotations = (Map.empty, Map.empty)
}),
ms_hs_date = time,
ms_obj_date = Nothing,
ms_iface_date = hi_timestamp
}
newInstalledUnitId :: ComponentId -> Maybe FastString -> InstalledUnitId
newInstalledUnitId (ComponentId cid_fs) (Just fs)
= InstalledUnitId (cid_fs `appendFS` mkFastString "+" `appendFS` fs)
newInstalledUnitId (ComponentId cid_fs) Nothing
= InstalledUnitId cid_fs