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 ParsePkgConf ( loadPackageConfig )
40 import DynFlags ( dopt, DynFlag(..), DynFlags(..), PackageFlag(..) )
42 import Config ( cProjectVersion )
43 import Name ( Name, nameModule_maybe )
52 import System.Environment ( getEnv )
53 import Distribution.InstalledPackageInfo
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 emptyPackageConfigMap :: PackageConfigMap
131 emptyPackageConfigMap = emptyUFM
133 -- | Find the package we know about with the given id (e.g. \"foo-1.0\"), if any
134 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
135 lookupPackage = lookupUFM
137 extendPackageConfigMap
138 :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
139 extendPackageConfigMap pkg_map new_pkgs
140 = foldl add pkg_map new_pkgs
141 where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
143 -- | Looks up the package with the given id in the package state, panicing if it is
145 getPackageDetails :: PackageState -> PackageId -> PackageConfig
146 getPackageDetails ps pid = expectJust "getPackageDetails" (lookupPackage (pkgIdMap ps) pid)
148 -- ----------------------------------------------------------------------------
149 -- Loading the package config files and building up the package state
151 -- | Call this after 'DynFlags.parseDynFlags'. It reads the package
152 -- configuration files, and sets up various internal tables of package
153 -- information, according to the package-related flags on the
154 -- command-line (@-package@, @-hide-package@ etc.)
156 -- Returns a list of packages to link in if we're doing dynamic linking.
157 -- This list contains the packages that the user explicitly mentioned with
160 -- 'initPackages' can be called again subsequently after updating the
161 -- 'packageFlags' field of the 'DynFlags', and it will update the
162 -- 'pkgState' in 'DynFlags' and return a list of packages to
164 initPackages :: DynFlags -> IO (DynFlags, [PackageId])
165 initPackages dflags = do
166 pkg_db <- case pkgDatabase dflags of
167 Nothing -> readPackageConfigs dflags
169 (pkg_state, preload, this_pkg)
170 <- mkPackageState dflags pkg_db [] (thisPackage dflags)
171 return (dflags{ pkgDatabase = Just pkg_db,
172 pkgState = pkg_state,
173 thisPackage = this_pkg },
176 -- -----------------------------------------------------------------------------
177 -- Reading the package database(s)
179 readPackageConfigs :: DynFlags -> IO [PackageConfig]
180 readPackageConfigs dflags = do
181 e_pkg_path <- tryIO (getEnv "GHC_PACKAGE_PATH")
182 system_pkgconfs <- getSystemPackageConfigs dflags
184 let pkgconfs = case e_pkg_path of
185 Left _ -> system_pkgconfs
187 | last cs == "" -> init cs ++ system_pkgconfs
189 where cs = parseSearchPath path
190 -- if the path ends in a separator (eg. "/foo/bar:")
191 -- the we tack on the system paths.
193 pkgs <- mapM (readPackageConfig dflags)
194 (reverse pkgconfs ++ reverse (extraPkgConfs dflags))
195 -- later packages shadow earlier ones. extraPkgConfs
196 -- is in the opposite order to the flags on the
202 getSystemPackageConfigs :: DynFlags -> IO [FilePath]
203 getSystemPackageConfigs dflags = do
204 -- System one always comes first
205 let system_pkgconf = systemPackageConfig dflags
207 -- allow package.conf.d to contain a bunch of .conf files
208 -- containing package specifications. This is an easier way
209 -- to maintain the package database on systems with a package
210 -- management system, or systems that don't want to run ghc-pkg
211 -- to register or unregister packages. Undocumented feature for now.
212 let system_pkgconf_dir = system_pkgconf <.> "d"
213 system_pkgconf_dir_exists <- doesDirectoryExist system_pkgconf_dir
215 if system_pkgconf_dir_exists
216 then do files <- getDirectoryContents system_pkgconf_dir
217 return [ system_pkgconf_dir </> file
219 , takeExtension file == ".conf" ]
222 -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
223 -- unless the -no-user-package-conf flag was given.
224 -- We only do this when getAppUserDataDirectory is available
227 appdir <- getAppUserDataDirectory "ghc"
230 </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
232 flg <- doesFileExist pkgconf
233 if (flg && dopt Opt_ReadUserPackageConf dflags)
234 then return [pkgconf]
236 `catchIO` (\_ -> return [])
238 return (user_pkgconf ++ system_pkgconfs ++ [system_pkgconf])
241 readPackageConfig :: DynFlags -> FilePath -> IO [PackageConfig]
242 readPackageConfig dflags conf_file = do
243 debugTraceMsg dflags 2 (text "Using package config file:" <+> text conf_file)
244 proto_pkg_configs <- loadPackageConfig dflags conf_file
246 top_dir = topDir dflags
247 pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
248 pkg_configs2 = maybeHidePackages dflags pkg_configs1
252 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
253 maybeHidePackages dflags pkgs
254 | dopt Opt_HideAllPackages dflags = map hide pkgs
257 hide pkg = pkg{ exposed = False }
259 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
260 -- Replace the string "$topdir" at the beginning of a path
261 -- with the current topdir (obtained from the -B option).
262 mungePackagePaths top_dir ps = map munge_pkg ps
264 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
265 includeDirs = munge_paths (includeDirs p),
266 libraryDirs = munge_paths (libraryDirs p),
267 frameworkDirs = munge_paths (frameworkDirs p),
268 haddockInterfaces = munge_paths (haddockInterfaces p),
269 haddockHTMLs = munge_paths (haddockHTMLs p)
272 munge_paths = map munge_path
275 | Just p' <- stripPrefix "$topdir" p = top_dir ++ p'
276 | Just p' <- stripPrefix "$httptopdir" p = toHttpPath top_dir ++ p'
279 toHttpPath p = "file:///" ++ p
282 -- -----------------------------------------------------------------------------
283 -- Modify our copy of the package database based on a package flag
284 -- (-package, -hide-package, -ignore-package).
288 -> [PackageConfig] -- Initial database
289 -> PackageFlag -- flag to apply
290 -> IO [PackageConfig] -- new database
292 applyPackageFlag unusable pkgs flag =
295 case selectPackages (matchingStr str) pkgs unusable of
296 Left ps -> packageFlagErr flag ps
297 Right (p:ps,qs) -> return (p':ps')
298 where p' = p {exposed=True}
299 ps' = hideAll (pkgName (sourcePackageId p)) (ps++qs)
300 _ -> panic "applyPackageFlag"
302 ExposePackageId str ->
303 case selectPackages (matchingId str) pkgs unusable of
304 Left ps -> packageFlagErr flag ps
305 Right (p:ps,qs) -> return (p':ps')
306 where p' = p {exposed=True}
307 ps' = hideAll (pkgName (sourcePackageId p)) (ps++qs)
308 _ -> panic "applyPackageFlag"
311 case selectPackages (matchingStr str) pkgs unusable of
312 Left ps -> packageFlagErr flag ps
313 Right (ps,qs) -> return (map hide ps ++ qs)
314 where hide p = p {exposed=False}
316 _ -> panic "applyPackageFlag"
319 -- When a package is requested to be exposed, we hide all other
320 -- packages with the same name.
321 hideAll name ps = map maybe_hide ps
323 | pkgName (sourcePackageId p) == name = p {exposed=False}
327 selectPackages :: (PackageConfig -> Bool) -> [PackageConfig]
329 -> Either [(PackageConfig, UnusablePackageReason)]
330 ([PackageConfig], [PackageConfig])
331 selectPackages matches pkgs unusable
333 (ps,rest) = partition matches pkgs
334 reasons = [ (p, lookupFM unusable (installedPackageId p))
337 if all (isJust.snd) reasons
338 then Left [ (p, reason) | (p,Just reason) <- reasons ]
339 else Right (sortByVersion [ p | (p,Nothing) <- reasons ], rest)
341 -- A package named on the command line can either include the
342 -- version, or just the name if it is unambiguous.
343 matchingStr :: String -> PackageConfig -> Bool
345 = str == display (sourcePackageId p)
346 || str == display (pkgName (sourcePackageId p))
348 matchingId :: String -> PackageConfig -> Bool
349 matchingId str p = InstalledPackageId str == installedPackageId p
351 sortByVersion :: [InstalledPackageInfo_ m] -> [InstalledPackageInfo_ m]
352 sortByVersion = sortBy (flip (comparing (pkgVersion.sourcePackageId)))
354 comparing :: Ord a => (t -> a) -> t -> t -> Ordering
355 comparing f a b = f a `compare` f b
357 packageFlagErr :: PackageFlag
358 -> [(PackageConfig, UnusablePackageReason)]
360 packageFlagErr flag reasons = ghcError (CmdLineError (showSDoc $ err))
361 where err = text "cannot satisfy " <> ppr_flag <>
362 (if null reasons then empty else text ": ") $$
363 nest 4 (ppr_reasons $$
364 text "(use -v for more information)")
365 ppr_flag = case flag of
366 IgnorePackage p -> text "-ignore-package " <> text p
367 HidePackage p -> text "-hide-package " <> text p
368 ExposePackage p -> text "-package " <> text p
369 ExposePackageId p -> text "-package-id " <> text p
370 ppr_reasons = vcat (map ppr_reason reasons)
371 ppr_reason (p, reason) = pprReason (pprIPkg p <+> text "is") reason
373 -- -----------------------------------------------------------------------------
374 -- Hide old versions of packages
377 -- hide all packages for which there is also a later version
378 -- that is already exposed. This just makes it non-fatal to have two
379 -- versions of a package exposed, which can happen if you install a
380 -- later version of a package in the user database, for example.
382 hideOldPackages :: DynFlags -> [PackageConfig] -> IO [PackageConfig]
383 hideOldPackages dflags pkgs = mapM maybe_hide pkgs
385 | not (exposed p) = return p
386 | (p' : _) <- later_versions = do
387 debugTraceMsg dflags 2 $
388 (ptext (sLit "hiding package") <+> pprSPkg p <+>
389 ptext (sLit "to avoid conflict with later version") <+>
391 return (p {exposed=False})
392 | otherwise = return p
393 where myname = pkgName (sourcePackageId p)
394 myversion = pkgVersion (sourcePackageId p)
395 later_versions = [ p | p <- pkgs, exposed p,
396 let pkg = sourcePackageId p,
397 pkgName pkg == myname,
398 pkgVersion pkg > myversion ]
400 -- -----------------------------------------------------------------------------
405 -> [PackageConfig] -- database
406 -> IO [PackageConfig]
408 findWiredInPackages dflags pkgs = do
410 -- Now we must find our wired-in packages, and rename them to
411 -- their canonical names (eg. base-1.0 ==> base).
414 wired_in_pkgids :: [String]
415 wired_in_pkgids = map packageIdString
425 matches :: PackageConfig -> String -> Bool
426 pc `matches` pid = display (pkgName (sourcePackageId pc)) == pid
428 -- find which package corresponds to each wired-in package
429 -- delete any other packages with the same name
430 -- update the package and any dependencies to point to the new
433 -- When choosing which package to map to a wired-in package
434 -- name, we prefer exposed packages, and pick the latest
435 -- version. To override the default choice, -hide-package
436 -- could be used to hide newer versions.
438 findWiredInPackage :: [PackageConfig] -> String
439 -> IO (Maybe InstalledPackageId)
440 findWiredInPackage pkgs wired_pkg =
441 let all_ps = [ p | p <- pkgs, p `matches` wired_pkg ] in
444 many -> pick (head (sortByVersion many))
447 debugTraceMsg dflags 2 $
448 ptext (sLit "wired-in package ")
450 <> ptext (sLit " not found.")
452 pick :: InstalledPackageInfo_ ModuleName
453 -> IO (Maybe InstalledPackageId)
455 debugTraceMsg dflags 2 $
456 ptext (sLit "wired-in package ")
458 <> ptext (sLit " mapped to ")
460 return (Just (installedPackageId pkg))
463 mb_wired_in_ids <- mapM (findWiredInPackage pkgs) wired_in_pkgids
465 wired_in_ids = catMaybes mb_wired_in_ids
467 -- this is old: we used to assume that if there were
468 -- multiple versions of wired-in packages installed that
469 -- they were mutually exclusive. Now we're assuming that
470 -- you have one "main" version of each wired-in package
471 -- (the latest version), and the others are backward-compat
472 -- wrappers that depend on this one. e.g. base-4.0 is the
473 -- latest, base-3.0 is a compat wrapper depending on base-4.0.
475 deleteOtherWiredInPackages pkgs = filterOut bad pkgs
476 where bad p = any (p `matches`) wired_in_pkgids
477 && package p `notElem` map fst wired_in_ids
480 updateWiredInDependencies pkgs = map upd_pkg pkgs
482 | installedPackageId p `elem` wired_in_ids
483 = p { sourcePackageId = (sourcePackageId p){ pkgVersion = Version [] [] } }
487 return $ updateWiredInDependencies pkgs
489 -- ----------------------------------------------------------------------------
491 data UnusablePackageReason
493 | MissingDependencies [InstalledPackageId]
494 | ShadowedBy InstalledPackageId
496 type UnusablePackages = FiniteMap InstalledPackageId UnusablePackageReason
498 pprReason :: SDoc -> UnusablePackageReason -> SDoc
499 pprReason pref reason = case reason of
501 pref <+> ptext (sLit "ignored due to an -ignore-package flag")
502 MissingDependencies deps ->
504 ptext (sLit "unusable due to missing or recursive dependencies:") $$
505 nest 2 (hsep (map (text.display) deps))
507 pref <+> ptext (sLit "shadowed by package ") <> text (display ipid)
509 reportUnusable :: DynFlags -> UnusablePackages -> IO ()
510 reportUnusable dflags pkgs = mapM_ report (fmToList pkgs)
512 report (ipid, reason) =
513 debugTraceMsg dflags 2 $
515 (ptext (sLit "package") <+>
516 text (display ipid) <+> text "is") reason
518 -- ----------------------------------------------------------------------------
520 -- Detect any packages that have missing dependencies, and also any
521 -- mutually-recursive groups of packages (loops in the package graph
522 -- are not allowed). We do this by taking the least fixpoint of the
523 -- dependency graph, repeatedly adding packages whose dependencies are
524 -- satisfied until no more can be added.
526 findBroken :: [PackageConfig] -> UnusablePackages
527 findBroken pkgs = go [] emptyFM pkgs
529 go avail ipids not_avail =
530 case partitionWith (depsAvailable ipids) not_avail of
532 listToFM [ (installedPackageId p, MissingDependencies deps)
533 | (p,deps) <- not_avail ]
534 (new_avail, not_avail) ->
535 go (new_avail ++ avail) new_ipids (map fst not_avail)
536 where new_ipids = addListToFM ipids
537 [ (installedPackageId p, p) | p <- new_avail ]
539 depsAvailable :: FiniteMap InstalledPackageId PackageConfig
541 -> Either PackageConfig (PackageConfig, [InstalledPackageId])
542 depsAvailable ipids pkg
543 | null dangling = Left pkg
544 | otherwise = Right (pkg, dangling)
545 where dangling = filter (not . (`elemFM` ipids)) (depends pkg)
547 -- -----------------------------------------------------------------------------
548 -- Eliminate shadowed packages, giving the user some feedback
550 -- later packages in the list should shadow earlier ones with the same
551 -- package name/version.
552 shadowPackages :: [PackageConfig] -> UnusablePackages
554 = let (_,shadowed) = foldl check (emptyUFM,[]) pkgs
557 check (pkgmap,shadowed) pkg
558 = (addToUFM pkgmap (packageConfigId pkg) pkg, shadowed')
561 | Just oldpkg <- lookupUFM pkgmap (packageConfigId pkg)
562 = (installedPackageId oldpkg, ShadowedBy (installedPackageId pkg))
567 -- -----------------------------------------------------------------------------
569 ignorePackages :: [PackageFlag] -> [PackageConfig] -> UnusablePackages
570 ignorePackages flags pkgs = listToFM (concatMap doit flags)
572 doit (IgnorePackage str) =
573 case partition (matchingStr str) pkgs of
574 (ps, _) -> [ (installedPackageId p, IgnoredWithFlag)
576 -- missing package is not an error for -ignore-package,
577 -- because a common usage is to -ignore-package P as
578 -- a preventative measure just in case P exists.
579 doit _ = panic "ignorePackages"
581 -- -----------------------------------------------------------------------------
582 -- When all the command-line options are in, we can process our package
583 -- settings and populate the package state.
587 -> [PackageConfig] -- initial database
588 -> [PackageId] -- preloaded packages
589 -> PackageId -- this package
591 [PackageId], -- new packages to preload
592 PackageId) -- this package, might be modified if the current
594 -- package is a wired-in package.
596 mkPackageState dflags pkgs0 preload0 this_package = do
599 flags = reverse (packageFlags dflags)
600 (ignore_flags, other_flags) = partition is_ignore flags
601 is_ignore IgnorePackage{} = True
604 shadowed = shadowPackages pkgs0
605 ignored = ignorePackages ignore_flags pkgs0
607 pkgs0' = filter (not . (`elemFM` (plusFM shadowed ignored)) . installedPackageId) pkgs0
608 broken = findBroken pkgs0'
609 unusable = shadowed `plusFM` ignored `plusFM` broken
611 reportUnusable dflags unusable
614 -- Modify the package database according to the command-line flags
615 -- (-package, -hide-package, -ignore-package, -hide-all-packages).
617 pkgs1 <- foldM (applyPackageFlag unusable) pkgs0 other_flags
618 let pkgs2 = filter (not . (`elemFM` unusable) . installedPackageId) pkgs1
620 -- Here we build up a set of the packages mentioned in -package
621 -- flags on the command line; these are called the "preload"
622 -- packages. we link these packages in eagerly. The preload set
623 -- should contain at least rts & base, which is why we pretend that
624 -- the command line contains -package rts & -package base.
626 let preload1 = [ installedPackageId p | f <- flags, p <- get_exposed f ]
628 get_exposed (ExposePackage s) = filter (matchingStr s) pkgs2
629 get_exposed (ExposePackageId s) = filter (matchingId s) pkgs2
632 -- hide packages that are subsumed by later versions
633 pkgs3 <- hideOldPackages dflags pkgs2
635 -- sort out which packages are wired in
636 pkgs4 <- findWiredInPackages dflags pkgs3
638 let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs4
640 ipid_map = listToFM [ (installedPackageId p, packageConfigId p)
643 lookupIPID ipid@(InstalledPackageId str)
644 | Just pid <- lookupFM ipid_map ipid = return pid
645 | otherwise = missingPackageErr str
647 preload2 <- mapM lookupIPID preload1
650 -- add base & rts to the preload packages
652 | dopt Opt_AutoLinkPackages dflags
653 = filter (flip elemUFM pkg_db) [basePackageId, rtsPackageId]
655 -- but in any case remove the current package from the set of
656 -- preloaded packages so that base/rts does not end up in the
657 -- set up preloaded package when we are just building it
658 preload3 = nub $ filter (/= this_package)
659 $ (basicLinkedPackages ++ preload2)
661 -- Close the preload packages with their dependencies
662 dep_preload <- closeDeps pkg_db ipid_map (zip preload3 (repeat Nothing))
663 let new_dep_preload = filter (`notElem` preload0) dep_preload
665 let pstate = PackageState{ preloadPackages = dep_preload,
667 moduleToPkgConfAll = mkModuleMap pkg_db,
668 installedPackageIdMap = ipid_map
671 return (pstate, new_dep_preload, this_package)
674 -- -----------------------------------------------------------------------------
675 -- Make the mapping from module to package info
679 -> UniqFM [(PackageConfig, Bool)]
680 mkModuleMap pkg_db = foldr extend_modmap emptyUFM pkgids
682 pkgids = map packageConfigId (eltsUFM pkg_db)
684 extend_modmap pkgid modmap =
685 addListToUFM_C (++) modmap
686 ([(m, [(pkg, True)]) | m <- exposed_mods] ++
687 [(m, [(pkg, False)]) | m <- hidden_mods])
689 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
690 exposed_mods = exposedModules pkg
691 hidden_mods = hiddenModules pkg
693 pprSPkg :: PackageConfig -> SDoc
694 pprSPkg p = text (display (sourcePackageId p))
696 pprIPkg :: PackageConfig -> SDoc
697 pprIPkg p = text (display (installedPackageId p))
699 -- -----------------------------------------------------------------------------
700 -- Extracting information from the packages in scope
702 -- Many of these functions take a list of packages: in those cases,
703 -- the list is expected to contain the "dependent packages",
704 -- i.e. those packages that were found to be depended on by the
705 -- current module/program. These can be auto or non-auto packages, it
706 -- doesn't really matter. The list is always combined with the list
707 -- of preload (command-line) packages to determine which packages to
710 -- | Find all the include directories in these and the preload packages
711 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
712 getPackageIncludePath dflags pkgs =
713 collectIncludeDirs `fmap` getPreloadPackagesAnd dflags pkgs
715 collectIncludeDirs :: [PackageConfig] -> [FilePath]
716 collectIncludeDirs ps = nub (filter notNull (concatMap includeDirs ps))
718 -- | Find all the library paths in these and the preload packages
719 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
720 getPackageLibraryPath dflags pkgs =
721 collectLibraryPaths `fmap` getPreloadPackagesAnd dflags pkgs
723 collectLibraryPaths :: [PackageConfig] -> [FilePath]
724 collectLibraryPaths ps = nub (filter notNull (concatMap libraryDirs ps))
726 -- | Find all the link options in these and the preload packages
727 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
728 getPackageLinkOpts dflags pkgs =
729 collectLinkOpts dflags `fmap` getPreloadPackagesAnd dflags pkgs
731 collectLinkOpts :: DynFlags -> [PackageConfig] -> [String]
732 collectLinkOpts dflags ps = concat (map all_opts ps)
734 libs p = packageHsLibs dflags p ++ extraLibraries p
735 all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
737 packageHsLibs :: DynFlags -> PackageConfig -> [String]
738 packageHsLibs dflags p = map (mkDynName . addSuffix) (hsLibraries p)
740 non_dyn_ways = filter ((/= WayDyn) . wayName) (ways dflags)
741 -- the name of a shared library is libHSfoo-ghc<version>.so
742 -- we leave out the _dyn, because it is superfluous
744 tag = mkBuildTag (filter (not . wayRTSOnly) non_dyn_ways)
745 rts_tag = mkBuildTag non_dyn_ways
747 mkDynName | opt_Static = id
748 | otherwise = (++ ("-ghc" ++ cProjectVersion))
750 addSuffix rts@"HSrts" = rts ++ (expandTag rts_tag)
751 addSuffix other_lib = other_lib ++ (expandTag tag)
753 expandTag t | null t = ""
756 -- | Find all the C-compiler options in these and the preload packages
757 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
758 getPackageExtraCcOpts dflags pkgs = do
759 ps <- getPreloadPackagesAnd dflags pkgs
760 return (concatMap ccOptions ps)
762 -- | Find all the package framework paths in these and the preload packages
763 getPackageFrameworkPath :: DynFlags -> [PackageId] -> IO [String]
764 getPackageFrameworkPath dflags pkgs = do
765 ps <- getPreloadPackagesAnd dflags pkgs
766 return (nub (filter notNull (concatMap frameworkDirs ps)))
768 -- | Find all the package frameworks in these and the preload packages
769 getPackageFrameworks :: DynFlags -> [PackageId] -> IO [String]
770 getPackageFrameworks dflags pkgs = do
771 ps <- getPreloadPackagesAnd dflags pkgs
772 return (concatMap frameworks ps)
774 -- -----------------------------------------------------------------------------
777 -- | Takes a 'Module', and if the module is in a package returns
778 -- @(pkgconf, exposed)@ where pkgconf is the PackageConfig for that package,
779 -- and exposed is @True@ if the package exposes the module.
780 lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
781 lookupModuleInAllPackages dflags m =
782 case lookupUFM (moduleToPkgConfAll (pkgState dflags)) m of
786 -- | Find all the 'PackageConfig' in both the preload packages from 'DynFlags' and corresponding to the list of
788 getPreloadPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
789 getPreloadPackagesAnd dflags pkgids =
791 state = pkgState dflags
792 pkg_map = pkgIdMap state
793 ipid_map = installedPackageIdMap state
794 preload = preloadPackages state
795 pairs = zip pkgids (repeat Nothing)
797 all_pkgs <- throwErr (foldM (add_package pkg_map ipid_map) preload pairs)
798 return (map (getPackageDetails state) all_pkgs)
800 -- Takes a list of packages, and returns the list with dependencies included,
801 -- in reverse dependency order (a package appears before those it depends on).
802 closeDeps :: PackageConfigMap
803 -> FiniteMap InstalledPackageId PackageId
804 -> [(PackageId, Maybe PackageId)]
806 closeDeps pkg_map ipid_map ps = throwErr (closeDepsErr pkg_map ipid_map ps)
808 throwErr :: MaybeErr Message a -> IO a
809 throwErr m = case m of
810 Failed e -> ghcError (CmdLineError (showSDoc e))
811 Succeeded r -> return r
813 closeDepsErr :: PackageConfigMap
814 -> FiniteMap InstalledPackageId PackageId
815 -> [(PackageId,Maybe PackageId)]
816 -> MaybeErr Message [PackageId]
817 closeDepsErr pkg_map ipid_map ps = foldM (add_package pkg_map ipid_map) [] ps
820 add_package :: PackageConfigMap
821 -> FiniteMap InstalledPackageId PackageId
823 -> (PackageId,Maybe PackageId)
824 -> MaybeErr Message [PackageId]
825 add_package pkg_db ipid_map ps (p, mb_parent)
826 | p `elem` ps = return ps -- Check if we've already added this package
828 case lookupPackage pkg_db p of
829 Nothing -> Failed (missingPackageMsg (packageIdString p) <>
830 missingDependencyMsg mb_parent)
832 -- Add the package's dependents also
833 ps' <- foldM add_package_ipid ps (depends pkg)
836 add_package_ipid ps ipid@(InstalledPackageId str)
837 | Just pid <- lookupFM ipid_map ipid
838 = add_package pkg_db ipid_map ps (pid, Just p)
840 = Failed (missingPackageMsg str <> missingDependencyMsg mb_parent)
842 missingPackageErr :: String -> IO a
843 missingPackageErr p = ghcError (CmdLineError (showSDoc (missingPackageMsg p)))
845 missingPackageMsg :: String -> SDoc
846 missingPackageMsg p = ptext (sLit "unknown package:") <+> text p
848 missingDependencyMsg :: Maybe PackageId -> SDoc
849 missingDependencyMsg Nothing = empty
850 missingDependencyMsg (Just parent)
851 = space <> parens (ptext (sLit "dependency of") <+> ftext (packageIdFS parent))
853 -- -----------------------------------------------------------------------------
855 -- | Will the 'Name' come from a dynamically linked library?
856 isDllName :: PackageId -> Name -> Bool
857 isDllName this_pkg name
859 | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
860 | otherwise = False -- no, it is not even an external name
862 -- -----------------------------------------------------------------------------
863 -- Displaying packages
865 -- | Show package info on console, if verbosity is >= 3
866 dumpPackages :: DynFlags -> IO ()
868 = do let pkg_map = pkgIdMap (pkgState dflags)
870 vcat (map (text . showInstalledPackageInfo
871 . packageConfigToInstalledPackageInfo)