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