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