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
17 moduleToPackageConfig,
21 -- * Inspecting the set of packages in scope
22 getPackageIncludePath,
24 getPackageLibraryPath,
26 getPackageExtraCcOpts,
27 getPackageFrameworkPath,
29 getExplicitPackagesAnd,
36 #include "HsVersions.h"
39 import DriverState ( v_Build_tag, v_RTS_Build_tag, v_Static )
40 import SysTools ( getTopDir, getPackageConfigPath )
41 import ParsePkgConf ( loadPackageConfig )
42 import CmdLineOpts ( DynFlags(..), PackageFlag(..), verbosity,
44 import Config ( cTARGETARCH, cTARGETOS, cProjectVersion )
45 import Name ( Name, nameModule_maybe )
46 import Module ( Module, mkModule )
53 #if __GLASGOW_HASKELL__ >= 603
54 import System.Directory ( getAppUserDataDirectory )
56 import Compat.Directory ( getAppUserDataDirectory )
59 import Distribution.InstalledPackageInfo
60 import Distribution.Package
61 import Distribution.Version
62 import System.IO ( hPutStrLn, stderr )
63 import Data.Maybe ( fromJust, 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 )
76 -- ---------------------------------------------------------------------------
79 -- Package state is all stored in DynFlags, including the details of
80 -- all packages, which packages are exposed, and which modules they
83 -- The package state is computed by initPackages, and kept in DynFlags.
85 -- * -package <pkg> causes <pkg> to become exposed, and all other packages
86 -- with the same name to become hidden.
88 -- * -hide-package <pkg> causes <pkg> to become hidden.
90 -- * Let exposedPackages be the set of packages thus exposed.
91 -- Let depExposedPackages be the transitive closure from exposedPackages of
92 -- their dependencies.
94 -- * It is an error for any two packages in depExposedPackages to provide the
97 -- * When searching for a module from an explicit import declaration,
98 -- only the exposed modules in exposedPackages are valid.
100 -- * When searching for a module from an implicit import, all modules
101 -- from depExposedPackages are valid.
103 -- * When linking in a comp manager mode, we link in packages the
104 -- program depends on (the compiler knows this list by the
105 -- time it gets to the link step). Also, we link in all packages
106 -- which were mentioned with explicit -package flags on the command-line,
107 -- or are a transitive dependency of same, or are "base"/"rts".
108 -- The reason for (b) is that we might need packages which don't
109 -- contain any Haskell modules, and therefore won't be discovered
110 -- by the normal mechanism of dependency tracking.
113 -- One important thing that the package state provides is a way to
114 -- tell, for a given module, whether it is part of the current package
115 -- or not. We need to know this for two reasons:
117 -- * generating cross-DLL calls is different from intra-DLL calls
119 -- * we don't record version information in interface files for entities
120 -- in a different package.
124 -- When compiling module A, which imports module B, we need to
125 -- know whether B will be in the same DLL as A.
126 -- If it's in the same DLL, we refer to B_f_closure
127 -- If it isn't, we refer to _imp__B_f_closure
128 -- When compiling A, we record in B's Module value whether it's
129 -- in a different DLL, by setting the DLL flag.
131 data PackageState = PackageState {
133 explicitPackages :: [PackageId],
134 -- The packages we're going to link in eagerly. This list
135 -- should be in reverse dependency order; that is, a package
136 -- is always mentioned before the packages it depends on.
138 pkgIdMap :: PackageConfigMap, -- PackageId -> PackageConfig
139 -- mapping derived from the package databases and
140 -- command-line package flags.
142 moduleToPkgConf :: UniqFM (PackageConfig,Bool),
143 -- Maps Module to (pkgconf,exposed), where pkgconf is the
144 -- PackageConfig for the package containing the module, and
145 -- exposed is True if the package exposes that module.
147 -- The PackageIds of some known packages
148 basePackageId :: Maybe PackageId,
149 rtsPackageId :: Maybe PackageId,
150 haskell98PackageId :: Maybe PackageId,
151 thPackageId :: Maybe PackageId
154 -- A PackageConfigMap maps a PackageId to a PackageConfig
155 type PackageConfigMap = UniqFM PackageConfig
157 emptyPackageConfigMap :: PackageConfigMap
158 emptyPackageConfigMap = emptyUFM
160 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
161 lookupPackage = lookupUFM
163 extendPackageConfigMap
164 :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
165 extendPackageConfigMap pkg_map new_pkgs
166 = foldl add pkg_map new_pkgs
167 where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
169 getPackageDetails :: PackageState -> PackageId -> PackageConfig
170 getPackageDetails dflags ps = fromJust (lookupPackage (pkgIdMap dflags) ps)
172 -- ----------------------------------------------------------------------------
173 -- Loading the package config files and building up the package state
175 initPackages :: DynFlags -> IO DynFlags
176 initPackages dflags = do
177 pkg_map <- readPackageConfigs dflags;
178 state <- mkPackageState dflags pkg_map
179 return dflags{ pkgState = state }
181 -- -----------------------------------------------------------------------------
182 -- Reading the package database(s)
184 readPackageConfigs :: DynFlags -> IO PackageConfigMap
185 readPackageConfigs dflags = do
186 -- System one always comes first
187 system_pkgconf <- getPackageConfigPath
188 pkg_map1 <- readPackageConfig dflags emptyPackageConfigMap system_pkgconf
190 -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
191 -- unless the -no-user-package-conf flag was given.
192 -- We only do this when getAppUserDataDirectory is available
194 appdir <- getAppUserDataDirectory "ghc"
196 pkgconf = appdir ++ '/':cTARGETARCH ++ '-':cTARGETOS
197 ++ '-':cProjectVersion ++ "/package.conf"
199 exists <- doesFileExist pkgconf
200 pkg_map2 <- if (readUserPkgConf dflags && exists)
201 then readPackageConfig dflags pkg_map1 pkgconf
204 -- Read all the ones mentioned in -package-conf flags
205 pkg_map <- foldM (readPackageConfig dflags) pkg_map2
206 (extraPkgConfs dflags)
212 :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
213 readPackageConfig dflags pkg_map conf_file = do
214 when (verbosity dflags >= 2) $
215 hPutStrLn stderr ("Reading package config file: "
217 proto_pkg_configs <- loadPackageConfig conf_file
219 let pkg_configs = mungePackagePaths top_dir proto_pkg_configs
220 return (extendPackageConfigMap pkg_map pkg_configs)
223 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
224 -- Replace the string "$libdir" at the beginning of a path
225 -- with the current libdir (obtained from the -B option).
226 mungePackagePaths top_dir ps = map munge_pkg ps
228 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
229 includeDirs = munge_paths (includeDirs p),
230 libraryDirs = munge_paths (libraryDirs p),
231 frameworkDirs = munge_paths (frameworkDirs p) }
233 munge_paths = map munge_path
236 | Just p' <- maybePrefixMatch "$libdir" p = top_dir ++ p'
240 -- -----------------------------------------------------------------------------
241 -- When all the command-line options are in, we can process our package
242 -- settings and populate the package state.
244 mkPackageState :: DynFlags -> PackageConfigMap -> IO PackageState
245 mkPackageState dflags pkg_db = do
247 -- Modify the package database according to the command-line flags
248 -- (-package, -hide-package, -ignore-package).
250 -- Also, here we build up a set of the packages mentioned in -package
251 -- flags on the command line; these are called the "explicit" packages.
252 -- we link these packages in eagerly. The explicit set should contain
253 -- at least rts & base, which is why we pretend that the command line
254 -- contains -package rts & -package base.
257 flags = reverse (packageFlags dflags)
259 procflags pkgs expl [] = return (pkgs,expl)
260 procflags pkgs expl (ExposePackage str : flags) = do
261 case partition (matches str) pkgs of
262 ([],_) -> missingPackageErr str
263 ([p],ps) -> procflags (p':ps) (addOneToUniqSet expl pkgid) flags
264 where pkgid = packageConfigId p
265 p' = p {exposed=True}
266 (ps,_) -> multiplePackagesErr str ps
267 procflags pkgs expl (HidePackage str : flags) = do
268 case partition (matches str) pkgs of
269 ([],_) -> missingPackageErr str
270 ([p],ps) -> procflags (p':ps) expl flags
271 where p' = p {exposed=False}
272 (ps,_) -> multiplePackagesErr str ps
273 procflags pkgs expl (IgnorePackage str : flags) = do
274 case partition (matches str) pkgs of
275 (ps,qs) -> procflags qs expl flags
276 -- missing package is not an error for -ignore-package,
277 -- because a common usage is to -ignore-package P as
278 -- a preventative measure just in case P exists.
280 -- A package named on the command line can either include the
281 -- version, or just the name if it is unambiguous.
283 = str == showPackageId (package p)
284 || str == pkgName (package p)
286 (pkgs1,explicit) <- procflags (eltsUFM pkg_db) emptyUniqSet flags
289 elimDanglingDeps pkgs =
290 case partition (hasDanglingDeps pkgs) pkgs of
292 (ps,qs) -> elimDanglingDeps qs
294 hasDanglingDeps pkgs p = any dangling (depends p)
295 where dangling pid = pid `notElem` all_pids
296 all_pids = map package pkgs
298 -- Eliminate any packages which have dangling dependencies (perhaps
299 -- because the package was removed by -ignore-package).
301 let pkgs = elimDanglingDeps pkgs1
302 pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
304 -- Find the transitive closure of dependencies of exposed
306 let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
307 dep_exposed <- closeDeps pkg_db exposed_pkgids
309 -- Look up some known PackageIds
312 lookupPackageByName nm =
313 case [ conf | p <- dep_exposed,
314 Just conf <- [lookupPackage pkg_db p],
315 nm == mkFastString (pkgName (package conf)) ] of
317 (p:ps) -> Just (mkPackageId (package p))
319 -- Get the PackageIds for some known packages (we know the names,
320 -- but we don't know the versions). Some of these packages might
321 -- not exist in the database, so they are Maybes.
322 basePackageId = lookupPackageByName basePackageName
323 rtsPackageId = lookupPackageByName rtsPackageName
324 haskell98PackageId = lookupPackageByName haskell98PackageName
325 thPackageId = lookupPackageByName thPackageName
327 -- add base & rts to the explicit packages
328 basicLinkedPackages = [basePackageId,rtsPackageId]
329 explicit' = addListToUniqSet explicit
330 [ p | Just p <- basicLinkedPackages ]
332 -- Close the explicit packages with their dependencies
334 dep_explicit <- closeDeps pkg_db (uniqSetToList explicit')
336 -- Build up a mapping from Module -> PackageConfig for all modules.
337 -- Discover any conflicts at the same time, and factor in the new exposed
338 -- status of each package.
341 extend_modmap modmap pkgname = do
343 pkg = fromJust (lookupPackage pkg_db pkgname)
344 exposed_mods = map mkModule (exposedModules pkg)
345 hidden_mods = map mkModule (hiddenModules pkg)
346 all_mods = exposed_mods ++ hidden_mods
348 -- check for overlaps
351 overlaps = [ (m,pkg) | m <- all_mods,
352 Just (pkg,_) <- [lookupUFM modmap m] ]
354 when (not (null overlaps)) $ overlappingError pkg overlaps
357 return (addListToUFM modmap
358 [(m, (pkg, m `elem` exposed_mods))
361 mod_map <- foldM extend_modmap emptyUFM dep_exposed
363 return PackageState{ explicitPackages = dep_explicit,
365 moduleToPkgConf = mod_map,
366 basePackageId = basePackageId,
367 rtsPackageId = rtsPackageId,
368 haskell98PackageId = haskell98PackageId,
369 thPackageId = thPackageId
373 basePackageName = FSLIT("base")
374 rtsPackageName = FSLIT("rts")
375 haskell98PackageName = FSLIT("haskell98")
376 thPackageName = FSLIT("template-haskell")
377 -- Template Haskell libraries in here
379 overlappingError pkg overlaps
380 = throwDyn (CmdLineError (showSDoc (vcat (map msg overlaps))))
382 this_pkg = text (showPackageId (package pkg))
383 msg (mod,other_pkg) =
384 text "Error: module '" <> ppr mod
385 <> text "' is exposed by package "
386 <> this_pkg <> text " and package "
387 <> text (showPackageId (package other_pkg))
389 multiplePackagesErr str ps =
390 throwDyn (CmdLineError (showSDoc (
391 text "Error; multiple packages match" <+>
392 text str <> colon <+>
393 sep (punctuate comma (map (text.showPackageId.package) ps))
396 -- -----------------------------------------------------------------------------
397 -- Extracting information from the packages in scope
399 -- Many of these functions take a list of packages: in those cases,
400 -- the list is expected to contain the "dependent packages",
401 -- i.e. those packages that were found to be depended on by the
402 -- current module/program. These can be auto or non-auto packages, it
403 -- doesn't really matter. The list is always combined with the list
404 -- of explicit (command-line) packages to determine which packages to
407 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
408 getPackageIncludePath dflags pkgs = do
409 ps <- getExplicitPackagesAnd dflags pkgs
410 return (nub (filter notNull (concatMap includeDirs ps)))
412 -- includes are in reverse dependency order (i.e. rts first)
413 getPackageCIncludes :: [PackageConfig] -> IO [String]
414 getPackageCIncludes pkg_configs = do
415 return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
417 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
418 getPackageLibraryPath dflags pkgs = do
419 ps <- getExplicitPackagesAnd dflags pkgs
420 return (nub (filter notNull (concatMap libraryDirs ps)))
422 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
423 getPackageLinkOpts dflags pkgs = do
424 ps <- getExplicitPackagesAnd dflags pkgs
425 tag <- readIORef v_Build_tag
426 rts_tag <- readIORef v_RTS_Build_tag
427 static <- readIORef v_Static
429 imp = if static then "" else "_imp"
430 libs p = map addSuffix (hACK (hsLibraries p)) ++ extraLibraries p
431 imp_libs p = map (++imp) (libs p)
432 all_opts p = map ("-l" ++) (imp_libs p) ++ extraLdOpts p
434 suffix = if null tag then "" else '_':tag
435 rts_suffix = if null rts_tag then "" else '_':rts_tag
437 addSuffix rts@"HSrts" = rts ++ rts_suffix
438 addSuffix other_lib = other_lib ++ suffix
440 return (concat (map all_opts ps))
443 -- This is a totally horrible (temporary) hack, for Win32. Problem is
444 -- that package.conf for Win32 says that the main prelude lib is
445 -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
446 -- in the GNU linker (PEi386 backend). However, we still only
447 -- have HSbase.a for static linking, not HSbase{1,2,3}.a
448 -- getPackageLibraries is called to find the .a's to add to the static
449 -- link line. On Win32, this hACK detects HSbase{1,2,3} and
450 -- replaces them with HSbase, so static linking still works.
451 -- Libraries needed for dynamic (GHCi) linking are discovered via
452 -- different route (in InteractiveUI.linkPackage).
453 -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
454 -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
455 -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
456 -- KAA 29 Mar 02: Same appalling hack for HSobjectio[1,2,3,4]
458 # if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
461 = if "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
462 then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
464 if "HSwin321" `elem` libs && "HSwin322" `elem` libs
465 then "HSwin32" : filter (not.(isPrefixOf "HSwin32")) libs
467 if "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
468 then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
473 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
474 getPackageExtraCcOpts dflags pkgs = do
475 ps <- getExplicitPackagesAnd dflags pkgs
476 return (concatMap extraCcOpts ps)
478 getPackageFrameworkPath :: DynFlags -> [PackageId] -> IO [String]
479 getPackageFrameworkPath dflags pkgs = do
480 ps <- getExplicitPackagesAnd dflags pkgs
481 return (nub (filter notNull (concatMap frameworkDirs ps)))
483 getPackageFrameworks :: DynFlags -> [PackageId] -> IO [String]
484 getPackageFrameworks dflags pkgs = do
485 ps <- getExplicitPackagesAnd dflags pkgs
486 return (concatMap extraFrameworks ps)
488 -- -----------------------------------------------------------------------------
491 -- Takes a Module, and if the module is in a package returns
492 -- (pkgconf,exposed) where pkgconf is the PackageConfig for that package,
493 -- and exposed is True if the package exposes the module.
494 moduleToPackageConfig :: DynFlags -> Module -> Maybe (PackageConfig,Bool)
495 moduleToPackageConfig dflags m =
496 lookupUFM (moduleToPkgConf (pkgState dflags)) m
498 isHomeModule :: DynFlags -> Module -> Bool
499 isHomeModule dflags mod = isNothing (moduleToPackageConfig dflags mod)
501 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
502 getExplicitPackagesAnd dflags pkgids =
504 state = pkgState dflags
505 pkg_map = pkgIdMap state
506 expl = explicitPackages state
508 all_pkgs <- foldM (add_package pkg_map) expl pkgids
509 return (map (getPackageDetails state) all_pkgs)
511 -- Takes a list of packages, and returns the list with dependencies included,
512 -- in reverse dependency order (a package appears before those it depends on).
513 closeDeps :: PackageConfigMap -> [PackageId] -> IO [PackageId]
514 closeDeps pkg_map ps = foldM (add_package pkg_map) [] ps
517 add_package :: PackageConfigMap -> [PackageId] -> PackageId -> IO [PackageId]
518 add_package pkg_db ps p
519 | p `elem` ps = return ps -- Check if we've already added this package
521 case lookupPackage pkg_db p of
522 Nothing -> missingPackageErr (packageIdString p)
524 -- Add the package's dependents also
525 let deps = map mkPackageId (depends pkg)
526 ps' <- foldM (add_package pkg_db) ps deps
529 missingPackageErr p = throwDyn (CmdLineError ("unknown package: " ++ p))
531 -- -----------------------------------------------------------------------------
532 -- Determining whether a Name refers to something in another package or not.
533 -- Cross-package references need to be handled differently when dynamically-
534 -- linked libraries are involved.
536 isDllName :: DynFlags -> Name -> Bool
537 isDllName dflags name
540 case nameModule_maybe name of
541 Nothing -> False -- no, it is not even an external name
543 case lookupUFM (moduleToPkgConf (pkgState dflags)) mod of
544 Just _ -> True -- yes, its a package module
545 Nothing -> False -- no, must be a home module
547 -- -----------------------------------------------------------------------------
548 -- Displaying packages
550 dumpPackages :: DynFlags -> IO ()
551 -- Show package info on console, if verbosity is >= 3
553 = do let pkg_map = pkgIdMap (pkgState dflags)
554 hPutStrLn stderr $ showSDoc $
555 vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))