[project @ 2004-12-02 16:33:16 by simonpj]
[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         PackageState(..),
16         initPackages,
17         moduleToPackageConfig,
18         getPackageDetails,
19         isHomeModule,
20
21         -- * Inspecting the set of packages in scope
22         getPackageIncludePath,
23         getPackageCIncludes,
24         getPackageLibraryPath,
25         getPackageLinkOpts,
26         getPackageExtraCcOpts,
27         getPackageFrameworkPath,
28         getPackageFrameworks,
29         getExplicitPackagesAnd,
30
31         -- * Utils
32         isDllName
33     )
34 where
35
36 #include "HsVersions.h"
37
38 import PackageConfig    
39 import DriverState      ( v_Build_tag, v_RTS_Build_tag, v_Static )
40 import SysTools         ( getTopDir, getPackageConfigPath )
41 import ParsePkgConf     ( loadPackageConfig )
42 import CmdLineOpts      ( DynFlags(..), PackageFlag(..), verbosity,
43                           opt_Static )
44 import Config           ( cTARGETARCH, cTARGETOS, cProjectVersion )
45 import Name             ( Name, nameModule_maybe )
46 import Module           ( Module, mkModule )
47 import UniqFM
48 import UniqSet
49 import Util
50 import Panic
51 import Outputable
52
53 #if __GLASGOW_HASKELL__ >= 603
54 import System.Directory ( getAppUserDataDirectory )
55 #else
56 import Compat.Directory ( getAppUserDataDirectory )
57 #endif
58
59 import Distribution.InstalledPackageInfo
60 import Distribution.Package
61 import Distribution.Version
62 import System.IO        ( hPutStrLn, stderr )
63 import Data.Maybe       ( fromJust, isNothing )
64 import System.Directory ( doesFileExist )
65 import Control.Monad    ( when, foldM )
66 import Data.List        ( nub, partition )
67
68 #ifdef mingw32_TARGET_OS
69 import Data.List        ( isPrefixOf )
70 #endif
71
72 import FastString
73 import DATA_IOREF
74 import EXCEPTION        ( throwDyn )
75
76 -- ---------------------------------------------------------------------------
77 -- The Package state
78
79 -- Package state is all stored in DynFlags, including the details of
80 -- all packages, which packages are exposed, and which modules they
81 -- provide.
82
83 -- The package state is computed by initPackages, and kept in DynFlags.
84 --
85 --   * -package <pkg> causes <pkg> to become exposed, and all other packages 
86 --      with the same name to become hidden.
87 -- 
88 --   * -hide-package <pkg> causes <pkg> to become hidden.
89 -- 
90 --   * Let exposedPackages be the set of packages thus exposed.  
91 --     Let depExposedPackages be the transitive closure from exposedPackages of
92 --     their dependencies.
93 --
94 --   * It is an error for any two packages in depExposedPackages to provide the
95 --     same module.
96 -- 
97 --   * When searching for a module from an explicit import declaration,
98 --     only the exposed modules in exposedPackages are valid.
99 --
100 --   * When searching for a module from an implicit import, all modules
101 --     from depExposedPackages are valid.
102 --
103 --   * When linking in a comp manager mode, we link in packages the
104 --     program depends on (the compiler knows this list by the
105 --     time it gets to the link step).  Also, we link in all packages
106 --     which were mentioned with explicit -package flags on the command-line,
107 --     or are a transitive dependency of same, or are "base"/"rts".
108 --     The reason for (b) is that we might need packages which don't
109 --     contain any Haskell modules, and therefore won't be discovered
110 --     by the normal mechanism of dependency tracking.
111
112
113 -- One important thing that the package state provides is a way to
114 -- tell, for a given module, whether it is part of the current package
115 -- or not.  We need to know this for two reasons:
116 --
117 --  * generating cross-DLL calls is different from intra-DLL calls 
118 --    (see below).
119 --  * we don't record version information in interface files for entities
120 --    in a different package.
121 -- 
122 -- Notes on DLLs
123 -- ~~~~~~~~~~~~~
124 -- When compiling module A, which imports module B, we need to 
125 -- know whether B will be in the same DLL as A.  
126 --      If it's in the same DLL, we refer to B_f_closure
127 --      If it isn't, we refer to _imp__B_f_closure
128 -- When compiling A, we record in B's Module value whether it's
129 -- in a different DLL, by setting the DLL flag.
130
131 data PackageState = PackageState {
132
133   explicitPackages      :: [PackageId],
134         -- The packages we're going to link in eagerly.  This list
135         -- should be in reverse dependency order; that is, a package
136         -- is always mentioned before the packages it depends on.
137
138   pkgIdMap              :: PackageConfigMap, -- PackageId   -> PackageConfig
139         -- mapping derived from the package databases and
140         -- command-line package flags.
141
142   moduleToPkgConf       :: UniqFM (PackageConfig,Bool),
143         -- Maps Module to (pkgconf,exposed), where pkgconf is the
144         -- PackageConfig for the package containing the module, and
145         -- exposed is True if the package exposes that module.
146
147   -- The PackageIds of some known packages
148   basePackageId         :: Maybe PackageId,
149   rtsPackageId          :: Maybe PackageId,
150   haskell98PackageId    :: Maybe PackageId,
151   thPackageId           :: Maybe PackageId
152   }
153
154 -- A PackageConfigMap maps a PackageId to a PackageConfig
155 type PackageConfigMap = UniqFM PackageConfig
156
157 emptyPackageConfigMap :: PackageConfigMap
158 emptyPackageConfigMap = emptyUFM
159
160 lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
161 lookupPackage = lookupUFM
162
163 extendPackageConfigMap
164    :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
165 extendPackageConfigMap pkg_map new_pkgs 
166   = foldl add pkg_map new_pkgs
167   where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
168
169 getPackageDetails :: PackageState -> PackageId -> PackageConfig
170 getPackageDetails dflags ps = fromJust (lookupPackage (pkgIdMap dflags) ps)
171
172 -- ----------------------------------------------------------------------------
173 -- Loading the package config files and building up the package state
174
175 initPackages :: DynFlags -> IO DynFlags
176 initPackages dflags = do 
177   pkg_map <- readPackageConfigs dflags; 
178   state <- mkPackageState dflags pkg_map
179   return dflags{ pkgState = state }
180
181 -- -----------------------------------------------------------------------------
182 -- Reading the package database(s)
183
184 readPackageConfigs :: DynFlags -> IO PackageConfigMap
185 readPackageConfigs dflags = do
186         -- System one always comes first
187    system_pkgconf <- getPackageConfigPath
188    pkg_map1 <- readPackageConfig dflags emptyPackageConfigMap system_pkgconf
189
190         -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
191         -- unless the -no-user-package-conf flag was given.
192         -- We only do this when getAppUserDataDirectory is available 
193         -- (GHC >= 6.3).
194    appdir <- getAppUserDataDirectory "ghc"
195    let 
196          pkgconf = appdir ++ '/':cTARGETARCH ++ '-':cTARGETOS
197                         ++ '-':cProjectVersion ++ "/package.conf"
198    --
199    exists <- doesFileExist pkgconf
200    pkg_map2 <- if (readUserPkgConf dflags && exists)
201                   then readPackageConfig dflags pkg_map1 pkgconf
202                   else return pkg_map1
203
204         -- Read all the ones mentioned in -package-conf flags
205    pkg_map <- foldM (readPackageConfig dflags) pkg_map2
206                  (extraPkgConfs dflags)
207
208    return pkg_map
209
210
211 readPackageConfig
212    :: DynFlags -> PackageConfigMap -> FilePath -> IO PackageConfigMap
213 readPackageConfig dflags pkg_map conf_file = do
214   when (verbosity dflags >= 2) $
215         hPutStrLn stderr ("Reading package config file: "
216                          ++ conf_file)
217   proto_pkg_configs <- loadPackageConfig conf_file
218   top_dir           <- getTopDir
219   let pkg_configs = mungePackagePaths top_dir proto_pkg_configs
220   return (extendPackageConfigMap pkg_map pkg_configs)
221
222
223 mungePackagePaths :: String -> [PackageConfig] -> [PackageConfig]
224 -- Replace the string "$libdir" at the beginning of a path
225 -- with the current libdir (obtained from the -B option).
226 mungePackagePaths top_dir ps = map munge_pkg ps
227  where 
228   munge_pkg p = p{ importDirs  = munge_paths (importDirs p),
229                    includeDirs = munge_paths (includeDirs p),
230                    libraryDirs = munge_paths (libraryDirs p),
231                    frameworkDirs = munge_paths (frameworkDirs p) }
232
233   munge_paths = map munge_path
234
235   munge_path p 
236           | Just p' <- maybePrefixMatch "$libdir" p = top_dir ++ p'
237           | otherwise                               = p
238
239
240 -- -----------------------------------------------------------------------------
241 -- When all the command-line options are in, we can process our package
242 -- settings and populate the package state.
243
244 mkPackageState :: DynFlags -> PackageConfigMap -> IO PackageState
245 mkPackageState dflags pkg_db = do
246   --
247   -- Modify the package database according to the command-line flags
248   -- (-package, -hide-package, -ignore-package).
249   --
250   -- Also, here we build up a set of the packages mentioned in -package
251   -- flags on the command line; these are called the "explicit" packages.
252   -- we link these packages in eagerly.  The explicit set should contain
253   -- at least rts & base, which is why we pretend that the command line
254   -- contains -package rts & -package base.
255   --
256   let
257         flags = reverse (packageFlags dflags)
258
259         procflags pkgs expl [] = return (pkgs,expl)
260         procflags pkgs expl (ExposePackage str : flags) = do
261            case partition (matches str) pkgs of
262                 ([],_)   -> missingPackageErr str
263                 ([p],ps) -> procflags (p':ps) (addOneToUniqSet expl pkgid) flags
264                   where pkgid = packageConfigId p
265                         p' = p {exposed=True}
266                 (ps,_)   -> multiplePackagesErr str ps
267         procflags pkgs expl (HidePackage str : flags) = do
268            case partition (matches str) pkgs of
269                 ([],_)   -> missingPackageErr str
270                 ([p],ps) -> procflags (p':ps) expl flags
271                   where p' = p {exposed=False}
272                 (ps,_)   -> multiplePackagesErr str ps
273         procflags pkgs expl (IgnorePackage str : flags) = do
274            case partition (matches str) pkgs of
275                 (ps,qs) -> procflags qs expl flags
276                 -- missing package is not an error for -ignore-package,
277                 -- because a common usage is to -ignore-package P as
278                 -- a preventative measure just in case P exists.
279
280         -- A package named on the command line can either include the
281         -- version, or just the name if it is unambiguous.
282         matches str p
283                 =  str == showPackageId (package p)
284                 || str == pkgName (package p)
285   --
286   (pkgs1,explicit) <- procflags (eltsUFM pkg_db) emptyUniqSet flags
287   --
288   let
289         elimDanglingDeps pkgs = 
290            case partition (hasDanglingDeps pkgs) pkgs of
291               ([],ps) -> ps
292               (ps,qs) -> elimDanglingDeps qs
293
294         hasDanglingDeps pkgs p = any dangling (depends p)
295           where dangling pid = pid `notElem` all_pids
296                 all_pids = map package pkgs
297   --
298   -- Eliminate any packages which have dangling dependencies (perhaps
299   -- because the package was removed by -ignore-package).
300   --
301   let pkgs = elimDanglingDeps pkgs1
302       pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs
303   --
304   -- Find the transitive closure of dependencies of exposed
305   --
306   let exposed_pkgids = [ packageConfigId p | p <- pkgs, exposed p ]
307   dep_exposed <- closeDeps pkg_db exposed_pkgids
308   --
309   -- Look up some known PackageIds
310   --
311   let
312         lookupPackageByName nm = 
313           case [ conf | p <- dep_exposed,
314                         Just conf <- [lookupPackage pkg_db p],
315                         nm == mkFastString (pkgName (package conf)) ] of
316                 []     -> Nothing
317                 (p:ps) -> Just (mkPackageId (package p))
318
319         -- Get the PackageIds for some known packages (we know the names,
320         -- but we don't know the versions).  Some of these packages might
321         -- not exist in the database, so they are Maybes.
322         basePackageId           = lookupPackageByName basePackageName
323         rtsPackageId            = lookupPackageByName rtsPackageName
324         haskell98PackageId      = lookupPackageByName haskell98PackageName
325         thPackageId             = lookupPackageByName thPackageName
326
327         -- add base & rts to the explicit packages
328         basicLinkedPackages = [basePackageId,rtsPackageId]
329         explicit' = addListToUniqSet explicit 
330                         [ p | Just p <- basicLinkedPackages ]
331   --
332   -- Close the explicit packages with their dependencies
333   --
334   dep_explicit <- closeDeps pkg_db (uniqSetToList explicit')
335   --
336   -- Build up a mapping from Module -> PackageConfig for all modules.
337   -- Discover any conflicts at the same time, and factor in the new exposed
338   -- status of each package.
339   --
340   let
341         extend_modmap modmap pkgname = do
342           let 
343                 pkg = fromJust (lookupPackage pkg_db pkgname)
344                 exposed_mods = map mkModule (exposedModules pkg)
345                 hidden_mods  = map mkModule (hiddenModules pkg)
346                 all_mods = exposed_mods ++ hidden_mods
347           --
348           -- check for overlaps
349           --
350           let
351                 overlaps = [ (m,pkg) | m <- all_mods, 
352                                        Just (pkg,_) <- [lookupUFM modmap m] ]
353           --
354           when (not (null overlaps)) $ overlappingError pkg overlaps
355           --
356           let
357           return (addListToUFM modmap 
358                     [(m, (pkg, m `elem` exposed_mods)) 
359                     | m <- all_mods])
360   --
361   mod_map <- foldM extend_modmap emptyUFM dep_exposed
362
363   return PackageState{ explicitPackages    = dep_explicit,
364                        pkgIdMap            = pkg_db,
365                        moduleToPkgConf     = mod_map,
366                        basePackageId       = basePackageId,
367                        rtsPackageId        = rtsPackageId,
368                        haskell98PackageId  = haskell98PackageId,
369                        thPackageId         = thPackageId
370                      }
371   -- done!
372
373 basePackageName      = FSLIT("base")
374 rtsPackageName       = FSLIT("rts")
375 haskell98PackageName = FSLIT("haskell98")
376 thPackageName        = FSLIT("template-haskell")
377                                 -- Template Haskell libraries in here
378
379 overlappingError pkg overlaps
380   = throwDyn (CmdLineError (showSDoc (vcat (map msg overlaps))))
381   where 
382         this_pkg = text (showPackageId (package pkg))
383         msg (mod,other_pkg) =
384            text "Error: module '" <> ppr mod
385                  <> text "' is exposed by package "
386                  <> this_pkg <> text " and package "
387                  <> text (showPackageId (package other_pkg))
388
389 multiplePackagesErr str ps =
390   throwDyn (CmdLineError (showSDoc (
391                    text "Error; multiple packages match" <+> 
392                         text str <> colon <+>
393                     sep (punctuate comma (map (text.showPackageId.package) ps))
394                 )))
395
396 -- -----------------------------------------------------------------------------
397 -- Extracting information from the packages in scope
398
399 -- Many of these functions take a list of packages: in those cases,
400 -- the list is expected to contain the "dependent packages",
401 -- i.e. those packages that were found to be depended on by the
402 -- current module/program.  These can be auto or non-auto packages, it
403 -- doesn't really matter.  The list is always combined with the list
404 -- of explicit (command-line) packages to determine which packages to
405 -- use.
406
407 getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
408 getPackageIncludePath dflags pkgs = do
409   ps <- getExplicitPackagesAnd dflags pkgs
410   return (nub (filter notNull (concatMap includeDirs ps)))
411
412         -- includes are in reverse dependency order (i.e. rts first)
413 getPackageCIncludes :: [PackageConfig] -> IO [String]
414 getPackageCIncludes pkg_configs = do
415   return (reverse (nub (filter notNull (concatMap includes pkg_configs))))
416
417 getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
418 getPackageLibraryPath dflags pkgs = do 
419   ps <- getExplicitPackagesAnd dflags pkgs
420   return (nub (filter notNull (concatMap libraryDirs ps)))
421
422 getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
423 getPackageLinkOpts dflags pkgs = do
424   ps <- getExplicitPackagesAnd dflags pkgs
425   tag <- readIORef v_Build_tag
426   rts_tag <- readIORef v_RTS_Build_tag
427   static <- readIORef v_Static
428   let 
429         imp        = if static then "" else "_imp"
430         libs p     = map addSuffix (hACK (hsLibraries p)) ++ extraLibraries p
431         imp_libs p = map (++imp) (libs p)
432         all_opts p = map ("-l" ++) (imp_libs p) ++ extraLdOpts p
433
434         suffix     = if null tag then "" else  '_':tag
435         rts_suffix = if null rts_tag then "" else  '_':rts_tag
436
437         addSuffix rts@"HSrts"    = rts       ++ rts_suffix
438         addSuffix other_lib      = other_lib ++ suffix
439
440   return (concat (map all_opts ps))
441   where
442
443      -- This is a totally horrible (temporary) hack, for Win32.  Problem is
444      -- that package.conf for Win32 says that the main prelude lib is 
445      -- split into HSbase1, HSbase2 and HSbase3, which is needed due to a bug
446      -- in the GNU linker (PEi386 backend). However, we still only
447      -- have HSbase.a for static linking, not HSbase{1,2,3}.a
448      -- getPackageLibraries is called to find the .a's to add to the static
449      -- link line.  On Win32, this hACK detects HSbase{1,2,3} and 
450      -- replaces them with HSbase, so static linking still works.
451      -- Libraries needed for dynamic (GHCi) linking are discovered via
452      -- different route (in InteractiveUI.linkPackage).
453      -- See driver/PackageSrc.hs for the HSbase1/HSbase2 split definition.
454      -- THIS IS A STRICTLY TEMPORARY HACK (famous last words ...)
455      -- JRS 04 Sept 01: Same appalling hack for HSwin32[1,2]
456      -- KAA 29 Mar  02: Same appalling hack for HSobjectio[1,2,3,4]
457      hACK libs
458 #      if !defined(mingw32_TARGET_OS) && !defined(cygwin32_TARGET_OS)
459        = libs
460 #      else
461        = if   "HSbase1" `elem` libs && "HSbase2" `elem` libs && "HSbase3" `elem` libs
462          then "HSbase" : filter (not.(isPrefixOf "HSbase")) libs
463          else
464          if   "HSwin321" `elem` libs && "HSwin322" `elem` libs
465          then "HSwin32" : filter (not.(isPrefixOf "HSwin32")) libs
466          else 
467          if   "HSobjectio1" `elem` libs && "HSobjectio2" `elem` libs && "HSobjectio3" `elem` libs && "HSobjectio4" `elem` libs
468          then "HSobjectio" : filter (not.(isPrefixOf "HSobjectio")) libs
469          else 
470          libs
471 #      endif
472
473 getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
474 getPackageExtraCcOpts dflags pkgs = do
475   ps <- getExplicitPackagesAnd dflags pkgs
476   return (concatMap extraCcOpts ps)
477
478 getPackageFrameworkPath  :: DynFlags -> [PackageId] -> IO [String]
479 getPackageFrameworkPath dflags pkgs = do
480   ps <- getExplicitPackagesAnd dflags pkgs
481   return (nub (filter notNull (concatMap frameworkDirs ps)))
482
483 getPackageFrameworks  :: DynFlags -> [PackageId] -> IO [String]
484 getPackageFrameworks dflags pkgs = do
485   ps <- getExplicitPackagesAnd dflags pkgs
486   return (concatMap extraFrameworks ps)
487
488 -- -----------------------------------------------------------------------------
489 -- Package Utils
490
491 -- Takes a Module, and if the module is in a package returns 
492 -- (pkgconf,exposed) where pkgconf is the PackageConfig for that package,
493 -- and exposed is True if the package exposes the module.
494 moduleToPackageConfig :: DynFlags -> Module -> Maybe (PackageConfig,Bool)
495 moduleToPackageConfig dflags m = 
496   lookupUFM (moduleToPkgConf (pkgState dflags)) m
497
498 isHomeModule :: DynFlags -> Module -> Bool
499 isHomeModule dflags mod = isNothing (moduleToPackageConfig dflags mod)
500
501 getExplicitPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
502 getExplicitPackagesAnd dflags pkgids =
503   let 
504       state   = pkgState dflags
505       pkg_map = pkgIdMap state
506       expl    = explicitPackages state
507   in do
508   all_pkgs <- foldM (add_package pkg_map) expl pkgids
509   return (map (getPackageDetails state) all_pkgs)
510
511 -- Takes a list of packages, and returns the list with dependencies included,
512 -- in reverse dependency order (a package appears before those it depends on).
513 closeDeps :: PackageConfigMap -> [PackageId] -> IO [PackageId]
514 closeDeps pkg_map ps = foldM (add_package pkg_map) [] ps
515
516 -- internal helper
517 add_package :: PackageConfigMap -> [PackageId] -> PackageId -> IO [PackageId]
518 add_package pkg_db ps p
519   | p `elem` ps = return ps     -- Check if we've already added this package
520   | otherwise =
521       case lookupPackage pkg_db p of
522         Nothing -> missingPackageErr (packageIdString p)
523         Just pkg -> do
524            -- Add the package's dependents also
525            let deps = map mkPackageId (depends pkg)
526            ps' <- foldM (add_package pkg_db) ps deps
527            return (p : ps')
528
529 missingPackageErr p =  throwDyn (CmdLineError ("unknown package: " ++ p))
530
531 -- -----------------------------------------------------------------------------
532 -- Determining whether a Name refers to something in another package or not.
533 -- Cross-package references need to be handled differently when dynamically-
534 -- linked libraries are involved.
535
536 isDllName :: DynFlags -> Name -> Bool
537 isDllName dflags name
538   | opt_Static = False
539   | otherwise =
540     case nameModule_maybe name of
541         Nothing -> False  -- no, it is not even an external name
542         Just mod ->
543             case lookupUFM (moduleToPkgConf (pkgState dflags)) mod of
544                 Just _  -> True   -- yes, its a package module
545                 Nothing -> False  -- no, must be a home module
546
547 -- -----------------------------------------------------------------------------
548 -- Displaying packages
549
550 dumpPackages :: DynFlags -> IO ()
551 -- Show package info on console, if verbosity is >= 3
552 dumpPackages dflags
553   = do  let pkg_map = pkgIdMap (pkgState dflags)
554         hPutStrLn stderr $ showSDoc $
555               vcat (map (text.showInstalledPackageInfo) (eltsUFM pkg_map))
556 \end{code}