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