Follow changes in the base library
[ghc-hetmet.git] / compiler / main / Packages.lhs
1  %
2 % (c) The University of Glasgow, 2006
3 %
4 % Package manipulation
5 %
6 \begin{code}
7 module Packages (
8         module PackageConfig,
9
10         -- * The PackageConfigMap
11         PackageConfigMap, emptyPackageConfigMap, lookupPackage,
12         extendPackageConfigMap, dumpPackages,
13
14         -- * Reading the package config, and processing cmdline args
15         PackageState(..),
16         initPackages,
17         getPackageDetails,
18         lookupModuleInAllPackages,
19
20         -- * Inspecting the set of packages in scope
21         getPackageIncludePath,
22         getPackageLibraryPath,
23         getPackageLinkOpts,
24         getPackageExtraCcOpts,
25         getPackageFrameworkPath,
26         getPackageFrameworks,
27         getPreloadPackagesAnd,
28
29         collectIncludeDirs, collectLibraryPaths, collectLinkOpts,
30
31         -- * Utils
32         isDllName
33     )
34 where
35
36 #include "HsVersions.h"
37
38 import PackageConfig    
39 import ParsePkgConf     ( loadPackageConfig )
40 import DynFlags         ( dopt, DynFlag(..), DynFlags(..), PackageFlag(..) )
41 import StaticFlags      ( opt_Static )
42 import Config           ( cProjectVersion )
43 import Name             ( Name, nameModule_maybe )
44 import UniqFM
45 import Module
46 import Util
47 import Maybes           ( expectJust, MaybeErr(..) )
48 import Panic
49 import Outputable
50
51 import System.Environment ( getEnv )
52 import Distribution.InstalledPackageInfo hiding (depends)
53 import Distribution.Package hiding (depends)
54 import Distribution.Text
55 import Distribution.Version
56 import FastString
57 import ErrUtils         ( debugTraceMsg, putMsg, Message )
58 import Exception
59
60 import System.Directory
61 import System.FilePath
62 import Data.Maybe
63 import Control.Monad
64 import Data.List
65
66 -- ---------------------------------------------------------------------------
67 -- The Package state
68
69 -- Package state is all stored in DynFlags, including the details of
70 -- all packages, which packages are exposed, and which modules they
71 -- provide.
72
73 -- The package state is computed by initPackages, and kept in DynFlags.
74 --
75 --   * -package <pkg> causes <pkg> to become exposed, and all other packages 
76 --      with the same name to become hidden.
77 -- 
78 --   * -hide-package <pkg> causes <pkg> to become hidden.
79 -- 
80 --   * Let exposedPackages be the set of packages thus exposed.  
81 --     Let depExposedPackages be the transitive closure from exposedPackages of
82 --     their dependencies.
83 --
84 --   * When searching for a module from an preload import declaration,
85 --     only the exposed modules in exposedPackages are valid.
86 --
87 --   * When searching for a module from an implicit import, all modules
88 --     from depExposedPackages are valid.
89 --
90 --   * When linking in a comp manager mode, we link in packages the
91 --     program depends on (the compiler knows this list by the
92 --     time it gets to the link step).  Also, we link in all packages
93 --     which were mentioned with preload -package flags on the command-line,
94 --     or are a transitive dependency of same, or are "base"/"rts".
95 --     The reason for (b) is that we might need packages which don't
96 --     contain any Haskell modules, and therefore won't be discovered
97 --     by the normal mechanism of dependency tracking.
98
99 -- Notes on DLLs
100 -- ~~~~~~~~~~~~~
101 -- When compiling module A, which imports module B, we need to 
102 -- know whether B will be in the same DLL as A.  
103 --      If it's in the same DLL, we refer to B_f_closure
104 --      If it isn't, we refer to _imp__B_f_closure
105 -- When compiling A, we record in B's Module value whether it's
106 -- in a different DLL, by setting the DLL flag.
107
108 data PackageState = PackageState {
109   pkgIdMap              :: PackageConfigMap, -- PackageId   -> PackageConfig
110         -- The exposed flags are adjusted according to -package and
111         -- -hide-package flags, and -ignore-package removes packages.
112
113   preloadPackages      :: [PackageId],
114         -- The packages we're going to link in eagerly.  This list
115         -- should be in reverse dependency order; that is, a package
116         -- is always mentioned before the packages it depends on.
117
118   moduleToPkgConfAll    :: UniqFM [(PackageConfig,Bool)] -- ModuleEnv mapping
119         -- Derived from pkgIdMap.       
120         -- Maps Module to (pkgconf,exposed), where pkgconf is the
121         -- PackageConfig for the package containing the module, and
122         -- exposed is True if the package exposes that module.
123   }
124
125 -- A PackageConfigMap maps a PackageId to a PackageConfig
126 type PackageConfigMap = UniqFM PackageConfig
127
128 emptyPackageConfigMap :: PackageConfigMap
129 emptyPackageConfigMap = emptyUFM
130
131 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
132 lookupPackage = lookupUFM
133
134 extendPackageConfigMap
135    :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
136 extendPackageConfigMap pkg_map new_pkgs 
137   = foldl add pkg_map new_pkgs
138   where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
139
140 getPackageDetails :: PackageState -> PackageId -> PackageConfig
141 getPackageDetails ps pid = expectJust "getPackageDetails" (lookupPackage (pkgIdMap ps) pid)
142
143 -- ----------------------------------------------------------------------------
144 -- Loading the package config files and building up the package state
145
146 -- | Call this after 'DynFlags.parseDynFlags'.  It reads the package
147 -- configuration files, and sets up various internal tables of package
148 -- information, according to the package-related flags on the
149 -- command-line (@-package@, @-hide-package@ etc.)
150 --
151 -- Returns a list of packages to link in if we're doing dynamic linking.
152 -- This list contains the packages that the user explicitly mentioned with
153 -- -package flags.
154 --
155 -- 'initPackages' can be called again subsequently after updating the
156 -- 'packageFlags' field of the 'DynFlags', and it will update the
157 -- 'packageState' in 'DynFlags' and return a list of packages to
158 -- link in.
159 initPackages :: DynFlags -> IO (DynFlags, [PackageId])
160 initPackages dflags = do 
161   pkg_db <- case pkgDatabase dflags of
162                 Nothing -> readPackageConfigs dflags
163                 Just db -> return db
164   (pkg_state, preload, this_pkg)       
165         <- mkPackageState dflags pkg_db [] (thisPackage dflags)
166   return (dflags{ pkgDatabase = Just pkg_db,
167                   pkgState = pkg_state,
168                   thisPackage = this_pkg },
169           preload)
170
171 -- -----------------------------------------------------------------------------
172 -- Reading the package database(s)
173
174 readPackageConfigs :: DynFlags -> IO PackageConfigMap
175 readPackageConfigs dflags = do
176    e_pkg_path <- tryIO (getEnv "GHC_PACKAGE_PATH")
177    system_pkgconfs <- getSystemPackageConfigs dflags
178
179    let pkgconfs = case e_pkg_path of
180                     Left _   -> system_pkgconfs
181                     Right path
182                      | last cs == "" -> init cs ++ system_pkgconfs
183                      | otherwise     -> cs
184                      where cs = parseSearchPath path
185                      -- if the path ends in a separator (eg. "/foo/bar:")
186                      -- the we tack on the system paths.
187
188         -- Read all the ones mentioned in -package-conf flags
189    pkg_map <- foldM (readPackageConfig dflags) emptyPackageConfigMap
190                  (reverse pkgconfs ++ extraPkgConfs dflags)
191
192    return pkg_map
193
194
195 getSystemPackageConfigs :: DynFlags -> IO [FilePath]
196 getSystemPackageConfigs dflags = do
197         -- System one always comes first
198    let system_pkgconf = systemPackageConfig dflags
199
200         -- allow package.conf.d to contain a bunch of .conf files
201         -- containing package specifications.  This is an easier way
202         -- to maintain the package database on systems with a package
203         -- management system, or systems that don't want to run ghc-pkg
204         -- to register or unregister packages.  Undocumented feature for now.
205    let system_pkgconf_dir = system_pkgconf <.> "d"
206    system_pkgconf_dir_exists <- doesDirectoryExist system_pkgconf_dir
207    system_pkgconfs <-
208      if system_pkgconf_dir_exists
209        then do files <- getDirectoryContents system_pkgconf_dir
210                return [ system_pkgconf_dir </> file
211                       | file <- files
212                       , takeExtension file == ".conf" ]
213        else return []
214
215         -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
216         -- unless the -no-user-package-conf flag was given.
217         -- We only do this when getAppUserDataDirectory is available 
218         -- (GHC >= 6.3).
219    user_pkgconf <- do
220       appdir <- getAppUserDataDirectory "ghc"
221       let 
222          pkgconf = appdir
223                    </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
224                    </> "package.conf"
225       flg <- doesFileExist pkgconf
226       if (flg && dopt Opt_ReadUserPackageConf dflags)
227         then return [pkgconf]
228         else return []
229     `catchIO` (\_ -> return [])
230
231    return (user_pkgconf ++ system_pkgconfs ++ [system_pkgconf])
232
233
234 readPackageConfig
235    :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
236 readPackageConfig dflags pkg_map conf_file = do
237   debugTraceMsg dflags 2 (text "Using package config file:" <+> text conf_file)
238   proto_pkg_configs <- loadPackageConfig dflags conf_file
239   let top_dir = topDir dflags
240       pkg_configs1 = mungePackagePaths top_dir proto_pkg_configs
241       pkg_configs2 = maybeHidePackages dflags pkg_configs1
242   return (extendPackageConfigMap pkg_map pkg_configs2)
243
244 maybeHidePackages :: DynFlags -> [PackageConfig] -> [PackageConfig]
245 maybeHidePackages dflags pkgs
246   | dopt Opt_HideAllPackages dflags = map hide pkgs
247   | otherwise                       = pkgs
248   where
249     hide pkg = pkg{ exposed = False }
250
251 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
252 -- Replace the string "$topdir" at the beginning of a path
253 -- with the current topdir (obtained from the -B option).
254 mungePackagePaths top_dir ps = map munge_pkg ps
255  where 
256   munge_pkg p = p{ importDirs  = munge_paths (importDirs p),
257                    includeDirs = munge_paths (includeDirs p),
258                    libraryDirs = munge_paths (libraryDirs p),
259                    frameworkDirs = munge_paths (frameworkDirs p),
260                    haddockInterfaces = munge_paths (haddockInterfaces p),
261                    haddockHTMLs = munge_paths (haddockHTMLs p)
262                     }
263
264   munge_paths = map munge_path
265
266   munge_path p 
267           | Just p' <- maybePrefixMatch "$topdir"     p =            top_dir ++ p'
268           | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
269           | otherwise                               = p
270
271   toHttpPath p = "file:///" ++ p
272
273
274 -- -----------------------------------------------------------------------------
275 -- Modify our copy of the package database based on a package flag
276 -- (-package, -hide-package, -ignore-package).
277
278 applyPackageFlag
279    :: [PackageConfig]           -- Initial database
280    -> PackageFlag               -- flag to apply
281    -> IO [PackageConfig]        -- new database
282
283 applyPackageFlag pkgs flag = 
284   case flag of
285         ExposePackage str ->
286            case matchingPackages str pkgs of
287                 Nothing -> missingPackageErr str
288                 Just ([], _) -> panic "applyPackageFlag"
289                 Just (p:ps,qs) -> return (p':ps')
290                   where p' = p {exposed=True}
291                         ps' = hideAll (pkgName (package p)) (ps++qs)
292
293         HidePackage str ->
294            case matchingPackages str pkgs of
295                 Nothing -> missingPackageErr str
296                 Just (ps,qs) -> return (map hide ps ++ qs)
297                   where hide p = p {exposed=False}
298
299         IgnorePackage str ->
300            case matchingPackages str pkgs of
301                 Nothing -> return pkgs
302                 Just (_, qs) -> return qs
303                 -- missing package is not an error for -ignore-package,
304                 -- because a common usage is to -ignore-package P as
305                 -- a preventative measure just in case P exists.
306    where
307         -- When a package is requested to be exposed, we hide all other
308         -- packages with the same name.
309         hideAll name ps = map maybe_hide ps
310           where maybe_hide p | pkgName (package p) == name = p {exposed=False}
311                              | otherwise                   = p
312
313
314 matchingPackages :: String -> [PackageConfig]
315          -> Maybe ([PackageConfig], [PackageConfig])
316 matchingPackages str pkgs
317   = case partition (matches str) pkgs of
318         ([],_)    -> Nothing
319         (ps,rest) -> Just (sortByVersion ps, rest)
320   where
321         -- A package named on the command line can either include the
322         -- version, or just the name if it is unambiguous.
323         matches str p
324                 =  str == display (package p)
325                 || str == display (pkgName (package p))
326
327 pickPackages :: [PackageConfig] -> [String] -> [PackageConfig]
328 pickPackages pkgs strs = 
329   [ p | p <- strs, Just (p:_, _) <- [matchingPackages p pkgs] ]
330
331 sortByVersion :: [InstalledPackageInfo_ m] -> [InstalledPackageInfo_ m]
332 sortByVersion = sortBy (flip (comparing (pkgVersion.package)))
333
334 comparing :: Ord a => (t -> a) -> t -> t -> Ordering
335 comparing f a b = f a `compare` f b
336
337 -- -----------------------------------------------------------------------------
338 -- Hide old versions of packages
339
340 --
341 -- hide all packages for which there is also a later version
342 -- that is already exposed.  This just makes it non-fatal to have two
343 -- versions of a package exposed, which can happen if you install a
344 -- later version of a package in the user database, for example.
345 --
346 hideOldPackages :: DynFlags -> [PackageConfig] -> IO [PackageConfig]
347 hideOldPackages dflags pkgs = mapM maybe_hide pkgs
348   where maybe_hide p
349            | not (exposed p) = return p
350            | (p' : _) <- later_versions = do
351                 debugTraceMsg dflags 2 $
352                    (ptext (sLit "hiding package") <+> 
353                     text (display (package p)) <+>
354                     ptext (sLit "to avoid conflict with later version") <+>
355                     text (display (package p')))
356                 return (p {exposed=False})
357            | otherwise = return p
358           where myname = pkgName (package p)
359                 myversion = pkgVersion (package p)
360                 later_versions = [ p | p <- pkgs, exposed p,
361                                     let pkg = package p,
362                                     pkgName pkg == myname,
363                                     pkgVersion pkg > myversion ]
364
365 -- -----------------------------------------------------------------------------
366 -- Wired-in packages
367
368 findWiredInPackages
369    :: DynFlags
370    -> [PackageConfig]           -- database
371    -> [PackageIdentifier]       -- preload packages
372    -> PackageId                 -- this package
373    -> IO ([PackageConfig],
374           [PackageIdentifier],
375           PackageId)
376
377 findWiredInPackages dflags pkgs preload this_package = do
378   --
379   -- Now we must find our wired-in packages, and rename them to
380   -- their canonical names (eg. base-1.0 ==> base).
381   --
382   let
383         wired_in_pkgids :: [(PackageId, [String])]
384         wired_in_pkgids = [ (primPackageId, [""]),
385                             (integerPackageId, [""]),
386                             (basePackageId, [""]),
387                             (rtsPackageId, [""]),
388                             (haskell98PackageId, [""]),
389                             (thPackageId, [""]),
390                             (dphSeqPackageId, [""]),
391                             (dphParPackageId, [""]),
392                             (ndpPackageId, ["-seq", "-par"]) ]
393
394         matches :: PackageConfig -> (PackageId, [String]) -> Bool
395         pc `matches` (pid, suffixes)
396             = display (pkgName (package pc)) `elem`
397               (map (packageIdString pid ++) suffixes)
398
399         -- find which package corresponds to each wired-in package
400         -- delete any other packages with the same name
401         -- update the package and any dependencies to point to the new
402         -- one.
403         --
404         -- When choosing which package to map to a wired-in package
405         -- name, we prefer exposed packages, and pick the latest
406         -- version.  To override the default choice, -hide-package
407         -- could be used to hide newer versions.
408         --
409         findWiredInPackage :: [PackageConfig] -> (PackageId, [String])
410                            -> IO (Maybe (PackageIdentifier, PackageId))
411         findWiredInPackage pkgs wired_pkg =
412            let all_ps = [ p | p <- pkgs, p `matches` wired_pkg ] in
413            case filter exposed all_ps of
414                 [] -> case all_ps of
415                         []   -> notfound
416                         many -> pick (head (sortByVersion many))
417                 many  -> pick (head (sortByVersion many))
418           where
419                 suffixes = snd wired_pkg
420                 notfound = do
421                           debugTraceMsg dflags 2 $
422                             ptext (sLit "wired-in package ")
423                                  <> ppr (fst wired_pkg)
424                                  <> (if null suffixes
425                                      then empty
426                                      else text (show suffixes))
427                                  <> ptext (sLit " not found.")
428                           return Nothing
429                 pick :: InstalledPackageInfo_ ModuleName
430                      -> IO (Maybe (PackageIdentifier, PackageId))
431                 pick pkg = do
432                         debugTraceMsg dflags 2 $
433                             ptext (sLit "wired-in package ")
434                                  <> ppr (fst wired_pkg)
435                                  <> ptext (sLit " mapped to ")
436                                  <> text (display (package pkg))
437                         return (Just (package pkg, fst wired_pkg))
438
439
440   mb_wired_in_ids <- mapM (findWiredInPackage pkgs) wired_in_pkgids
441   let 
442         wired_in_ids = catMaybes mb_wired_in_ids
443
444         deleteOtherWiredInPackages pkgs = filterOut bad pkgs
445           where bad p = any (p `matches`) wired_in_pkgids
446                      && package p `notElem` map fst wired_in_ids
447
448         updateWiredInDependencies pkgs = map upd_pkg pkgs
449           where upd_pkg p = p{ package = upd_pid (package p),
450                                depends = map upd_pid (depends p) }
451
452         upd_pid pid = case filter ((== pid) . fst) wired_in_ids of
453                                 [] -> pid
454                                 ((x, y):_) -> x{ pkgName = PackageName (packageIdString y),
455                                                  pkgVersion = Version [] [] }
456
457         pkgs1 = deleteOtherWiredInPackages pkgs
458
459         pkgs2 = updateWiredInDependencies pkgs1
460
461         preload1 = map upd_pid preload
462
463         -- we must return an updated thisPackage, just in case we
464         -- are actually compiling one of the wired-in packages
465         Just old_this_pkg = unpackPackageId this_package
466         new_this_pkg = mkPackageId (upd_pid old_this_pkg)
467
468   return (pkgs2, preload1, new_this_pkg)
469
470 -- ----------------------------------------------------------------------------
471 --
472 -- Detect any packages that have missing dependencies, and also any
473 -- mutually-recursive groups of packages (loops in the package graph
474 -- are not allowed).  We do this by taking the least fixpoint of the
475 -- dependency graph, repeatedly adding packages whose dependencies are
476 -- satisfied until no more can be added.
477 --
478 elimDanglingDeps
479    :: DynFlags
480    -> [PackageConfig]
481    -> [PackageId]       -- ignored packages
482    -> IO [PackageConfig]
483
484 elimDanglingDeps dflags pkgs ignored = go [] pkgs'
485  where
486    pkgs' = filter (\p -> packageConfigId p `notElem` ignored) pkgs
487
488    go avail not_avail =
489      case partitionWith (depsAvailable avail) not_avail of
490         ([],        not_avail) -> do mapM_ reportElim not_avail; return avail
491         (new_avail, not_avail) -> go (new_avail ++ avail) (map fst not_avail)
492
493    depsAvailable :: [PackageConfig] -> PackageConfig
494                  -> Either PackageConfig (PackageConfig, [PackageIdentifier])
495    depsAvailable pkgs_ok pkg 
496         | null dangling = Left pkg
497         | otherwise     = Right (pkg, dangling)
498         where dangling = filter (`notElem` pids) (depends pkg)
499               pids = map package pkgs_ok
500
501    reportElim (p, deps) = 
502         debugTraceMsg dflags 2 $
503              (ptext (sLit "package") <+> pprPkg p <+> 
504                   ptext (sLit "will be ignored due to missing or recursive dependencies:") $$ 
505               nest 2 (hsep (map (text.display) deps)))
506
507 -- -----------------------------------------------------------------------------
508 -- When all the command-line options are in, we can process our package
509 -- settings and populate the package state.
510
511 mkPackageState
512     :: DynFlags
513     -> PackageConfigMap         -- initial database
514     -> [PackageId]              -- preloaded packages
515     -> PackageId                -- this package
516     -> IO (PackageState,
517            [PackageId],         -- new packages to preload
518            PackageId) -- this package, might be modified if the current
519
520                       -- package is a wired-in package.
521
522 mkPackageState dflags orig_pkg_db preload0 this_package = do
523   --
524   -- Modify the package database according to the command-line flags
525   -- (-package, -hide-package, -ignore-package, -hide-all-packages).
526   --
527   let flags = reverse (packageFlags dflags)
528   let pkgs0 = eltsUFM orig_pkg_db
529   pkgs1 <- foldM applyPackageFlag pkgs0 flags
530
531   -- Here we build up a set of the packages mentioned in -package
532   -- flags on the command line; these are called the "preload"
533   -- packages.  we link these packages in eagerly.  The preload set
534   -- should contain at least rts & base, which is why we pretend that
535   -- the command line contains -package rts & -package base.
536   --
537   let new_preload_packages = 
538         map package (pickPackages pkgs0 [ p | ExposePackage p <- flags ])
539
540   -- hide packages that are subsumed by later versions
541   pkgs2 <- hideOldPackages dflags pkgs1
542
543   -- sort out which packages are wired in
544   (pkgs3, preload1, new_this_pkg)
545         <- findWiredInPackages dflags pkgs2 new_preload_packages this_package
546
547   let ignored = map packageConfigId $
548                    pickPackages pkgs0 [ p | IgnorePackage p <- flags ]
549   pkgs <- elimDanglingDeps dflags pkgs3 ignored
550
551   let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
552
553       -- add base & rts to the preload packages
554       basicLinkedPackages
555        | dopt Opt_AutoLinkPackages dflags
556           = filter (flip elemUFM pkg_db) [basePackageId, rtsPackageId]
557        | otherwise = []
558       -- but in any case remove the current package from the set of
559       -- preloaded packages so that base/rts does not end up in the
560       -- set up preloaded package when we are just building it
561       preload2 = nub (filter (/= new_this_pkg)
562                              (basicLinkedPackages ++ map mkPackageId preload1))
563
564   -- Close the preload packages with their dependencies
565   dep_preload <- closeDeps pkg_db (zip preload2 (repeat Nothing))
566   let new_dep_preload = filter (`notElem` preload0) dep_preload
567
568   let pstate = PackageState{ preloadPackages     = dep_preload,
569                              pkgIdMap            = pkg_db,
570                              moduleToPkgConfAll  = mkModuleMap pkg_db
571                            }
572
573   return (pstate, new_dep_preload, new_this_pkg)
574
575
576 -- -----------------------------------------------------------------------------
577 -- Make the mapping from module to package info
578
579 mkModuleMap
580   :: PackageConfigMap
581   -> UniqFM [(PackageConfig, Bool)]
582 mkModuleMap pkg_db = foldr extend_modmap emptyUFM pkgids
583   where
584         pkgids = map packageConfigId (eltsUFM pkg_db)
585         
586         extend_modmap pkgid modmap =
587                 addListToUFM_C (++) modmap 
588                    ([(m, [(pkg, True)])  | m <- exposed_mods] ++
589                     [(m, [(pkg, False)]) | m <- hidden_mods])
590           where
591                 pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
592                 exposed_mods = exposedModules pkg
593                 hidden_mods  = hiddenModules pkg
594
595 pprPkg :: PackageConfig -> SDoc
596 pprPkg p = text (display (package p))
597
598 -- -----------------------------------------------------------------------------
599 -- Extracting information from the packages in scope
600
601 -- Many of these functions take a list of packages: in those cases,
602 -- the list is expected to contain the "dependent packages",
603 -- i.e. those packages that were found to be depended on by the
604 -- current module/program.  These can be auto or non-auto packages, it
605 -- doesn't really matter.  The list is always combined with the list
606 -- of preload (command-line) packages to determine which packages to
607 -- use.
608
609 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
610 getPackageIncludePath dflags pkgs =
611   collectIncludeDirs `fmap` getPreloadPackagesAnd dflags pkgs
612
613 collectIncludeDirs :: [PackageConfig] -> [FilePath] 
614 collectIncludeDirs ps = nub (filter notNull (concatMap includeDirs ps))
615
616 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
617 getPackageLibraryPath dflags pkgs =
618   collectLibraryPaths `fmap` getPreloadPackagesAnd dflags pkgs
619
620 collectLibraryPaths :: [PackageConfig] -> [FilePath]
621 collectLibraryPaths ps = nub (filter notNull (concatMap libraryDirs ps))
622
623 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
624 getPackageLinkOpts dflags pkgs = 
625   collectLinkOpts dflags `fmap` getPreloadPackagesAnd dflags pkgs
626
627 collectLinkOpts :: DynFlags -> [PackageConfig] -> [String]
628 collectLinkOpts dflags ps = concat (map all_opts ps)
629   where
630         tag = buildTag dflags
631         rts_tag = rtsBuildTag dflags
632
633         mkDynName | opt_Static = id
634                   | otherwise = (++ ("-ghc" ++ cProjectVersion))
635         libs p     = map (mkDynName . addSuffix) (hsLibraries p)
636                          ++ extraLibraries p
637         all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
638
639         addSuffix rts@"HSrts"    = rts       ++ (expandTag rts_tag)
640         addSuffix other_lib      = other_lib ++ (expandTag tag)
641
642         expandTag t | null t = ""
643                     | otherwise = '_':t
644
645 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
646 getPackageExtraCcOpts dflags pkgs = do
647   ps <- getPreloadPackagesAnd dflags pkgs
648   return (concatMap ccOptions ps)
649
650 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
651 getPackageFrameworkPath dflags pkgs = do
652   ps <- getPreloadPackagesAnd dflags pkgs
653   return (nub (filter notNull (concatMap frameworkDirs ps)))
654
655 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
656 getPackageFrameworks dflags pkgs = do
657   ps <- getPreloadPackagesAnd dflags pkgs
658   return (concatMap frameworks ps)
659
660 -- -----------------------------------------------------------------------------
661 -- Package Utils
662
663 -- | Takes a Module, and if the module is in a package returns 
664 -- @(pkgconf,exposed)@ where pkgconf is the PackageConfig for that package,
665 -- and exposed is True if the package exposes the module.
666 lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
667 lookupModuleInAllPackages dflags m =
668   case lookupUFM (moduleToPkgConfAll (pkgState dflags)) m of
669         Nothing -> []
670         Just ps -> ps
671
672 getPreloadPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
673 getPreloadPackagesAnd dflags pkgids =
674   let 
675       state   = pkgState dflags
676       pkg_map = pkgIdMap state
677       preload = preloadPackages state
678       pairs = zip pkgids (repeat Nothing)
679   in do
680   all_pkgs <- throwErr (foldM (add_package pkg_map) preload pairs)
681   return (map (getPackageDetails state) all_pkgs)
682
683 -- Takes a list of packages, and returns the list with dependencies included,
684 -- in reverse dependency order (a package appears before those it depends on).
685 closeDeps :: PackageConfigMap -> [(PackageId, Maybe PackageId)]
686         -> IO [PackageId]
687 closeDeps pkg_map ps = throwErr (closeDepsErr pkg_map ps)
688
689 throwErr :: MaybeErr Message a -> IO a
690 throwErr m = case m of
691                 Failed e    -> ghcError (CmdLineError (showSDoc e))
692                 Succeeded r -> return r
693
694 closeDepsErr :: PackageConfigMap -> [(PackageId,Maybe PackageId)]
695         -> MaybeErr Message [PackageId]
696 closeDepsErr pkg_map ps = foldM (add_package pkg_map) [] ps
697
698 -- internal helper
699 add_package :: PackageConfigMap -> [PackageId] -> (PackageId,Maybe PackageId)
700         -> MaybeErr Message [PackageId]
701 add_package pkg_db ps (p, mb_parent)
702   | p `elem` ps = return ps     -- Check if we've already added this package
703   | otherwise =
704       case lookupPackage pkg_db p of
705         Nothing -> Failed (missingPackageMsg (packageIdString p) <> 
706                            missingDependencyMsg mb_parent)
707         Just pkg -> do
708            -- Add the package's dependents also
709            let deps = map mkPackageId (depends pkg)
710            ps' <- foldM (add_package pkg_db) ps (zip deps (repeat (Just p)))
711            return (p : ps')
712
713 missingPackageErr :: String -> IO [PackageConfig]
714 missingPackageErr p = ghcError (CmdLineError (showSDoc (missingPackageMsg p)))
715
716 missingPackageMsg :: String -> SDoc
717 missingPackageMsg p = ptext (sLit "unknown package:") <+> text p
718
719 missingDependencyMsg :: Maybe PackageId -> SDoc
720 missingDependencyMsg Nothing = empty
721 missingDependencyMsg (Just parent)
722   = space <> parens (ptext (sLit "dependency of") <+> ftext (packageIdFS parent))
723
724 -- -----------------------------------------------------------------------------
725
726 isDllName :: PackageId -> Name -> Bool
727 isDllName this_pkg name
728   | opt_Static = False
729   | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
730   | otherwise = False  -- no, it is not even an external name
731
732 -- -----------------------------------------------------------------------------
733 -- Displaying packages
734
735 dumpPackages :: DynFlags -> IO ()
736 -- Show package info on console, if verbosity is >= 3
737 dumpPackages dflags
738   = do  let pkg_map = pkgIdMap (pkgState dflags)
739         putMsg dflags $
740               vcat (map (text . showInstalledPackageInfo
741                               . packageConfigToInstalledPackageInfo)
742                         (eltsUFM pkg_map))
743 \end{code}