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