e2a0a047f2834d4e85a9fad0606706c3a712ed09
[ghc-hetmet.git] / compiler / main / Packages.lhs
1 %
2 % (c) The University of Glasgow, 2006
3 %
4 \begin{code}
5 -- | Package manipulation
6 module Packages (
7         module PackageConfig,
8
9         -- * The PackageConfigMap
10         PackageConfigMap, emptyPackageConfigMap, lookupPackage,
11         extendPackageConfigMap, dumpPackages,
12
13         -- * Reading the package config, and processing cmdline args
14         PackageState(..),
15         initPackages,
16         getPackageDetails,
17         lookupModuleInAllPackages,
18
19         -- * Inspecting the set of packages in scope
20         getPackageIncludePath,
21         getPackageLibraryPath,
22         getPackageLinkOpts,
23         getPackageExtraCcOpts,
24         getPackageFrameworkPath,
25         getPackageFrameworks,
26         getPreloadPackagesAnd,
27
28         collectIncludeDirs, collectLibraryPaths, collectLinkOpts,
29         packageHsLibs,
30
31         -- * Utils
32         isDllName
33     )
34 where
35
36 #include "HsVersions.h"
37
38 import PackageConfig    
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 Util
47 import Maybes           ( expectJust, MaybeErr(..) )
48 import Panic
49 import Outputable
50
51 import System.Environment ( getEnv )
52 import Distribution.InstalledPackageInfo hiding (depends)
53 import Distribution.Package hiding (depends, PackageId)
54 import Distribution.Text
55 import Distribution.Version
56 import FastString
57 import ErrUtils         ( debugTraceMsg, putMsg, Message )
58 import Exception
59
60 import System.Directory
61 import System.FilePath
62 import Data.Maybe
63 import Control.Monad
64 import Data.List
65
66 -- ---------------------------------------------------------------------------
67 -- The Package state
68
69 -- | Package state is all stored in 'DynFlag's, including the details of
70 -- all packages, which packages are exposed, and which modules they
71 -- provide.
72 --
73 -- The package state is computed by 'initPackages', and kept in DynFlags.
74 --
75 --   * @-package <pkg>@ causes @<pkg>@ to become exposed, and all other packages 
76 --      with the same name to become hidden.
77 -- 
78 --   * @-hide-package <pkg>@ causes @<pkg>@ to become hidden.
79 -- 
80 --   * Let @exposedPackages@ be the set of packages thus exposed.  
81 --     Let @depExposedPackages@ be the transitive closure from @exposedPackages@ of
82 --     their dependencies.
83 --
84 --   * When searching for a module from an preload import declaration,
85 --     only the exposed modules in @exposedPackages@ are valid.
86 --
87 --   * When searching for a module from an implicit import, all modules
88 --     from @depExposedPackages@ are valid.
89 --
90 --   * When linking in a compilation manager mode, we link in packages the
91 --     program depends on (the compiler knows this list by the
92 --     time it gets to the link step).  Also, we link in all packages
93 --     which were mentioned with preload @-package@ flags on the command-line,
94 --     or are a transitive dependency of same, or are \"base\"\/\"rts\".
95 --     The reason for this is that we might need packages which don't
96 --     contain any Haskell modules, and therefore won't be discovered
97 --     by the normal mechanism of dependency tracking.
98
99 -- Notes on DLLs
100 -- ~~~~~~~~~~~~~
101 -- When compiling module A, which imports module B, we need to 
102 -- know whether B will be in the same DLL as A.  
103 --      If it's in the same DLL, we refer to B_f_closure
104 --      If it isn't, we refer to _imp__B_f_closure
105 -- When compiling A, we record in B's Module value whether it's
106 -- in a different DLL, by setting the DLL flag.
107
108 data PackageState = PackageState {
109   pkgIdMap              :: PackageConfigMap, -- PackageId   -> PackageConfig
110         -- The exposed flags are adjusted according to -package and
111         -- -hide-package flags, and -ignore-package removes packages.
112
113   preloadPackages      :: [PackageId],
114         -- The packages we're going to link in eagerly.  This list
115         -- should be in reverse dependency order; that is, a package
116         -- is always mentioned before the packages it depends on.
117
118   moduleToPkgConfAll    :: UniqFM [(PackageConfig,Bool)] -- ModuleEnv mapping
119         -- Derived from pkgIdMap.       
120         -- Maps Module to (pkgconf,exposed), where pkgconf is the
121         -- PackageConfig for the package containing the module, and
122         -- exposed is True if the package exposes that module.
123   }
124
125 -- | A PackageConfigMap maps a 'PackageId' to a 'PackageConfig'
126 type PackageConfigMap = UniqFM PackageConfig
127
128 emptyPackageConfigMap :: PackageConfigMap
129 emptyPackageConfigMap = emptyUFM
130
131 -- | Find the package we know about with the given id (e.g. \"foo-1.0\"), if any
132 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
133 lookupPackage = lookupUFM
134
135 extendPackageConfigMap
136    :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
137 extendPackageConfigMap pkg_map new_pkgs 
138   = foldl add pkg_map new_pkgs
139   where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
140
141 -- | Looks up the package with the given id in the package state, panicing if it is
142 -- not found
143 getPackageDetails :: PackageState -> PackageId -> PackageConfig
144 getPackageDetails ps pid = expectJust "getPackageDetails" (lookupPackage (pkgIdMap ps) pid)
145
146 -- ----------------------------------------------------------------------------
147 -- Loading the package config files and building up the package state
148
149 -- | Call this after 'DynFlags.parseDynFlags'.  It reads the package
150 -- configuration files, and sets up various internal tables of package
151 -- information, according to the package-related flags on the
152 -- command-line (@-package@, @-hide-package@ etc.)
153 --
154 -- Returns a list of packages to link in if we're doing dynamic linking.
155 -- This list contains the packages that the user explicitly mentioned with
156 -- @-package@ flags.
157 --
158 -- 'initPackages' can be called again subsequently after updating the
159 -- 'packageFlags' field of the 'DynFlags', and it will update the
160 -- 'pkgState' in 'DynFlags' and return a list of packages to
161 -- link in.
162 initPackages :: DynFlags -> IO (DynFlags, [PackageId])
163 initPackages dflags = do 
164   pkg_db <- case pkgDatabase dflags of
165                 Nothing -> readPackageConfigs dflags
166                 Just db -> return db
167   (pkg_state, preload, this_pkg)       
168         <- mkPackageState dflags pkg_db [] (thisPackage dflags)
169   return (dflags{ pkgDatabase = Just pkg_db,
170                   pkgState = pkg_state,
171                   thisPackage = this_pkg },
172           preload)
173
174 -- -----------------------------------------------------------------------------
175 -- Reading the package database(s)
176
177 readPackageConfigs :: DynFlags -> IO PackageConfigMap
178 readPackageConfigs dflags = do
179    e_pkg_path <- tryIO (getEnv "GHC_PACKAGE_PATH")
180    system_pkgconfs <- getSystemPackageConfigs dflags
181
182    let pkgconfs = case e_pkg_path of
183                     Left _   -> system_pkgconfs
184                     Right path
185                      | last cs == "" -> init cs ++ system_pkgconfs
186                      | otherwise     -> cs
187                      where cs = parseSearchPath path
188                      -- if the path ends in a separator (eg. "/foo/bar:")
189                      -- the we tack on the system paths.
190
191         -- Read all the ones mentioned in -package-conf flags
192    pkg_map <- foldM (readPackageConfig dflags) emptyPackageConfigMap
193                  (reverse pkgconfs ++ extraPkgConfs dflags)
194
195    return pkg_map
196
197
198 getSystemPackageConfigs :: DynFlags -> IO [FilePath]
199 getSystemPackageConfigs dflags = do
200         -- System one always comes first
201    let system_pkgconf = systemPackageConfig dflags
202
203         -- allow package.conf.d to contain a bunch of .conf files
204         -- containing package specifications.  This is an easier way
205         -- to maintain the package database on systems with a package
206         -- management system, or systems that don't want to run ghc-pkg
207         -- to register or unregister packages.  Undocumented feature for now.
208    let system_pkgconf_dir = system_pkgconf <.> "d"
209    system_pkgconf_dir_exists <- doesDirectoryExist system_pkgconf_dir
210    system_pkgconfs <-
211      if system_pkgconf_dir_exists
212        then do files <- getDirectoryContents system_pkgconf_dir
213                return [ system_pkgconf_dir </> file
214                       | file <- files
215                       , takeExtension file == ".conf" ]
216        else return []
217
218         -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
219         -- unless the -no-user-package-conf flag was given.
220         -- We only do this when getAppUserDataDirectory is available 
221         -- (GHC >= 6.3).
222    user_pkgconf <- do
223       appdir <- getAppUserDataDirectory "ghc"
224       let 
225          pkgconf = appdir
226                    </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
227                    </> "package.conf"
228       flg <- doesFileExist pkgconf
229       if (flg && dopt Opt_ReadUserPackageConf dflags)
230         then return [pkgconf]
231         else return []
232     `catchIO` (\_ -> return [])
233
234    return (user_pkgconf ++ system_pkgconfs ++ [system_pkgconf])
235
236
237 readPackageConfig
238    :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
239 readPackageConfig dflags pkg_map conf_file = do
240   debugTraceMsg dflags 2 (text "Using package config file:" <+> text conf_file)
241   proto_pkg_configs <- loadPackageConfig dflags conf_file
242   let top_dir = topDir dflags
243       pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
244       pkg_configs2 = maybeHidePackages dflags pkg_configs1
245   return (extendPackageConfigMap pkg_map pkg_configs2)
246
247 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
248 maybeHidePackages dflags pkgs
249   | dopt Opt_HideAllPackages dflags = map hide pkgs
250   | otherwise                       = pkgs
251   where
252     hide pkg = pkg{ exposed = False }
253
254 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
255 -- Replace the string "$topdir" at the beginning of a path
256 -- with the current topdir (obtained from the -B option).
257 mungePackagePaths top_dir ps = map munge_pkg ps
258  where 
259   munge_pkg p = p{ importDirs  = munge_paths (importDirs p),
260                    includeDirs = munge_paths (includeDirs p),
261                    libraryDirs = munge_paths (libraryDirs p),
262                    frameworkDirs = munge_paths (frameworkDirs p),
263                    haddockInterfaces = munge_paths (haddockInterfaces p),
264                    haddockHTMLs = munge_paths (haddockHTMLs p)
265                     }
266
267   munge_paths = map munge_path
268
269   munge_path p 
270           | Just p' <- maybePrefixMatch "$topdir"     p =            top_dir ++ p'
271           | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
272           | otherwise                               = p
273
274   toHttpPath p = "file:///" ++ p
275
276
277 -- -----------------------------------------------------------------------------
278 -- Modify our copy of the package database based on a package flag
279 -- (-package, -hide-package, -ignore-package).
280
281 applyPackageFlag
282    :: [PackageConfig]           -- Initial database
283    -> PackageFlag               -- flag to apply
284    -> IO [PackageConfig]        -- new database
285
286 applyPackageFlag pkgs flag = 
287   case flag of
288         ExposePackage str ->
289            case matchingPackages str pkgs of
290                 Nothing -> missingPackageErr str
291                 Just ([], _) -> panic "applyPackageFlag"
292                 Just (p:ps,qs) -> return (p':ps')
293                   where p' = p {exposed=True}
294                         ps' = hideAll (pkgName (package p)) (ps++qs)
295
296         HidePackage str ->
297            case matchingPackages str pkgs of
298                 Nothing -> missingPackageErr str
299                 Just (ps,qs) -> return (map hide ps ++ qs)
300                   where hide p = p {exposed=False}
301
302         IgnorePackage str ->
303            case matchingPackages str pkgs of
304                 Nothing -> return pkgs
305                 Just (_, qs) -> return qs
306                 -- missing package is not an error for -ignore-package,
307                 -- because a common usage is to -ignore-package P as
308                 -- a preventative measure just in case P exists.
309    where
310         -- When a package is requested to be exposed, we hide all other
311         -- packages with the same name.
312         hideAll name ps = map maybe_hide ps
313           where maybe_hide p | pkgName (package p) == name = p {exposed=False}
314                              | otherwise                   = p
315
316
317 matchingPackages :: String -> [PackageConfig]
318          -> Maybe ([PackageConfig], [PackageConfig])
319 matchingPackages str pkgs
320   = case partition (packageMatches str) pkgs of
321         ([],_)    -> Nothing
322         (ps,rest) -> Just (sortByVersion ps, rest)
323
324 -- A package named on the command line can either include the
325 -- version, or just the name if it is unambiguous.
326 packageMatches :: String -> PackageConfig -> Bool
327 packageMatches str p
328         =  str == display (package p)
329         || str == display (pkgName (package p))
330
331 pickPackages :: [PackageConfig] -> [String] -> [PackageConfig]
332 pickPackages pkgs strs = 
333   [ p | p <- strs, Just (p:_, _) <- [matchingPackages p pkgs] ]
334
335 sortByVersion :: [InstalledPackageInfo_ m] -> [InstalledPackageInfo_ m]
336 sortByVersion = sortBy (flip (comparing (pkgVersion.package)))
337
338 comparing :: Ord a => (t -> a) -> t -> t -> Ordering
339 comparing f a b = f a `compare` f b
340
341 -- -----------------------------------------------------------------------------
342 -- Hide old versions of packages
343
344 --
345 -- hide all packages for which there is also a later version
346 -- that is already exposed.  This just makes it non-fatal to have two
347 -- versions of a package exposed, which can happen if you install a
348 -- later version of a package in the user database, for example.
349 --
350 hideOldPackages :: DynFlags -> [PackageConfig] -> IO [PackageConfig]
351 hideOldPackages dflags pkgs = mapM maybe_hide pkgs
352   where maybe_hide p
353            | not (exposed p) = return p
354            | (p' : _) <- later_versions = do
355                 debugTraceMsg dflags 2 $
356                    (ptext (sLit "hiding package") <+> 
357                     text (display (package p)) <+>
358                     ptext (sLit "to avoid conflict with later version") <+>
359                     text (display (package p')))
360                 return (p {exposed=False})
361            | otherwise = return p
362           where myname = pkgName (package p)
363                 myversion = pkgVersion (package p)
364                 later_versions = [ p | p <- pkgs, exposed p,
365                                     let pkg = package p,
366                                     pkgName pkg == myname,
367                                     pkgVersion pkg > myversion ]
368
369 -- -----------------------------------------------------------------------------
370 -- Wired-in packages
371
372 findWiredInPackages
373    :: DynFlags
374    -> [PackageConfig]           -- database
375    -> [PackageIdentifier]       -- preload packages
376    -> PackageId                 -- this package
377    -> IO ([PackageConfig],
378           [PackageIdentifier],
379           PackageId)
380
381 findWiredInPackages dflags pkgs preload this_package = do
382   --
383   -- Now we must find our wired-in packages, and rename them to
384   -- their canonical names (eg. base-1.0 ==> base).
385   --
386   let
387         wired_in_pkgids :: [(PackageId, [String])]
388         wired_in_pkgids = [ (primPackageId, [""]),
389                             (integerPackageId, [""]),
390                             (basePackageId, [""]),
391                             (rtsPackageId, [""]),
392                             (haskell98PackageId, [""]),
393                             (sybPackageId, [""]),
394                             (thPackageId, [""]),
395                             (dphSeqPackageId, [""]),
396                             (dphParPackageId, [""]),
397                             (ndpPackageId, ["-seq", "-par"]) ]
398
399         matches :: PackageConfig -> (PackageId, [String]) -> Bool
400         pc `matches` (pid, suffixes)
401             = display (pkgName (package pc)) `elem`
402               (map (packageIdString pid ++) suffixes)
403
404         -- find which package corresponds to each wired-in package
405         -- delete any other packages with the same name
406         -- update the package and any dependencies to point to the new
407         -- one.
408         --
409         -- When choosing which package to map to a wired-in package
410         -- name, we prefer exposed packages, and pick the latest
411         -- version.  To override the default choice, -hide-package
412         -- could be used to hide newer versions.
413         --
414         findWiredInPackage :: [PackageConfig] -> (PackageId, [String])
415                            -> IO (Maybe (PackageIdentifier, PackageId))
416         findWiredInPackage pkgs wired_pkg =
417            let all_ps = [ p | p <- pkgs, p `matches` wired_pkg ] in
418            case all_ps of
419                 []   -> notfound
420                 many -> pick (head (sortByVersion many))
421           where
422                 suffixes = snd wired_pkg
423                 notfound = do
424                           debugTraceMsg dflags 2 $
425                             ptext (sLit "wired-in package ")
426                                  <> ppr (fst wired_pkg)
427                                  <> (if null suffixes
428                                      then empty
429                                      else text (show suffixes))
430                                  <> ptext (sLit " not found.")
431                           return Nothing
432                 pick :: InstalledPackageInfo_ ModuleName
433                      -> IO (Maybe (PackageIdentifier, PackageId))
434                 pick pkg = do
435                         debugTraceMsg dflags 2 $
436                             ptext (sLit "wired-in package ")
437                                  <> ppr (fst wired_pkg)
438                                  <> ptext (sLit " mapped to ")
439                                  <> text (display (package pkg))
440                         return (Just (package pkg, fst wired_pkg))
441
442
443   mb_wired_in_ids <- mapM (findWiredInPackage pkgs) wired_in_pkgids
444   let 
445         wired_in_ids = catMaybes mb_wired_in_ids
446
447         -- this is old: we used to assume that if there were
448         -- multiple versions of wired-in packages installed that
449         -- they were mutually exclusive.  Now we're assuming that
450         -- you have one "main" version of each wired-in package
451         -- (the latest version), and the others are backward-compat
452         -- wrappers that depend on this one.  e.g. base-4.0 is the
453         -- latest, base-3.0 is a compat wrapper depending on base-4.0.
454         {-
455         deleteOtherWiredInPackages pkgs = filterOut bad pkgs
456           where bad p = any (p `matches`) wired_in_pkgids
457                       && package p `notElem` map fst wired_in_ids
458         -}
459
460         updateWiredInDependencies pkgs = map upd_pkg pkgs
461           where upd_pkg p = p{ package = upd_pid (package p),
462                                depends = map upd_pid (depends p) }
463
464         upd_pid pid = case filter ((== pid) . fst) wired_in_ids of
465                                 [] -> pid
466                                 ((x, y):_) -> x{ pkgName = PackageName (packageIdString y),
467                                                  pkgVersion = Version [] [] }
468
469         -- pkgs1 = deleteOtherWiredInPackages pkgs
470
471         pkgs2 = updateWiredInDependencies pkgs
472
473         preload1 = map upd_pid preload
474
475         -- we must return an updated thisPackage, just in case we
476         -- are actually compiling one of the wired-in packages
477         Just old_this_pkg = unpackPackageId this_package
478         new_this_pkg = mkPackageId (upd_pid old_this_pkg)
479
480   return (pkgs2, preload1, new_this_pkg)
481
482 -- ----------------------------------------------------------------------------
483 --
484 -- Detect any packages that have missing dependencies, and also any
485 -- mutually-recursive groups of packages (loops in the package graph
486 -- are not allowed).  We do this by taking the least fixpoint of the
487 -- dependency graph, repeatedly adding packages whose dependencies are
488 -- satisfied until no more can be added.
489 --
490 elimDanglingDeps
491    :: DynFlags
492    -> [PackageConfig]
493    -> [PackageId]       -- ignored packages
494    -> IO [PackageConfig]
495
496 elimDanglingDeps dflags pkgs ignored = go [] pkgs'
497  where
498    pkgs' = filter (\p -> packageConfigId p `notElem` ignored) pkgs
499
500    go avail not_avail =
501      case partitionWith (depsAvailable avail) not_avail of
502         ([],        not_avail) -> do mapM_ reportElim not_avail; return avail
503         (new_avail, not_avail) -> go (new_avail ++ avail) (map fst not_avail)
504
505    depsAvailable :: [PackageConfig] -> PackageConfig
506                  -> Either PackageConfig (PackageConfig, [PackageIdentifier])
507    depsAvailable pkgs_ok pkg 
508         | null dangling = Left pkg
509         | otherwise     = Right (pkg, dangling)
510         where dangling = filter (`notElem` pids) (depends pkg)
511               pids = map package pkgs_ok
512
513    reportElim (p, deps) = 
514         debugTraceMsg dflags 2 $
515              (ptext (sLit "package") <+> pprPkg p <+> 
516                   ptext (sLit "will be ignored due to missing or recursive dependencies:") $$ 
517               nest 2 (hsep (map (text.display) deps)))
518
519 -- -----------------------------------------------------------------------------
520 -- When all the command-line options are in, we can process our package
521 -- settings and populate the package state.
522
523 mkPackageState
524     :: DynFlags
525     -> PackageConfigMap         -- initial database
526     -> [PackageId]              -- preloaded packages
527     -> PackageId                -- this package
528     -> IO (PackageState,
529            [PackageId],         -- new packages to preload
530            PackageId) -- this package, might be modified if the current
531
532                       -- package is a wired-in package.
533
534 mkPackageState dflags orig_pkg_db preload0 this_package = do
535   --
536   -- Modify the package database according to the command-line flags
537   -- (-package, -hide-package, -ignore-package, -hide-all-packages).
538   --
539   let flags = reverse (packageFlags dflags)
540   let pkgs0 = eltsUFM orig_pkg_db
541   pkgs1 <- foldM applyPackageFlag pkgs0 flags
542
543   -- Here we build up a set of the packages mentioned in -package
544   -- flags on the command line; these are called the "preload"
545   -- packages.  we link these packages in eagerly.  The preload set
546   -- should contain at least rts & base, which is why we pretend that
547   -- the command line contains -package rts & -package base.
548   --
549   let new_preload_packages = 
550         map package (pickPackages pkgs0 [ p | ExposePackage p <- flags ])
551
552   -- hide packages that are subsumed by later versions
553   pkgs2 <- hideOldPackages dflags pkgs1
554
555   -- sort out which packages are wired in
556   (pkgs3, preload1, new_this_pkg)
557         <- findWiredInPackages dflags pkgs2 new_preload_packages this_package
558
559   let ignored = map packageConfigId $
560                    pickPackages pkgs0 [ p | IgnorePackage p <- flags ]
561   pkgs <- elimDanglingDeps dflags pkgs3 ignored
562
563   let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
564
565       -- add base & rts to the preload packages
566       basicLinkedPackages
567        | dopt Opt_AutoLinkPackages dflags
568           = filter (flip elemUFM pkg_db) [basePackageId, rtsPackageId]
569        | otherwise = []
570       -- but in any case remove the current package from the set of
571       -- preloaded packages so that base/rts does not end up in the
572       -- set up preloaded package when we are just building it
573       preload2 = nub (filter (/= new_this_pkg)
574                              (basicLinkedPackages ++ map mkPackageId preload1))
575
576   -- Close the preload packages with their dependencies
577   dep_preload <- closeDeps pkg_db (zip preload2 (repeat Nothing))
578   let new_dep_preload = filter (`notElem` preload0) dep_preload
579
580   let pstate = PackageState{ preloadPackages     = dep_preload,
581                              pkgIdMap            = pkg_db,
582                              moduleToPkgConfAll  = mkModuleMap pkg_db
583                            }
584
585   return (pstate, new_dep_preload, new_this_pkg)
586
587
588 -- -----------------------------------------------------------------------------
589 -- Make the mapping from module to package info
590
591 mkModuleMap
592   :: PackageConfigMap
593   -> UniqFM [(PackageConfig, Bool)]
594 mkModuleMap pkg_db = foldr extend_modmap emptyUFM pkgids
595   where
596         pkgids = map packageConfigId (eltsUFM pkg_db)
597         
598         extend_modmap pkgid modmap =
599                 addListToUFM_C (++) modmap 
600                    ([(m, [(pkg, True)])  | m <- exposed_mods] ++
601                     [(m, [(pkg, False)]) | m <- hidden_mods])
602           where
603                 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
604                 exposed_mods = exposedModules pkg
605                 hidden_mods  = hiddenModules pkg
606
607 pprPkg :: PackageConfig -> SDoc
608 pprPkg p = text (display (package p))
609
610 -- -----------------------------------------------------------------------------
611 -- Extracting information from the packages in scope
612
613 -- Many of these functions take a list of packages: in those cases,
614 -- the list is expected to contain the "dependent packages",
615 -- i.e. those packages that were found to be depended on by the
616 -- current module/program.  These can be auto or non-auto packages, it
617 -- doesn't really matter.  The list is always combined with the list
618 -- of preload (command-line) packages to determine which packages to
619 -- use.
620
621 -- | Find all the include directories in these and the preload packages
622 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
623 getPackageIncludePath dflags pkgs =
624   collectIncludeDirs `fmap` getPreloadPackagesAnd dflags pkgs
625
626 collectIncludeDirs :: [PackageConfig] -> [FilePath] 
627 collectIncludeDirs ps = nub (filter notNull (concatMap includeDirs ps))
628
629 -- | Find all the library paths in these and the preload packages
630 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
631 getPackageLibraryPath dflags pkgs =
632   collectLibraryPaths `fmap` getPreloadPackagesAnd dflags pkgs
633
634 collectLibraryPaths :: [PackageConfig] -> [FilePath]
635 collectLibraryPaths ps = nub (filter notNull (concatMap libraryDirs ps))
636
637 -- | Find all the link options in these and the preload packages
638 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
639 getPackageLinkOpts dflags pkgs = 
640   collectLinkOpts dflags `fmap` getPreloadPackagesAnd dflags pkgs
641
642 collectLinkOpts :: DynFlags -> [PackageConfig] -> [String]
643 collectLinkOpts dflags ps = concat (map all_opts ps)
644   where
645         libs p     = packageHsLibs dflags p ++ extraLibraries p
646         all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
647
648 packageHsLibs :: DynFlags -> PackageConfig -> [String]
649 packageHsLibs dflags p = map (mkDynName . addSuffix) (hsLibraries p)
650   where
651         tag = buildTag dflags
652         rts_tag = rtsBuildTag dflags
653
654         mkDynName | opt_Static = id
655                   | otherwise = (++ ("-ghc" ++ cProjectVersion))
656
657         addSuffix rts@"HSrts"    = rts       ++ (expandTag rts_tag)
658         addSuffix other_lib      = other_lib ++ (expandTag tag)
659
660         expandTag t | null t = ""
661                     | otherwise = '_':t
662
663 -- | Find all the C-compiler options in these and the preload packages
664 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
665 getPackageExtraCcOpts dflags pkgs = do
666   ps <- getPreloadPackagesAnd dflags pkgs
667   return (concatMap ccOptions ps)
668
669 -- | Find all the package framework paths in these and the preload packages
670 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
671 getPackageFrameworkPath dflags pkgs = do
672   ps <- getPreloadPackagesAnd dflags pkgs
673   return (nub (filter notNull (concatMap frameworkDirs ps)))
674
675 -- | Find all the package frameworks in these and the preload packages
676 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
677 getPackageFrameworks dflags pkgs = do
678   ps <- getPreloadPackagesAnd dflags pkgs
679   return (concatMap frameworks ps)
680
681 -- -----------------------------------------------------------------------------
682 -- Package Utils
683
684 -- | Takes a 'Module', and if the module is in a package returns 
685 -- @(pkgconf, exposed)@ where pkgconf is the PackageConfig for that package,
686 -- and exposed is @True@ if the package exposes the module.
687 lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
688 lookupModuleInAllPackages dflags m =
689   case lookupUFM (moduleToPkgConfAll (pkgState dflags)) m of
690         Nothing -> []
691         Just ps -> ps
692
693 -- | Find all the 'PackageConfig' in both the preload packages from 'DynFlags' and corresponding to the list of
694 -- 'PackageConfig's
695 getPreloadPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
696 getPreloadPackagesAnd dflags pkgids =
697   let 
698       state   = pkgState dflags
699       pkg_map = pkgIdMap state
700       preload = preloadPackages state
701       pairs = zip pkgids (repeat Nothing)
702   in do
703   all_pkgs <- throwErr (foldM (add_package pkg_map) preload pairs)
704   return (map (getPackageDetails state) all_pkgs)
705
706 -- Takes a list of packages, and returns the list with dependencies included,
707 -- in reverse dependency order (a package appears before those it depends on).
708 closeDeps :: PackageConfigMap -> [(PackageId, Maybe PackageId)]
709         -> IO [PackageId]
710 closeDeps pkg_map ps = throwErr (closeDepsErr pkg_map ps)
711
712 throwErr :: MaybeErr Message a -> IO a
713 throwErr m = case m of
714                 Failed e    -> ghcError (CmdLineError (showSDoc e))
715                 Succeeded r -> return r
716
717 closeDepsErr :: PackageConfigMap -> [(PackageId,Maybe PackageId)]
718         -> MaybeErr Message [PackageId]
719 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
720
721 -- internal helper
722 add_package :: PackageConfigMap -> [PackageId] -> (PackageId,Maybe PackageId)
723         -> MaybeErr Message [PackageId]
724 add_package pkg_db ps (p, mb_parent)
725   | p `elem` ps = return ps     -- Check if we've already added this package
726   | otherwise =
727       case lookupPackage pkg_db p of
728         Nothing -> Failed (missingPackageMsg (packageIdString p) <> 
729                            missingDependencyMsg mb_parent)
730         Just pkg -> do
731            -- Add the package's dependents also
732            let deps = map mkPackageId (depends pkg)
733            ps' <- foldM (add_package pkg_db) ps (zip deps (repeat (Just p)))
734            return (p : ps')
735
736 missingPackageErr :: String -> IO [PackageConfig]
737 missingPackageErr p = ghcError (CmdLineError (showSDoc (missingPackageMsg p)))
738
739 missingPackageMsg :: String -> SDoc
740 missingPackageMsg p = ptext (sLit "unknown package:") <+> text p
741
742 missingDependencyMsg :: Maybe PackageId -> SDoc
743 missingDependencyMsg Nothing = empty
744 missingDependencyMsg (Just parent)
745   = space <> parens (ptext (sLit "dependency of") <+> ftext (packageIdFS parent))
746
747 -- -----------------------------------------------------------------------------
748
749 -- | Will the 'Name' come from a dynamically linked library?
750 isDllName :: PackageId -> Name -> Bool
751 isDllName this_pkg name
752   | opt_Static = False
753   | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
754   | otherwise = False  -- no, it is not even an external name
755
756 -- -----------------------------------------------------------------------------
757 -- Displaying packages
758
759 -- | Show package info on console, if verbosity is >= 3
760 dumpPackages :: DynFlags -> IO ()
761 dumpPackages dflags
762   = do  let pkg_map = pkgIdMap (pkgState dflags)
763         putMsg dflags $
764               vcat (map (text . showInstalledPackageInfo
765                               . packageConfigToInstalledPackageInfo)
766                         (eltsUFM pkg_map))
767 \end{code}