21c5596b64ba28fefc8541013da2afc2e7f6757e
[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, exposed p,
350                                             let pkg = package p,
351                                             pkgName pkg == myname,
352                                             pkgVersion pkg > myversion ])
353   --
354   -- Eliminate any packages which have dangling dependencies (perhaps
355   -- because the package was removed by -ignore-package).
356   --
357   let
358         elimDanglingDeps pkgs = 
359            case partition (hasDanglingDeps pkgs) pkgs of
360               ([],ps) -> ps
361               (ps,qs) -> elimDanglingDeps qs
362
363         hasDanglingDeps pkgs p = any dangling (depends p)
364           where dangling pid = pid `notElem` all_pids
365                 all_pids = map package pkgs
366   --
367   let pkgs = elimDanglingDeps pkgs2
368       pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
369   --
370   -- Find the transitive closure of dependencies of exposed
371   --
372   let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
373   dep_exposed <- closeDeps pkg_db exposed_pkgids
374   --
375   -- Look up some known PackageIds
376   --
377   let
378         lookupPackageByName :: FastString -> PackageIdH
379         lookupPackageByName nm = 
380           case [ conf | p <- dep_exposed,
381                         Just conf <- [lookupPackage pkg_db p],
382                         nm == mkFastString (pkgName (package conf)) ] of
383                 []     -> HomePackage
384                 (p:ps) -> ExtPackage (mkPackageId (package p))
385
386         -- Get the PackageIds for some known packages (we know the names,
387         -- but we don't know the versions).  Some of these packages might
388         -- not exist in the database, so they are Maybes.
389         basePackageId           = lookupPackageByName basePackageName
390         rtsPackageId            = lookupPackageByName rtsPackageName
391         haskell98PackageId      = lookupPackageByName haskell98PackageName
392         thPackageId             = lookupPackageByName thPackageName
393
394         -- add base & rts to the explicit packages
395         basicLinkedPackages = [basePackageId,rtsPackageId]
396         explicit' = addListToUniqSet explicit 
397                         [ p | ExtPackage p <- basicLinkedPackages ]
398   --
399   -- Close the explicit packages with their dependencies
400   --
401   dep_explicit <- closeDeps pkg_db (uniqSetToList explicit')
402   --
403   -- Build up a mapping from Module -> PackageConfig for all modules.
404   -- Discover any conflicts at the same time, and factor in the new exposed
405   -- status of each package.
406   --
407   let mod_map = mkModuleMap pkg_db dep_exposed
408
409   return PackageState{ explicitPackages     = dep_explicit,
410                        origPkgIdMap         = orig_pkg_db,
411                        pkgIdMap             = pkg_db,
412                        moduleToPkgConfAll   = mod_map,
413                        basePackageId        = basePackageId,
414                        rtsPackageId         = rtsPackageId,
415                        haskell98PackageId   = haskell98PackageId,
416                        thPackageId          = thPackageId
417                      }
418   -- done!
419
420 basePackageName      = FSLIT("base")
421 rtsPackageName       = FSLIT("rts")
422 haskell98PackageName = FSLIT("haskell98")
423 thPackageName        = FSLIT("template-haskell")
424                                 -- Template Haskell libraries in here
425
426 mkModuleMap
427   :: PackageConfigMap
428   -> [PackageId]
429   -> ModuleEnv [(PackageConfig, Bool)]
430 mkModuleMap pkg_db pkgs = foldr extend_modmap emptyUFM pkgs
431   where
432         extend_modmap pkgname modmap =
433                 addListToUFM_C (++) modmap 
434                     [(m, [(pkg, m `elem` exposed_mods)]) | m <- all_mods]
435           where
436                 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgname)
437                 exposed_mods = map mkModule (exposedModules pkg)
438                 hidden_mods  = map mkModule (hiddenModules pkg)
439                 all_mods = exposed_mods ++ hidden_mods
440
441 -- -----------------------------------------------------------------------------
442 -- Check for conflicts in the program.
443
444 -- | A conflict arises if the program contains two modules with the same
445 -- name, which can arise if the program depends on multiple packages that
446 -- expose the same module, or if the program depends on a package that
447 -- contains a module also present in the program (the "home package").
448 --
449 checkForPackageConflicts
450    :: DynFlags
451    -> [Module]          -- modules in the home package
452    -> [PackageId]       -- packages on which the program depends
453    -> MaybeErr Message ()
454
455 checkForPackageConflicts dflags mods pkgs = do
456     let 
457         state   = pkgState dflags
458         pkg_db  = pkgIdMap state
459     --
460     dep_pkgs <- closeDepsErr pkg_db pkgs
461
462     let 
463         extend_modmap pkgname modmap  =
464                 addListToFM_C (++) modmap
465                     [(m, [(pkg, m `elem` exposed_mods)]) | m <- all_mods]
466           where
467                 pkg = expectJust "checkForPackageConflicts" 
468                                 (lookupPackage pkg_db pkgname)
469                 exposed_mods = map mkModule (exposedModules pkg)
470                 hidden_mods  = map mkModule (hiddenModules pkg)
471                 all_mods = exposed_mods ++ hidden_mods
472
473         mod_map = foldr extend_modmap emptyFM pkgs
474         mod_map_list :: [(Module,[(PackageConfig,Bool)])]
475         mod_map_list = fmToList mod_map
476
477         overlaps = [ (m, map fst ps) | (m,ps@(_:_:_)) <- mod_map_list ]
478     --
479     if not (null overlaps)
480         then Failed (pkgOverlapError overlaps)
481         else do
482
483     let 
484         overlap_mods = [ (mod,pkg)
485                        | mod <- mods,
486                          Just ((pkg,_):_) <- [lookupFM mod_map mod] ]    
487                                 -- will be only one package here
488     if not (null overlap_mods)
489         then Failed (modOverlapError overlap_mods)
490         else do
491
492     return ()
493        
494 pkgOverlapError overlaps =  vcat (map msg overlaps)
495   where 
496         msg (mod,pkgs) =
497            text "conflict: module" <+> quotes (ppr mod)
498                  <+> ptext SLIT("is present in multiple packages:")
499                  <+> hsep (punctuate comma (map (text.showPackageId.package) pkgs))
500
501 modOverlapError overlaps =   vcat (map msg overlaps)
502   where 
503         msg (mod,pkg) = fsep [
504                 text "conflict: module",
505                 quotes (ppr mod),
506                 ptext SLIT("belongs to the current program/library"),
507                 ptext SLIT("and also to package"),
508                 text (showPackageId (package pkg)) ]
509
510 -- -----------------------------------------------------------------------------
511 -- Extracting information from the packages in scope
512
513 -- Many of these functions take a list of packages: in those cases,
514 -- the list is expected to contain the "dependent packages",
515 -- i.e. those packages that were found to be depended on by the
516 -- current module/program.  These can be auto or non-auto packages, it
517 -- doesn't really matter.  The list is always combined with the list
518 -- of explicit (command-line) packages to determine which packages to
519 -- use.
520
521 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
522 getPackageIncludePath dflags pkgs = do
523   ps <- getExplicitPackagesAnd dflags pkgs
524   return (nub (filter notNull (concatMap includeDirs ps)))
525
526         -- includes are in reverse dependency order (i.e. rts first)
527 getPackageCIncludes :: [PackageConfig] -> IO [String]
528 getPackageCIncludes pkg_configs = do
529   return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
530
531 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
532 getPackageLibraryPath dflags pkgs = do 
533   ps <- getExplicitPackagesAnd dflags pkgs
534   return (nub (filter notNull (concatMap libraryDirs ps)))
535
536 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
537 getPackageLinkOpts dflags pkgs = do
538   ps <- getExplicitPackagesAnd dflags pkgs
539   let tag = buildTag dflags
540       rts_tag = rtsBuildTag dflags
541   let 
542         imp        = if opt_Static then "" else "_dyn"
543         libs p     = map ((++imp) . addSuffix) (hACK (hsLibraries p))
544                          ++ hACK_dyn (extraLibraries p)
545         all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
546
547         suffix     = if null tag then "" else  '_':tag
548         rts_suffix = if null rts_tag then "" else  '_':rts_tag
549
550         addSuffix rts@"HSrts"    = rts       ++ rts_suffix
551         addSuffix other_lib      = other_lib ++ suffix
552
553         -- This is a hack that's even more horrible (and hopefully more temporary)
554         -- than the one below. HSbase_cbits and friends require the _dyn suffix
555         -- for dynamic linking, but not _p or other 'way' suffix. So we just add
556         -- _dyn to extraLibraries if they already have a _cbits suffix.
557         
558         hACK_dyn = map hack
559           where hack lib | not opt_Static && "_cbits" `isSuffixOf` lib = lib ++ "_dyn"
560                          | otherwise = lib
561
562   return (concat (map all_opts ps))
563   where
564
565      -- This is a totally horrible (temporary) hack, for Win32.  Problem is
566      -- that package.conf for Win32 says that the main prelude lib is 
567      -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
568      -- in the GNU linker (PEi386 backend). However, we still only
569      -- have HSbase.a for static linking, not HSbase{1,2,3}.a
570      -- getPackageLibraries is called to find the .a's to add to the static
571      -- link line.  On Win32, this hACK detects HSbase{1,2,3} and 
572      -- replaces them with HSbase, so static linking still works.
573      -- Libraries needed for dynamic (GHCi) linking are discovered via
574      -- different route (in InteractiveUI.linkPackage).
575      -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
576      -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
577      -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
578      -- KAA 29 Mar  02: Same appalling hack for HSobjectio[1,2,3,4]
579      --
580      -- [sof 03/05: Renamed the (moribund) HSwin32 to HSwin_32 so as to
581      --  avoid filename conflicts with the 'Win32' package on a case-insensitive filesystem]
582      hACK libs
583 #      if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
584        = libs
585 #      else
586        = if   "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
587          then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
588          else
589          if   "HSwin_321" `elem` libs && "HSwin_322" `elem` libs
590          then "HSwin_32" : filter (not.(isPrefixOf "HSwin_32")) libs
591          else 
592          if   "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
593          then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
594          else 
595          libs
596 #      endif
597
598
599 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
600 getPackageExtraCcOpts dflags pkgs = do
601   ps <- getExplicitPackagesAnd dflags pkgs
602   return (concatMap ccOptions ps)
603
604 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
605 getPackageFrameworkPath dflags pkgs = do
606   ps <- getExplicitPackagesAnd dflags pkgs
607   return (nub (filter notNull (concatMap frameworkDirs ps)))
608
609 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
610 getPackageFrameworks dflags pkgs = do
611   ps <- getExplicitPackagesAnd dflags pkgs
612   return (concatMap frameworks ps)
613
614 -- -----------------------------------------------------------------------------
615 -- Package Utils
616
617 -- | Takes a Module, and if the module is in a package returns 
618 -- @(pkgconf,exposed)@ where pkgconf is the PackageConfig for that package,
619 -- and exposed is True if the package exposes the module.
620 lookupModuleInAllPackages :: DynFlags -> Module -> [(PackageConfig,Bool)]
621 lookupModuleInAllPackages dflags m =
622   case lookupModuleEnv (moduleToPkgConfAll (pkgState dflags)) m of
623         Nothing -> []
624         Just ps -> ps
625
626 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
627 getExplicitPackagesAnd dflags pkgids =
628   let 
629       state   = pkgState dflags
630       pkg_map = pkgIdMap state
631       expl    = explicitPackages state
632   in do
633   all_pkgs <- throwErr (foldM (add_package pkg_map) expl pkgids)
634   return (map (getPackageDetails state) all_pkgs)
635
636 -- Takes a list of packages, and returns the list with dependencies included,
637 -- in reverse dependency order (a package appears before those it depends on).
638 closeDeps :: PackageConfigMap -> [PackageId] -> IO [PackageId]
639 closeDeps pkg_map ps = throwErr (closeDepsErr pkg_map ps)
640
641 throwErr :: MaybeErr Message a -> IO a
642 throwErr m = case m of
643                 Failed e    -> throwDyn (CmdLineError (showSDoc e))
644                 Succeeded r -> return r
645
646 closeDepsErr :: PackageConfigMap -> [PackageId]
647         -> MaybeErr Message [PackageId]
648 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
649
650 -- internal helper
651 add_package :: PackageConfigMap -> [PackageId] -> PackageId 
652         -> MaybeErr Message [PackageId]
653 add_package pkg_db ps p
654   | p `elem` ps = return ps     -- Check if we've already added this package
655   | otherwise =
656       case lookupPackage pkg_db p of
657         Nothing -> Failed (missingPackageMsg (packageIdString p))
658         Just pkg -> do
659            -- Add the package's dependents also
660            let deps = map mkPackageId (depends pkg)
661            ps' <- foldM (add_package pkg_db) ps deps
662            return (p : ps')
663
664 missingPackageErr p = throwDyn (CmdLineError (showSDoc (missingPackageMsg p)))
665 missingPackageMsg p = ptext SLIT("unknown package:") <+> text p
666
667 -- -----------------------------------------------------------------------------
668 -- The home module set
669
670 newtype HomeModules = HomeModules ModuleSet
671
672 mkHomeModules :: [Module] -> HomeModules
673 mkHomeModules = HomeModules . mkModuleSet
674
675 isHomeModule :: HomeModules -> Module -> Bool
676 isHomeModule (HomeModules set) mod  = elemModuleSet mod set
677
678 -- Determining whether a Name refers to something in another package or not.
679 -- Cross-package references need to be handled differently when dynamically-
680 -- linked libraries are involved.
681
682 isDllName :: HomeModules -> Name -> Bool
683 isDllName pdeps name
684   | opt_Static = False
685   | Just mod <- nameModule_maybe name = not (isHomeModule pdeps mod)
686   | otherwise = False  -- no, it is not even an external name
687
688 -- -----------------------------------------------------------------------------
689 -- Displaying packages
690
691 dumpPackages :: DynFlags -> IO ()
692 -- Show package info on console, if verbosity is >= 3
693 dumpPackages dflags
694   = do  let pkg_map = pkgIdMap (pkgState dflags)
695         putMsg $ showSDoc $
696               vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))
697 \end{code}