2 % (c) The University of Glasgow, 2000
4 \section{Package manipulation}
10 -- * The PackageConfigMap
11 PackageConfigMap, emptyPackageConfigMap, lookupPackage,
12 extendPackageConfigMap, dumpPackages,
14 -- * Reading the package config, and processing cmdline args
18 lookupModuleInAllPackages,
20 -- * Inspecting the set of packages in scope
21 getPackageIncludePath,
23 getPackageLibraryPath,
25 getPackageExtraCcOpts,
26 getPackageFrameworkPath,
28 getExplicitPackagesAnd,
35 #include "HsVersions.h"
38 import SysTools ( getTopDir, getPackageConfigPath )
39 import ParsePkgConf ( loadPackageConfig )
40 import DynFlags ( dopt, DynFlag(..), DynFlags(..), PackageFlag(..) )
41 import StaticFlags ( opt_Static )
42 import Config ( cProjectVersion )
43 import Name ( Name, nameModule_maybe )
48 import Maybes ( expectJust, MaybeErr(..) )
52 #if __GLASGOW_HASKELL__ >= 603
53 import System.Directory ( getAppUserDataDirectory )
55 import Compat.Directory ( getAppUserDataDirectory )
58 import System.Environment ( getEnv )
59 import Distribution.InstalledPackageInfo
60 import Distribution.Package
61 import Distribution.Version
62 import System.Directory ( doesFileExist, doesDirectoryExist,
63 getDirectoryContents )
64 import Data.Maybe ( catMaybes )
65 import Control.Monad ( foldM )
66 import Data.List ( nub, partition, sortBy, isSuffixOf )
68 import EXCEPTION ( throwDyn )
69 import ErrUtils ( debugTraceMsg, putMsg, Message )
71 -- ---------------------------------------------------------------------------
74 -- Package state is all stored in DynFlags, including the details of
75 -- all packages, which packages are exposed, and which modules they
78 -- The package state is computed by initPackages, and kept in DynFlags.
80 -- * -package <pkg> causes <pkg> to become exposed, and all other packages
81 -- with the same name to become hidden.
83 -- * -hide-package <pkg> causes <pkg> to become hidden.
85 -- * Let exposedPackages be the set of packages thus exposed.
86 -- Let depExposedPackages be the transitive closure from exposedPackages of
87 -- their dependencies.
89 -- * When searching for a module from an explicit import declaration,
90 -- only the exposed modules in exposedPackages are valid.
92 -- * When searching for a module from an implicit import, all modules
93 -- from depExposedPackages are valid.
95 -- * When linking in a comp manager mode, we link in packages the
96 -- program depends on (the compiler knows this list by the
97 -- time it gets to the link step). Also, we link in all packages
98 -- which were mentioned with explicit -package flags on the command-line,
99 -- or are a transitive dependency of same, or are "base"/"rts".
100 -- The reason for (b) is that we might need packages which don't
101 -- contain any Haskell modules, and therefore won't be discovered
102 -- by the normal mechanism of dependency tracking.
106 -- When compiling module A, which imports module B, we need to
107 -- know whether B will be in the same DLL as A.
108 -- If it's in the same DLL, we refer to B_f_closure
109 -- If it isn't, we refer to _imp__B_f_closure
110 -- When compiling A, we record in B's Module value whether it's
111 -- in a different DLL, by setting the DLL flag.
113 data PackageState = PackageState {
115 explicitPackages :: [PackageId],
116 -- The packages we're going to link in eagerly. This list
117 -- should be in reverse dependency order; that is, a package
118 -- is always mentioned before the packages it depends on.
120 origPkgIdMap :: PackageConfigMap, -- PackageId -> PackageConfig
121 -- the full package database
123 pkgIdMap :: PackageConfigMap, -- PackageId -> PackageConfig
124 -- Derived from origPkgIdMap.
125 -- The exposed flags are adjusted according to -package and
126 -- -hide-package flags, and -ignore-package removes packages.
128 moduleToPkgConfAll :: UniqFM [(PackageConfig,Bool)] -- ModuleEnv mapping
129 -- Derived from pkgIdMap.
130 -- Maps Module to (pkgconf,exposed), where pkgconf is the
131 -- PackageConfig for the package containing the module, and
132 -- exposed is True if the package exposes that module.
135 -- A PackageConfigMap maps a PackageId to a PackageConfig
136 type PackageConfigMap = UniqFM PackageConfig
138 emptyPackageConfigMap :: PackageConfigMap
139 emptyPackageConfigMap = emptyUFM
141 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
142 lookupPackage = lookupUFM
144 extendPackageConfigMap
145 :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
146 extendPackageConfigMap pkg_map new_pkgs
147 = foldl add pkg_map new_pkgs
148 where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
150 getPackageDetails :: PackageState -> PackageId -> PackageConfig
151 getPackageDetails dflags ps = expectJust "getPackageDetails" (lookupPackage (pkgIdMap dflags) ps)
153 -- ----------------------------------------------------------------------------
154 -- Loading the package config files and building up the package state
156 -- | Call this after parsing the DynFlags. It reads the package
157 -- configuration files, and sets up various internal tables of package
158 -- information, according to the package-related flags on the
159 -- command-line (@-package@, @-hide-package@ etc.)
160 initPackages :: DynFlags -> IO DynFlags
161 initPackages dflags = do
162 pkg_map <- readPackageConfigs dflags;
163 mkPackageState dflags pkg_map
165 -- -----------------------------------------------------------------------------
166 -- Reading the package database(s)
168 readPackageConfigs :: DynFlags -> IO PackageConfigMap
169 readPackageConfigs dflags = do
170 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
171 system_pkgconfs <- getSystemPackageConfigs dflags
173 let pkgconfs = case e_pkg_path of
174 Left _ -> system_pkgconfs
176 | last cs == "" -> init cs ++ system_pkgconfs
178 where cs = parseSearchPath path
179 -- if the path ends in a separator (eg. "/foo/bar:")
180 -- the we tack on the system paths.
182 -- Read all the ones mentioned in -package-conf flags
183 pkg_map <- foldM (readPackageConfig dflags) emptyPackageConfigMap
184 (reverse pkgconfs ++ extraPkgConfs dflags)
189 getSystemPackageConfigs :: DynFlags -> IO [FilePath]
190 getSystemPackageConfigs dflags = do
191 -- System one always comes first
192 system_pkgconf <- getPackageConfigPath
194 -- allow package.conf.d to contain a bunch of .conf files
195 -- containing package specifications. This is an easier way
196 -- to maintain the package database on systems with a package
197 -- management system, or systems that don't want to run ghc-pkg
198 -- to register or unregister packages. Undocumented feature for now.
199 let system_pkgconf_dir = system_pkgconf ++ ".d"
200 system_pkgconf_dir_exists <- doesDirectoryExist system_pkgconf_dir
202 if system_pkgconf_dir_exists
203 then do files <- getDirectoryContents system_pkgconf_dir
204 return [ system_pkgconf_dir ++ '/' : file
206 , isSuffixOf ".conf" file]
209 -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
210 -- unless the -no-user-package-conf flag was given.
211 -- We only do this when getAppUserDataDirectory is available
213 user_pkgconf <- handle (\_ -> return []) $ do
214 appdir <- getAppUserDataDirectory "ghc"
217 `joinFileName` (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
218 `joinFileName` "package.conf"
219 flg <- doesFileExist pkgconf
220 if (flg && dopt Opt_ReadUserPackageConf dflags)
221 then return [pkgconf]
224 return (user_pkgconf ++ system_pkgconfs ++ [system_pkgconf])
228 :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
229 readPackageConfig dflags pkg_map conf_file = do
230 debugTraceMsg dflags 2 (text "Using package config file:" <+> text conf_file)
231 proto_pkg_configs <- loadPackageConfig conf_file
233 let pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
234 pkg_configs2 = maybeHidePackages dflags pkg_configs1
235 return (extendPackageConfigMap pkg_map pkg_configs2)
237 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
238 maybeHidePackages dflags pkgs
239 | dopt Opt_HideAllPackages dflags = map hide pkgs
242 hide pkg = pkg{ exposed = False }
244 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
245 -- Replace the string "$topdir" at the beginning of a path
246 -- with the current topdir (obtained from the -B option).
247 mungePackagePaths top_dir ps = map munge_pkg ps
249 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
250 includeDirs = munge_paths (includeDirs p),
251 libraryDirs = munge_paths (libraryDirs p),
252 frameworkDirs = munge_paths (frameworkDirs p) }
254 munge_paths = map munge_path
257 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
261 -- -----------------------------------------------------------------------------
262 -- When all the command-line options are in, we can process our package
263 -- settings and populate the package state.
265 mkPackageState :: DynFlags -> PackageConfigMap -> IO DynFlags
266 mkPackageState dflags orig_pkg_db = do
268 -- Modify the package database according to the command-line flags
269 -- (-package, -hide-package, -ignore-package, -hide-all-packages).
271 -- Also, here we build up a set of the packages mentioned in -package
272 -- flags on the command line; these are called the "explicit" packages.
273 -- we link these packages in eagerly. The explicit set should contain
274 -- at least rts & base, which is why we pretend that the command line
275 -- contains -package rts & -package base.
278 flags = reverse (packageFlags dflags)
280 procflags pkgs expl [] = return (pkgs,expl)
281 procflags pkgs expl (ExposePackage str : flags) = do
282 case pick str pkgs of
283 Nothing -> missingPackageErr str
284 Just (p,ps) -> procflags (p':ps') expl' flags
285 where p' = p {exposed=True}
286 ps' = hideAll (pkgName (package p)) ps
287 expl' = package p : expl
288 procflags pkgs expl (HidePackage str : flags) = do
289 case partition (matches str) pkgs of
290 ([],_) -> missingPackageErr str
291 (ps,qs) -> procflags (map hide ps ++ qs) expl flags
292 where hide p = p {exposed=False}
293 procflags pkgs expl (IgnorePackage str : flags) = do
294 case partition (matches str) pkgs of
295 (ps,qs) -> procflags qs expl flags
296 -- missing package is not an error for -ignore-package,
297 -- because a common usage is to -ignore-package P as
298 -- a preventative measure just in case P exists.
301 = case partition (matches str) pkgs of
304 case sortBy (flip (comparing (pkgVersion.package))) ps of
305 (p:ps) -> Just (p, ps ++ rest)
306 _ -> panic "Packages.pick"
308 comparing f a b = f a `compare` f b
310 -- A package named on the command line can either include the
311 -- version, or just the name if it is unambiguous.
313 = str == showPackageId (package p)
314 || str == pkgName (package p)
316 -- When a package is requested to be exposed, we hide all other
317 -- packages with the same name.
318 hideAll name ps = map maybe_hide ps
319 where maybe_hide p | pkgName (package p) == name = p {exposed=False}
322 (pkgs1,explicit) <- procflags (eltsUFM orig_pkg_db) [] flags
324 -- hide all packages for which there is also a later version
325 -- that is already exposed. This just makes it non-fatal to have two
326 -- versions of a package exposed, which can happen if you install a
327 -- later version of a package in the user database, for example.
330 | not (exposed p) = return p
331 | (p' : _) <- later_versions = do
332 debugTraceMsg dflags 2 $
333 (ptext SLIT("hiding package") <+> text (showPackageId (package p)) <+>
334 ptext SLIT("to avoid conflict with later version") <+>
335 text (showPackageId (package p')))
336 return (p {exposed=False})
337 | otherwise = return p
338 where myname = pkgName (package p)
339 myversion = pkgVersion (package p)
340 later_versions = [ p | p <- pkgs1, exposed p,
342 pkgName pkg == myname,
343 pkgVersion pkg > myversion ]
345 pkgs2 <- mapM maybe_hide pkgs1
347 -- Now we must find our wired-in packages, and rename them to
348 -- their canonical names (eg. base-1.0 ==> base).
351 wired_in_pkgids = [ basePackageId,
356 wired_in_names = map packageIdString wired_in_pkgids
358 -- find which package corresponds to each wired-in package
359 -- delete any other packages with the same name
360 -- update the package and any dependencies to point to the new
362 findWiredInPackage :: [PackageConfig] -> String
363 -> IO (Maybe PackageIdentifier)
364 findWiredInPackage pkgs wired_pkg =
365 case [ p | p <- pkgs, pkgName (package p) == wired_pkg,
368 debugTraceMsg dflags 2 $
369 ptext SLIT("wired-in package ")
371 <> ptext SLIT(" not found.")
374 debugTraceMsg dflags 2 $
375 ptext SLIT("wired-in package ")
377 <> ptext SLIT(" mapped to ")
378 <> text (showPackageId (package one))
379 return (Just (package one))
381 throwDyn (CmdLineError (showSDoc $
382 ptext SLIT("there are multiple exposed packages that match wired-in package ") <> text wired_pkg))
384 mb_wired_in_ids <- mapM (findWiredInPackage pkgs2) wired_in_names
386 wired_in_ids = catMaybes mb_wired_in_ids
388 deleteHiddenWiredInPackages pkgs = filter ok pkgs
389 where ok p = pkgName (package p) `notElem` wired_in_names
392 updateWiredInDependencies pkgs = map upd_pkg pkgs
393 where upd_pkg p = p{ package = upd_pid (package p),
394 depends = map upd_pid (depends p) }
396 upd_pid pid = case filter (== pid) wired_in_ids of
398 (x:_) -> x{ pkgVersion = Version [] [] }
400 pkgs3 = deleteHiddenWiredInPackages pkgs2
402 pkgs4 = updateWiredInDependencies pkgs3
404 explicit1 = map upd_pid explicit
406 -- we must return an updated thisPackage, just in case we
407 -- are actually compiling one of the wired-in packages
408 Just old_this_pkg = unpackPackageId (thisPackage dflags)
409 new_this_pkg = mkPackageId (upd_pid old_this_pkg)
412 -- Eliminate any packages which have dangling dependencies (perhaps
413 -- because the package was removed by -ignore-package).
416 elimDanglingDeps pkgs =
417 case partition (not.null.snd) (map (getDanglingDeps pkgs) pkgs) of
418 ([],ps) -> return (map fst ps)
421 elimDanglingDeps (map fst qs)
423 reportElim (p, deps) =
424 debugTraceMsg dflags 2 $
425 (ptext SLIT("package") <+> pprPkg p <+>
426 ptext SLIT("will be ignored due to missing dependencies:") $$
427 nest 2 (hsep (map (text.showPackageId) deps)))
429 getDanglingDeps pkgs p = (p, filter dangling (depends p))
430 where dangling pid = pid `notElem` all_pids
431 all_pids = map package pkgs
433 pkgs <- elimDanglingDeps pkgs4
434 let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
436 -- Find the transitive closure of dependencies of exposed
438 let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
439 dep_exposed <- closeDeps pkg_db exposed_pkgids
441 -- add base & rts to the explicit packages
442 basicLinkedPackages = filter (flip elemUFM pkg_db)
443 [basePackageId,rtsPackageId]
444 explicit2 = addListToUniqSet (mkUniqSet (map mkPackageId explicit1))
447 -- Close the explicit packages with their dependencies
449 dep_explicit <- closeDeps pkg_db (uniqSetToList explicit2)
451 -- Build up a mapping from Module -> PackageConfig for all modules.
452 -- Discover any conflicts at the same time, and factor in the new exposed
453 -- status of each package.
455 let mod_map = mkModuleMap pkg_db dep_exposed
457 pstate = PackageState{ explicitPackages = dep_explicit,
458 origPkgIdMap = orig_pkg_db,
460 moduleToPkgConfAll = mod_map
463 return dflags{ pkgState = pstate, thisPackage = new_this_pkg }
470 -> UniqFM [(PackageConfig, Bool)]
471 mkModuleMap pkg_db pkgs = foldr extend_modmap emptyUFM pkgs
473 extend_modmap pkgid modmap =
474 addListToUFM_C (++) modmap
475 [(m, [(pkg, m `elem` exposed_mods)]) | m <- all_mods]
477 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
478 exposed_mods = map mkModuleName (exposedModules pkg)
479 hidden_mods = map mkModuleName (hiddenModules pkg)
480 all_mods = exposed_mods ++ hidden_mods
482 pprPkg :: PackageConfig -> SDoc
483 pprPkg p = text (showPackageId (package p))
485 -- -----------------------------------------------------------------------------
486 -- Extracting information from the packages in scope
488 -- Many of these functions take a list of packages: in those cases,
489 -- the list is expected to contain the "dependent packages",
490 -- i.e. those packages that were found to be depended on by the
491 -- current module/program. These can be auto or non-auto packages, it
492 -- doesn't really matter. The list is always combined with the list
493 -- of explicit (command-line) packages to determine which packages to
496 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
497 getPackageIncludePath dflags pkgs = do
498 ps <- getExplicitPackagesAnd dflags pkgs
499 return (nub (filter notNull (concatMap includeDirs ps)))
501 -- includes are in reverse dependency order (i.e. rts first)
502 getPackageCIncludes :: [PackageConfig] -> IO [String]
503 getPackageCIncludes pkg_configs = do
504 return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
506 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
507 getPackageLibraryPath dflags pkgs = do
508 ps <- getExplicitPackagesAnd dflags pkgs
509 return (nub (filter notNull (concatMap libraryDirs ps)))
511 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
512 getPackageLinkOpts dflags pkgs = do
513 ps <- getExplicitPackagesAnd dflags pkgs
514 let tag = buildTag dflags
515 rts_tag = rtsBuildTag dflags
517 imp = if opt_Static then "" else "_dyn"
518 libs p = map ((++imp) . addSuffix) (hsLibraries p)
519 ++ hACK_dyn (extraLibraries p)
520 all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
522 suffix = if null tag then "" else '_':tag
523 rts_suffix = if null rts_tag then "" else '_':rts_tag
525 addSuffix rts@"HSrts" = rts ++ rts_suffix
526 addSuffix other_lib = other_lib ++ suffix
528 -- This is a hack that's even more horrible (and hopefully more temporary)
529 -- than the one below [referring to previous splittage of HSbase into chunks
530 -- to work around GNU ld bug]. HSbase_cbits and friends require the _dyn suffix
531 -- for dynamic linking, but not _p or other 'way' suffix. So we just add
532 -- _dyn to extraLibraries if they already have a _cbits suffix.
535 where hack lib | not opt_Static && "_cbits" `isSuffixOf` lib = lib ++ "_dyn"
538 return (concat (map all_opts ps))
540 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
541 getPackageExtraCcOpts dflags pkgs = do
542 ps <- getExplicitPackagesAnd dflags pkgs
543 return (concatMap ccOptions ps)
545 getPackageFrameworkPath :: DynFlags -> [PackageId] -> IO [String]
546 getPackageFrameworkPath dflags pkgs = do
547 ps <- getExplicitPackagesAnd dflags pkgs
548 return (nub (filter notNull (concatMap frameworkDirs ps)))
550 getPackageFrameworks :: DynFlags -> [PackageId] -> IO [String]
551 getPackageFrameworks dflags pkgs = do
552 ps <- getExplicitPackagesAnd dflags pkgs
553 return (concatMap frameworks ps)
555 -- -----------------------------------------------------------------------------
558 -- | Takes a Module, and if the module is in a package returns
559 -- @(pkgconf,exposed)@ where pkgconf is the PackageConfig for that package,
560 -- and exposed is True if the package exposes the module.
561 lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
562 lookupModuleInAllPackages dflags m =
563 case lookupUFM (moduleToPkgConfAll (pkgState dflags)) m of
567 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
568 getExplicitPackagesAnd dflags pkgids =
570 state = pkgState dflags
571 pkg_map = pkgIdMap state
572 expl = explicitPackages state
574 all_pkgs <- throwErr (foldM (add_package pkg_map) expl pkgids)
575 return (map (getPackageDetails state) all_pkgs)
577 -- Takes a list of packages, and returns the list with dependencies included,
578 -- in reverse dependency order (a package appears before those it depends on).
579 closeDeps :: PackageConfigMap -> [PackageId] -> IO [PackageId]
580 closeDeps pkg_map ps = throwErr (closeDepsErr pkg_map ps)
582 throwErr :: MaybeErr Message a -> IO a
583 throwErr m = case m of
584 Failed e -> throwDyn (CmdLineError (showSDoc e))
585 Succeeded r -> return r
587 closeDepsErr :: PackageConfigMap -> [PackageId]
588 -> MaybeErr Message [PackageId]
589 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
592 add_package :: PackageConfigMap -> [PackageId] -> PackageId
593 -> MaybeErr Message [PackageId]
594 add_package pkg_db ps p
595 | p `elem` ps = return ps -- Check if we've already added this package
597 case lookupPackage pkg_db p of
598 Nothing -> Failed (missingPackageMsg (packageIdString p))
600 -- Add the package's dependents also
601 let deps = map mkPackageId (depends pkg)
602 ps' <- foldM (add_package pkg_db) ps deps
605 missingPackageErr p = throwDyn (CmdLineError (showSDoc (missingPackageMsg p)))
606 missingPackageMsg p = ptext SLIT("unknown package:") <+> text p
608 -- -----------------------------------------------------------------------------
610 isDllName :: PackageId -> Name -> Bool
611 isDllName this_pkg name
613 | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
614 | otherwise = False -- no, it is not even an external name
616 -- -----------------------------------------------------------------------------
617 -- Displaying packages
619 dumpPackages :: DynFlags -> IO ()
620 -- Show package info on console, if verbosity is >= 3
622 = do let pkg_map = pkgIdMap (pkgState dflags)
624 vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))