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