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