[project @ 2005-09-18 07:09:50 by wolfgang]
[ghc-hetmet.git] / ghc / compiler / main / Packages.lhs
1 %
2 % (c) The University of Glasgow, 2000
3 %
4 \section{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         PackageIdH(..), isHomePackage,
16         PackageState(..), 
17         initPackages,
18         getPackageDetails,
19         checkForPackageConflicts,
20         lookupModuleInAllPackages,
21
22         HomeModules, mkHomeModules, isHomeModule,
23
24         -- * Inspecting the set of packages in scope
25         getPackageIncludePath,
26         getPackageCIncludes,
27         getPackageLibraryPath,
28         getPackageLinkOpts,
29         getPackageExtraCcOpts,
30         getPackageFrameworkPath,
31         getPackageFrameworks,
32         getExplicitPackagesAnd,
33
34         -- * Utils
35         isDllName
36     )
37 where
38
39 #include "HsVersions.h"
40
41 import PackageConfig    
42 import SysTools         ( getTopDir, getPackageConfigPath )
43 import ParsePkgConf     ( loadPackageConfig )
44 import DynFlags         ( dopt, DynFlag(..), DynFlags(..), PackageFlag(..) )
45 import StaticFlags      ( opt_Static )
46 import Config           ( cProjectVersion )
47 import Name             ( Name, nameModule_maybe )
48 import UniqFM
49 import Module
50 import FiniteMap
51 import UniqSet
52 import Util
53 import Maybes           ( expectJust, MaybeErr(..) )
54 import Panic
55 import Outputable
56
57 #if __GLASGOW_HASKELL__ >= 603
58 import System.Directory ( getAppUserDataDirectory )
59 #else
60 import Compat.Directory ( getAppUserDataDirectory )
61 #endif
62
63 import Distribution.InstalledPackageInfo
64 import Distribution.Package
65 import Distribution.Version
66 import Data.Maybe       ( isNothing )
67 import System.Directory ( doesFileExist )
68 import Control.Monad    ( foldM )
69 import Data.List        ( nub, partition, sortBy )
70
71 #ifdef mingw32_TARGET_OS
72 import Data.List        ( isPrefixOf )
73 #endif
74 import Data.List        ( isSuffixOf )
75
76 import FastString
77 import EXCEPTION        ( throwDyn )
78 import ErrUtils         ( debugTraceMsg, putMsg, Message )
79
80 -- ---------------------------------------------------------------------------
81 -- The Package state
82
83 -- Package state is all stored in DynFlags, including the details of
84 -- all packages, which packages are exposed, and which modules they
85 -- provide.
86
87 -- The package state is computed by initPackages, and kept in DynFlags.
88 --
89 --   * -package <pkg> causes <pkg> to become exposed, and all other packages 
90 --      with the same name to become hidden.
91 -- 
92 --   * -hide-package <pkg> causes <pkg> to become hidden.
93 -- 
94 --   * Let exposedPackages be the set of packages thus exposed.  
95 --     Let depExposedPackages be the transitive closure from exposedPackages of
96 --     their dependencies.
97 --
98 --   * It is an error for any two packages in depExposedPackages to provide the
99 --     same module.
100 -- 
101 --   * When searching for a module from an explicit import declaration,
102 --     only the exposed modules in exposedPackages are valid.
103 --
104 --   * When searching for a module from an implicit import, all modules
105 --     from depExposedPackages are valid.
106 --
107 --   * When linking in a comp manager mode, we link in packages the
108 --     program depends on (the compiler knows this list by the
109 --     time it gets to the link step).  Also, we link in all packages
110 --     which were mentioned with explicit -package flags on the command-line,
111 --     or are a transitive dependency of same, or are "base"/"rts".
112 --     The reason for (b) is that we might need packages which don't
113 --     contain any Haskell modules, and therefore won't be discovered
114 --     by the normal mechanism of dependency tracking.
115
116
117 -- One important thing that the package state provides is a way to
118 -- tell, for a given module, whether it is part of the current package
119 -- or not.  We need to know this for two reasons:
120 --
121 --  * generating cross-DLL calls is different from intra-DLL calls 
122 --    (see below).
123 --  * we don't record version information in interface files for entities
124 --    in a different package.
125 -- 
126 -- Notes on DLLs
127 -- ~~~~~~~~~~~~~
128 -- When compiling module A, which imports module B, we need to 
129 -- know whether B will be in the same DLL as A.  
130 --      If it's in the same DLL, we refer to B_f_closure
131 --      If it isn't, we refer to _imp__B_f_closure
132 -- When compiling A, we record in B's Module value whether it's
133 -- in a different DLL, by setting the DLL flag.
134
135 data PackageState = PackageState {
136
137   explicitPackages      :: [PackageId],
138         -- The packages we're going to link in eagerly.  This list
139         -- should be in reverse dependency order; that is, a package
140         -- is always mentioned before the packages it depends on.
141
142   origPkgIdMap          :: PackageConfigMap, -- PackageId   -> PackageConfig
143         -- the full package database
144
145   pkgIdMap              :: PackageConfigMap, -- PackageId   -> PackageConfig
146         -- Derived from origPkgIdMap.
147         -- The exposed flags are adjusted according to -package and
148         -- -hide-package flags, and -ignore-package removes packages.
149
150   moduleToPkgConfAll    :: ModuleEnv [(PackageConfig,Bool)],
151         -- Derived from pkgIdMap.       
152         -- Maps Module to (pkgconf,exposed), where pkgconf is the
153         -- PackageConfig for the package containing the module, and
154         -- exposed is True if the package exposes that module.
155
156   -- The PackageIds of some known packages
157   basePackageId         :: PackageIdH,
158   rtsPackageId          :: PackageIdH,
159   haskell98PackageId    :: PackageIdH,
160   thPackageId           :: PackageIdH
161   }
162
163 data PackageIdH 
164    = HomePackage                -- The "home" package is the package curently
165                                 -- being compiled
166    | ExtPackage PackageId       -- An "external" package is any other package
167
168
169 isHomePackage :: PackageIdH -> Bool
170 isHomePackage HomePackage    = True
171 isHomePackage (ExtPackage _) = False
172
173 -- A PackageConfigMap maps a PackageId to a PackageConfig
174 type PackageConfigMap = UniqFM PackageConfig
175
176 emptyPackageConfigMap :: PackageConfigMap
177 emptyPackageConfigMap = emptyUFM
178
179 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
180 lookupPackage = lookupUFM
181
182 extendPackageConfigMap
183    :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
184 extendPackageConfigMap pkg_map new_pkgs 
185   = foldl add pkg_map new_pkgs
186   where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
187
188 getPackageDetails :: PackageState -> PackageId -> PackageConfig
189 getPackageDetails dflags ps = expectJust "getPackageDetails" (lookupPackage (pkgIdMap dflags) ps)
190
191 -- ----------------------------------------------------------------------------
192 -- Loading the package config files and building up the package state
193
194 -- | Call this after parsing the DynFlags.  It reads the package
195 -- configuration files, and sets up various internal tables of package
196 -- information, according to the package-related flags on the
197 -- command-line (@-package@, @-hide-package@ etc.)
198 initPackages :: DynFlags -> IO DynFlags
199 initPackages dflags = do 
200   pkg_map <- readPackageConfigs dflags; 
201   state <- mkPackageState dflags pkg_map
202   return dflags{ pkgState = state }
203
204 -- -----------------------------------------------------------------------------
205 -- Reading the package database(s)
206
207 readPackageConfigs :: DynFlags -> IO PackageConfigMap
208 readPackageConfigs dflags = do
209         -- System one always comes first
210    system_pkgconf <- getPackageConfigPath
211    pkg_map1 <- readPackageConfig dflags emptyPackageConfigMap system_pkgconf
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    (exists, pkgconf) <- catch (do
218       appdir <- getAppUserDataDirectory "ghc"
219       let 
220          pkgconf = appdir
221                    `joinFileName` (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
222                    `joinFileName` "package.conf"
223       flg <- doesFileExist pkgconf
224       return (flg, pkgconf))
225        -- gobble them all up and turn into False.
226       (\ _ -> return (False, ""))
227    pkg_map2 <- if (dopt Opt_ReadUserPackageConf dflags && exists)
228                   then readPackageConfig dflags pkg_map1 pkgconf
229                   else return pkg_map1
230
231         -- Read all the ones mentioned in -package-conf flags
232    pkg_map <- foldM (readPackageConfig dflags) pkg_map2
233                  (extraPkgConfs dflags)
234
235    return pkg_map
236
237
238 readPackageConfig
239    :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
240 readPackageConfig dflags pkg_map conf_file = do
241   debugTraceMsg dflags 2 ("Using package config file: " ++ conf_file)
242   proto_pkg_configs <- loadPackageConfig conf_file
243   top_dir           <- getTopDir
244   let pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
245       pkg_configs2 = maybeHidePackages dflags pkg_configs1
246   return (extendPackageConfigMap pkg_map pkg_configs2)
247
248 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
249 maybeHidePackages dflags pkgs
250   | dopt Opt_HideAllPackages dflags = map hide pkgs
251   | otherwise                       = pkgs
252   where
253     hide pkg = pkg{ exposed = False }
254
255 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
256 -- Replace the string "$topdir" at the beginning of a path
257 -- with the current topdir (obtained from the -B option).
258 mungePackagePaths top_dir ps = map munge_pkg ps
259  where 
260   munge_pkg p = p{ importDirs  = munge_paths (importDirs p),
261                    includeDirs = munge_paths (includeDirs p),
262                    libraryDirs = munge_paths (libraryDirs p),
263                    frameworkDirs = munge_paths (frameworkDirs p) }
264
265   munge_paths = map munge_path
266
267   munge_path p 
268           | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
269           | otherwise                               = p
270
271
272 -- -----------------------------------------------------------------------------
273 -- When all the command-line options are in, we can process our package
274 -- settings and populate the package state.
275
276 mkPackageState :: DynFlags -> PackageConfigMap -> IO PackageState
277 mkPackageState dflags orig_pkg_db = do
278   --
279   -- Modify the package database according to the command-line flags
280   -- (-package, -hide-package, -ignore-package, -hide-all-packages).
281   --
282   -- Also, here we build up a set of the packages mentioned in -package
283   -- flags on the command line; these are called the "explicit" packages.
284   -- we link these packages in eagerly.  The explicit set should contain
285   -- at least rts & base, which is why we pretend that the command line
286   -- contains -package rts & -package base.
287   --
288   let
289         flags = reverse (packageFlags dflags)
290
291         procflags pkgs expl [] = return (pkgs,expl)
292         procflags pkgs expl (ExposePackage str : flags) = do
293            case pick str pkgs of
294                 Nothing -> missingPackageErr str
295                 Just (p,ps) -> procflags (p':ps') expl' flags
296                   where pkgid = packageConfigId p
297                         p' = p {exposed=True}
298                         ps' = hideAll (pkgName (package p)) ps
299                         expl' = addOneToUniqSet expl pkgid
300         procflags pkgs expl (HidePackage str : flags) = do
301            case partition (matches str) pkgs of
302                 ([],_)   -> missingPackageErr str
303                 (ps,qs) -> procflags (map hide ps ++ qs) expl flags
304                   where hide p = p {exposed=False}
305         procflags pkgs expl (IgnorePackage str : flags) = do
306            case partition (matches str) pkgs of
307                 (ps,qs) -> procflags qs expl flags
308                 -- missing package is not an error for -ignore-package,
309                 -- because a common usage is to -ignore-package P as
310                 -- a preventative measure just in case P exists.
311
312         pick str pkgs
313           = case partition (matches str) pkgs of
314                 ([],_) -> Nothing
315                 (ps,rest) -> 
316                    case sortBy (flip (comparing (pkgVersion.package))) ps of
317                         (p:ps) -> Just (p, ps ++ rest)
318                         _ -> panic "Packages.pick"
319
320         comparing f a b = f a `compare` f b
321
322         -- A package named on the command line can either include the
323         -- version, or just the name if it is unambiguous.
324         matches str p
325                 =  str == showPackageId (package p)
326                 || str == pkgName (package p)
327
328         -- When a package is requested to be exposed, we hide all other
329         -- packages with the same name.
330         hideAll name ps = map maybe_hide ps
331           where maybe_hide p | pkgName (package p) == name = p {exposed=False}
332                              | otherwise                   = p
333   --
334   (pkgs1,explicit) <- procflags (eltsUFM orig_pkg_db) emptyUniqSet flags
335   --
336   -- hide all packages for which there is also a later version
337   -- that is already exposed.  This just makes it non-fatal to have two
338   -- versions of a package exposed, which can happen if you install a
339   -- later version of a package in the user database, for example.
340   --
341   let
342         pkgs2 = map maybe_hide pkgs1
343            where maybe_hide p
344                    | a_later_version_is_exposed = p {exposed=False}
345                    | otherwise                  = p
346                   where myname = pkgName (package p)
347                         myversion = pkgVersion (package p)
348                         a_later_version_is_exposed
349                           = not (null [ p | p <- pkgs1, let pkg = package p,
350                                             pkgName pkg == myname,
351                                             pkgVersion pkg > myversion ])
352   --
353   -- Eliminate any packages which have dangling dependencies (perhaps
354   -- because the package was removed by -ignore-package).
355   --
356   let
357         elimDanglingDeps pkgs = 
358            case partition (hasDanglingDeps pkgs) pkgs of
359               ([],ps) -> ps
360               (ps,qs) -> elimDanglingDeps qs
361
362         hasDanglingDeps pkgs p = any dangling (depends p)
363           where dangling pid = pid `notElem` all_pids
364                 all_pids = map package pkgs
365   --
366   let pkgs = elimDanglingDeps pkgs2
367       pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
368   --
369   -- Find the transitive closure of dependencies of exposed
370   --
371   let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
372   dep_exposed <- closeDeps pkg_db exposed_pkgids
373   --
374   -- Look up some known PackageIds
375   --
376   let
377         lookupPackageByName :: FastString -> PackageIdH
378         lookupPackageByName nm = 
379           case [ conf | p <- dep_exposed,
380                         Just conf <- [lookupPackage pkg_db p],
381                         nm == mkFastString (pkgName (package conf)) ] of
382                 []     -> HomePackage
383                 (p:ps) -> ExtPackage (mkPackageId (package p))
384
385         -- Get the PackageIds for some known packages (we know the names,
386         -- but we don't know the versions).  Some of these packages might
387         -- not exist in the database, so they are Maybes.
388         basePackageId           = lookupPackageByName basePackageName
389         rtsPackageId            = lookupPackageByName rtsPackageName
390         haskell98PackageId      = lookupPackageByName haskell98PackageName
391         thPackageId             = lookupPackageByName thPackageName
392
393         -- add base & rts to the explicit packages
394         basicLinkedPackages = [basePackageId,rtsPackageId]
395         explicit' = addListToUniqSet explicit 
396                         [ p | ExtPackage p <- basicLinkedPackages ]
397   --
398   -- Close the explicit packages with their dependencies
399   --
400   dep_explicit <- closeDeps pkg_db (uniqSetToList explicit')
401   --
402   -- Build up a mapping from Module -> PackageConfig for all modules.
403   -- Discover any conflicts at the same time, and factor in the new exposed
404   -- status of each package.
405   --
406   let mod_map = mkModuleMap pkg_db dep_exposed
407
408   return PackageState{ explicitPackages     = dep_explicit,
409                        origPkgIdMap         = orig_pkg_db,
410                        pkgIdMap             = pkg_db,
411                        moduleToPkgConfAll   = mod_map,
412                        basePackageId        = basePackageId,
413                        rtsPackageId         = rtsPackageId,
414                        haskell98PackageId   = haskell98PackageId,
415                        thPackageId          = thPackageId
416                      }
417   -- done!
418
419 basePackageName      = FSLIT("base")
420 rtsPackageName       = FSLIT("rts")
421 haskell98PackageName = FSLIT("haskell98")
422 thPackageName        = FSLIT("template-haskell")
423                                 -- Template Haskell libraries in here
424
425 mkModuleMap
426   :: PackageConfigMap
427   -> [PackageId]
428   -> ModuleEnv [(PackageConfig, Bool)]
429 mkModuleMap pkg_db pkgs = foldr extend_modmap emptyUFM pkgs
430   where
431         extend_modmap pkgname modmap =
432                 addListToUFM_C (++) modmap 
433                     [(m, [(pkg, m `elem` exposed_mods)]) | m <- all_mods]
434           where
435                 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgname)
436                 exposed_mods = map mkModule (exposedModules pkg)
437                 hidden_mods  = map mkModule (hiddenModules pkg)
438                 all_mods = exposed_mods ++ hidden_mods
439
440 -- -----------------------------------------------------------------------------
441 -- Check for conflicts in the program.
442
443 -- | A conflict arises if the program contains two modules with the same
444 -- name, which can arise if the program depends on multiple packages that
445 -- expose the same module, or if the program depends on a package that
446 -- contains a module also present in the program (the "home package").
447 --
448 checkForPackageConflicts
449    :: DynFlags
450    -> [Module]          -- modules in the home package
451    -> [PackageId]       -- packages on which the program depends
452    -> MaybeErr Message ()
453
454 checkForPackageConflicts dflags mods pkgs = do
455     let 
456         state   = pkgState dflags
457         pkg_db  = pkgIdMap state
458     --
459     dep_pkgs <- closeDepsErr pkg_db pkgs
460
461     let 
462         extend_modmap pkgname modmap  =
463                 addListToFM_C (++) modmap
464                     [(m, [(pkg, m `elem` exposed_mods)]) | m <- all_mods]
465           where
466                 pkg = expectJust "checkForPackageConflicts" 
467                                 (lookupPackage pkg_db pkgname)
468                 exposed_mods = map mkModule (exposedModules pkg)
469                 hidden_mods  = map mkModule (hiddenModules pkg)
470                 all_mods = exposed_mods ++ hidden_mods
471
472         mod_map = foldr extend_modmap emptyFM pkgs
473         mod_map_list :: [(Module,[(PackageConfig,Bool)])]
474         mod_map_list = fmToList mod_map
475
476         overlaps = [ (m, map fst ps) | (m,ps@(_:_:_)) <- mod_map_list ]
477     --
478     if not (null overlaps)
479         then Failed (pkgOverlapError overlaps)
480         else do
481
482     let 
483         overlap_mods = [ (mod,pkg)
484                        | mod <- mods,
485                          Just ((pkg,_):_) <- [lookupFM mod_map mod] ]    
486                                 -- will be only one package here
487     if not (null overlap_mods)
488         then Failed (modOverlapError overlap_mods)
489         else do
490
491     return ()
492        
493 pkgOverlapError overlaps =  vcat (map msg overlaps)
494   where 
495         msg (mod,pkgs) =
496            text "conflict: module" <+> quotes (ppr mod)
497                  <+> ptext SLIT("is present in multiple packages:")
498                  <+> hsep (punctuate comma (map (text.showPackageId.package) pkgs))
499
500 modOverlapError overlaps =   vcat (map msg overlaps)
501   where 
502         msg (mod,pkg) = fsep [
503                 text "conflict: module",
504                 quotes (ppr mod),
505                 ptext SLIT("belongs to the current program/library"),
506                 ptext SLIT("and also to package"),
507                 text (showPackageId (package pkg)) ]
508
509 -- -----------------------------------------------------------------------------
510 -- Extracting information from the packages in scope
511
512 -- Many of these functions take a list of packages: in those cases,
513 -- the list is expected to contain the "dependent packages",
514 -- i.e. those packages that were found to be depended on by the
515 -- current module/program.  These can be auto or non-auto packages, it
516 -- doesn't really matter.  The list is always combined with the list
517 -- of explicit (command-line) packages to determine which packages to
518 -- use.
519
520 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
521 getPackageIncludePath dflags pkgs = do
522   ps <- getExplicitPackagesAnd dflags pkgs
523   return (nub (filter notNull (concatMap includeDirs ps)))
524
525         -- includes are in reverse dependency order (i.e. rts first)
526 getPackageCIncludes :: [PackageConfig] -> IO [String]
527 getPackageCIncludes pkg_configs = do
528   return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
529
530 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
531 getPackageLibraryPath dflags pkgs = do 
532   ps <- getExplicitPackagesAnd dflags pkgs
533   return (nub (filter notNull (concatMap libraryDirs ps)))
534
535 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
536 getPackageLinkOpts dflags pkgs = do
537   ps <- getExplicitPackagesAnd dflags pkgs
538   let tag = buildTag dflags
539       rts_tag = rtsBuildTag dflags
540   let 
541         imp        = if opt_Static then "" else "_dyn"
542         libs p     = map ((++imp) . addSuffix) (hACK (hsLibraries p))
543                          ++ hACK_dyn (extraLibraries p)
544         all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
545
546         suffix     = if null tag then "" else  '_':tag
547         rts_suffix = if null rts_tag then "" else  '_':rts_tag
548
549         addSuffix rts@"HSrts"    = rts       ++ rts_suffix
550         addSuffix other_lib      = other_lib ++ suffix
551
552         -- This is a hack that's even more horrible (and hopefully more temporary)
553         -- than the one below. HSbase_cbits and friends require the _dyn suffix
554         -- for dynamic linking, but not _p or other 'way' suffix. So we just add
555         -- _dyn to extraLibraries if they already have a _cbits suffix.
556         
557         hACK_dyn = map hack
558           where hack lib | not static && "_cbits" `isSuffixOf` lib = lib ++ "_dyn"
559                          | otherwise = lib
560
561   return (concat (map all_opts ps))
562   where
563
564      -- This is a totally horrible (temporary) hack, for Win32.  Problem is
565      -- that package.conf for Win32 says that the main prelude lib is 
566      -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
567      -- in the GNU linker (PEi386 backend). However, we still only
568      -- have HSbase.a for static linking, not HSbase{1,2,3}.a
569      -- getPackageLibraries is called to find the .a's to add to the static
570      -- link line.  On Win32, this hACK detects HSbase{1,2,3} and 
571      -- replaces them with HSbase, so static linking still works.
572      -- Libraries needed for dynamic (GHCi) linking are discovered via
573      -- different route (in InteractiveUI.linkPackage).
574      -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
575      -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
576      -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
577      -- KAA 29 Mar  02: Same appalling hack for HSobjectio[1,2,3,4]
578      --
579      -- [sof 03/05: Renamed the (moribund) HSwin32 to HSwin_32 so as to
580      --  avoid filename conflicts with the 'Win32' package on a case-insensitive filesystem]
581      hACK libs
582 #      if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
583        = libs
584 #      else
585        = if   "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
586          then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
587          else
588          if   "HSwin_321" `elem` libs && "HSwin_322" `elem` libs
589          then "HSwin_32" : filter (not.(isPrefixOf "HSwin_32")) libs
590          else 
591          if   "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
592          then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
593          else 
594          libs
595 #      endif
596
597
598 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
599 getPackageExtraCcOpts dflags pkgs = do
600   ps <- getExplicitPackagesAnd dflags pkgs
601   return (concatMap ccOptions ps)
602
603 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
604 getPackageFrameworkPath dflags pkgs = do
605   ps <- getExplicitPackagesAnd dflags pkgs
606   return (nub (filter notNull (concatMap frameworkDirs ps)))
607
608 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
609 getPackageFrameworks dflags pkgs = do
610   ps <- getExplicitPackagesAnd dflags pkgs
611   return (concatMap frameworks ps)
612
613 -- -----------------------------------------------------------------------------
614 -- Package Utils
615
616 -- | Takes a Module, and if the module is in a package returns 
617 -- @(pkgconf,exposed)@ where pkgconf is the PackageConfig for that package,
618 -- and exposed is True if the package exposes the module.
619 lookupModuleInAllPackages :: DynFlags -> Module -> [(PackageConfig,Bool)]
620 lookupModuleInAllPackages dflags m =
621   case lookupModuleEnv (moduleToPkgConfAll (pkgState dflags)) m of
622         Nothing -> []
623         Just ps -> ps
624
625 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
626 getExplicitPackagesAnd dflags pkgids =
627   let 
628       state   = pkgState dflags
629       pkg_map = pkgIdMap state
630       expl    = explicitPackages state
631   in do
632   all_pkgs <- throwErr (foldM (add_package pkg_map) expl pkgids)
633   return (map (getPackageDetails state) all_pkgs)
634
635 -- Takes a list of packages, and returns the list with dependencies included,
636 -- in reverse dependency order (a package appears before those it depends on).
637 closeDeps :: PackageConfigMap -> [PackageId] -> IO [PackageId]
638 closeDeps pkg_map ps = throwErr (closeDepsErr pkg_map ps)
639
640 throwErr :: MaybeErr Message a -> IO a
641 throwErr m = case m of
642                 Failed e    -> throwDyn (CmdLineError (showSDoc e))
643                 Succeeded r -> return r
644
645 closeDepsErr :: PackageConfigMap -> [PackageId]
646         -> MaybeErr Message [PackageId]
647 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
648
649 -- internal helper
650 add_package :: PackageConfigMap -> [PackageId] -> PackageId 
651         -> MaybeErr Message [PackageId]
652 add_package pkg_db ps p
653   | p `elem` ps = return ps     -- Check if we've already added this package
654   | otherwise =
655       case lookupPackage pkg_db p of
656         Nothing -> Failed (missingPackageErr (packageIdString p))
657         Just pkg -> do
658            -- Add the package's dependents also
659            let deps = map mkPackageId (depends pkg)
660            ps' <- foldM (add_package pkg_db) ps deps
661            return (p : ps')
662
663 missingPackageErr p = throwDyn (CmdLineError (showSDoc (missingPackageMsg p)))
664 missingPackageMsg p = ptext SLIT("unknown package:") <> text p
665
666 -- -----------------------------------------------------------------------------
667 -- The home module set
668
669 newtype HomeModules = HomeModules ModuleSet
670
671 mkHomeModules :: [Module] -> HomeModules
672 mkHomeModules = HomeModules . mkModuleSet
673
674 isHomeModule :: HomeModules -> Module -> Bool
675 isHomeModule (HomeModules set) mod  = elemModuleSet mod set
676
677 -- Determining whether a Name refers to something in another package or not.
678 -- Cross-package references need to be handled differently when dynamically-
679 -- linked libraries are involved.
680
681 isDllName :: HomeModules -> Name -> Bool
682 isDllName pdeps name
683   | opt_Static = False
684   | Just mod <- nameModule_maybe name = not (isHomeModule pdeps mod)
685   | otherwise = False  -- no, it is not even an external name
686
687 -- -----------------------------------------------------------------------------
688 -- Displaying packages
689
690 dumpPackages :: DynFlags -> IO ()
691 -- Show package info on console, if verbosity is >= 3
692 dumpPackages dflags
693   = do  let pkg_map = pkgIdMap (pkgState dflags)
694         putMsg $ showSDoc $
695               vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))
696 \end{code}