2 % (c) The University of Glasgow, 2006
5 -- | Package manipulation
9 -- * The PackageConfigMap
10 PackageConfigMap, emptyPackageConfigMap, lookupPackage,
11 extendPackageConfigMap, dumpPackages,
13 -- * Reading the package config, and processing cmdline args
17 lookupModuleInAllPackages,
19 -- * Inspecting the set of packages in scope
20 getPackageIncludePath,
21 getPackageLibraryPath,
23 getPackageExtraCcOpts,
24 getPackageFrameworkPath,
26 getPreloadPackagesAnd,
28 collectIncludeDirs, collectLibraryPaths, collectLinkOpts,
36 #include "HsVersions.h"
39 import DynFlags ( dopt, DynFlag(..), DynFlags(..), PackageFlag(..) )
41 import Config ( cProjectVersion )
42 import Name ( Name, nameModule_maybe )
51 import System.Environment ( getEnv )
52 import Distribution.InstalledPackageInfo
53 import Distribution.InstalledPackageInfo.Binary
54 import Distribution.Package hiding (PackageId,depends)
56 import ErrUtils ( debugTraceMsg, putMsg, Message )
59 import System.Directory
60 import System.FilePath
62 import Data.List as List
64 -- ---------------------------------------------------------------------------
67 -- | Package state is all stored in 'DynFlag's, including the details of
68 -- all packages, which packages are exposed, and which modules they
71 -- The package state is computed by 'initPackages', and kept in DynFlags.
73 -- * @-package <pkg>@ causes @<pkg>@ to become exposed, and all other packages
74 -- with the same name to become hidden.
76 -- * @-hide-package <pkg>@ causes @<pkg>@ to become hidden.
78 -- * Let @exposedPackages@ be the set of packages thus exposed.
79 -- Let @depExposedPackages@ be the transitive closure from @exposedPackages@ of
80 -- their dependencies.
82 -- * When searching for a module from an preload import declaration,
83 -- only the exposed modules in @exposedPackages@ are valid.
85 -- * When searching for a module from an implicit import, all modules
86 -- from @depExposedPackages@ are valid.
88 -- * When linking in a compilation manager mode, we link in packages the
89 -- program depends on (the compiler knows this list by the
90 -- time it gets to the link step). Also, we link in all packages
91 -- which were mentioned with preload @-package@ flags on the command-line,
92 -- or are a transitive dependency of same, or are \"base\"\/\"rts\".
93 -- The reason for this is that we might need packages which don't
94 -- contain any Haskell modules, and therefore won't be discovered
95 -- by the normal mechanism of dependency tracking.
99 -- When compiling module A, which imports module B, we need to
100 -- know whether B will be in the same DLL as A.
101 -- If it's in the same DLL, we refer to B_f_closure
102 -- If it isn't, we refer to _imp__B_f_closure
103 -- When compiling A, we record in B's Module value whether it's
104 -- in a different DLL, by setting the DLL flag.
106 data PackageState = PackageState {
107 pkgIdMap :: PackageConfigMap, -- PackageId -> PackageConfig
108 -- The exposed flags are adjusted according to -package and
109 -- -hide-package flags, and -ignore-package removes packages.
111 preloadPackages :: [PackageId],
112 -- The packages we're going to link in eagerly. This list
113 -- should be in reverse dependency order; that is, a package
114 -- is always mentioned before the packages it depends on.
116 moduleToPkgConfAll :: UniqFM [(PackageConfig,Bool)], -- ModuleEnv mapping
117 -- Derived from pkgIdMap.
118 -- Maps Module to (pkgconf,exposed), where pkgconf is the
119 -- PackageConfig for the package containing the module, and
120 -- exposed is True if the package exposes that module.
122 installedPackageIdMap :: InstalledPackageIdMap
125 -- | A PackageConfigMap maps a 'PackageId' to a 'PackageConfig'
126 type PackageConfigMap = UniqFM PackageConfig
128 type InstalledPackageIdMap = FiniteMap InstalledPackageId PackageId
130 type InstalledPackageIndex = FiniteMap InstalledPackageId PackageConfig
132 emptyPackageConfigMap :: PackageConfigMap
133 emptyPackageConfigMap = emptyUFM
135 -- | Find the package we know about with the given id (e.g. \"foo-1.0\"), if any
136 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
137 lookupPackage = lookupUFM
139 extendPackageConfigMap
140 :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
141 extendPackageConfigMap pkg_map new_pkgs
142 = foldl add pkg_map new_pkgs
143 where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
145 -- | Looks up the package with the given id in the package state, panicing if it is
147 getPackageDetails :: PackageState -> PackageId -> PackageConfig
148 getPackageDetails ps pid = expectJust "getPackageDetails" (lookupPackage (pkgIdMap ps) pid)
150 -- ----------------------------------------------------------------------------
151 -- Loading the package config files and building up the package state
153 -- | Call this after 'DynFlags.parseDynFlags'. It reads the package
154 -- configuration files, and sets up various internal tables of package
155 -- information, according to the package-related flags on the
156 -- command-line (@-package@, @-hide-package@ etc.)
158 -- Returns a list of packages to link in if we're doing dynamic linking.
159 -- This list contains the packages that the user explicitly mentioned with
162 -- 'initPackages' can be called again subsequently after updating the
163 -- 'packageFlags' field of the 'DynFlags', and it will update the
164 -- 'pkgState' in 'DynFlags' and return a list of packages to
166 initPackages :: DynFlags -> IO (DynFlags, [PackageId])
167 initPackages dflags = do
168 pkg_db <- case pkgDatabase dflags of
169 Nothing -> readPackageConfigs dflags
171 (pkg_state, preload, this_pkg)
172 <- mkPackageState dflags pkg_db [] (thisPackage dflags)
173 return (dflags{ pkgDatabase = Just pkg_db,
174 pkgState = pkg_state,
175 thisPackage = this_pkg },
178 -- -----------------------------------------------------------------------------
179 -- Reading the package database(s)
181 readPackageConfigs :: DynFlags -> IO [PackageConfig]
182 readPackageConfigs dflags = do
183 e_pkg_path <- tryIO (getEnv "GHC_PACKAGE_PATH")
184 system_pkgconfs <- getSystemPackageConfigs dflags
186 let pkgconfs = case e_pkg_path of
187 Left _ -> system_pkgconfs
189 | last cs == "" -> init cs ++ system_pkgconfs
191 where cs = parseSearchPath path
192 -- if the path ends in a separator (eg. "/foo/bar:")
193 -- the we tack on the system paths.
195 pkgs <- mapM (readPackageConfig dflags)
196 (reverse pkgconfs ++ reverse (extraPkgConfs dflags))
197 -- later packages shadow earlier ones. extraPkgConfs
198 -- is in the opposite order to the flags on the
204 getSystemPackageConfigs :: DynFlags -> IO [FilePath]
205 getSystemPackageConfigs dflags = do
206 -- System one always comes first
207 let system_pkgconf = systemPackageConfig dflags
209 -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
210 -- unless the -no-user-package-conf flag was given.
212 if not (dopt Opt_ReadUserPackageConf dflags) then return [] else do
213 appdir <- getAppUserDataDirectory "ghc"
215 dir = appdir </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
216 pkgconf = dir </> "package.conf.d"
218 exist <- doesDirectoryExist pkgconf
219 if exist then return [pkgconf] else return []
220 `catchIO` (\_ -> return [])
222 return (user_pkgconf ++ [system_pkgconf])
224 readPackageConfig :: DynFlags -> FilePath -> IO [PackageConfig]
225 readPackageConfig dflags conf_file = do
226 isdir <- doesDirectoryExist conf_file
230 then do let filename = conf_file </> "package.cache"
231 debugTraceMsg dflags 2 (text "Using binary package database:" <+> text filename)
232 conf <- readBinPackageDB filename
233 return (map installedPackageInfoToPackageConfig conf)
236 isfile <- doesFileExist conf_file
238 ghcError $ InstallationError $
239 "can't find a package database at " ++ conf_file
240 debugTraceMsg dflags 2 (text "Using package config file:" <+> text conf_file)
241 str <- readFile conf_file
242 return (map installedPackageInfoToPackageConfig $ read str)
245 top_dir = topDir dflags
246 pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
247 pkg_configs2 = maybeHidePackages dflags pkg_configs1
251 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
252 maybeHidePackages dflags pkgs
253 | dopt Opt_HideAllPackages dflags = map hide pkgs
256 hide pkg = pkg{ exposed = False }
258 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
259 -- Replace the string "$topdir" at the beginning of a path
260 -- with the current topdir (obtained from the -B option).
261 mungePackagePaths top_dir ps = map munge_pkg ps
263 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
264 includeDirs = munge_paths (includeDirs p),
265 libraryDirs = munge_paths (libraryDirs p),
266 frameworkDirs = munge_paths (frameworkDirs p),
267 haddockInterfaces = munge_paths (haddockInterfaces p),
268 haddockHTMLs = munge_paths (haddockHTMLs p)
271 munge_paths = map munge_path
274 | Just p' <- stripPrefix "$topdir" p = top_dir ++ p'
275 | Just p' <- stripPrefix "$httptopdir" p = toHttpPath top_dir ++ p'
278 toHttpPath p = "file:///" ++ p
281 -- -----------------------------------------------------------------------------
282 -- Modify our copy of the package database based on a package flag
283 -- (-package, -hide-package, -ignore-package).
287 -> [PackageConfig] -- Initial database
288 -> PackageFlag -- flag to apply
289 -> IO [PackageConfig] -- new database
291 applyPackageFlag unusable pkgs flag =
294 case selectPackages (matchingStr str) pkgs unusable of
295 Left ps -> packageFlagErr flag ps
296 Right (p:ps,qs) -> return (p':ps')
297 where p' = p {exposed=True}
298 ps' = hideAll (pkgName (sourcePackageId p)) (ps++qs)
299 _ -> panic "applyPackageFlag"
301 ExposePackageId str ->
302 case selectPackages (matchingId str) pkgs unusable of
303 Left ps -> packageFlagErr flag ps
304 Right (p:ps,qs) -> return (p':ps')
305 where p' = p {exposed=True}
306 ps' = hideAll (pkgName (sourcePackageId p)) (ps++qs)
307 _ -> panic "applyPackageFlag"
310 case selectPackages (matchingStr str) pkgs unusable of
311 Left ps -> packageFlagErr flag ps
312 Right (ps,qs) -> return (map hide ps ++ qs)
313 where hide p = p {exposed=False}
315 _ -> panic "applyPackageFlag"
318 -- When a package is requested to be exposed, we hide all other
319 -- packages with the same name.
320 hideAll name ps = map maybe_hide ps
322 | pkgName (sourcePackageId p) == name = p {exposed=False}
326 selectPackages :: (PackageConfig -> Bool) -> [PackageConfig]
328 -> Either [(PackageConfig, UnusablePackageReason)]
329 ([PackageConfig], [PackageConfig])
330 selectPackages matches pkgs unusable
332 (ps,rest) = partition matches pkgs
333 reasons = [ (p, lookupFM unusable (installedPackageId p))
336 if all (isJust.snd) reasons
337 then Left [ (p, reason) | (p,Just reason) <- reasons ]
338 else Right (sortByVersion [ p | (p,Nothing) <- reasons ], rest)
340 -- A package named on the command line can either include the
341 -- version, or just the name if it is unambiguous.
342 matchingStr :: String -> PackageConfig -> Bool
344 = str == display (sourcePackageId p)
345 || str == display (pkgName (sourcePackageId p))
347 matchingId :: String -> PackageConfig -> Bool
348 matchingId str p = InstalledPackageId str == installedPackageId p
350 sortByVersion :: [InstalledPackageInfo_ m] -> [InstalledPackageInfo_ m]
351 sortByVersion = sortBy (flip (comparing (pkgVersion.sourcePackageId)))
353 comparing :: Ord a => (t -> a) -> t -> t -> Ordering
354 comparing f a b = f a `compare` f b
356 packageFlagErr :: PackageFlag
357 -> [(PackageConfig, UnusablePackageReason)]
359 packageFlagErr flag reasons = ghcError (CmdLineError (showSDoc $ err))
360 where err = text "cannot satisfy " <> ppr_flag <>
361 (if null reasons then empty else text ": ") $$
362 nest 4 (ppr_reasons $$
363 text "(use -v for more information)")
364 ppr_flag = case flag of
365 IgnorePackage p -> text "-ignore-package " <> text p
366 HidePackage p -> text "-hide-package " <> text p
367 ExposePackage p -> text "-package " <> text p
368 ExposePackageId p -> text "-package-id " <> text p
369 ppr_reasons = vcat (map ppr_reason reasons)
370 ppr_reason (p, reason) = pprReason (pprIPkg p <+> text "is") reason
372 -- -----------------------------------------------------------------------------
373 -- Hide old versions of packages
376 -- hide all packages for which there is also a later version
377 -- that is already exposed. This just makes it non-fatal to have two
378 -- versions of a package exposed, which can happen if you install a
379 -- later version of a package in the user database, for example.
381 hideOldPackages :: DynFlags -> [PackageConfig] -> IO [PackageConfig]
382 hideOldPackages dflags pkgs = mapM maybe_hide pkgs
384 | not (exposed p) = return p
385 | (p' : _) <- later_versions = do
386 debugTraceMsg dflags 2 $
387 (ptext (sLit "hiding package") <+> pprSPkg p <+>
388 ptext (sLit "to avoid conflict with later version") <+>
390 return (p {exposed=False})
391 | otherwise = return p
392 where myname = pkgName (sourcePackageId p)
393 myversion = pkgVersion (sourcePackageId p)
394 later_versions = [ p | p <- pkgs, exposed p,
395 let pkg = sourcePackageId p,
396 pkgName pkg == myname,
397 pkgVersion pkg > myversion ]
399 -- -----------------------------------------------------------------------------
404 -> [PackageConfig] -- database
405 -> IO [PackageConfig]
407 findWiredInPackages dflags pkgs = do
409 -- Now we must find our wired-in packages, and rename them to
410 -- their canonical names (eg. base-1.0 ==> base).
413 wired_in_pkgids :: [String]
414 wired_in_pkgids = map packageIdString
424 matches :: PackageConfig -> String -> Bool
425 pc `matches` pid = display (pkgName (sourcePackageId pc)) == pid
427 -- find which package corresponds to each wired-in package
428 -- delete any other packages with the same name
429 -- update the package and any dependencies to point to the new
432 -- When choosing which package to map to a wired-in package
433 -- name, we prefer exposed packages, and pick the latest
434 -- version. To override the default choice, -hide-package
435 -- could be used to hide newer versions.
437 findWiredInPackage :: [PackageConfig] -> String
438 -> IO (Maybe InstalledPackageId)
439 findWiredInPackage pkgs wired_pkg =
440 let all_ps = [ p | p <- pkgs, p `matches` wired_pkg ] in
443 many -> pick (head (sortByVersion many))
446 debugTraceMsg dflags 2 $
447 ptext (sLit "wired-in package ")
449 <> ptext (sLit " not found.")
451 pick :: InstalledPackageInfo_ ModuleName
452 -> IO (Maybe InstalledPackageId)
454 debugTraceMsg dflags 2 $
455 ptext (sLit "wired-in package ")
457 <> ptext (sLit " mapped to ")
459 return (Just (installedPackageId pkg))
462 mb_wired_in_ids <- mapM (findWiredInPackage pkgs) wired_in_pkgids
464 wired_in_ids = catMaybes mb_wired_in_ids
466 -- this is old: we used to assume that if there were
467 -- multiple versions of wired-in packages installed that
468 -- they were mutually exclusive. Now we're assuming that
469 -- you have one "main" version of each wired-in package
470 -- (the latest version), and the others are backward-compat
471 -- wrappers that depend on this one. e.g. base-4.0 is the
472 -- latest, base-3.0 is a compat wrapper depending on base-4.0.
474 deleteOtherWiredInPackages pkgs = filterOut bad pkgs
475 where bad p = any (p `matches`) wired_in_pkgids
476 && package p `notElem` map fst wired_in_ids
479 updateWiredInDependencies pkgs = map upd_pkg pkgs
481 | installedPackageId p `elem` wired_in_ids
482 = p { sourcePackageId = (sourcePackageId p){ pkgVersion = Version [] [] } }
486 return $ updateWiredInDependencies pkgs
488 -- ----------------------------------------------------------------------------
490 data UnusablePackageReason
492 | MissingDependencies [InstalledPackageId]
493 | ShadowedBy InstalledPackageId
495 type UnusablePackages = FiniteMap InstalledPackageId UnusablePackageReason
497 pprReason :: SDoc -> UnusablePackageReason -> SDoc
498 pprReason pref reason = case reason of
500 pref <+> ptext (sLit "ignored due to an -ignore-package flag")
501 MissingDependencies deps ->
503 ptext (sLit "unusable due to missing or recursive dependencies:") $$
504 nest 2 (hsep (map (text.display) deps))
506 pref <+> ptext (sLit "shadowed by package ") <> text (display ipid)
508 reportUnusable :: DynFlags -> UnusablePackages -> IO ()
509 reportUnusable dflags pkgs = mapM_ report (fmToList pkgs)
511 report (ipid, reason) =
512 debugTraceMsg dflags 2 $
514 (ptext (sLit "package") <+>
515 text (display ipid) <+> text "is") reason
517 -- ----------------------------------------------------------------------------
519 -- Detect any packages that have missing dependencies, and also any
520 -- mutually-recursive groups of packages (loops in the package graph
521 -- are not allowed). We do this by taking the least fixpoint of the
522 -- dependency graph, repeatedly adding packages whose dependencies are
523 -- satisfied until no more can be added.
525 findBroken :: [PackageConfig] -> UnusablePackages
526 findBroken pkgs = go [] emptyFM pkgs
528 go avail ipids not_avail =
529 case partitionWith (depsAvailable ipids) not_avail of
531 listToFM [ (installedPackageId p, MissingDependencies deps)
532 | (p,deps) <- not_avail ]
533 (new_avail, not_avail) ->
534 go (new_avail ++ avail) new_ipids (map fst not_avail)
535 where new_ipids = addListToFM ipids
536 [ (installedPackageId p, p) | p <- new_avail ]
538 depsAvailable :: InstalledPackageIndex
540 -> Either PackageConfig (PackageConfig, [InstalledPackageId])
541 depsAvailable ipids pkg
542 | null dangling = Left pkg
543 | otherwise = Right (pkg, dangling)
544 where dangling = filter (not . (`elemFM` ipids)) (depends pkg)
546 -- -----------------------------------------------------------------------------
547 -- Eliminate shadowed packages, giving the user some feedback
549 -- later packages in the list should shadow earlier ones with the same
550 -- package name/version. Additionally, a package may be preferred if
551 -- it is in the transitive closure of packages selected using -package-id
553 shadowPackages :: [PackageConfig] -> [InstalledPackageId] -> UnusablePackages
554 shadowPackages pkgs preferred
555 = let (shadowed,_) = foldl check ([],emptyUFM) pkgs
558 check (shadowed,pkgmap) pkg
559 | Just oldpkg <- lookupUFM pkgmap (packageConfigId pkg),
561 ipid_new = installedPackageId pkg
562 ipid_old = installedPackageId oldpkg,
565 = if ipid_old `elem` preferred
566 then ( (ipid_new, ShadowedBy ipid_old) : shadowed, pkgmap )
567 else ( (ipid_old, ShadowedBy ipid_new) : shadowed, pkgmap' )
569 = (shadowed, pkgmap')
571 pkgmap' = addToUFM pkgmap (packageConfigId pkg) pkg
573 -- -----------------------------------------------------------------------------
575 ignorePackages :: [PackageFlag] -> [PackageConfig] -> UnusablePackages
576 ignorePackages flags pkgs = listToFM (concatMap doit flags)
578 doit (IgnorePackage str) =
579 case partition (matchingStr str) pkgs of
580 (ps, _) -> [ (installedPackageId p, IgnoredWithFlag)
582 -- missing package is not an error for -ignore-package,
583 -- because a common usage is to -ignore-package P as
584 -- a preventative measure just in case P exists.
585 doit _ = panic "ignorePackages"
587 -- -----------------------------------------------------------------------------
589 depClosure :: InstalledPackageIndex
590 -> [InstalledPackageId]
591 -> [InstalledPackageId]
592 depClosure index ipids = closure emptyFM ipids
594 closure set [] = keysFM set
595 closure set (ipid : ipids)
596 | ipid `elemFM` set = closure set ipids
597 | Just p <- lookupFM index ipid = closure (addToFM set ipid p)
599 | otherwise = closure set ipids
601 -- -----------------------------------------------------------------------------
602 -- When all the command-line options are in, we can process our package
603 -- settings and populate the package state.
607 -> [PackageConfig] -- initial database
608 -> [PackageId] -- preloaded packages
609 -> PackageId -- this package
611 [PackageId], -- new packages to preload
612 PackageId) -- this package, might be modified if the current
614 -- package is a wired-in package.
616 mkPackageState dflags pkgs0 preload0 this_package = do
621 1. P = transitive closure of packages selected by -package-id
623 2. Apply shadowing. When there are multiple packages with the same
625 * if one is in P, use that one
626 * otherwise, use the one highest in the package stack
628 rationale: we cannot use two packages with the same sourcePackageId
629 in the same program, because sourcePackageId is the symbol prefix.
630 Hence we must select a consistent set of packages to use. We have
631 a default algorithm for doing this: packages higher in the stack
632 shadow those lower down. This default algorithm can be overriden
633 by giving explicit -package-id flags; then we have to take these
634 preferences into account when selecting which other packages are
637 Our simple algorithm throws away some solutions: there may be other
638 consistent sets that would satisfy the -package flags, but it's
639 not GHC's job to be doing constraint solving.
642 3. remove packages selected by -ignore-package
644 4. remove any packages with missing dependencies, or mutually recursive
647 5. report (with -v) any packages that were removed by steps 2-4
649 6. apply flags to set exposed/hidden on the resulting packages
650 - if any flag refers to a package which was removed by 2-4, then
651 we can give an error message explaining why
653 7. hide any packages which are superseded by later exposed packages
657 flags = reverse (packageFlags dflags)
659 ipid_map = listToFM [ (installedPackageId p, p) | p <- pkgs0 ]
661 -- pkgs0 with duplicate packages filtered out. This is
662 -- important: it is possible for a package in the user package
663 -- DB to have the same IPID as a package in the global DB, and
664 -- we want the former to take precedence. This is not the same
665 -- as shadowing (below), since in this case the two packages
666 -- have the same ABI and are interchangeable.
667 pkgs0_unique = eltsFM ipid_map
669 ipid_selected = depClosure ipid_map [ InstalledPackageId i
670 | ExposePackageId i <- flags ]
672 (ignore_flags, other_flags) = partition is_ignore flags
673 is_ignore IgnorePackage{} = True
676 shadowed = shadowPackages pkgs0_unique ipid_selected
678 ignored = ignorePackages ignore_flags pkgs0_unique
680 pkgs0' = filter (not . (`elemFM` (plusFM shadowed ignored)) . installedPackageId) pkgs0_unique
681 broken = findBroken pkgs0'
682 unusable = shadowed `plusFM` ignored `plusFM` broken
684 reportUnusable dflags unusable
687 -- Modify the package database according to the command-line flags
688 -- (-package, -hide-package, -ignore-package, -hide-all-packages).
690 pkgs1 <- foldM (applyPackageFlag unusable) pkgs0_unique other_flags
691 let pkgs2 = filter (not . (`elemFM` unusable) . installedPackageId) pkgs1
693 -- Here we build up a set of the packages mentioned in -package
694 -- flags on the command line; these are called the "preload"
695 -- packages. we link these packages in eagerly. The preload set
696 -- should contain at least rts & base, which is why we pretend that
697 -- the command line contains -package rts & -package base.
699 let preload1 = [ installedPackageId p | f <- flags, p <- get_exposed f ]
701 get_exposed (ExposePackage s) = filter (matchingStr s) pkgs2
702 get_exposed (ExposePackageId s) = filter (matchingId s) pkgs2
705 -- hide packages that are subsumed by later versions
706 pkgs3 <- hideOldPackages dflags pkgs2
708 -- sort out which packages are wired in
709 pkgs4 <- findWiredInPackages dflags pkgs3
711 let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs4
713 ipid_map = listToFM [ (installedPackageId p, packageConfigId p)
716 lookupIPID ipid@(InstalledPackageId str)
717 | Just pid <- lookupFM ipid_map ipid = return pid
718 | otherwise = missingPackageErr str
720 preload2 <- mapM lookupIPID preload1
723 -- add base & rts to the preload packages
725 | dopt Opt_AutoLinkPackages dflags
726 = filter (flip elemUFM pkg_db) [basePackageId, rtsPackageId]
728 -- but in any case remove the current package from the set of
729 -- preloaded packages so that base/rts does not end up in the
730 -- set up preloaded package when we are just building it
731 preload3 = nub $ filter (/= this_package)
732 $ (basicLinkedPackages ++ preload2)
734 -- Close the preload packages with their dependencies
735 dep_preload <- closeDeps pkg_db ipid_map (zip preload3 (repeat Nothing))
736 let new_dep_preload = filter (`notElem` preload0) dep_preload
738 let pstate = PackageState{ preloadPackages = dep_preload,
740 moduleToPkgConfAll = mkModuleMap pkg_db,
741 installedPackageIdMap = ipid_map
744 return (pstate, new_dep_preload, this_package)
747 -- -----------------------------------------------------------------------------
748 -- Make the mapping from module to package info
752 -> UniqFM [(PackageConfig, Bool)]
753 mkModuleMap pkg_db = foldr extend_modmap emptyUFM pkgids
755 pkgids = map packageConfigId (eltsUFM pkg_db)
757 extend_modmap pkgid modmap =
758 addListToUFM_C (++) modmap
759 ([(m, [(pkg, True)]) | m <- exposed_mods] ++
760 [(m, [(pkg, False)]) | m <- hidden_mods])
762 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
763 exposed_mods = exposedModules pkg
764 hidden_mods = hiddenModules pkg
766 pprSPkg :: PackageConfig -> SDoc
767 pprSPkg p = text (display (sourcePackageId p))
769 pprIPkg :: PackageConfig -> SDoc
770 pprIPkg p = text (display (installedPackageId p))
772 -- -----------------------------------------------------------------------------
773 -- Extracting information from the packages in scope
775 -- Many of these functions take a list of packages: in those cases,
776 -- the list is expected to contain the "dependent packages",
777 -- i.e. those packages that were found to be depended on by the
778 -- current module/program. These can be auto or non-auto packages, it
779 -- doesn't really matter. The list is always combined with the list
780 -- of preload (command-line) packages to determine which packages to
783 -- | Find all the include directories in these and the preload packages
784 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
785 getPackageIncludePath dflags pkgs =
786 collectIncludeDirs `fmap` getPreloadPackagesAnd dflags pkgs
788 collectIncludeDirs :: [PackageConfig] -> [FilePath]
789 collectIncludeDirs ps = nub (filter notNull (concatMap includeDirs ps))
791 -- | Find all the library paths in these and the preload packages
792 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
793 getPackageLibraryPath dflags pkgs =
794 collectLibraryPaths `fmap` getPreloadPackagesAnd dflags pkgs
796 collectLibraryPaths :: [PackageConfig] -> [FilePath]
797 collectLibraryPaths ps = nub (filter notNull (concatMap libraryDirs ps))
799 -- | Find all the link options in these and the preload packages
800 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
801 getPackageLinkOpts dflags pkgs =
802 collectLinkOpts dflags `fmap` getPreloadPackagesAnd dflags pkgs
804 collectLinkOpts :: DynFlags -> [PackageConfig] -> [String]
805 collectLinkOpts dflags ps = concat (map all_opts ps)
807 libs p = packageHsLibs dflags p ++ extraLibraries p
808 all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
810 packageHsLibs :: DynFlags -> PackageConfig -> [String]
811 packageHsLibs dflags p = map (mkDynName . addSuffix) (hsLibraries p)
815 ways1 = filter ((/= WayDyn) . wayName) ways0
816 -- the name of a shared library is libHSfoo-ghc<version>.so
817 -- we leave out the _dyn, because it is superfluous
819 -- debug RTS includes support for -eventlog
820 ways2 | WayDebug `elem` map wayName ways1
821 = filter ((/= WayEventLog) . wayName) ways1
825 tag = mkBuildTag (filter (not . wayRTSOnly) ways2)
826 rts_tag = mkBuildTag ways2
828 mkDynName | opt_Static = id
829 | otherwise = (++ ("-ghc" ++ cProjectVersion))
831 addSuffix rts@"HSrts" = rts ++ (expandTag rts_tag)
832 addSuffix other_lib = other_lib ++ (expandTag tag)
834 expandTag t | null t = ""
837 -- | Find all the C-compiler options in these and the preload packages
838 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
839 getPackageExtraCcOpts dflags pkgs = do
840 ps <- getPreloadPackagesAnd dflags pkgs
841 return (concatMap ccOptions ps)
843 -- | Find all the package framework paths in these and the preload packages
844 getPackageFrameworkPath :: DynFlags -> [PackageId] -> IO [String]
845 getPackageFrameworkPath dflags pkgs = do
846 ps <- getPreloadPackagesAnd dflags pkgs
847 return (nub (filter notNull (concatMap frameworkDirs ps)))
849 -- | Find all the package frameworks in these and the preload packages
850 getPackageFrameworks :: DynFlags -> [PackageId] -> IO [String]
851 getPackageFrameworks dflags pkgs = do
852 ps <- getPreloadPackagesAnd dflags pkgs
853 return (concatMap frameworks ps)
855 -- -----------------------------------------------------------------------------
858 -- | Takes a 'Module', and if the module is in a package returns
859 -- @(pkgconf, exposed)@ where pkgconf is the PackageConfig for that package,
860 -- and exposed is @True@ if the package exposes the module.
861 lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
862 lookupModuleInAllPackages dflags m =
863 case lookupUFM (moduleToPkgConfAll (pkgState dflags)) m of
867 -- | Find all the 'PackageConfig' in both the preload packages from 'DynFlags' and corresponding to the list of
869 getPreloadPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
870 getPreloadPackagesAnd dflags pkgids =
872 state = pkgState dflags
873 pkg_map = pkgIdMap state
874 ipid_map = installedPackageIdMap state
875 preload = preloadPackages state
876 pairs = zip pkgids (repeat Nothing)
878 all_pkgs <- throwErr (foldM (add_package pkg_map ipid_map) preload pairs)
879 return (map (getPackageDetails state) all_pkgs)
881 -- Takes a list of packages, and returns the list with dependencies included,
882 -- in reverse dependency order (a package appears before those it depends on).
883 closeDeps :: PackageConfigMap
884 -> FiniteMap InstalledPackageId PackageId
885 -> [(PackageId, Maybe PackageId)]
887 closeDeps pkg_map ipid_map ps = throwErr (closeDepsErr pkg_map ipid_map ps)
889 throwErr :: MaybeErr Message a -> IO a
890 throwErr m = case m of
891 Failed e -> ghcError (CmdLineError (showSDoc e))
892 Succeeded r -> return r
894 closeDepsErr :: PackageConfigMap
895 -> FiniteMap InstalledPackageId PackageId
896 -> [(PackageId,Maybe PackageId)]
897 -> MaybeErr Message [PackageId]
898 closeDepsErr pkg_map ipid_map ps = foldM (add_package pkg_map ipid_map) [] ps
901 add_package :: PackageConfigMap
902 -> FiniteMap InstalledPackageId PackageId
904 -> (PackageId,Maybe PackageId)
905 -> MaybeErr Message [PackageId]
906 add_package pkg_db ipid_map ps (p, mb_parent)
907 | p `elem` ps = return ps -- Check if we've already added this package
909 case lookupPackage pkg_db p of
910 Nothing -> Failed (missingPackageMsg (packageIdString p) <>
911 missingDependencyMsg mb_parent)
913 -- Add the package's dependents also
914 ps' <- foldM add_package_ipid ps (depends pkg)
917 add_package_ipid ps ipid@(InstalledPackageId str)
918 | Just pid <- lookupFM ipid_map ipid
919 = add_package pkg_db ipid_map ps (pid, Just p)
921 = Failed (missingPackageMsg str <> missingDependencyMsg mb_parent)
923 missingPackageErr :: String -> IO a
924 missingPackageErr p = ghcError (CmdLineError (showSDoc (missingPackageMsg p)))
926 missingPackageMsg :: String -> SDoc
927 missingPackageMsg p = ptext (sLit "unknown package:") <+> text p
929 missingDependencyMsg :: Maybe PackageId -> SDoc
930 missingDependencyMsg Nothing = empty
931 missingDependencyMsg (Just parent)
932 = space <> parens (ptext (sLit "dependency of") <+> ftext (packageIdFS parent))
934 -- -----------------------------------------------------------------------------
936 -- | Will the 'Name' come from a dynamically linked library?
937 isDllName :: PackageId -> Name -> Bool
938 isDllName this_pkg name
940 | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
941 | otherwise = False -- no, it is not even an external name
943 -- -----------------------------------------------------------------------------
944 -- Displaying packages
946 -- | Show package info on console, if verbosity is >= 3
947 dumpPackages :: DynFlags -> IO ()
949 = do let pkg_map = pkgIdMap (pkgState dflags)
951 vcat (map (text . showInstalledPackageInfo
952 . packageConfigToInstalledPackageInfo)