Generalise Package Support
[ghc-hetmet.git] / compiler / main / Packages.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section{Package manipulation}
5
6 \begin{code}
7 module Packages (
8         module PackageConfig,
9
10         -- * The PackageConfigMap
11         PackageConfigMap, emptyPackageConfigMap, lookupPackage,
12         extendPackageConfigMap, dumpPackages,
13
14         -- * Reading the package config, and processing cmdline args
15         PackageState(..),
16         initPackages,
17         getPackageDetails,
18         lookupModuleInAllPackages,
19
20         -- * Inspecting the set of packages in scope
21         getPackageIncludePath,
22         getPackageCIncludes,
23         getPackageLibraryPath,
24         getPackageLinkOpts,
25         getPackageExtraCcOpts,
26         getPackageFrameworkPath,
27         getPackageFrameworks,
28         getExplicitPackagesAnd,
29
30         -- * Utils
31         isDllName
32     )
33 where
34
35 #include "HsVersions.h"
36
37 import PackageConfig    
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 )
44 import UniqFM
45 import Module
46 import UniqSet
47 import Util
48 import Maybes           ( expectJust, MaybeErr(..) )
49 import Panic
50 import Outputable
51
52 #if __GLASGOW_HASKELL__ >= 603
53 import System.Directory ( getAppUserDataDirectory )
54 #else
55 import Compat.Directory ( getAppUserDataDirectory )
56 #endif
57
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 )
67 import FastString
68 import EXCEPTION        ( throwDyn )
69 import ErrUtils         ( debugTraceMsg, putMsg, Message )
70
71 -- ---------------------------------------------------------------------------
72 -- The Package state
73
74 -- Package state is all stored in DynFlags, including the details of
75 -- all packages, which packages are exposed, and which modules they
76 -- provide.
77
78 -- The package state is computed by initPackages, and kept in DynFlags.
79 --
80 --   * -package <pkg> causes <pkg> to become exposed, and all other packages 
81 --      with the same name to become hidden.
82 -- 
83 --   * -hide-package <pkg> causes <pkg> to become hidden.
84 -- 
85 --   * Let exposedPackages be the set of packages thus exposed.  
86 --     Let depExposedPackages be the transitive closure from exposedPackages of
87 --     their dependencies.
88 --
89 --   * When searching for a module from an explicit import declaration,
90 --     only the exposed modules in exposedPackages are valid.
91 --
92 --   * When searching for a module from an implicit import, all modules
93 --     from depExposedPackages are valid.
94 --
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.
103
104 -- Notes on DLLs
105 -- ~~~~~~~~~~~~~
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.
112
113 data PackageState = PackageState {
114
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.
119
120   origPkgIdMap          :: PackageConfigMap, -- PackageId   -> PackageConfig
121         -- the full package database
122
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.
127
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.
133   }
134
135 -- A PackageConfigMap maps a PackageId to a PackageConfig
136 type PackageConfigMap = UniqFM PackageConfig
137
138 emptyPackageConfigMap :: PackageConfigMap
139 emptyPackageConfigMap = emptyUFM
140
141 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
142 lookupPackage = lookupUFM
143
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
149
150 getPackageDetails :: PackageState -> PackageId -> PackageConfig
151 getPackageDetails dflags ps = expectJust "getPackageDetails" (lookupPackage (pkgIdMap dflags) ps)
152
153 -- ----------------------------------------------------------------------------
154 -- Loading the package config files and building up the package state
155
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
164
165 -- -----------------------------------------------------------------------------
166 -- Reading the package database(s)
167
168 readPackageConfigs :: DynFlags -> IO PackageConfigMap
169 readPackageConfigs dflags = do
170    e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
171    system_pkgconfs <- getSystemPackageConfigs dflags
172
173    let pkgconfs = case e_pkg_path of
174                     Left _   -> system_pkgconfs
175                     Right path
176                      | last cs == "" -> init cs ++ system_pkgconfs
177                      | otherwise     -> cs
178                      where cs = parseSearchPath path
179                      -- if the path ends in a separator (eg. "/foo/bar:")
180                      -- the we tack on the system paths.
181
182         -- Read all the ones mentioned in -package-conf flags
183    pkg_map <- foldM (readPackageConfig dflags) emptyPackageConfigMap
184                  (reverse pkgconfs ++ extraPkgConfs dflags)
185
186    return pkg_map
187
188
189 getSystemPackageConfigs :: DynFlags -> IO [FilePath]
190 getSystemPackageConfigs dflags = do
191         -- System one always comes first
192    system_pkgconf <- getPackageConfigPath
193
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
201    system_pkgconfs <-
202      if system_pkgconf_dir_exists
203        then do files <- getDirectoryContents system_pkgconf_dir
204                return [ system_pkgconf_dir ++ '/' : file
205                       | file <- files
206                       , isSuffixOf ".conf" file]
207        else return []
208
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 
212         -- (GHC >= 6.3).
213    user_pkgconf <- handle (\_ -> return []) $ do
214       appdir <- getAppUserDataDirectory "ghc"
215       let 
216          pkgconf = appdir
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]
222         else return []
223
224    return (user_pkgconf ++ system_pkgconfs ++ [system_pkgconf])
225
226
227 readPackageConfig
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
232   top_dir           <- getTopDir
233   let pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
234       pkg_configs2 = maybeHidePackages dflags pkg_configs1
235   return (extendPackageConfigMap pkg_map pkg_configs2)
236
237 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
238 maybeHidePackages dflags pkgs
239   | dopt Opt_HideAllPackages dflags = map hide pkgs
240   | otherwise                       = pkgs
241   where
242     hide pkg = pkg{ exposed = False }
243
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
248  where 
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) }
253
254   munge_paths = map munge_path
255
256   munge_path p 
257           | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
258           | otherwise                               = p
259
260
261 -- -----------------------------------------------------------------------------
262 -- When all the command-line options are in, we can process our package
263 -- settings and populate the package state.
264
265 mkPackageState :: DynFlags -> PackageConfigMap -> IO DynFlags
266 mkPackageState dflags orig_pkg_db = do
267   --
268   -- Modify the package database according to the command-line flags
269   -- (-package, -hide-package, -ignore-package, -hide-all-packages).
270   --
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.
276   --
277   let
278         flags = reverse (packageFlags dflags)
279
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.
299
300         pick str pkgs
301           = case partition (matches str) pkgs of
302                 ([],_) -> Nothing
303                 (ps,rest) -> 
304                    case sortBy (flip (comparing (pkgVersion.package))) ps of
305                         (p:ps) -> Just (p, ps ++ rest)
306                         _ -> panic "Packages.pick"
307
308         comparing f a b = f a `compare` f b
309
310         -- A package named on the command line can either include the
311         -- version, or just the name if it is unambiguous.
312         matches str p
313                 =  str == showPackageId (package p)
314                 || str == pkgName (package p)
315
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}
320                              | otherwise                   = p
321   --
322   (pkgs1,explicit) <- procflags (eltsUFM orig_pkg_db) [] flags
323   --
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.
328   --
329   let maybe_hide p
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,
341                                     let pkg = package p,
342                                     pkgName pkg == myname,
343                                     pkgVersion pkg > myversion ]
344
345   pkgs2 <- mapM maybe_hide pkgs1
346   --
347   -- Now we must find our wired-in packages, and rename them to
348   -- their canonical names (eg. base-1.0 ==> base).
349   --
350   let
351         wired_in_pkgids = [ basePackageId,
352                             rtsPackageId,
353                             haskell98PackageId,
354                             thPackageId ]
355
356         wired_in_names = map packageIdString wired_in_pkgids
357
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
361         -- one.
362         findWiredInPackage :: [PackageConfig] -> String
363                            -> IO (Maybe PackageIdentifier)
364         findWiredInPackage pkgs wired_pkg =
365            case [ p | p <- pkgs, pkgName (package p) == wired_pkg,
366                                  exposed p ] of
367                 [] -> do 
368                         debugTraceMsg dflags 2 $
369                             ptext SLIT("wired-in package ")
370                                  <> text wired_pkg
371                                  <> ptext SLIT(" not found.")
372                         return Nothing
373                 [one] -> do 
374                         debugTraceMsg dflags 2 $
375                             ptext SLIT("wired-in package ")
376                                  <> text wired_pkg
377                                  <> ptext SLIT(" mapped to ")
378                                  <> text (showPackageId (package one))
379                         return (Just (package one))
380                 more -> do
381                         throwDyn (CmdLineError (showSDoc $
382                             ptext SLIT("there are multiple exposed packages that match wired-in package ") <> text wired_pkg))
383
384   mb_wired_in_ids <- mapM (findWiredInPackage pkgs2) wired_in_names
385   let 
386         wired_in_ids = catMaybes mb_wired_in_ids
387
388         deleteHiddenWiredInPackages pkgs = filter ok pkgs
389           where ok p = pkgName (package p) `notElem` wired_in_names
390                          || exposed p
391
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) }
395
396         upd_pid pid = case filter (== pid) wired_in_ids of
397                                 [] -> pid
398                                 (x:_) -> x{ pkgVersion = Version [] [] }
399
400         pkgs3 = deleteHiddenWiredInPackages pkgs2
401
402         pkgs4 = updateWiredInDependencies pkgs3
403
404         explicit1 = map upd_pid explicit
405
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)
410
411   --
412   -- Eliminate any packages which have dangling dependencies (perhaps
413   -- because the package was removed by -ignore-package).
414   --
415   let
416         elimDanglingDeps pkgs = 
417            case partition (not.null.snd) (map (getDanglingDeps pkgs) pkgs) of
418               ([],ps) -> return (map fst ps)
419               (ps,qs) -> do
420                  mapM_ reportElim ps
421                  elimDanglingDeps (map fst qs)
422
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)))
428
429         getDanglingDeps pkgs p = (p, filter dangling (depends p))
430           where dangling pid = pid `notElem` all_pids
431                 all_pids = map package pkgs
432   --
433   pkgs <- elimDanglingDeps pkgs4
434   let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
435   --
436   -- Find the transitive closure of dependencies of exposed
437   --
438   let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
439   dep_exposed <- closeDeps pkg_db exposed_pkgids
440   let
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))
445                                      basicLinkedPackages
446   --
447   -- Close the explicit packages with their dependencies
448   --
449   dep_explicit <- closeDeps pkg_db (uniqSetToList explicit2)
450   --
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.
454   --
455   let mod_map = mkModuleMap pkg_db dep_exposed
456
457       pstate = PackageState{ explicitPackages     = dep_explicit,
458                              origPkgIdMap           = orig_pkg_db,
459                              pkgIdMap               = pkg_db,
460                              moduleToPkgConfAll   = mod_map
461                            }
462
463   return dflags{ pkgState = pstate, thisPackage = new_this_pkg }
464   -- done!
465
466
467 mkModuleMap
468   :: PackageConfigMap
469   -> [PackageId]
470   -> UniqFM [(PackageConfig, Bool)]
471 mkModuleMap pkg_db pkgs = foldr extend_modmap emptyUFM pkgs
472   where
473         extend_modmap pkgid modmap =
474                 addListToUFM_C (++) modmap 
475                     [(m, [(pkg, m `elem` exposed_mods)]) | m <- all_mods]
476           where
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
481
482 pprPkg :: PackageConfig -> SDoc
483 pprPkg p = text (showPackageId (package p))
484
485 -- -----------------------------------------------------------------------------
486 -- Extracting information from the packages in scope
487
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
494 -- use.
495
496 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
497 getPackageIncludePath dflags pkgs = do
498   ps <- getExplicitPackagesAnd dflags pkgs
499   return (nub (filter notNull (concatMap includeDirs ps)))
500
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))))
505
506 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
507 getPackageLibraryPath dflags pkgs = do 
508   ps <- getExplicitPackagesAnd dflags pkgs
509   return (nub (filter notNull (concatMap libraryDirs ps)))
510
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
516   let 
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
521
522         suffix     = if null tag then "" else  '_':tag
523         rts_suffix = if null rts_tag then "" else  '_':rts_tag
524
525         addSuffix rts@"HSrts"    = rts       ++ rts_suffix
526         addSuffix other_lib      = other_lib ++ suffix
527
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.
533         
534         hACK_dyn = map hack
535           where hack lib | not opt_Static && "_cbits" `isSuffixOf` lib = lib ++ "_dyn"
536                          | otherwise = lib
537
538   return (concat (map all_opts ps))
539
540 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
541 getPackageExtraCcOpts dflags pkgs = do
542   ps <- getExplicitPackagesAnd dflags pkgs
543   return (concatMap ccOptions ps)
544
545 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
546 getPackageFrameworkPath dflags pkgs = do
547   ps <- getExplicitPackagesAnd dflags pkgs
548   return (nub (filter notNull (concatMap frameworkDirs ps)))
549
550 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
551 getPackageFrameworks dflags pkgs = do
552   ps <- getExplicitPackagesAnd dflags pkgs
553   return (concatMap frameworks ps)
554
555 -- -----------------------------------------------------------------------------
556 -- Package Utils
557
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
564         Nothing -> []
565         Just ps -> ps
566
567 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
568 getExplicitPackagesAnd dflags pkgids =
569   let 
570       state   = pkgState dflags
571       pkg_map = pkgIdMap state
572       expl    = explicitPackages state
573   in do
574   all_pkgs <- throwErr (foldM (add_package pkg_map) expl pkgids)
575   return (map (getPackageDetails state) all_pkgs)
576
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)
581
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
586
587 closeDepsErr :: PackageConfigMap -> [PackageId]
588         -> MaybeErr Message [PackageId]
589 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
590
591 -- internal helper
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
596   | otherwise =
597       case lookupPackage pkg_db p of
598         Nothing -> Failed (missingPackageMsg (packageIdString p))
599         Just pkg -> do
600            -- Add the package's dependents also
601            let deps = map mkPackageId (depends pkg)
602            ps' <- foldM (add_package pkg_db) ps deps
603            return (p : ps')
604
605 missingPackageErr p = throwDyn (CmdLineError (showSDoc (missingPackageMsg p)))
606 missingPackageMsg p = ptext SLIT("unknown package:") <+> text p
607
608 -- -----------------------------------------------------------------------------
609
610 isDllName :: PackageId -> Name -> Bool
611 isDllName this_pkg name
612   | opt_Static = False
613   | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
614   | otherwise = False  -- no, it is not even an external name
615
616 -- -----------------------------------------------------------------------------
617 -- Displaying packages
618
619 dumpPackages :: DynFlags -> IO ()
620 -- Show package info on console, if verbosity is >= 3
621 dumpPackages dflags
622   = do  let pkg_map = pkgIdMap (pkgState dflags)
623         putMsg dflags $
624               vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))
625 \end{code}