Follow library changes
[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                    haddockInterfaces = munge_paths (haddockInterfaces p),
265                    haddockHTMLs = munge_paths (haddockHTMLs p)
266                     }
267
268   munge_paths = map munge_path
269
270   munge_path p 
271           | Just p' <- maybePrefixMatch "$topdir"     p =            top_dir ++ p'
272           | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
273           | otherwise                               = p
274
275   toHttpPath p = "file:///" ++ p
276
277
278 -- -----------------------------------------------------------------------------
279 -- Modify our copy of the package database based on a package flag
280 -- (-package, -hide-package, -ignore-package).
281
282 applyPackageFlag
283    :: [PackageConfig]           -- Initial database
284    -> PackageFlag               -- flag to apply
285    -> IO [PackageConfig]        -- new database
286
287 applyPackageFlag pkgs flag = 
288   case flag of
289         ExposePackage str ->
290            case matchingPackages str pkgs of
291                 Nothing -> missingPackageErr str
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 (ps,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 (matches str) pkgs of
321         ([],_)    -> Nothing
322         (ps,rest) -> Just (sortByVersion ps, rest)
323   where
324         -- A package named on the command line can either include the
325         -- version, or just the name if it is unambiguous.
326         matches str p
327                 =  str == showPackageId (package p)
328                 || str == pkgName (package p)
329
330
331 pickPackages pkgs strs = 
332   [ p | p <- strs, Just (p:ps,_) <- [matchingPackages p pkgs] ]
333
334 sortByVersion = sortBy (flip (comparing (pkgVersion.package)))
335 comparing f a b = f a `compare` f b
336
337 -- -----------------------------------------------------------------------------
338 -- Hide old versions of packages
339
340 --
341 -- hide all packages for which there is also a later version
342 -- that is already exposed.  This just makes it non-fatal to have two
343 -- versions of a package exposed, which can happen if you install a
344 -- later version of a package in the user database, for example.
345 --
346 hideOldPackages :: DynFlags -> [PackageConfig] -> IO [PackageConfig]
347 hideOldPackages dflags pkgs = mapM maybe_hide pkgs
348   where maybe_hide p
349            | not (exposed p) = return p
350            | (p' : _) <- later_versions = do
351                 debugTraceMsg dflags 2 $
352                    (ptext SLIT("hiding package") <+> 
353                     text (showPackageId (package p)) <+>
354                     ptext SLIT("to avoid conflict with later version") <+>
355                     text (showPackageId (package p')))
356                 return (p {exposed=False})
357            | otherwise = return p
358           where myname = pkgName (package p)
359                 myversion = pkgVersion (package p)
360                 later_versions = [ p | p <- pkgs, exposed p,
361                                     let pkg = package p,
362                                     pkgName pkg == myname,
363                                     pkgVersion pkg > myversion ]
364
365 -- -----------------------------------------------------------------------------
366 -- Wired-in packages
367
368 findWiredInPackages
369    :: DynFlags
370    -> [PackageConfig]           -- database
371    -> [PackageIdentifier]       -- preload packages
372    -> PackageId                 -- this package
373    -> IO ([PackageConfig],
374           [PackageIdentifier],
375           PackageId)
376
377 findWiredInPackages dflags pkgs preload this_package = do
378   --
379   -- Now we must find our wired-in packages, and rename them to
380   -- their canonical names (eg. base-1.0 ==> base).
381   --
382   let
383         wired_in_pkgids = [ primPackageId,
384                             integerPackageId,
385                             basePackageId,
386                             rtsPackageId,
387                             haskell98PackageId,
388                             thPackageId,
389                             ndpPackageId ]
390
391         wired_in_names = map packageIdString wired_in_pkgids
392
393         -- find which package corresponds to each wired-in package
394         -- delete any other packages with the same name
395         -- update the package and any dependencies to point to the new
396         -- one.
397         --
398         -- When choosing which package to map to a wired-in package
399         -- name, we prefer exposed packages, and pick the latest
400         -- version.  To override the default choice, -hide-package
401         -- could be used to hide newer versions.
402         --
403         findWiredInPackage :: [PackageConfig] -> String
404                            -> IO (Maybe PackageIdentifier)
405         findWiredInPackage pkgs wired_pkg =
406            let all_ps = [ p | p <- pkgs, pkgName (package p) == wired_pkg ] in
407            case filter exposed all_ps of
408                 [] -> case all_ps of
409                         []   -> notfound
410                         many -> pick (head (sortByVersion many))
411                 many  -> pick (head (sortByVersion many))
412           where
413                 notfound = do
414                           debugTraceMsg dflags 2 $
415                             ptext SLIT("wired-in package ")
416                                  <> text wired_pkg
417                                  <> ptext SLIT(" not found.")
418                           return Nothing
419                 pick pkg = do
420                         debugTraceMsg dflags 2 $
421                             ptext SLIT("wired-in package ")
422                                  <> text wired_pkg
423                                  <> ptext SLIT(" mapped to ")
424                                  <> text (showPackageId (package pkg))
425                         return (Just (package pkg))
426
427
428   mb_wired_in_ids <- mapM (findWiredInPackage pkgs) wired_in_names
429   let 
430         wired_in_ids = catMaybes mb_wired_in_ids
431
432         deleteOtherWiredInPackages pkgs = filter ok pkgs
433           where ok p = pkgName (package p) `notElem` wired_in_names
434                      || package p `elem` wired_in_ids
435
436         updateWiredInDependencies pkgs = map upd_pkg pkgs
437           where upd_pkg p = p{ package = upd_pid (package p),
438                                depends = map upd_pid (depends p) }
439
440         upd_pid pid = case filter (== pid) wired_in_ids of
441                                 [] -> pid
442                                 (x:_) -> x{ pkgVersion = Version [] [] }
443
444         pkgs1 = deleteOtherWiredInPackages pkgs
445
446         pkgs2 = updateWiredInDependencies pkgs1
447
448         preload1 = map upd_pid preload
449
450         -- we must return an updated thisPackage, just in case we
451         -- are actually compiling one of the wired-in packages
452         Just old_this_pkg = unpackPackageId this_package
453         new_this_pkg = mkPackageId (upd_pid old_this_pkg)
454
455   return (pkgs2, preload1, new_this_pkg)
456
457 -- ----------------------------------------------------------------------------
458 --
459 -- Detect any packages that have missing dependencies, and also any
460 -- mutually-recursive groups of packages (loops in the package graph
461 -- are not allowed).  We do this by taking the least fixpoint of the
462 -- dependency graph, repeatedly adding packages whose dependencies are
463 -- satisfied until no more can be added.
464 --
465 elimDanglingDeps
466    :: DynFlags
467    -> [PackageConfig]
468    -> [PackageId]       -- ignored packages
469    -> IO [PackageConfig]
470
471 elimDanglingDeps dflags pkgs ignored = go [] pkgs'
472  where
473    pkgs' = filter (\p -> packageConfigId p `notElem` ignored) pkgs
474
475    go avail not_avail =
476      case partitionWith (depsAvailable avail) not_avail of
477         ([],        not_avail) -> do mapM_ reportElim not_avail; return avail
478         (new_avail, not_avail) -> go (new_avail ++ avail) (map fst not_avail)
479
480    depsAvailable :: [PackageConfig] -> PackageConfig
481                  -> Either PackageConfig (PackageConfig, [PackageIdentifier])
482    depsAvailable pkgs_ok pkg 
483         | null dangling = Left pkg
484         | otherwise     = Right (pkg, dangling)
485         where dangling = filter (`notElem` pids) (depends pkg)
486               pids = map package pkgs_ok
487
488    reportElim (p, deps) = 
489         debugTraceMsg dflags 2 $
490              (ptext SLIT("package") <+> pprPkg p <+> 
491                   ptext SLIT("will be ignored due to missing or recursive dependencies:") $$ 
492               nest 2 (hsep (map (text.showPackageId) deps)))
493
494 -- -----------------------------------------------------------------------------
495 -- When all the command-line options are in, we can process our package
496 -- settings and populate the package state.
497
498 mkPackageState
499     :: DynFlags
500     -> PackageConfigMap         -- initial database
501     -> [PackageId]              -- preloaded packages
502     -> PackageId                -- this package
503     -> IO (PackageState,
504            [PackageId],         -- new packages to preload
505            PackageId) -- this package, might be modified if the current
506
507                       -- package is a wired-in package.
508
509 mkPackageState dflags orig_pkg_db preload0 this_package = do
510   --
511   -- Modify the package database according to the command-line flags
512   -- (-package, -hide-package, -ignore-package, -hide-all-packages).
513   --
514   let flags = reverse (packageFlags dflags)
515   let pkgs0 = eltsUFM orig_pkg_db
516   pkgs1 <- foldM applyPackageFlag pkgs0 flags
517
518   -- Here we build up a set of the packages mentioned in -package
519   -- flags on the command line; these are called the "preload"
520   -- packages.  we link these packages in eagerly.  The preload set
521   -- should contain at least rts & base, which is why we pretend that
522   -- the command line contains -package rts & -package base.
523   --
524   let new_preload_packages = 
525         map package (pickPackages pkgs0 [ p | ExposePackage p <- flags ])
526
527   -- hide packages that are subsumed by later versions
528   pkgs2 <- hideOldPackages dflags pkgs1
529
530   -- sort out which packages are wired in
531   (pkgs3, preload1, new_this_pkg)
532         <- findWiredInPackages dflags pkgs2 new_preload_packages this_package
533
534   let ignored = map packageConfigId $
535                    pickPackages pkgs0 [ p | IgnorePackage p <- flags ]
536   pkgs <- elimDanglingDeps dflags pkgs3 ignored
537
538   let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
539       pkgids = map packageConfigId pkgs
540
541       -- add base & rts to the preload packages
542       basicLinkedPackages = filter (flip elemUFM pkg_db)
543                                  [basePackageId,rtsPackageId]
544       -- but in any case remove the current package from the set of
545       -- preloaded packages so that base/rts does not end up in the
546       -- set up preloaded package when we are just building it
547       preload2 = nub (filter (/= new_this_pkg)
548                              (basicLinkedPackages ++ map mkPackageId preload1))
549
550   -- Close the preload packages with their dependencies
551   dep_preload <- closeDeps pkg_db (zip preload2 (repeat Nothing))
552   let new_dep_preload = filter (`notElem` preload0) dep_preload
553
554   let pstate = PackageState{ preloadPackages     = dep_preload,
555                              pkgIdMap            = pkg_db,
556                              moduleToPkgConfAll  = mkModuleMap pkg_db
557                            }
558
559   return (pstate, new_dep_preload, new_this_pkg)
560
561
562 -- -----------------------------------------------------------------------------
563 -- Make the mapping from module to package info
564
565 mkModuleMap
566   :: PackageConfigMap
567   -> UniqFM [(PackageConfig, Bool)]
568 mkModuleMap pkg_db = foldr extend_modmap emptyUFM pkgids
569   where
570         pkgids = map packageConfigId (eltsUFM pkg_db)
571         
572         extend_modmap pkgid modmap =
573                 addListToUFM_C (++) modmap 
574                    ([(m, [(pkg, True)])  | m <- exposed_mods] ++
575                     [(m, [(pkg, False)]) | m <- hidden_mods])
576           where
577                 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
578                 exposed_mods = exposedModules pkg
579                 hidden_mods  = hiddenModules pkg
580
581 pprPkg :: PackageConfig -> SDoc
582 pprPkg p = text (showPackageId (package p))
583
584 -- -----------------------------------------------------------------------------
585 -- Extracting information from the packages in scope
586
587 -- Many of these functions take a list of packages: in those cases,
588 -- the list is expected to contain the "dependent packages",
589 -- i.e. those packages that were found to be depended on by the
590 -- current module/program.  These can be auto or non-auto packages, it
591 -- doesn't really matter.  The list is always combined with the list
592 -- of preload (command-line) packages to determine which packages to
593 -- use.
594
595 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
596 getPackageIncludePath dflags pkgs = do
597   ps <- getPreloadPackagesAnd dflags pkgs
598   return (nub (filter notNull (concatMap includeDirs ps)))
599
600         -- includes are in reverse dependency order (i.e. rts first)
601 getPackageCIncludes :: [PackageConfig] -> IO [String]
602 getPackageCIncludes pkg_configs = do
603   return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
604
605 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
606 getPackageLibraryPath dflags pkgs = do 
607   ps <- getPreloadPackagesAnd dflags pkgs
608   return (nub (filter notNull (concatMap libraryDirs ps)))
609
610 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
611 getPackageLinkOpts dflags pkgs = do
612   ps <- getPreloadPackagesAnd dflags pkgs
613   let tag = buildTag dflags
614       rts_tag = rtsBuildTag dflags
615   let 
616         mkDynName | opt_Static = id
617                   | otherwise = (++ ("-ghc" ++ cProjectVersion))
618         libs p     = map (mkDynName . addSuffix) (hsLibraries p)
619                          ++ extraLibraries p
620         all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
621
622         addSuffix rts@"HSrts"    = rts       ++ (expandTag rts_tag)
623         addSuffix other_lib      = other_lib ++ (expandTag tag)
624
625         expandTag t | null t = ""
626                     | otherwise = '_':t
627
628   return (concat (map all_opts ps))
629
630 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
631 getPackageExtraCcOpts dflags pkgs = do
632   ps <- getPreloadPackagesAnd dflags pkgs
633   return (concatMap ccOptions ps)
634
635 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
636 getPackageFrameworkPath dflags pkgs = do
637   ps <- getPreloadPackagesAnd dflags pkgs
638   return (nub (filter notNull (concatMap frameworkDirs ps)))
639
640 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
641 getPackageFrameworks dflags pkgs = do
642   ps <- getPreloadPackagesAnd dflags pkgs
643   return (concatMap frameworks ps)
644
645 -- -----------------------------------------------------------------------------
646 -- Package Utils
647
648 -- | Takes a Module, and if the module is in a package returns 
649 -- @(pkgconf,exposed)@ where pkgconf is the PackageConfig for that package,
650 -- and exposed is True if the package exposes the module.
651 lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
652 lookupModuleInAllPackages dflags m =
653   case lookupUFM (moduleToPkgConfAll (pkgState dflags)) m of
654         Nothing -> []
655         Just ps -> ps
656
657 getPreloadPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
658 getPreloadPackagesAnd dflags pkgids =
659   let 
660       state   = pkgState dflags
661       pkg_map = pkgIdMap state
662       preload = preloadPackages state
663       pairs = zip pkgids (repeat Nothing)
664   in do
665   all_pkgs <- throwErr (foldM (add_package pkg_map) preload pairs)
666   return (map (getPackageDetails state) all_pkgs)
667
668 -- Takes a list of packages, and returns the list with dependencies included,
669 -- in reverse dependency order (a package appears before those it depends on).
670 closeDeps :: PackageConfigMap -> [(PackageId, Maybe PackageId)]
671         -> IO [PackageId]
672 closeDeps pkg_map ps = throwErr (closeDepsErr pkg_map ps)
673
674 throwErr :: MaybeErr Message a -> IO a
675 throwErr m = case m of
676                 Failed e    -> throwDyn (CmdLineError (showSDoc e))
677                 Succeeded r -> return r
678
679 closeDepsErr :: PackageConfigMap -> [(PackageId,Maybe PackageId)]
680         -> MaybeErr Message [PackageId]
681 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
682
683 -- internal helper
684 add_package :: PackageConfigMap -> [PackageId] -> (PackageId,Maybe PackageId)
685         -> MaybeErr Message [PackageId]
686 add_package pkg_db ps (p, mb_parent)
687   | p `elem` ps = return ps     -- Check if we've already added this package
688   | otherwise =
689       case lookupPackage pkg_db p of
690         Nothing -> Failed (missingPackageMsg (packageIdString p) <> 
691                            missingDependencyMsg mb_parent)
692         Just pkg -> do
693            -- Add the package's dependents also
694            let deps = map mkPackageId (depends pkg)
695            ps' <- foldM (add_package pkg_db) ps (zip deps (repeat (Just p)))
696            return (p : ps')
697
698 missingPackageErr p = throwDyn (CmdLineError (showSDoc (missingPackageMsg p)))
699 missingPackageMsg p = ptext SLIT("unknown package:") <+> text p
700
701 missingDependencyMsg Nothing = empty
702 missingDependencyMsg (Just parent)
703   = space <> parens (ptext SLIT("dependency of") <+> ftext (packageIdFS parent))
704
705 -- -----------------------------------------------------------------------------
706
707 isDllName :: PackageId -> Name -> Bool
708 isDllName this_pkg name
709   | opt_Static = False
710   | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
711   | otherwise = False  -- no, it is not even an external name
712
713 -- -----------------------------------------------------------------------------
714 -- Displaying packages
715
716 dumpPackages :: DynFlags -> IO ()
717 -- Show package info on console, if verbosity is >= 3
718 dumpPackages dflags
719   = do  let pkg_map = pkgIdMap (pkgState dflags)
720         putMsg dflags $
721               vcat (map (text.showInstalledPackageInfo.to_ipi) (eltsUFM pkg_map))
722  where
723   to_ipi pkgconf@InstalledPackageInfo_{ exposedModules = e,
724                                         hiddenModules = h } = 
725     pkgconf{ exposedModules = map moduleNameString e,
726              hiddenModules  = map moduleNameString h }
727 \end{code}