PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/main/Packages.lhs

http://github.com/ilyasergey/GHC-XAppFix
Haskell | 1057 lines | 618 code | 157 blank | 282 comment | 20 complexity | 1253f8e4b795fe1585f876226db8a521 MD5 | raw file
  1. %
  2. % (c) The University of Glasgow, 2006
  3. %
  4. \begin{code}
  5. {-# OPTIONS -fno-warn-tabs #-}
  6. -- The above warning supression flag is a temporary kludge.
  7. -- While working on this module you are encouraged to remove it and
  8. -- detab the module (please do the detabbing in a separate patch). See
  9. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  10. -- for details
  11. -- | Package manipulation
  12. module Packages (
  13. module PackageConfig,
  14. -- * The PackageConfigMap
  15. PackageConfigMap, emptyPackageConfigMap, lookupPackage,
  16. extendPackageConfigMap, dumpPackages,
  17. -- * Reading the package config, and processing cmdline args
  18. PackageState(..),
  19. initPackages,
  20. getPackageDetails,
  21. lookupModuleInAllPackages, lookupModuleWithSuggestions,
  22. -- * Inspecting the set of packages in scope
  23. getPackageIncludePath,
  24. getPackageLibraryPath,
  25. getPackageLinkOpts,
  26. getPackageExtraCcOpts,
  27. getPackageFrameworkPath,
  28. getPackageFrameworks,
  29. getPreloadPackagesAnd,
  30. collectIncludeDirs, collectLibraryPaths, collectLinkOpts,
  31. packageHsLibs,
  32. -- * Utils
  33. isDllName
  34. )
  35. where
  36. #include "HsVersions.h"
  37. import PackageConfig
  38. import DynFlags
  39. import StaticFlags
  40. import Config ( cProjectVersion )
  41. import Name ( Name, nameModule_maybe )
  42. import UniqFM
  43. import Module
  44. import Util
  45. import Panic
  46. import Outputable
  47. import Maybes
  48. import System.Environment ( getEnv )
  49. import Distribution.InstalledPackageInfo
  50. import Distribution.InstalledPackageInfo.Binary
  51. import Distribution.Package hiding (PackageId,depends)
  52. import FastString
  53. import ErrUtils ( debugTraceMsg, putMsg, Message )
  54. import Exception
  55. import System.Directory
  56. import System.FilePath as FilePath
  57. import qualified System.FilePath.Posix as FilePath.Posix
  58. import Control.Monad
  59. import Data.List as List
  60. import Data.Map (Map)
  61. import qualified Data.Map as Map
  62. import qualified FiniteMap as Map
  63. import qualified Data.Set as Set
  64. -- ---------------------------------------------------------------------------
  65. -- The Package state
  66. -- | Package state is all stored in 'DynFlag's, including the details of
  67. -- all packages, which packages are exposed, and which modules they
  68. -- provide.
  69. --
  70. -- The package state is computed by 'initPackages', and kept in DynFlags.
  71. --
  72. -- * @-package <pkg>@ causes @<pkg>@ to become exposed, and all other packages
  73. -- with the same name to become hidden.
  74. --
  75. -- * @-hide-package <pkg>@ causes @<pkg>@ to become hidden.
  76. --
  77. -- * Let @exposedPackages@ be the set of packages thus exposed.
  78. -- Let @depExposedPackages@ be the transitive closure from @exposedPackages@ of
  79. -- their dependencies.
  80. --
  81. -- * When searching for a module from an preload import declaration,
  82. -- only the exposed modules in @exposedPackages@ are valid.
  83. --
  84. -- * When searching for a module from an implicit import, all modules
  85. -- from @depExposedPackages@ are valid.
  86. --
  87. -- * When linking in a compilation manager mode, we link in packages the
  88. -- program depends on (the compiler knows this list by the
  89. -- time it gets to the link step). Also, we link in all packages
  90. -- which were mentioned with preload @-package@ flags on the command-line,
  91. -- or are a transitive dependency of same, or are \"base\"\/\"rts\".
  92. -- The reason for this is that we might need packages which don't
  93. -- contain any Haskell modules, and therefore won't be discovered
  94. -- by the normal mechanism of dependency tracking.
  95. -- Notes on DLLs
  96. -- ~~~~~~~~~~~~~
  97. -- When compiling module A, which imports module B, we need to
  98. -- know whether B will be in the same DLL as A.
  99. -- If it's in the same DLL, we refer to B_f_closure
  100. -- If it isn't, we refer to _imp__B_f_closure
  101. -- When compiling A, we record in B's Module value whether it's
  102. -- in a different DLL, by setting the DLL flag.
  103. data PackageState = PackageState {
  104. pkgIdMap :: PackageConfigMap, -- PackageId -> PackageConfig
  105. -- The exposed flags are adjusted according to -package and
  106. -- -hide-package flags, and -ignore-package removes packages.
  107. preloadPackages :: [PackageId],
  108. -- The packages we're going to link in eagerly. This list
  109. -- should be in reverse dependency order; that is, a package
  110. -- is always mentioned before the packages it depends on.
  111. moduleToPkgConfAll :: UniqFM [(PackageConfig,Bool)], -- ModuleEnv mapping
  112. -- Derived from pkgIdMap.
  113. -- Maps Module to (pkgconf,exposed), where pkgconf is the
  114. -- PackageConfig for the package containing the module, and
  115. -- exposed is True if the package exposes that module.
  116. installedPackageIdMap :: InstalledPackageIdMap
  117. }
  118. -- | A PackageConfigMap maps a 'PackageId' to a 'PackageConfig'
  119. type PackageConfigMap = UniqFM PackageConfig
  120. type InstalledPackageIdMap = Map InstalledPackageId PackageId
  121. type InstalledPackageIndex = Map InstalledPackageId PackageConfig
  122. emptyPackageConfigMap :: PackageConfigMap
  123. emptyPackageConfigMap = emptyUFM
  124. -- | Find the package we know about with the given id (e.g. \"foo-1.0\"), if any
  125. lookupPackage :: PackageConfigMap -> PackageId -> Maybe PackageConfig
  126. lookupPackage = lookupUFM
  127. extendPackageConfigMap
  128. :: PackageConfigMap -> [PackageConfig] -> PackageConfigMap
  129. extendPackageConfigMap pkg_map new_pkgs
  130. = foldl add pkg_map new_pkgs
  131. where add pkg_map p = addToUFM pkg_map (packageConfigId p) p
  132. -- | Looks up the package with the given id in the package state, panicing if it is
  133. -- not found
  134. getPackageDetails :: PackageState -> PackageId -> PackageConfig
  135. getPackageDetails ps pid = expectJust "getPackageDetails" (lookupPackage (pkgIdMap ps) pid)
  136. -- ----------------------------------------------------------------------------
  137. -- Loading the package config files and building up the package state
  138. -- | Call this after 'DynFlags.parseDynFlags'. It reads the package
  139. -- configuration files, and sets up various internal tables of package
  140. -- information, according to the package-related flags on the
  141. -- command-line (@-package@, @-hide-package@ etc.)
  142. --
  143. -- Returns a list of packages to link in if we're doing dynamic linking.
  144. -- This list contains the packages that the user explicitly mentioned with
  145. -- @-package@ flags.
  146. --
  147. -- 'initPackages' can be called again subsequently after updating the
  148. -- 'packageFlags' field of the 'DynFlags', and it will update the
  149. -- 'pkgState' in 'DynFlags' and return a list of packages to
  150. -- link in.
  151. initPackages :: DynFlags -> IO (DynFlags, [PackageId])
  152. initPackages dflags = do
  153. pkg_db <- case pkgDatabase dflags of
  154. Nothing -> readPackageConfigs dflags
  155. Just db -> return $ setBatchPackageFlags dflags db
  156. (pkg_state, preload, this_pkg)
  157. <- mkPackageState dflags pkg_db [] (thisPackage dflags)
  158. return (dflags{ pkgDatabase = Just pkg_db,
  159. pkgState = pkg_state,
  160. thisPackage = this_pkg },
  161. preload)
  162. -- -----------------------------------------------------------------------------
  163. -- Reading the package database(s)
  164. readPackageConfigs :: DynFlags -> IO [PackageConfig]
  165. readPackageConfigs dflags = do
  166. e_pkg_path <- tryIO (getEnv "GHC_PACKAGE_PATH")
  167. system_pkgconfs <- getSystemPackageConfigs dflags
  168. let pkgconfs = case e_pkg_path of
  169. Left _ -> system_pkgconfs
  170. Right path
  171. | last cs == "" -> init cs ++ system_pkgconfs
  172. | otherwise -> cs
  173. where cs = parseSearchPath path
  174. -- if the path ends in a separator (eg. "/foo/bar:")
  175. -- the we tack on the system paths.
  176. pkgs <- mapM (readPackageConfig dflags)
  177. (pkgconfs ++ reverse (extraPkgConfs dflags))
  178. -- later packages shadow earlier ones. extraPkgConfs
  179. -- is in the opposite order to the flags on the
  180. -- command line.
  181. return (concat pkgs)
  182. getSystemPackageConfigs :: DynFlags -> IO [FilePath]
  183. getSystemPackageConfigs dflags = do
  184. -- System one always comes first
  185. let system_pkgconf = systemPackageConfig dflags
  186. -- Read user's package conf (eg. ~/.ghc/i386-linux-6.3/package.conf)
  187. -- unless the -no-user-package-conf flag was given.
  188. user_pkgconf <- do
  189. if not (dopt Opt_ReadUserPackageConf dflags) then return [] else do
  190. appdir <- getAppUserDataDirectory "ghc"
  191. let
  192. dir = appdir </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':cProjectVersion)
  193. pkgconf = dir </> "package.conf.d"
  194. --
  195. exist <- doesDirectoryExist pkgconf
  196. if exist then return [pkgconf] else return []
  197. `catchIO` (\_ -> return [])
  198. return (system_pkgconf : user_pkgconf)
  199. readPackageConfig :: DynFlags -> FilePath -> IO [PackageConfig]
  200. readPackageConfig dflags conf_file = do
  201. isdir <- doesDirectoryExist conf_file
  202. proto_pkg_configs <-
  203. if isdir
  204. then do let filename = conf_file </> "package.cache"
  205. debugTraceMsg dflags 2 (text "Using binary package database:" <+> text filename)
  206. conf <- readBinPackageDB filename
  207. return (map installedPackageInfoToPackageConfig conf)
  208. else do
  209. isfile <- doesFileExist conf_file
  210. when (not isfile) $
  211. ghcError $ InstallationError $
  212. "can't find a package database at " ++ conf_file
  213. debugTraceMsg dflags 2 (text "Using package config file:" <+> text conf_file)
  214. str <- readFile conf_file
  215. return (map installedPackageInfoToPackageConfig $ read str)
  216. let
  217. top_dir = topDir dflags
  218. pkgroot = takeDirectory conf_file
  219. pkg_configs1 = map (mungePackagePaths top_dir pkgroot) proto_pkg_configs
  220. pkg_configs2 = setBatchPackageFlags dflags pkg_configs1
  221. --
  222. return pkg_configs2
  223. setBatchPackageFlags :: DynFlags -> [PackageConfig] -> [PackageConfig]
  224. setBatchPackageFlags dflags pkgs = (maybeDistrustAll . maybeHideAll) pkgs
  225. where
  226. maybeHideAll pkgs'
  227. | dopt Opt_HideAllPackages dflags = map hide pkgs'
  228. | otherwise = pkgs'
  229. maybeDistrustAll pkgs'
  230. | dopt Opt_DistrustAllPackages dflags = map distrust pkgs'
  231. | otherwise = pkgs'
  232. hide pkg = pkg{ exposed = False }
  233. distrust pkg = pkg{ exposed = False }
  234. -- TODO: This code is duplicated in utils/ghc-pkg/Main.hs
  235. mungePackagePaths :: FilePath -> FilePath -> PackageConfig -> PackageConfig
  236. -- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
  237. -- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
  238. -- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
  239. -- The "pkgroot" is the directory containing the package database.
  240. --
  241. -- Also perform a similar substitution for the older GHC-specific
  242. -- "$topdir" variable. The "topdir" is the location of the ghc
  243. -- installation (obtained from the -B option).
  244. mungePackagePaths top_dir pkgroot pkg =
  245. pkg {
  246. importDirs = munge_paths (importDirs pkg),
  247. includeDirs = munge_paths (includeDirs pkg),
  248. libraryDirs = munge_paths (libraryDirs pkg),
  249. frameworkDirs = munge_paths (frameworkDirs pkg),
  250. haddockInterfaces = munge_paths (haddockInterfaces pkg),
  251. haddockHTMLs = munge_urls (haddockHTMLs pkg)
  252. }
  253. where
  254. munge_paths = map munge_path
  255. munge_urls = map munge_url
  256. munge_path p
  257. | Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
  258. | Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
  259. | otherwise = p
  260. munge_url p
  261. | Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
  262. | Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
  263. | otherwise = p
  264. toUrlPath r p = "file:///"
  265. -- URLs always use posix style '/' separators:
  266. ++ FilePath.Posix.joinPath
  267. (r : -- We need to drop a leading "/" or "\\"
  268. -- if there is one:
  269. dropWhile (all isPathSeparator)
  270. (FilePath.splitDirectories p))
  271. -- We could drop the separator here, and then use </> above. However,
  272. -- by leaving it in and using ++ we keep the same path separator
  273. -- rather than letting FilePath change it to use \ as the separator
  274. stripVarPrefix var path = case stripPrefix var path of
  275. Just [] -> Just []
  276. Just cs@(c : _) | isPathSeparator c -> Just cs
  277. _ -> Nothing
  278. -- -----------------------------------------------------------------------------
  279. -- Modify our copy of the package database based on a package flag
  280. -- (-package, -hide-package, -ignore-package).
  281. applyPackageFlag
  282. :: UnusablePackages
  283. -> [PackageConfig] -- Initial database
  284. -> PackageFlag -- flag to apply
  285. -> IO [PackageConfig] -- new database
  286. applyPackageFlag unusable pkgs flag =
  287. case flag of
  288. ExposePackage str ->
  289. case selectPackages (matchingStr str) pkgs unusable of
  290. Left ps -> packageFlagErr flag ps
  291. Right (p:ps,qs) -> return (p':ps')
  292. where p' = p {exposed=True}
  293. ps' = hideAll (pkgName (sourcePackageId p)) (ps++qs)
  294. _ -> panic "applyPackageFlag"
  295. ExposePackageId str ->
  296. case selectPackages (matchingId str) pkgs unusable of
  297. Left ps -> packageFlagErr flag ps
  298. Right (p:ps,qs) -> return (p':ps')
  299. where p' = p {exposed=True}
  300. ps' = hideAll (pkgName (sourcePackageId p)) (ps++qs)
  301. _ -> panic "applyPackageFlag"
  302. HidePackage str ->
  303. case selectPackages (matchingStr str) pkgs unusable of
  304. Left ps -> packageFlagErr flag ps
  305. Right (ps,qs) -> return (map hide ps ++ qs)
  306. where hide p = p {exposed=False}
  307. -- we trust all matching packages. Maybe should only trust first one?
  308. -- and leave others the same or set them untrusted
  309. TrustPackage str ->
  310. case selectPackages (matchingStr str) pkgs unusable of
  311. Left ps -> packageFlagErr flag ps
  312. Right (ps,qs) -> return (map trust ps ++ qs)
  313. where trust p = p {trusted=True}
  314. DistrustPackage str ->
  315. case selectPackages (matchingStr str) pkgs unusable of
  316. Left ps -> packageFlagErr flag ps
  317. Right (ps,qs) -> return (map distrust ps ++ qs)
  318. where distrust p = p {trusted=False}
  319. _ -> panic "applyPackageFlag"
  320. where
  321. -- When a package is requested to be exposed, we hide all other
  322. -- packages with the same name.
  323. hideAll name ps = map maybe_hide ps
  324. where maybe_hide p
  325. | pkgName (sourcePackageId p) == name = p {exposed=False}
  326. | otherwise = p
  327. selectPackages :: (PackageConfig -> Bool) -> [PackageConfig]
  328. -> UnusablePackages
  329. -> Either [(PackageConfig, UnusablePackageReason)]
  330. ([PackageConfig], [PackageConfig])
  331. selectPackages matches pkgs unusable
  332. = let
  333. (ps,rest) = partition matches pkgs
  334. reasons = [ (p, Map.lookup (installedPackageId p) unusable)
  335. | p <- ps ]
  336. in
  337. if all (isJust.snd) reasons
  338. then Left [ (p, reason) | (p,Just reason) <- reasons ]
  339. else Right (sortByVersion [ p | (p,Nothing) <- reasons ], rest)
  340. -- A package named on the command line can either include the
  341. -- version, or just the name if it is unambiguous.
  342. matchingStr :: String -> PackageConfig -> Bool
  343. matchingStr str p
  344. = str == display (sourcePackageId p)
  345. || str == display (pkgName (sourcePackageId p))
  346. matchingId :: String -> PackageConfig -> Bool
  347. matchingId str p = InstalledPackageId str == installedPackageId p
  348. sortByVersion :: [InstalledPackageInfo_ m] -> [InstalledPackageInfo_ m]
  349. sortByVersion = sortBy (flip (comparing (pkgVersion.sourcePackageId)))
  350. comparing :: Ord a => (t -> a) -> t -> t -> Ordering
  351. comparing f a b = f a `compare` f b
  352. packageFlagErr :: PackageFlag
  353. -> [(PackageConfig, UnusablePackageReason)]
  354. -> IO a
  355. -- for missing DPH package we emit a more helpful error message, because
  356. -- this may be the result of using -fdph-par or -fdph-seq.
  357. packageFlagErr (ExposePackage pkg) [] | is_dph_package pkg
  358. = ghcError (CmdLineError (showSDoc $ dph_err))
  359. where dph_err = text "the " <> text pkg <> text " package is not installed."
  360. $$ text "To install it: \"cabal install dph\"."
  361. is_dph_package pkg = "dph" `isPrefixOf` pkg
  362. packageFlagErr flag reasons = ghcError (CmdLineError (showSDoc $ err))
  363. where err = text "cannot satisfy " <> ppr_flag <>
  364. (if null reasons then empty else text ": ") $$
  365. nest 4 (ppr_reasons $$
  366. text "(use -v for more information)")
  367. ppr_flag = case flag of
  368. IgnorePackage p -> text "-ignore-package " <> text p
  369. HidePackage p -> text "-hide-package " <> text p
  370. ExposePackage p -> text "-package " <> text p
  371. ExposePackageId p -> text "-package-id " <> text p
  372. TrustPackage p -> text "-trust " <> text p
  373. DistrustPackage p -> text "-distrust " <> text p
  374. ppr_reasons = vcat (map ppr_reason reasons)
  375. ppr_reason (p, reason) = pprReason (pprIPkg p <+> text "is") reason
  376. -- -----------------------------------------------------------------------------
  377. -- Hide old versions of packages
  378. --
  379. -- hide all packages for which there is also a later version
  380. -- that is already exposed. This just makes it non-fatal to have two
  381. -- versions of a package exposed, which can happen if you install a
  382. -- later version of a package in the user database, for example.
  383. --
  384. hideOldPackages :: DynFlags -> [PackageConfig] -> IO [PackageConfig]
  385. hideOldPackages dflags pkgs = mapM maybe_hide pkgs
  386. where maybe_hide p
  387. | not (exposed p) = return p
  388. | (p' : _) <- later_versions = do
  389. debugTraceMsg dflags 2 $
  390. (ptext (sLit "hiding package") <+> pprSPkg p <+>
  391. ptext (sLit "to avoid conflict with later version") <+>
  392. pprSPkg p')
  393. return (p {exposed=False})
  394. | otherwise = return p
  395. where myname = pkgName (sourcePackageId p)
  396. myversion = pkgVersion (sourcePackageId p)
  397. later_versions = [ p | p <- pkgs, exposed p,
  398. let pkg = sourcePackageId p,
  399. pkgName pkg == myname,
  400. pkgVersion pkg > myversion ]
  401. -- -----------------------------------------------------------------------------
  402. -- Wired-in packages
  403. findWiredInPackages
  404. :: DynFlags
  405. -> [PackageConfig] -- database
  406. -> IO [PackageConfig]
  407. findWiredInPackages dflags pkgs = do
  408. --
  409. -- Now we must find our wired-in packages, and rename them to
  410. -- their canonical names (eg. base-1.0 ==> base).
  411. --
  412. let
  413. wired_in_pkgids :: [String]
  414. wired_in_pkgids = map packageIdString
  415. [ primPackageId,
  416. integerPackageId,
  417. basePackageId,
  418. rtsPackageId,
  419. thPackageId,
  420. dphSeqPackageId,
  421. dphParPackageId ]
  422. matches :: PackageConfig -> String -> Bool
  423. pc `matches` pid = display (pkgName (sourcePackageId pc)) == pid
  424. -- find which package corresponds to each wired-in package
  425. -- delete any other packages with the same name
  426. -- update the package and any dependencies to point to the new
  427. -- one.
  428. --
  429. -- When choosing which package to map to a wired-in package
  430. -- name, we prefer exposed packages, and pick the latest
  431. -- version. To override the default choice, -hide-package
  432. -- could be used to hide newer versions.
  433. --
  434. findWiredInPackage :: [PackageConfig] -> String
  435. -> IO (Maybe InstalledPackageId)
  436. findWiredInPackage pkgs wired_pkg =
  437. let all_ps = [ p | p <- pkgs, p `matches` wired_pkg ] in
  438. case all_ps of
  439. [] -> notfound
  440. many -> pick (head (sortByVersion many))
  441. where
  442. notfound = do
  443. debugTraceMsg dflags 2 $
  444. ptext (sLit "wired-in package ")
  445. <> text wired_pkg
  446. <> ptext (sLit " not found.")
  447. return Nothing
  448. pick :: InstalledPackageInfo_ ModuleName
  449. -> IO (Maybe InstalledPackageId)
  450. pick pkg = do
  451. debugTraceMsg dflags 2 $
  452. ptext (sLit "wired-in package ")
  453. <> text wired_pkg
  454. <> ptext (sLit " mapped to ")
  455. <> pprIPkg pkg
  456. return (Just (installedPackageId pkg))
  457. mb_wired_in_ids <- mapM (findWiredInPackage pkgs) wired_in_pkgids
  458. let
  459. wired_in_ids = catMaybes mb_wired_in_ids
  460. -- this is old: we used to assume that if there were
  461. -- multiple versions of wired-in packages installed that
  462. -- they were mutually exclusive. Now we're assuming that
  463. -- you have one "main" version of each wired-in package
  464. -- (the latest version), and the others are backward-compat
  465. -- wrappers that depend on this one. e.g. base-4.0 is the
  466. -- latest, base-3.0 is a compat wrapper depending on base-4.0.
  467. {-
  468. deleteOtherWiredInPackages pkgs = filterOut bad pkgs
  469. where bad p = any (p `matches`) wired_in_pkgids
  470. && package p `notElem` map fst wired_in_ids
  471. -}
  472. updateWiredInDependencies pkgs = map upd_pkg pkgs
  473. where upd_pkg p
  474. | installedPackageId p `elem` wired_in_ids
  475. = p { sourcePackageId = (sourcePackageId p){ pkgVersion = Version [] [] } }
  476. | otherwise
  477. = p
  478. return $ updateWiredInDependencies pkgs
  479. -- ----------------------------------------------------------------------------
  480. data UnusablePackageReason
  481. = IgnoredWithFlag
  482. | MissingDependencies [InstalledPackageId]
  483. | ShadowedBy InstalledPackageId
  484. type UnusablePackages = Map InstalledPackageId UnusablePackageReason
  485. pprReason :: SDoc -> UnusablePackageReason -> SDoc
  486. pprReason pref reason = case reason of
  487. IgnoredWithFlag ->
  488. pref <+> ptext (sLit "ignored due to an -ignore-package flag")
  489. MissingDependencies deps ->
  490. pref <+>
  491. ptext (sLit "unusable due to missing or recursive dependencies:") $$
  492. nest 2 (hsep (map (text.display) deps))
  493. ShadowedBy ipid ->
  494. pref <+> ptext (sLit "shadowed by package ") <> text (display ipid)
  495. reportUnusable :: DynFlags -> UnusablePackages -> IO ()
  496. reportUnusable dflags pkgs = mapM_ report (Map.toList pkgs)
  497. where
  498. report (ipid, reason) =
  499. debugTraceMsg dflags 2 $
  500. pprReason
  501. (ptext (sLit "package") <+>
  502. text (display ipid) <+> text "is") reason
  503. -- ----------------------------------------------------------------------------
  504. --
  505. -- Detect any packages that have missing dependencies, and also any
  506. -- mutually-recursive groups of packages (loops in the package graph
  507. -- are not allowed). We do this by taking the least fixpoint of the
  508. -- dependency graph, repeatedly adding packages whose dependencies are
  509. -- satisfied until no more can be added.
  510. --
  511. findBroken :: [PackageConfig] -> UnusablePackages
  512. findBroken pkgs = go [] Map.empty pkgs
  513. where
  514. go avail ipids not_avail =
  515. case partitionWith (depsAvailable ipids) not_avail of
  516. ([], not_avail) ->
  517. Map.fromList [ (installedPackageId p, MissingDependencies deps)
  518. | (p,deps) <- not_avail ]
  519. (new_avail, not_avail) ->
  520. go (new_avail ++ avail) new_ipids (map fst not_avail)
  521. where new_ipids = Map.insertList
  522. [ (installedPackageId p, p) | p <- new_avail ]
  523. ipids
  524. depsAvailable :: InstalledPackageIndex
  525. -> PackageConfig
  526. -> Either PackageConfig (PackageConfig, [InstalledPackageId])
  527. depsAvailable ipids pkg
  528. | null dangling = Left pkg
  529. | otherwise = Right (pkg, dangling)
  530. where dangling = filter (not . (`Map.member` ipids)) (depends pkg)
  531. -- -----------------------------------------------------------------------------
  532. -- Eliminate shadowed packages, giving the user some feedback
  533. -- later packages in the list should shadow earlier ones with the same
  534. -- package name/version. Additionally, a package may be preferred if
  535. -- it is in the transitive closure of packages selected using -package-id
  536. -- flags.
  537. shadowPackages :: [PackageConfig] -> [InstalledPackageId] -> UnusablePackages
  538. shadowPackages pkgs preferred
  539. = let (shadowed,_) = foldl check ([],emptyUFM) pkgs
  540. in Map.fromList shadowed
  541. where
  542. check (shadowed,pkgmap) pkg
  543. | Just oldpkg <- lookupUFM pkgmap (packageConfigId pkg)
  544. , let
  545. ipid_new = installedPackageId pkg
  546. ipid_old = installedPackageId oldpkg
  547. --
  548. , ipid_old /= ipid_new
  549. = if ipid_old `elem` preferred
  550. then ( (ipid_new, ShadowedBy ipid_old) : shadowed, pkgmap )
  551. else ( (ipid_old, ShadowedBy ipid_new) : shadowed, pkgmap' )
  552. | otherwise
  553. = (shadowed, pkgmap')
  554. where
  555. pkgmap' = addToUFM pkgmap (packageConfigId pkg) pkg
  556. -- -----------------------------------------------------------------------------
  557. ignorePackages :: [PackageFlag] -> [PackageConfig] -> UnusablePackages
  558. ignorePackages flags pkgs = Map.fromList (concatMap doit flags)
  559. where
  560. doit (IgnorePackage str) =
  561. case partition (matchingStr str) pkgs of
  562. (ps, _) -> [ (installedPackageId p, IgnoredWithFlag)
  563. | p <- ps ]
  564. -- missing package is not an error for -ignore-package,
  565. -- because a common usage is to -ignore-package P as
  566. -- a preventative measure just in case P exists.
  567. doit _ = panic "ignorePackages"
  568. -- -----------------------------------------------------------------------------
  569. depClosure :: InstalledPackageIndex
  570. -> [InstalledPackageId]
  571. -> [InstalledPackageId]
  572. depClosure index ipids = closure Map.empty ipids
  573. where
  574. closure set [] = Map.keys set
  575. closure set (ipid : ipids)
  576. | ipid `Map.member` set = closure set ipids
  577. | Just p <- Map.lookup ipid index = closure (Map.insert ipid p set)
  578. (depends p ++ ipids)
  579. | otherwise = closure set ipids
  580. -- -----------------------------------------------------------------------------
  581. -- When all the command-line options are in, we can process our package
  582. -- settings and populate the package state.
  583. mkPackageState
  584. :: DynFlags
  585. -> [PackageConfig] -- initial database
  586. -> [PackageId] -- preloaded packages
  587. -> PackageId -- this package
  588. -> IO (PackageState,
  589. [PackageId], -- new packages to preload
  590. PackageId) -- this package, might be modified if the current
  591. -- package is a wired-in package.
  592. mkPackageState dflags pkgs0 preload0 this_package = do
  593. {-
  594. Plan.
  595. 1. P = transitive closure of packages selected by -package-id
  596. 2. Apply shadowing. When there are multiple packages with the same
  597. sourcePackageId,
  598. * if one is in P, use that one
  599. * otherwise, use the one highest in the package stack
  600. [
  601. rationale: we cannot use two packages with the same sourcePackageId
  602. in the same program, because sourcePackageId is the symbol prefix.
  603. Hence we must select a consistent set of packages to use. We have
  604. a default algorithm for doing this: packages higher in the stack
  605. shadow those lower down. This default algorithm can be overriden
  606. by giving explicit -package-id flags; then we have to take these
  607. preferences into account when selecting which other packages are
  608. made available.
  609. Our simple algorithm throws away some solutions: there may be other
  610. consistent sets that would satisfy the -package flags, but it's
  611. not GHC's job to be doing constraint solving.
  612. ]
  613. 3. remove packages selected by -ignore-package
  614. 4. remove any packages with missing dependencies, or mutually recursive
  615. dependencies.
  616. 5. report (with -v) any packages that were removed by steps 2-4
  617. 6. apply flags to set exposed/hidden on the resulting packages
  618. - if any flag refers to a package which was removed by 2-4, then
  619. we can give an error message explaining why
  620. 7. hide any packages which are superseded by later exposed packages
  621. -}
  622. let
  623. flags = reverse (packageFlags dflags)
  624. -- pkgs0 with duplicate packages filtered out. This is
  625. -- important: it is possible for a package in the global package
  626. -- DB to have the same IPID as a package in the user DB, and
  627. -- we want the latter to take precedence. This is not the same
  628. -- as shadowing (below), since in this case the two packages
  629. -- have the same ABI and are interchangeable.
  630. --
  631. -- #4072: note that we must retain the ordering of the list here
  632. -- so that shadowing behaves as expected when we apply it later.
  633. pkgs0_unique = snd $ foldr del (Set.empty,[]) pkgs0
  634. where del p (s,ps)
  635. | pid `Set.member` s = (s,ps)
  636. | otherwise = (Set.insert pid s, p:ps)
  637. where pid = installedPackageId p
  638. -- XXX this is just a variant of nub
  639. ipid_map = Map.fromList [ (installedPackageId p, p) | p <- pkgs0 ]
  640. ipid_selected = depClosure ipid_map [ InstalledPackageId i
  641. | ExposePackageId i <- flags ]
  642. (ignore_flags, other_flags) = partition is_ignore flags
  643. is_ignore IgnorePackage{} = True
  644. is_ignore _ = False
  645. shadowed = shadowPackages pkgs0_unique ipid_selected
  646. ignored = ignorePackages ignore_flags pkgs0_unique
  647. pkgs0' = filter (not . (`Map.member` (Map.union shadowed ignored)) . installedPackageId) pkgs0_unique
  648. broken = findBroken pkgs0'
  649. unusable = shadowed `Map.union` ignored `Map.union` broken
  650. reportUnusable dflags unusable
  651. --
  652. -- Modify the package database according to the command-line flags
  653. -- (-package, -hide-package, -ignore-package, -hide-all-packages).
  654. --
  655. pkgs1 <- foldM (applyPackageFlag unusable) pkgs0_unique other_flags
  656. let pkgs2 = filter (not . (`Map.member` unusable) . installedPackageId) pkgs1
  657. -- Here we build up a set of the packages mentioned in -package
  658. -- flags on the command line; these are called the "preload"
  659. -- packages. we link these packages in eagerly. The preload set
  660. -- should contain at least rts & base, which is why we pretend that
  661. -- the command line contains -package rts & -package base.
  662. --
  663. let preload1 = [ installedPackageId p | f <- flags, p <- get_exposed f ]
  664. get_exposed (ExposePackage s) = filter (matchingStr s) pkgs2
  665. get_exposed (ExposePackageId s) = filter (matchingId s) pkgs2
  666. get_exposed _ = []
  667. -- hide packages that are subsumed by later versions
  668. pkgs3 <- hideOldPackages dflags pkgs2
  669. -- sort out which packages are wired in
  670. pkgs4 <- findWiredInPackages dflags pkgs3
  671. let pkg_db = extendPackageConfigMap emptyPackageConfigMap pkgs4
  672. ipid_map = Map.fromList [ (installedPackageId p, packageConfigId p)
  673. | p <- pkgs4 ]
  674. lookupIPID ipid@(InstalledPackageId str)
  675. | Just pid <- Map.lookup ipid ipid_map = return pid
  676. | otherwise = missingPackageErr str
  677. preload2 <- mapM lookupIPID preload1
  678. let
  679. -- add base & rts to the preload packages
  680. basicLinkedPackages
  681. | dopt Opt_AutoLinkPackages dflags
  682. = filter (flip elemUFM pkg_db) [basePackageId, rtsPackageId]
  683. | otherwise = []
  684. -- but in any case remove the current package from the set of
  685. -- preloaded packages so that base/rts does not end up in the
  686. -- set up preloaded package when we are just building it
  687. preload3 = nub $ filter (/= this_package)
  688. $ (basicLinkedPackages ++ preload2)
  689. -- Close the preload packages with their dependencies
  690. dep_preload <- closeDeps pkg_db ipid_map (zip preload3 (repeat Nothing))
  691. let new_dep_preload = filter (`notElem` preload0) dep_preload
  692. let pstate = PackageState{ preloadPackages = dep_preload,
  693. pkgIdMap = pkg_db,
  694. moduleToPkgConfAll = mkModuleMap pkg_db,
  695. installedPackageIdMap = ipid_map
  696. }
  697. return (pstate, new_dep_preload, this_package)
  698. -- -----------------------------------------------------------------------------
  699. -- Make the mapping from module to package info
  700. mkModuleMap
  701. :: PackageConfigMap
  702. -> UniqFM [(PackageConfig, Bool)]
  703. mkModuleMap pkg_db = foldr extend_modmap emptyUFM pkgids
  704. where
  705. pkgids = map packageConfigId (eltsUFM pkg_db)
  706. extend_modmap pkgid modmap =
  707. addListToUFM_C (++) modmap
  708. ([(m, [(pkg, True)]) | m <- exposed_mods] ++
  709. [(m, [(pkg, False)]) | m <- hidden_mods])
  710. where
  711. pkg = expectJust "mkModuleMap" (lookupPackage pkg_db pkgid)
  712. exposed_mods = exposedModules pkg
  713. hidden_mods = hiddenModules pkg
  714. pprSPkg :: PackageConfig -> SDoc
  715. pprSPkg p = text (display (sourcePackageId p))
  716. pprIPkg :: PackageConfig -> SDoc
  717. pprIPkg p = text (display (installedPackageId p))
  718. -- -----------------------------------------------------------------------------
  719. -- Extracting information from the packages in scope
  720. -- Many of these functions take a list of packages: in those cases,
  721. -- the list is expected to contain the "dependent packages",
  722. -- i.e. those packages that were found to be depended on by the
  723. -- current module/program. These can be auto or non-auto packages, it
  724. -- doesn't really matter. The list is always combined with the list
  725. -- of preload (command-line) packages to determine which packages to
  726. -- use.
  727. -- | Find all the include directories in these and the preload packages
  728. getPackageIncludePath :: DynFlags -> [PackageId] -> IO [String]
  729. getPackageIncludePath dflags pkgs =
  730. collectIncludeDirs `fmap` getPreloadPackagesAnd dflags pkgs
  731. collectIncludeDirs :: [PackageConfig] -> [FilePath]
  732. collectIncludeDirs ps = nub (filter notNull (concatMap includeDirs ps))
  733. -- | Find all the library paths in these and the preload packages
  734. getPackageLibraryPath :: DynFlags -> [PackageId] -> IO [String]
  735. getPackageLibraryPath dflags pkgs =
  736. collectLibraryPaths `fmap` getPreloadPackagesAnd dflags pkgs
  737. collectLibraryPaths :: [PackageConfig] -> [FilePath]
  738. collectLibraryPaths ps = nub (filter notNull (concatMap libraryDirs ps))
  739. -- | Find all the link options in these and the preload packages
  740. getPackageLinkOpts :: DynFlags -> [PackageId] -> IO [String]
  741. getPackageLinkOpts dflags pkgs =
  742. collectLinkOpts dflags `fmap` getPreloadPackagesAnd dflags pkgs
  743. collectLinkOpts :: DynFlags -> [PackageConfig] -> [String]
  744. collectLinkOpts dflags ps = concat (map all_opts ps)
  745. where
  746. libs p = packageHsLibs dflags p ++ extraLibraries p
  747. all_opts p = map ("-l" ++) (libs p) ++ ldOptions p
  748. packageHsLibs :: DynFlags -> PackageConfig -> [String]
  749. packageHsLibs dflags p = map (mkDynName . addSuffix) (hsLibraries p)
  750. where
  751. ways0 = ways dflags
  752. ways1 = filter ((/= WayDyn) . wayName) ways0
  753. -- the name of a shared library is libHSfoo-ghc<version>.so
  754. -- we leave out the _dyn, because it is superfluous
  755. -- debug RTS includes support for -eventlog
  756. ways2 | WayDebug `elem` map wayName ways1
  757. = filter ((/= WayEventLog) . wayName) ways1
  758. | otherwise
  759. = ways1
  760. tag = mkBuildTag (filter (not . wayRTSOnly) ways2)
  761. rts_tag = mkBuildTag ways2
  762. mkDynName | opt_Static = id
  763. | otherwise = (++ ("-ghc" ++ cProjectVersion))
  764. addSuffix rts@"HSrts" = rts ++ (expandTag rts_tag)
  765. addSuffix other_lib = other_lib ++ (expandTag tag)
  766. expandTag t | null t = ""
  767. | otherwise = '_':t
  768. -- | Find all the C-compiler options in these and the preload packages
  769. getPackageExtraCcOpts :: DynFlags -> [PackageId] -> IO [String]
  770. getPackageExtraCcOpts dflags pkgs = do
  771. ps <- getPreloadPackagesAnd dflags pkgs
  772. return (concatMap ccOptions ps)
  773. -- | Find all the package framework paths in these and the preload packages
  774. getPackageFrameworkPath :: DynFlags -> [PackageId] -> IO [String]
  775. getPackageFrameworkPath dflags pkgs = do
  776. ps <- getPreloadPackagesAnd dflags pkgs
  777. return (nub (filter notNull (concatMap frameworkDirs ps)))
  778. -- | Find all the package frameworks in these and the preload packages
  779. getPackageFrameworks :: DynFlags -> [PackageId] -> IO [String]
  780. getPackageFrameworks dflags pkgs = do
  781. ps <- getPreloadPackagesAnd dflags pkgs
  782. return (concatMap frameworks ps)
  783. -- -----------------------------------------------------------------------------
  784. -- Package Utils
  785. -- | Takes a 'Module', and if the module is in a package returns
  786. -- @(pkgconf, exposed)@ where pkgconf is the PackageConfig for that package,
  787. -- and exposed is @True@ if the package exposes the module.
  788. lookupModuleInAllPackages :: DynFlags -> ModuleName -> [(PackageConfig,Bool)]
  789. lookupModuleInAllPackages dflags m
  790. = case lookupModuleWithSuggestions dflags m of
  791. Right pbs -> pbs
  792. Left _ -> []
  793. lookupModuleWithSuggestions
  794. :: DynFlags -> ModuleName
  795. -> Either [Module] [(PackageConfig,Bool)]
  796. -- Lookup module in all packages
  797. -- Right pbs => found in pbs
  798. -- Left ms => not found; but here are sugestions
  799. lookupModuleWithSuggestions dflags m
  800. = case lookupUFM (moduleToPkgConfAll pkg_state) m of
  801. Nothing -> Left suggestions
  802. Just ps -> Right ps
  803. where
  804. pkg_state = pkgState dflags
  805. suggestions
  806. | dopt Opt_HelpfulErrors dflags = fuzzyLookup (moduleNameString m) all_mods
  807. | otherwise = []
  808. all_mods :: [(String, Module)] -- All modules
  809. all_mods = [ (moduleNameString mod_nm, mkModule pkg_id mod_nm)
  810. | pkg_config <- eltsUFM (pkgIdMap pkg_state)
  811. , let pkg_id = packageConfigId pkg_config
  812. , mod_nm <- exposedModules pkg_config ]
  813. -- | Find all the 'PackageConfig' in both the preload packages from 'DynFlags' and corresponding to the list of
  814. -- 'PackageConfig's
  815. getPreloadPackagesAnd :: DynFlags -> [PackageId] -> IO [PackageConfig]
  816. getPreloadPackagesAnd dflags pkgids =
  817. let
  818. state = pkgState dflags
  819. pkg_map = pkgIdMap state
  820. ipid_map = installedPackageIdMap state
  821. preload = preloadPackages state
  822. pairs = zip pkgids (repeat Nothing)
  823. in do
  824. all_pkgs <- throwErr (foldM (add_package pkg_map ipid_map) preload pairs)
  825. return (map (getPackageDetails state) all_pkgs)
  826. -- Takes a list of packages, and returns the list with dependencies included,
  827. -- in reverse dependency order (a package appears before those it depends on).
  828. closeDeps :: PackageConfigMap
  829. -> Map InstalledPackageId PackageId
  830. -> [(PackageId, Maybe PackageId)]
  831. -> IO [PackageId]
  832. closeDeps pkg_map ipid_map ps = throwErr (closeDepsErr pkg_map ipid_map ps)
  833. throwErr :: MaybeErr Message a -> IO a
  834. throwErr m = case m of
  835. Failed e -> ghcError (CmdLineError (showSDoc e))
  836. Succeeded r -> return r
  837. closeDepsErr :: PackageConfigMap
  838. -> Map InstalledPackageId PackageId
  839. -> [(PackageId,Maybe PackageId)]
  840. -> MaybeErr Message [PackageId]
  841. closeDepsErr pkg_map ipid_map ps = foldM (add_package pkg_map ipid_map) [] ps
  842. -- internal helper
  843. add_package :: PackageConfigMap
  844. -> Map InstalledPackageId PackageId
  845. -> [PackageId]
  846. -> (PackageId,Maybe PackageId)
  847. -> MaybeErr Message [PackageId]
  848. add_package pkg_db ipid_map ps (p, mb_parent)
  849. | p `elem` ps = return ps -- Check if we've already added this package
  850. | otherwise =
  851. case lookupPackage pkg_db p of
  852. Nothing -> Failed (missingPackageMsg (packageIdString p) <>
  853. missingDependencyMsg mb_parent)
  854. Just pkg -> do
  855. -- Add the package's dependents also
  856. ps' <- foldM add_package_ipid ps (depends pkg)
  857. return (p : ps')
  858. where
  859. add_package_ipid ps ipid@(InstalledPackageId str)
  860. | Just pid <- Map.lookup ipid ipid_map
  861. = add_package pkg_db ipid_map ps (pid, Just p)
  862. | otherwise
  863. = Failed (missingPackageMsg str <> missingDependencyMsg mb_parent)
  864. missingPackageErr :: String -> IO a
  865. missingPackageErr p = ghcError (CmdLineError (showSDoc (missingPackageMsg p)))
  866. missingPackageMsg :: String -> SDoc
  867. missingPackageMsg p = ptext (sLit "unknown package:") <+> text p
  868. missingDependencyMsg :: Maybe PackageId -> SDoc
  869. missingDependencyMsg Nothing = empty
  870. missingDependencyMsg (Just parent)
  871. = space <> parens (ptext (sLit "dependency of") <+> ftext (packageIdFS parent))
  872. -- -----------------------------------------------------------------------------
  873. -- | Will the 'Name' come from a dynamically linked library?
  874. isDllName :: PackageId -> Name -> Bool
  875. -- Despite the "dll", I think this function just means that
  876. -- the synbol comes from another dynamically-linked package,
  877. -- and applies on all platforms, not just Windows
  878. isDllName this_pkg name
  879. | opt_Static = False
  880. | Just mod <- nameModule_maybe name = modulePackageId mod /= this_pkg
  881. | otherwise = False -- no, it is not even an external name
  882. -- -----------------------------------------------------------------------------
  883. -- Displaying packages
  884. -- | Show package info on console, if verbosity is >= 3
  885. dumpPackages :: DynFlags -> IO ()
  886. dumpPackages dflags
  887. = do let pkg_map = pkgIdMap (pkgState dflags)
  888. putMsg dflags $
  889. vcat (map (text . showInstalledPackageInfo
  890. . packageConfigToInstalledPackageInfo)
  891. (eltsUFM pkg_map))
  892. \end{code}