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