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