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
15 PackageIdH(..), isHomePackage,
18 moduleToPackageConfig,
22 -- * Inspecting the set of packages in scope
23 getPackageIncludePath,
25 getPackageLibraryPath,
27 getPackageExtraCcOpts,
28 getPackageFrameworkPath,
30 getExplicitPackagesAnd,
37 #include "HsVersions.h"
40 import SysTools ( getTopDir, getPackageConfigPath )
41 import ParsePkgConf ( loadPackageConfig )
42 import DynFlags ( dopt, DynFlag(..), DynFlags(..), PackageFlag(..) )
43 import StaticFlags ( opt_Static )
44 import Config ( cProjectVersion )
45 import Name ( Name, nameModule_maybe )
46 import Module ( Module, mkModule )
50 import Maybes ( expectJust )
54 #if __GLASGOW_HASKELL__ >= 603
55 import System.Directory ( getAppUserDataDirectory )
57 import Compat.Directory ( getAppUserDataDirectory )
60 import Distribution.InstalledPackageInfo
61 import Distribution.Package
62 import Distribution.Version
63 import Data.Maybe ( isNothing )
64 import System.Directory ( doesFileExist )
65 import Control.Monad ( when, foldM )
66 import Data.List ( nub, partition )
68 #ifdef mingw32_TARGET_OS
69 import Data.List ( isPrefixOf )
74 import EXCEPTION ( throwDyn )
75 import ErrUtils ( debugTraceMsg, putMsg )
77 -- ---------------------------------------------------------------------------
80 -- Package state is all stored in DynFlags, including the details of
81 -- all packages, which packages are exposed, and which modules they
84 -- The package state is computed by initPackages, and kept in DynFlags.
86 -- * -package <pkg> causes <pkg> to become exposed, and all other packages
87 -- with the same name to become hidden.
89 -- * -hide-package <pkg> causes <pkg> to become hidden.
91 -- * Let exposedPackages be the set of packages thus exposed.
92 -- Let depExposedPackages be the transitive closure from exposedPackages of
93 -- their dependencies.
95 -- * It is an error for any two packages in depExposedPackages to provide the
98 -- * When searching for a module from an explicit import declaration,
99 -- only the exposed modules in exposedPackages are valid.
101 -- * When searching for a module from an implicit import, all modules
102 -- from depExposedPackages are valid.
104 -- * When linking in a comp manager mode, we link in packages the
105 -- program depends on (the compiler knows this list by the
106 -- time it gets to the link step). Also, we link in all packages
107 -- which were mentioned with explicit -package flags on the command-line,
108 -- or are a transitive dependency of same, or are "base"/"rts".
109 -- The reason for (b) is that we might need packages which don't
110 -- contain any Haskell modules, and therefore won't be discovered
111 -- by the normal mechanism of dependency tracking.
114 -- One important thing that the package state provides is a way to
115 -- tell, for a given module, whether it is part of the current package
116 -- or not. We need to know this for two reasons:
118 -- * generating cross-DLL calls is different from intra-DLL calls
120 -- * we don't record version information in interface files for entities
121 -- in a different package.
125 -- When compiling module A, which imports module B, we need to
126 -- know whether B will be in the same DLL as A.
127 -- If it's in the same DLL, we refer to B_f_closure
128 -- If it isn't, we refer to _imp__B_f_closure
129 -- When compiling A, we record in B's Module value whether it's
130 -- in a different DLL, by setting the DLL flag.
132 data PackageState = PackageState {
134 explicitPackages :: [PackageId],
135 -- The packages we're going to link in eagerly. This list
136 -- should be in reverse dependency order; that is, a package
137 -- is always mentioned before the packages it depends on.
139 pkgIdMap :: PackageConfigMap, -- PackageId -> PackageConfig
140 -- mapping derived from the package databases and
141 -- command-line package flags.
143 moduleToPkgConf :: UniqFM (PackageConfig,Bool),
144 -- Maps Module to (pkgconf,exposed), where pkgconf is the
145 -- PackageConfig for the package containing the module, and
146 -- exposed is True if the package exposes that module.
148 -- The PackageIds of some known packages
149 basePackageId :: PackageIdH,
150 rtsPackageId :: PackageIdH,
151 haskell98PackageId :: PackageIdH,
152 thPackageId :: PackageIdH
156 = HomePackage -- The "home" package is the package curently
158 | ExtPackage PackageId -- An "external" package is any other package
161 isHomePackage :: PackageIdH -> Bool
162 isHomePackage HomePackage = True
163 isHomePackage (ExtPackage _) = False
165 -- A PackageConfigMap maps a PackageId to a PackageConfig
166 type PackageConfigMap = UniqFM PackageConfig
168 emptyPackageConfigMap :: PackageConfigMap
169 emptyPackageConfigMap = emptyUFM
171 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
172 lookupPackage = lookupUFM
174 extendPackageConfigMap
175 :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
176 extendPackageConfigMap pkg_map new_pkgs
177 = foldl add pkg_map new_pkgs
178 where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
180 getPackageDetails :: PackageState -> PackageId -> PackageConfig
181 getPackageDetails dflags ps = expectJust "getPackageDetails" (lookupPackage (pkgIdMap dflags) ps)
183 -- ----------------------------------------------------------------------------
184 -- Loading the package config files and building up the package state
186 initPackages :: DynFlags -> IO DynFlags
187 initPackages dflags = do
188 pkg_map <- readPackageConfigs dflags;
189 state <- mkPackageState dflags pkg_map
190 return dflags{ pkgState = state }
192 -- -----------------------------------------------------------------------------
193 -- Reading the package database(s)
195 readPackageConfigs :: DynFlags -> IO PackageConfigMap
196 readPackageConfigs dflags = do
197 -- System one always comes first
198 system_pkgconf <- getPackageConfigPath
199 pkg_map1 <- readPackageConfig dflags emptyPackageConfigMap system_pkgconf
201 -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
202 -- unless the -no-user-package-conf flag was given.
203 -- We only do this when getAppUserDataDirectory is available
205 (exists, pkgconf) <- catch (do
206 appdir <- getAppUserDataDirectory "ghc"
208 pkgconf = appdir ++ '/':TARGET_ARCH ++ '-':TARGET_OS
209 ++ '-':cProjectVersion ++ "/package.conf"
210 flg <- doesFileExist pkgconf
211 return (flg, pkgconf))
212 -- gobble them all up and turn into False.
213 (\ _ -> return (False, ""))
214 pkg_map2 <- if (dopt Opt_ReadUserPackageConf dflags && exists)
215 then readPackageConfig dflags pkg_map1 pkgconf
218 -- Read all the ones mentioned in -package-conf flags
219 pkg_map <- foldM (readPackageConfig dflags) pkg_map2
220 (extraPkgConfs dflags)
226 :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
227 readPackageConfig dflags pkg_map conf_file = do
228 debugTraceMsg dflags 2 ("Using package config file: " ++ conf_file)
229 proto_pkg_configs <- loadPackageConfig conf_file
231 let pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
232 pkg_configs2 = maybeHidePackages dflags pkg_configs1
233 return (extendPackageConfigMap pkg_map pkg_configs2)
235 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
236 maybeHidePackages dflags pkgs
237 | dopt Opt_HideAllPackages dflags = map hide pkgs
240 hide pkg = pkg{ exposed = False }
242 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
243 -- Replace the string "$topdir" at the beginning of a path
244 -- with the current topdir (obtained from the -B option).
245 mungePackagePaths top_dir ps = map munge_pkg ps
247 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
248 includeDirs = munge_paths (includeDirs p),
249 libraryDirs = munge_paths (libraryDirs p),
250 frameworkDirs = munge_paths (frameworkDirs p) }
252 munge_paths = map munge_path
255 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
259 -- -----------------------------------------------------------------------------
260 -- When all the command-line options are in, we can process our package
261 -- settings and populate the package state.
263 mkPackageState :: DynFlags -> PackageConfigMap -> IO PackageState
264 mkPackageState dflags pkg_db = do
266 -- Modify the package database according to the command-line flags
267 -- (-package, -hide-package, -ignore-package, -hide-all-packages).
269 -- Also, here we build up a set of the packages mentioned in -package
270 -- flags on the command line; these are called the "explicit" packages.
271 -- we link these packages in eagerly. The explicit set should contain
272 -- at least rts & base, which is why we pretend that the command line
273 -- contains -package rts & -package base.
276 flags = reverse (packageFlags dflags)
278 procflags pkgs expl [] = return (pkgs,expl)
279 procflags pkgs expl (ExposePackage str : flags) = do
280 case partition (matches str) pkgs of
281 ([],_) -> missingPackageErr str
282 ([p],ps) -> procflags (p':ps) (addOneToUniqSet expl pkgid) flags
283 where pkgid = packageConfigId p
284 p' = p {exposed=True}
285 (ps,_) -> multiplePackagesErr str ps
286 procflags pkgs expl (HidePackage str : flags) = do
287 case partition (matches str) pkgs of
288 ([],_) -> missingPackageErr str
289 ([p],ps) -> procflags (p':ps) expl flags
290 where p' = p {exposed=False}
291 (ps,_) -> multiplePackagesErr str ps
292 procflags pkgs expl (IgnorePackage str : flags) = do
293 case partition (matches str) pkgs of
294 (ps,qs) -> procflags qs expl flags
295 -- missing package is not an error for -ignore-package,
296 -- because a common usage is to -ignore-package P as
297 -- a preventative measure just in case P exists.
299 -- A package named on the command line can either include the
300 -- version, or just the name if it is unambiguous.
302 = str == showPackageId (package p)
303 || str == pkgName (package p)
305 (pkgs1,explicit) <- procflags (eltsUFM pkg_db) emptyUniqSet flags
308 elimDanglingDeps pkgs =
309 case partition (hasDanglingDeps pkgs) pkgs of
311 (ps,qs) -> elimDanglingDeps qs
313 hasDanglingDeps pkgs p = any dangling (depends p)
314 where dangling pid = pid `notElem` all_pids
315 all_pids = map package pkgs
317 -- Eliminate any packages which have dangling dependencies (perhaps
318 -- because the package was removed by -ignore-package).
320 let pkgs = elimDanglingDeps pkgs1
321 pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
323 -- Find the transitive closure of dependencies of exposed
325 let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
326 dep_exposed <- closeDeps pkg_db exposed_pkgids
328 -- Look up some known PackageIds
331 lookupPackageByName :: FastString -> PackageIdH
332 lookupPackageByName nm =
333 case [ conf | p <- dep_exposed,
334 Just conf <- [lookupPackage pkg_db p],
335 nm == mkFastString (pkgName (package conf)) ] of
337 (p:ps) -> ExtPackage (mkPackageId (package p))
339 -- Get the PackageIds for some known packages (we know the names,
340 -- but we don't know the versions). Some of these packages might
341 -- not exist in the database, so they are Maybes.
342 basePackageId = lookupPackageByName basePackageName
343 rtsPackageId = lookupPackageByName rtsPackageName
344 haskell98PackageId = lookupPackageByName haskell98PackageName
345 thPackageId = lookupPackageByName thPackageName
347 -- add base & rts to the explicit packages
348 basicLinkedPackages = [basePackageId,rtsPackageId]
349 explicit' = addListToUniqSet explicit
350 [ p | ExtPackage p <- basicLinkedPackages ]
352 -- Close the explicit packages with their dependencies
354 dep_explicit <- closeDeps pkg_db (uniqSetToList explicit')
356 -- Build up a mapping from Module -> PackageConfig for all modules.
357 -- Discover any conflicts at the same time, and factor in the new exposed
358 -- status of each package.
361 extend_modmap modmap pkgname = do
363 pkg = expectJust "mkPackageState" (lookupPackage pkg_db pkgname)
364 exposed_mods = map mkModule (exposedModules pkg)
365 hidden_mods = map mkModule (hiddenModules pkg)
366 all_mods = exposed_mods ++ hidden_mods
368 -- check for overlaps
371 overlaps = [ (m,pkg) | m <- all_mods,
372 Just (pkg,_) <- [lookupUFM modmap m] ]
374 when (not (null overlaps)) $ overlappingError pkg overlaps
376 return (addListToUFM modmap
377 [(m, (pkg, m `elem` exposed_mods))
380 mod_map <- foldM extend_modmap emptyUFM dep_exposed
382 return PackageState{ explicitPackages = dep_explicit,
384 moduleToPkgConf = mod_map,
385 basePackageId = basePackageId,
386 rtsPackageId = rtsPackageId,
387 haskell98PackageId = haskell98PackageId,
388 thPackageId = thPackageId
392 basePackageName = FSLIT("base")
393 rtsPackageName = FSLIT("rts")
394 haskell98PackageName = FSLIT("haskell98")
395 thPackageName = FSLIT("template-haskell")
396 -- Template Haskell libraries in here
398 overlappingError pkg overlaps
399 = throwDyn (CmdLineError (showSDoc (vcat (map msg overlaps))))
401 this_pkg = text (showPackageId (package pkg))
402 msg (mod,other_pkg) =
403 text "Error: module '" <> ppr mod
404 <> text "' is exposed by package "
405 <> this_pkg <> text " and package "
406 <> text (showPackageId (package other_pkg))
408 multiplePackagesErr str ps =
409 throwDyn (CmdLineError (showSDoc (
410 text "Error; multiple packages match" <+>
411 text str <> colon <+>
412 sep (punctuate comma (map (text.showPackageId.package) ps))
415 -- -----------------------------------------------------------------------------
416 -- Extracting information from the packages in scope
418 -- Many of these functions take a list of packages: in those cases,
419 -- the list is expected to contain the "dependent packages",
420 -- i.e. those packages that were found to be depended on by the
421 -- current module/program. These can be auto or non-auto packages, it
422 -- doesn't really matter. The list is always combined with the list
423 -- of explicit (command-line) packages to determine which packages to
426 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
427 getPackageIncludePath dflags pkgs = do
428 ps <- getExplicitPackagesAnd dflags pkgs
429 return (nub (filter notNull (concatMap includeDirs ps)))
431 -- includes are in reverse dependency order (i.e. rts first)
432 getPackageCIncludes :: [PackageConfig] -> IO [String]
433 getPackageCIncludes pkg_configs = do
434 return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
436 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
437 getPackageLibraryPath dflags pkgs = do
438 ps <- getExplicitPackagesAnd dflags pkgs
439 return (nub (filter notNull (concatMap libraryDirs ps)))
441 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
442 getPackageLinkOpts dflags pkgs = do
443 ps <- getExplicitPackagesAnd dflags pkgs
444 let tag = buildTag dflags
445 rts_tag = rtsBuildTag dflags
447 imp = if opt_Static then "" else "_dyn"
448 libs p = map ((++imp) . addSuffix) (hACK (hsLibraries p)) ++ extraLibraries p
449 all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
451 suffix = if null tag then "" else '_':tag
452 rts_suffix = if null rts_tag then "" else '_':rts_tag
454 addSuffix rts@"HSrts" = rts ++ rts_suffix
455 addSuffix other_lib = other_lib ++ suffix
457 return (concat (map all_opts ps))
460 -- This is a totally horrible (temporary) hack, for Win32. Problem is
461 -- that package.conf for Win32 says that the main prelude lib is
462 -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
463 -- in the GNU linker (PEi386 backend). However, we still only
464 -- have HSbase.a for static linking, not HSbase{1,2,3}.a
465 -- getPackageLibraries is called to find the .a's to add to the static
466 -- link line. On Win32, this hACK detects HSbase{1,2,3} and
467 -- replaces them with HSbase, so static linking still works.
468 -- Libraries needed for dynamic (GHCi) linking are discovered via
469 -- different route (in InteractiveUI.linkPackage).
470 -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
471 -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
472 -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
473 -- KAA 29 Mar 02: Same appalling hack for HSobjectio[1,2,3,4]
475 -- [sof 03/05: Renamed the (moribund) HSwin32 to HSwin_32 so as to
476 -- avoid filename conflicts with the 'Win32' package on a case-insensitive filesystem]
478 # if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
481 = if "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
482 then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
484 if "HSwin_321" `elem` libs && "HSwin_322" `elem` libs
485 then "HSwin_32" : filter (not.(isPrefixOf "HSwin_32")) libs
487 if "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
488 then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
493 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
494 getPackageExtraCcOpts dflags pkgs = do
495 ps <- getExplicitPackagesAnd dflags pkgs
496 return (concatMap ccOptions ps)
498 getPackageFrameworkPath :: DynFlags -> [PackageId] -> IO [String]
499 getPackageFrameworkPath dflags pkgs = do
500 ps <- getExplicitPackagesAnd dflags pkgs
501 return (nub (filter notNull (concatMap frameworkDirs ps)))
503 getPackageFrameworks :: DynFlags -> [PackageId] -> IO [String]
504 getPackageFrameworks dflags pkgs = do
505 ps <- getExplicitPackagesAnd dflags pkgs
506 return (concatMap frameworks ps)
508 -- -----------------------------------------------------------------------------
511 -- Takes a Module, and if the module is in a package returns
512 -- (pkgconf,exposed) where pkgconf is the PackageConfig for that package,
513 -- and exposed is True if the package exposes the module.
514 moduleToPackageConfig :: DynFlags -> Module -> Maybe (PackageConfig,Bool)
515 moduleToPackageConfig dflags m =
516 lookupUFM (moduleToPkgConf (pkgState dflags)) m
518 isHomeModule :: DynFlags -> Module -> Bool
519 isHomeModule dflags mod = isNothing (moduleToPackageConfig dflags mod)
521 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
522 getExplicitPackagesAnd dflags pkgids =
524 state = pkgState dflags
525 pkg_map = pkgIdMap state
526 expl = explicitPackages state
528 all_pkgs <- foldM (add_package pkg_map) expl pkgids
529 return (map (getPackageDetails state) all_pkgs)
531 -- Takes a list of packages, and returns the list with dependencies included,
532 -- in reverse dependency order (a package appears before those it depends on).
533 closeDeps :: PackageConfigMap -> [PackageId] -> IO [PackageId]
534 closeDeps pkg_map ps = foldM (add_package pkg_map) [] ps
537 add_package :: PackageConfigMap -> [PackageId] -> PackageId -> IO [PackageId]
538 add_package pkg_db ps p
539 | p `elem` ps = return ps -- Check if we've already added this package
541 case lookupPackage pkg_db p of
542 Nothing -> missingPackageErr (packageIdString p)
544 -- Add the package's dependents also
545 let deps = map mkPackageId (depends pkg)
546 ps' <- foldM (add_package pkg_db) ps deps
549 missingPackageErr p = throwDyn (CmdLineError ("unknown package: " ++ p))
551 -- -----------------------------------------------------------------------------
552 -- Determining whether a Name refers to something in another package or not.
553 -- Cross-package references need to be handled differently when dynamically-
554 -- linked libraries are involved.
556 isDllName :: DynFlags -> Name -> Bool
557 isDllName dflags name
560 case nameModule_maybe name of
561 Nothing -> False -- no, it is not even an external name
563 case lookupUFM (moduleToPkgConf (pkgState dflags)) mod of
564 Just _ -> True -- yes, its a package module
565 Nothing -> False -- no, must be a home module
567 -- -----------------------------------------------------------------------------
568 -- Displaying packages
570 dumpPackages :: DynFlags -> IO ()
571 -- Show package info on console, if verbosity is >= 3
573 = do let pkg_map = pkgIdMap (pkgState dflags)
575 vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))