State.hs 88.1 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2
-- (c) The University of Glasgow, 2006

Edward Z. Yang's avatar
Edward Z. Yang committed
3
{-# LANGUAGE CPP, ScopedTypeVariables, BangPatterns, FlexibleContexts #-}
4

5
-- | Package manipulation
6
module GHC.Unit.State (
7
        module GHC.Unit.Info,
8 9

        -- * Reading the package config, and processing cmdline args
10
        PackageState(..),
Sylvain Henry's avatar
Sylvain Henry committed
11 12
        UnitDatabase (..),
        ClosureUnitInfoMap,
13
        emptyPackageState,
Sylvain Henry's avatar
Sylvain Henry committed
14 15 16 17 18
        initUnits,
        readUnitDatabases,
        readUnitDatabase,
        getPackageDbRefs,
        resolveUnitDatabase,
19
        listUnitInfo,
20 21

        -- * Querying the package config
22 23
        lookupUnit,
        lookupUnit',
Sylvain Henry's avatar
Sylvain Henry committed
24 25 26 27 28
        unsafeLookupUnit,
        lookupUnitId,
        lookupUnitId',
        unsafeLookupUnitId,

Edward Z. Yang's avatar
Edward Z. Yang committed
29
        lookupPackageName,
30
        improveUnit,
31
        searchPackageId,
32
        displayUnitId,
33
        listVisibleModuleNames,
34 35
        lookupModuleInAllPackages,
        lookupModuleWithSuggestions,
36
        lookupPluginModuleWithSuggestions,
37
        LookupResult(..),
38 39
        ModuleSuggestion(..),
        ModuleOrigin(..),
Sylvain Henry's avatar
Sylvain Henry committed
40
        UnusableUnitReason(..),
41
        pprReason,
42 43

        -- * Inspecting the set of packages in scope
Sylvain Henry's avatar
Sylvain Henry committed
44 45 46 47 48 49 50
        getUnitIncludePath,
        getUnitLibraryPath,
        getUnitLinkOpts,
        getUnitExtraCcOpts,
        getUnitFrameworkPath,
        getUnitFrameworks,
        getPreloadUnitsAnd,
51

Moritz Angermann's avatar
Moritz Angermann committed
52
        collectArchives,
53
        collectIncludeDirs, collectLibraryPaths, collectLinkOpts,
54
        packageHsLibs, getLibs,
55

56
        -- * Utils
57 58 59
        mkIndefUnitId,
        updateIndefUnitId,
        unwireUnit,
60
        pprFlag,
61 62
        pprPackages,
        pprPackagesSimple,
63
        pprModuleMap,
Sylvain Henry's avatar
Sylvain Henry committed
64 65
        homeUnitIsIndefinite,
        homeUnitIsDefinite,
66
    )
67 68 69
where

#include "HsVersions.h"
70

71
import GHC.Prelude
72

73
import GHC.Unit.Database
74
import GHC.Unit.Info
75 76 77
import GHC.Unit.Types
import GHC.Unit.Module
import GHC.Unit.Subst
Sylvain Henry's avatar
Sylvain Henry committed
78
import GHC.Driver.Session
Sylvain Henry's avatar
Sylvain Henry committed
79
import GHC.Driver.Ways
Sylvain Henry's avatar
Sylvain Henry committed
80 81 82
import GHC.Types.Unique.FM
import GHC.Types.Unique.DFM
import GHC.Types.Unique.Set
83 84 85 86
import GHC.Utils.Misc
import GHC.Utils.Panic
import GHC.Utils.Outputable as Outputable
import GHC.Data.Maybe
87

88
import System.Environment ( getEnv )
89 90
import GHC.Data.FastString
import GHC.Utils.Error  ( debugTraceMsg, MsgDoc, dumpIfSet_dyn,
Sylvain Henry's avatar
Sylvain Henry committed
91
                          withTiming, DumpFormat (..) )
92
import GHC.Utils.Exception
93

Simon Marlow's avatar
Simon Marlow committed
94
import System.Directory
95
import System.FilePath as FilePath
Simon Marlow's avatar
Simon Marlow committed
96
import Control.Monad
97
import Data.Graph (stronglyConnComp, SCC(..))
98
import Data.Char ( toUpper )
99
import Data.List as List
100
import Data.Map (Map)
101
import Data.Set (Set)
Edward Z. Yang's avatar
Edward Z. Yang committed
102
import Data.Monoid (First(..))
103
import qualified Data.Semigroup as Semigroup
104
import qualified Data.Map as Map
105
import qualified Data.Map.Strict as MapStrict
106
import qualified Data.Set as Set
Simon Marlow's avatar
Simon Marlow committed
107

108 109 110
-- ---------------------------------------------------------------------------
-- The Package state

111
-- | Package state is all stored in 'DynFlags', including the details of
112 113 114
-- all packages, which packages are exposed, and which modules they
-- provide.
--
Sylvain Henry's avatar
Sylvain Henry committed
115
-- The package state is computed by 'initUnits', and kept in DynFlags.
116
-- It is influenced by various package flags:
117
--
118 119 120
--   * @-package <pkg>@ and @-package-id <pkg>@ cause @<pkg>@ to become exposed.
--     If @-hide-all-packages@ was not specified, these commands also cause
--      all other packages with the same name to become hidden.
121
--
122
--   * @-hide-package <pkg>@ causes @<pkg>@ to become hidden.
123
--
124 125 126 127
--   * (there are a few more flags, check below for their semantics)
--
-- The package state has the following properties.
--
128
--   * Let @exposedPackages@ be the set of packages thus exposed.
129
--     Let @depExposedPackages@ be the transitive closure from @exposedPackages@ of
130 131
--     their dependencies.
--
Gabor Greif's avatar
Gabor Greif committed
132
--   * When searching for a module from a preload import declaration,
133
--     only the exposed modules in @exposedPackages@ are valid.
134 135
--
--   * When searching for a module from an implicit import, all modules
136
--     from @depExposedPackages@ are valid.
137
--
138
--   * When linking in a compilation manager mode, we link in packages the
139 140
--     program depends on (the compiler knows this list by the
--     time it gets to the link step).  Also, we link in all packages
141
--     which were mentioned with preload @-package@ flags on the command-line,
Ian Lynagh's avatar
Ian Lynagh committed
142
--     or are a transitive dependency of same, or are \"base\"\/\"rts\".
143
--     The reason for this is that we might need packages which don't
144 145 146 147 148
--     contain any Haskell modules, and therefore won't be discovered
--     by the normal mechanism of dependency tracking.

-- Notes on DLLs
-- ~~~~~~~~~~~~~
149 150 151 152
-- When compiling module A, which imports module B, we need to
-- know whether B will be in the same DLL as A.
--      If it's in the same DLL, we refer to B_f_closure
--      If it isn't, we refer to _imp__B_f_closure
153 154 155
-- When compiling A, we record in B's Module value whether it's
-- in a different DLL, by setting the DLL flag.

156
-- | Given a module name, there may be multiple ways it came into scope,
157 158 159
-- possibly simultaneously.  This data type tracks all the possible ways
-- it could have come into scope.  Warning: don't use the record functions,
-- they're partial!
160
data ModuleOrigin =
161 162 163 164
    -- | Module is hidden, and thus never will be available for import.
    -- (But maybe the user didn't realize), so we'll still keep track
    -- of these modules.)
    ModHidden
165
    -- | Module is unavailable because the package is unusable.
Sylvain Henry's avatar
Sylvain Henry committed
166
  | ModUnusable UnusableUnitReason
167 168 169 170 171 172 173 174 175
    -- | Module is public, and could have come from some places.
  | ModOrigin {
        -- | @Just False@ means that this module is in
        -- someone's @exported-modules@ list, but that package is hidden;
        -- @Just True@ means that it is available; @Nothing@ means neither
        -- applies.
        fromOrigPackage :: Maybe Bool
        -- | Is the module available from a reexport of an exposed package?
        -- There could be multiple.
176
      , fromExposedReexport :: [UnitInfo]
177
        -- | Is the module available from a reexport of a hidden package?
178
      , fromHiddenReexport :: [UnitInfo]
179 180 181 182 183 184
        -- | Did the module export come from a package flag? (ToDo: track
        -- more information.
      , fromPackageFlag :: Bool
      }

instance Outputable ModuleOrigin where
185
    ppr ModHidden = text "hidden module"
186
    ppr (ModUnusable _) = text "unusable module"
187 188 189 190 191 192 193 194
    ppr (ModOrigin e res rhs f) = sep (punctuate comma (
        (case e of
            Nothing -> []
            Just False -> [text "hidden package"]
            Just True -> [text "exposed package"]) ++
        (if null res
            then []
            else [text "reexport by" <+>
195
                    sep (map (ppr . mkUnit) res)]) ++
196 197 198
        (if null rhs
            then []
            else [text "hidden reexport by" <+>
199
                    sep (map (ppr . mkUnit) res)]) ++
200 201 202
        (if f then [text "package flag"] else [])
        ))

203 204 205 206
-- | Smart constructor for a module which is in @exposed-modules@.  Takes
-- as an argument whether or not the defining package is exposed.
fromExposedModules :: Bool -> ModuleOrigin
fromExposedModules e = ModOrigin (Just e) [] [] False
207

208
-- | Smart constructor for a module which is in @reexported-modules@.  Takes
209
-- as an argument whether or not the reexporting package is exposed, and
210 211
-- also its 'UnitInfo'.
fromReexportedModules :: Bool -> UnitInfo -> ModuleOrigin
212 213
fromReexportedModules True pkg = ModOrigin Nothing [pkg] [] False
fromReexportedModules False pkg = ModOrigin Nothing [] [pkg] False
214 215 216 217 218

-- | Smart constructor for a module which was bound by a package flag.
fromFlag :: ModuleOrigin
fromFlag = ModOrigin Nothing [] [] True

219 220 221 222 223 224 225 226 227 228
instance Semigroup ModuleOrigin where
    ModOrigin e res rhs f <> ModOrigin e' res' rhs' f' =
        ModOrigin (g e e') (res ++ res') (rhs ++ rhs') (f || f')
      where g (Just b) (Just b')
                | b == b'   = Just b
                | otherwise = panic "ModOrigin: package both exposed/hidden"
            g Nothing x = x
            g x Nothing = x
    _x <> _y = panic "ModOrigin: hidden module redefined"

229 230
instance Monoid ModuleOrigin where
    mempty = ModOrigin Nothing [] [] False
231
    mappend = (Semigroup.<>)
232 233 234

-- | Is the name from the import actually visible? (i.e. does it cause
-- ambiguity, or is it only relevant when we're making suggestions?)
235 236
originVisible :: ModuleOrigin -> Bool
originVisible ModHidden = False
237
originVisible (ModUnusable _) = False
238 239 240 241 242 243 244
originVisible (ModOrigin b res _ f) = b == Just True || not (null res) || f

-- | Are there actually no providers for this module?  This will never occur
-- except when we're filtering based on package imports.
originEmpty :: ModuleOrigin -> Bool
originEmpty (ModOrigin Nothing [] [] False) = True
originEmpty _ = False
245

246 247
type PreloadUnitClosure = UniqSet UnitId

248 249
-- | Map from 'UnitId' to 'UnitInfo', plus
-- the transitive closure of preload units.
Sylvain Henry's avatar
Sylvain Henry committed
250
data ClosureUnitInfoMap = ClosureUnitInfoMap
251
   { unClosureUnitInfoMap :: UnitInfoMap
252 253
      -- ^ Map from 'UnitId' to 'UnitInfo'

254
   , preloadClosure :: PreloadUnitClosure
255 256 257 258 259 260
     -- ^ The set of transitively reachable units according
     -- to the explicitly provided command line arguments.
     -- A fully instantiated VirtUnit may only be replaced by a RealUnit from
     -- this set.
     -- See Note [VirtUnit to RealUnit improvement]
   }
Edward Z. Yang's avatar
Edward Z. Yang committed
261

262 263
-- | 'UniqFM' map from 'Unit' to a 'UnitVisibility'.
type VisibilityMap = Map Unit UnitVisibility
Edward Z. Yang's avatar
Edward Z. Yang committed
264 265

-- | 'UnitVisibility' records the various aspects of visibility of a particular
266
-- 'Unit'.
Edward Z. Yang's avatar
Edward Z. Yang committed
267 268 269 270 271 272 273
data UnitVisibility = UnitVisibility
    { uv_expose_all :: Bool
      --  ^ Should all modules in exposed-modules should be dumped into scope?
    , uv_renamings :: [(ModuleName, ModuleName)]
      -- ^ Any custom renamings that should bring extra 'ModuleName's into
      -- scope.
    , uv_package_name :: First FastString
274
      -- ^ The package name associated with the 'Unit'.  This is used
Edward Z. Yang's avatar
Edward Z. Yang committed
275 276
      -- to implement legacy behavior where @-package foo-0.1@ implicitly
      -- hides any packages named @foo@
277
    , uv_requirements :: Map ModuleName (Set InstantiatedModule)
Edward Z. Yang's avatar
Edward Z. Yang committed
278 279 280 281 282 283 284
      -- ^ The signatures which are contributed to the requirements context
      -- from this unit ID.
    , uv_explicit :: Bool
      -- ^ Whether or not this unit was explicitly brought into scope,
      -- as opposed to implicitly via the 'exposed' fields in the
      -- package database (when @-hide-all-packages@ is not passed.)
    }
285

Edward Z. Yang's avatar
Edward Z. Yang committed
286 287 288 289 290 291 292 293
instance Outputable UnitVisibility where
    ppr (UnitVisibility {
        uv_expose_all = b,
        uv_renamings = rns,
        uv_package_name = First mb_pn,
        uv_requirements = reqs,
        uv_explicit = explicit
    }) = ppr (b, rns, mb_pn, reqs, explicit)
294 295 296 297 298 299 300 301 302 303 304

instance Semigroup UnitVisibility where
    uv1 <> uv2
        = UnitVisibility
          { uv_expose_all = uv_expose_all uv1 || uv_expose_all uv2
          , uv_renamings = uv_renamings uv1 ++ uv_renamings uv2
          , uv_package_name = mappend (uv_package_name uv1) (uv_package_name uv2)
          , uv_requirements = Map.unionWith Set.union (uv_requirements uv1) (uv_requirements uv2)
          , uv_explicit = uv_explicit uv1 || uv_explicit uv2
          }

Edward Z. Yang's avatar
Edward Z. Yang committed
305 306 307 308 309 310 311 312
instance Monoid UnitVisibility where
    mempty = UnitVisibility
             { uv_expose_all = False
             , uv_renamings = []
             , uv_package_name = First Nothing
             , uv_requirements = Map.empty
             , uv_explicit = False
             }
313
    mappend = (Semigroup.<>)
314

315 316 317 318 319 320
-- | Map from 'ModuleName' to a set of of module providers (i.e. a 'Module' and
-- its 'ModuleOrigin').
--
-- NB: the set is in fact a 'Map Module ModuleOrigin', probably to keep only one
-- origin for a given 'Module'
type ModuleNameProvidersMap =
321
    Map ModuleName (Map Module ModuleOrigin)
322

323
data PackageState = PackageState {
324
  -- | A mapping of 'Unit' to 'UnitInfo'.  This list is adjusted
325
  -- so that only valid packages are here.  'UnitInfo' reflects
326 327 328
  -- what was stored *on disk*, except for the 'trusted' flag, which
  -- is adjusted at runtime.  (In particular, some packages in this map
  -- may have the 'exposed' flag be 'False'.)
Sylvain Henry's avatar
Sylvain Henry committed
329
  unitInfoMap :: ClosureUnitInfoMap,
330

331
  -- | A mapping of 'PackageName' to 'IndefUnitId'.  This is used when
Edward Z. Yang's avatar
Edward Z. Yang committed
332
  -- users refer to packages in Backpack includes.
333
  packageNameMap            :: Map PackageName IndefUnitId,
Edward Z. Yang's avatar
Edward Z. Yang committed
334 335 336

  -- | A mapping from wired in names to the original names from the
  -- package database.
Sylvain Henry's avatar
Sylvain Henry committed
337
  unwireMap :: Map UnitId UnitId,
Edward Z. Yang's avatar
Edward Z. Yang committed
338

339 340 341
  -- | The packages we're going to link in eagerly.  This list
  -- should be in reverse dependency order; that is, a package
  -- is always mentioned before the packages it depends on.
Sylvain Henry's avatar
Sylvain Henry committed
342
  preloadUnits      :: [UnitId],
343

344 345
  -- | Packages which we explicitly depend on (from a command line flag).
  -- We'll use this to generate version macros.
Sylvain Henry's avatar
Sylvain Henry committed
346
  explicitUnits      :: [Unit],
347

348 349 350
  -- | This is a full map from 'ModuleName' to all modules which may possibly
  -- be providing it.  These providers may be hidden (but we'll still want
  -- to report them in error messages), or it may be an ambiguous import.
351
  moduleNameProvidersMap    :: !ModuleNameProvidersMap,
352

353 354
  -- | A map, like 'moduleNameProvidersMap', but controlling plugin visibility.
  pluginModuleNameProvidersMap    :: !ModuleNameProvidersMap,
Edward Z. Yang's avatar
Edward Z. Yang committed
355 356 357 358 359 360 361 362

  -- | A map saying, for each requirement, what interfaces must be merged
  -- together when we use them.  For example, if our dependencies
  -- are @p[A=<A>]@ and @q[A=<A>,B=r[C=<A>]:B]@, then the interfaces
  -- to merge for A are @p[A=<A>]:A@, @q[A=<A>,B=r[C=<A>]:B]:A@
  -- and @r[C=<A>]:C@.
  --
  -- There's an entry in this map for each hole in our home library.
363 364 365 366 367 368 369
  requirementContext :: Map ModuleName [InstantiatedModule],

  -- | Indicate if we can instantiate units on-the-fly.
  --
  -- This should only be true when we are type-checking an indefinite unit.
  -- See Note [About units] in GHC.Unit.
  allowVirtualUnits :: !Bool
370 371
  }

372 373
emptyPackageState :: PackageState
emptyPackageState = PackageState {
Sylvain Henry's avatar
Sylvain Henry committed
374
    unitInfoMap = emptyClosureUnitInfoMap,
Edward Z. Yang's avatar
Edward Z. Yang committed
375 376
    packageNameMap = Map.empty,
    unwireMap = Map.empty,
Sylvain Henry's avatar
Sylvain Henry committed
377 378
    preloadUnits = [],
    explicitUnits = [],
379 380
    moduleNameProvidersMap = Map.empty,
    pluginModuleNameProvidersMap = Map.empty,
381 382
    requirementContext = Map.empty,
    allowVirtualUnits = False
383 384
    }

Sylvain Henry's avatar
Sylvain Henry committed
385 386 387 388
-- | Unit database
data UnitDatabase unit = UnitDatabase
   { unitDatabasePath  :: FilePath
   , unitDatabaseUnits :: [GenUnitInfo unit]
389 390
   }

Sylvain Henry's avatar
Sylvain Henry committed
391
type UnitInfoMap = Map UnitId UnitInfo
392

393
-- | Empty package configuration map
Sylvain Henry's avatar
Sylvain Henry committed
394
emptyClosureUnitInfoMap :: ClosureUnitInfoMap
395
emptyClosureUnitInfoMap = ClosureUnitInfoMap Map.empty emptyUniqSet
396

Sylvain Henry's avatar
Sylvain Henry committed
397
-- | Find the unit we know about with the given unit, if any
398 399
lookupUnit :: PackageState -> Unit -> Maybe UnitInfo
lookupUnit pkgs = lookupUnit' (allowVirtualUnits pkgs) (unitInfoMap pkgs)
Edward Z. Yang's avatar
Edward Z. Yang committed
400 401 402

-- | A more specialized interface, which takes a boolean specifying
-- whether or not to look for on-the-fly renamed interfaces, and
Sylvain Henry's avatar
Sylvain Henry committed
403
-- just a 'ClosureUnitInfoMap' rather than a 'PackageState' (so it can
Edward Z. Yang's avatar
Edward Z. Yang committed
404
-- be used while we're initializing 'DynFlags'
Sylvain Henry's avatar
Sylvain Henry committed
405
lookupUnit' :: Bool -> ClosureUnitInfoMap -> Unit -> Maybe UnitInfo
406
lookupUnit' allowOnTheFlyInst m@(ClosureUnitInfoMap pkg_map _) u = case u of
407
   HoleUnit   -> error "Hole unit"
408 409 410 411 412 413 414 415 416 417 418 419 420 421
   RealUnit i -> Map.lookup (unDefinite i) pkg_map
   VirtUnit i
      | allowOnTheFlyInst
      -> -- lookup UnitInfo of the indefinite unit to be instantiated and
         -- instantiate it on-the-fly
         fmap (renameUnitInfo m (instUnitInsts i))
           (Map.lookup (indefUnit (instUnitInstanceOf i)) pkg_map)

      | otherwise
      -> -- lookup UnitInfo by virtual UnitId. This is used to find indefinite
         -- units. Even if they are real, installed units, they can't use the
         -- `RealUnit` constructor (it is reserved for definite units) so we use
         -- the `VirtUnit` constructor.
         Map.lookup (virtualUnitId i) pkg_map
Edward Z. Yang's avatar
Edward Z. Yang committed
422

Sylvain Henry's avatar
Sylvain Henry committed
423 424 425 426 427
-- | Find the unit we know about with the given unit id, if any
lookupUnitId :: PackageState -> UnitId -> Maybe UnitInfo
lookupUnitId state uid = lookupUnitId' (unitInfoMap state) uid

-- | Find the unit we know about with the given unit id, if any
Sylvain Henry's avatar
Sylvain Henry committed
428
lookupUnitId' :: ClosureUnitInfoMap -> UnitId -> Maybe UnitInfo
429
lookupUnitId' (ClosureUnitInfoMap db _) uid = Map.lookup uid db
Sylvain Henry's avatar
Sylvain Henry committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444


-- | Looks up the given unit in the package state, panicing if it is not found
unsafeLookupUnit :: HasDebugCallStack => PackageState -> Unit -> UnitInfo
unsafeLookupUnit state u = case lookupUnit state u of
   Just info -> info
   Nothing   -> pprPanic "unsafeLookupUnit" (ppr u)

-- | Looks up the given unit id in the package state, panicing if it is not found
unsafeLookupUnitId :: HasDebugCallStack => PackageState -> UnitId -> UnitInfo
unsafeLookupUnitId state uid = case lookupUnitId state uid of
   Just info -> info
   Nothing   -> pprPanic "unsafeLookupUnitId" (ppr uid)


Edward Z. Yang's avatar
Edward Z. Yang committed
445 446
-- | Find the package we know about with the given package name (e.g. @foo@), if any
-- (NB: there might be a locally defined unit name which overrides this)
447
lookupPackageName :: PackageState -> PackageName -> Maybe IndefUnitId
Sylvain Henry's avatar
Sylvain Henry committed
448
lookupPackageName pkgstate n = Map.lookup n (packageNameMap pkgstate)
449 450

-- | Search for packages with a given package ID (e.g. \"foo-0.1\")
Sylvain Henry's avatar
Sylvain Henry committed
451 452
searchPackageId :: PackageState -> PackageId -> [UnitInfo]
searchPackageId pkgstate pid = filter ((pid ==) . unitPackageId)
453
                               (listUnitInfo pkgstate)
454

455 456 457 458 459 460 461 462 463
-- | Create a Map UnitId UnitInfo
--
-- For each instantiated unit, we add two map keys:
--    * the real unit id
--    * the virtual unit id made from its instantiation
--
-- We do the same thing for fully indefinite units (which are "instantiated"
-- with module holes).
--
Sylvain Henry's avatar
Sylvain Henry committed
464 465
mkClosureUnitInfoMap :: [UnitInfo] -> UnitInfoMap
mkClosureUnitInfoMap infos
466
  = ClosureUnitInfoMap (foldl' add Map.empty infos) emptyUniqSet
Sylvain Henry's avatar
Sylvain Henry committed
467
  where
468
   mkVirt      p = virtualUnitId (mkInstantiatedUnit (unitInstanceOf p) (unitInstantiations p))
469 470
   add pkg_map p
      | not (null (unitInstantiations p))
471 472 473
      = Map.insert (mkVirt p) p
         $ Map.insert (unitId p) p
         $ pkg_map
474
      | otherwise
475
      = Map.insert (unitId p) p pkg_map
476

477
-- | Get a list of entries from the package database.  NB: be careful with
478 479 480
-- this function, although all packages in this map are "visible", this
-- does not imply that the exposed-modules of the package are available
-- (they may have been thinned or renamed).
481
listUnitInfo :: PackageState -> [UnitInfo]
482
listUnitInfo pkgstate = Map.elems pkg_map
Edward Z. Yang's avatar
Edward Z. Yang committed
483
  where
Sylvain Henry's avatar
Sylvain Henry committed
484
    ClosureUnitInfoMap pkg_map _ = unitInfoMap pkgstate
485

486
-- ----------------------------------------------------------------------------
487
-- Loading the package db files and building up the package state
488

489 490
-- | Read the package database files, and sets up various internal tables of
-- package information, according to the package-related flags on the
491
-- command-line (@-package@, @-hide-package@ etc.)
492 493 494
--
-- Returns a list of packages to link in if we're doing dynamic linking.
-- This list contains the packages that the user explicitly mentioned with
495
-- @-package@ flags.
496
--
Sylvain Henry's avatar
Sylvain Henry committed
497
-- 'initUnits' can be called again subsequently after updating the
498
-- 'packageFlags' field of the 'DynFlags', and it will update the
Sylvain Henry's avatar
Sylvain Henry committed
499
-- 'unitState' in 'DynFlags' and return a list of packages to
500
-- link in.
Sylvain Henry's avatar
Sylvain Henry committed
501 502
initUnits :: DynFlags -> IO (DynFlags, [UnitId])
initUnits dflags = withTiming dflags
503 504
                                  (text "initializing package database")
                                  forcePkgDb $ do
505
  read_pkg_dbs <-
Sylvain Henry's avatar
Sylvain Henry committed
506 507
    case unitDatabases dflags of
        Nothing  -> readUnitDatabases dflags
508 509 510
        Just dbs -> return dbs

  let
Sylvain Henry's avatar
Sylvain Henry committed
511
      distrust_all db = db { unitDatabaseUnits = distrustAllUnits (unitDatabaseUnits db) }
512 513 514 515 516

      pkg_dbs
         | gopt Opt_DistrustAllPackages dflags = map distrust_all read_pkg_dbs
         | otherwise                           = read_pkg_dbs

517
  (pkg_state, preload, insts)
518
        <- mkPackageState dflags pkg_dbs []
Sylvain Henry's avatar
Sylvain Henry committed
519 520
  return (dflags{ unitDatabases = Just read_pkg_dbs,
                  unitState = pkg_state,
Sylvain Henry's avatar
Sylvain Henry committed
521
                  homeUnitInstantiations = insts },
522
          preload)
523
  where
Sylvain Henry's avatar
Sylvain Henry committed
524
    forcePkgDb (dflags, _) = unitInfoMap (unitState dflags) `seq` ()
525 526

-- -----------------------------------------------------------------------------
Sylvain Henry's avatar
Sylvain Henry committed
527
-- Reading the unit database(s)
528

Sylvain Henry's avatar
Sylvain Henry committed
529 530 531 532 533
readUnitDatabases :: DynFlags -> IO [UnitDatabase UnitId]
readUnitDatabases dflags = do
  conf_refs <- getPackageDbRefs dflags
  confs     <- liftM catMaybes $ mapM (resolveUnitDatabase dflags) conf_refs
  mapM (readUnitDatabase dflags) confs
534

535

Sylvain Henry's avatar
Sylvain Henry committed
536 537
getPackageDbRefs :: DynFlags -> IO [PkgDbRef]
getPackageDbRefs dflags = do
538
  let system_conf_refs = [UserPkgDb, GlobalPkgDb]
539

540
  e_pkg_path <- tryIO (getEnv $ map toUpper (programName dflags) ++ "_PACKAGE_PATH")
541 542 543
  let base_conf_refs = case e_pkg_path of
        Left _ -> system_conf_refs
        Right path
544
         | not (null path) && isSearchPathSeparator (last path)
545
         -> map PkgDbPath (splitSearchPath (init path)) ++ system_conf_refs
546
         | otherwise
547
         -> map PkgDbPath (splitSearchPath path)
548

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  -- Apply the package DB-related flags from the command line to get the
  -- final list of package DBs.
  --
  -- Notes on ordering:
  --  * The list of flags is reversed (later ones first)
  --  * We work with the package DB list in "left shadows right" order
  --  * and finally reverse it at the end, to get "right shadows left"
  --
  return $ reverse (foldr doFlag base_conf_refs (packageDBFlags dflags))
 where
  doFlag (PackageDB p) dbs = p : dbs
  doFlag NoUserPackageDB dbs = filter isNotUser dbs
  doFlag NoGlobalPackageDB dbs = filter isNotGlobal dbs
  doFlag ClearPackageDBs _ = []

564
  isNotUser UserPkgDb = False
565 566
  isNotUser _ = True

567
  isNotGlobal GlobalPkgDb = False
568
  isNotGlobal _ = True
569

570 571 572
-- | Return the path of a package database from a 'PkgDbRef'. Return 'Nothing'
-- when the user database filepath is expected but the latter doesn't exist.
--
573
-- NB: This logic is reimplemented in Cabal, so if you change it,
574
-- make sure you update Cabal. (Or, better yet, dump it in the
575
-- compiler info so Cabal can use the info.)
Sylvain Henry's avatar
Sylvain Henry committed
576 577 578
resolveUnitDatabase :: DynFlags -> PkgDbRef -> IO (Maybe FilePath)
resolveUnitDatabase dflags GlobalPkgDb = return $ Just (globalPackageDatabasePath dflags)
resolveUnitDatabase dflags UserPkgDb = runMaybeT $ do
579
  dir <- versionedAppDir dflags
Edsko de Vries's avatar
Edsko de Vries committed
580
  let pkgconf = dir </> "package.conf.d"
581 582
  exist <- tryMaybeT $ doesDirectoryExist pkgconf
  if exist then return pkgconf else mzero
Sylvain Henry's avatar
Sylvain Henry committed
583
resolveUnitDatabase _ (PkgDbPath name) = return $ Just name
584

Sylvain Henry's avatar
Sylvain Henry committed
585 586
readUnitDatabase :: DynFlags -> FilePath -> IO (UnitDatabase UnitId)
readUnitDatabase dflags conf_file = do
587 588
  isdir <- doesDirectoryExist conf_file

589
  proto_pkg_configs <-
590
    if isdir
591
       then readDirStyleUnitInfo conf_file
592
       else do
593
            isfile <- doesFileExist conf_file
594
            if isfile
595
               then do
596
                 mpkgs <- tryReadOldFileStyleUnitInfo
597 598 599
                 case mpkgs of
                   Just pkgs -> return pkgs
                   Nothing   -> throwGhcExceptionIO $ InstallationError $
600 601 602 603
                      "ghc no longer supports single-file style package " ++
                      "databases (" ++ conf_file ++
                      ") use 'ghc-pkg init' to create the database with " ++
                      "the correct format."
604 605
               else throwGhcExceptionIO $ InstallationError $
                      "can't find a package database at " ++ conf_file
606

607
  let
608
      -- Fix #16360: remove trailing slash from conf_file before calculating pkgroot
609
      conf_file' = dropTrailingPathSeparator conf_file
610
      top_dir = topDir dflags
611
      pkgroot = takeDirectory conf_file'
612
      pkg_configs1 = map (mungeUnitInfo top_dir pkgroot . mapUnitInfo (\(UnitKey x) -> UnitId x) unitIdFS . mkUnitKeyInfo)
613
                         proto_pkg_configs
614
  --
Sylvain Henry's avatar
Sylvain Henry committed
615
  return $ UnitDatabase conf_file' pkg_configs1
616
  where
617
    readDirStyleUnitInfo conf_dir = do
618
      let filename = conf_dir </> "package.cache"
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
      cache_exists <- doesFileExist filename
      if cache_exists
        then do
          debugTraceMsg dflags 2 $ text "Using binary package database:"
                                    <+> text filename
          readPackageDbForGhc filename
        else do
          -- If there is no package.cache file, we check if the database is not
          -- empty by inspecting if the directory contains any .conf file. If it
          -- does, something is wrong and we fail. Otherwise we assume that the
          -- database is empty.
          debugTraceMsg dflags 2 $ text "There is no package.cache in"
                               <+> text conf_dir
                                <> text ", checking if the database is empty"
          db_empty <- all (not . isSuffixOf ".conf")
                   <$> getDirectoryContents conf_dir
          if db_empty
            then do
              debugTraceMsg dflags 3 $ text "There are no .conf files in"
                                   <+> text conf_dir <> text ", treating"
                                   <+> text "package database as empty"
              return []
            else do
              throwGhcExceptionIO $ InstallationError $
                "there is no package.cache in " ++ conf_dir ++
                " even though package database is not empty"

646 647 648 649 650 651 652 653 654

    -- Single-file style package dbs have been deprecated for some time, but
    -- it turns out that Cabal was using them in one place. So this is a
    -- workaround to allow older Cabal versions to use this newer ghc.
    -- We check if the file db contains just "[]" and if so, we look for a new
    -- dir-style db in conf_file.d/, ie in a dir next to the given file.
    -- We cannot just replace the file with a new dir style since Cabal still
    -- assumes it's a file and tries to overwrite with 'writeFile'.
    -- ghc-pkg also cooperates with this workaround.
655
    tryReadOldFileStyleUnitInfo = do
656 657 658 659 660 661 662
      content <- readFile conf_file `catchIO` \_ -> return ""
      if take 2 content == "[]"
        then do
          let conf_dir = conf_file <.> "d"
          direxists <- doesDirectoryExist conf_dir
          if direxists
             then do debugTraceMsg dflags 2 (text "Ignoring old file-style db and trying:" <+> text conf_dir)
663
                     liftM Just (readDirStyleUnitInfo conf_dir)
664 665
             else return (Just []) -- ghc-pkg will create it when it's updated
        else return Nothing
666

667 668
distrustAllUnits :: [UnitInfo] -> [UnitInfo]
distrustAllUnits pkgs = map distrust pkgs
669
  where
Sylvain Henry's avatar
Sylvain Henry committed
670
    distrust pkg = pkg{ unitIsTrusted = False }
671

672 673 674
mungeUnitInfo :: FilePath -> FilePath
                   -> UnitInfo -> UnitInfo
mungeUnitInfo top_dir pkgroot =
675
    mungeDynLibFields
676
  . mungeUnitInfoPaths top_dir pkgroot
677

678
mungeDynLibFields :: UnitInfo -> UnitInfo
679 680
mungeDynLibFields pkg =
    pkg {
Sylvain Henry's avatar
Sylvain Henry committed
681 682 683
      unitLibraryDynDirs = case unitLibraryDynDirs pkg of
         [] -> unitLibraryDirs pkg
         ds -> ds
684 685
    }

686
-- -----------------------------------------------------------------------------
687 688 689 690 691
-- Modify our copy of the package database based on trust flags,
-- -trust and -distrust.

applyTrustFlag
   :: DynFlags
Sylvain Henry's avatar
Sylvain Henry committed
692 693
   -> UnitPrecedenceMap
   -> UnusableUnits
694
   -> [UnitInfo]
695
   -> TrustFlag
696
   -> IO [UnitInfo]
697
applyTrustFlag dflags prec_map unusable pkgs flag =
698 699 700 701
  case flag of
    -- we trust all matching packages. Maybe should only trust first one?
    -- and leave others the same or set them untrusted
    TrustPackage str ->
702
       case selectPackages prec_map (PackageArg str) pkgs unusable of
703 704
         Left ps       -> trustFlagErr dflags flag ps
         Right (ps,qs) -> return (map trust ps ++ qs)
Sylvain Henry's avatar
Sylvain Henry committed
705
          where trust p = p {unitIsTrusted=True}
706 707

    DistrustPackage str ->
708
       case selectPackages prec_map (PackageArg str) pkgs unusable of
709
         Left ps       -> trustFlagErr dflags flag ps
710
         Right (ps,qs) -> return (distrustAllUnits ps ++ qs)
711

Sylvain Henry's avatar
Sylvain Henry committed
712
-- | A little utility to tell if the home unit is indefinite
Edward Z. Yang's avatar
Edward Z. Yang committed
713
-- (if it is not, we should never use on-the-fly renaming.)
Sylvain Henry's avatar
Sylvain Henry committed
714 715 716 717 718 719 720
homeUnitIsIndefinite :: DynFlags -> Bool
homeUnitIsIndefinite dflags = not (homeUnitIsDefinite dflags)

-- | A little utility to tell if the home unit is definite
-- (if it is, we should never use on-the-fly renaming.)
homeUnitIsDefinite :: DynFlags -> Bool
homeUnitIsDefinite dflags = unitIsDefinite (homeUnit dflags)
Edward Z. Yang's avatar
Edward Z. Yang committed
721

722
applyPackageFlag
Ian Lynagh's avatar
Ian Lynagh committed
723
   :: DynFlags
Sylvain Henry's avatar
Sylvain Henry committed
724 725 726
   -> UnitPrecedenceMap
   -> ClosureUnitInfoMap
   -> UnusableUnits
727 728
   -> Bool -- if False, if you expose a package, it implicitly hides
           -- any previously exposed packages with the same name
729
   -> [UnitInfo]
730
   -> VisibilityMap           -- Initially exposed
731
   -> PackageFlag               -- flag to apply
732
   -> IO VisibilityMap        -- Now exposed
733

734
applyPackageFlag dflags prec_map pkg_db unusable no_hide_others pkgs vm flag =
735
  case flag of
736
    ExposePackage _ arg (ModRenaming b rns) ->
737
       case findPackages prec_map pkg_db arg pkgs unusable of
738
         Left ps         -> packageFlagErr dflags flag ps
Edward Z. Yang's avatar
Edward Z. Yang committed
739
         Right (p:_) -> return vm'
740 741
          where
           n = fsPackageName p
Edward Z. Yang's avatar
Edward Z. Yang committed
742 743 744 745 746 747 748 749 750

           -- If a user says @-unit-id p[A=<A>]@, this imposes
           -- a requirement on us: whatever our signature A is,
           -- it must fulfill all of p[A=<A>]:A's requirements.
           -- This method is responsible for computing what our
           -- inherited requirements are.
           reqs | UnitIdArg orig_uid <- arg = collectHoles orig_uid
                | otherwise                 = Map.empty

751 752 753 754
           collectHoles uid = case uid of
             HoleUnit       -> Map.empty
             RealUnit {}    -> Map.empty -- definite units don't have holes
             VirtUnit indef ->
755
                  let local = [ Map.singleton
Edward Z. Yang's avatar
Edward Z. Yang committed
756
                                  (moduleName mod)
757 758
                                  (Set.singleton $ Module indef mod_name)
                              | (mod_name, mod) <- instUnitInsts indef
Edward Z. Yang's avatar
Edward Z. Yang committed
759
                              , isHoleModule mod ]
760 761
                      recurse = [ collectHoles (moduleUnit mod)
                                | (_, mod) <- instUnitInsts indef ]
Edward Z. Yang's avatar
Edward Z. Yang committed
762 763 764 765 766 767 768 769 770
                  in Map.unionsWith Set.union $ local ++ recurse

           uv = UnitVisibility
                { uv_expose_all = b
                , uv_renamings = rns
                , uv_package_name = First (Just n)
                , uv_requirements = reqs
                , uv_explicit = True
                }
771
           vm' = Map.insertWith mappend (mkUnit p) uv vm_cleared
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
           -- In the old days, if you said `ghc -package p-0.1 -package p-0.2`
           -- (or if p-0.1 was registered in the pkgdb as exposed: True),
           -- the second package flag would override the first one and you
           -- would only see p-0.2 in exposed modules.  This is good for
           -- usability.
           --
           -- However, with thinning and renaming (or Backpack), there might be
           -- situations where you legitimately want to see two versions of a
           -- package at the same time, and this behavior would make it
           -- impossible to do so.  So we decided that if you pass
           -- -hide-all-packages, this should turn OFF the overriding behavior
           -- where an exposed package hides all other packages with the same
           -- name.  This should not affect Cabal at all, which only ever
           -- exposes one package at a time.
           --
           -- NB: Why a variable no_hide_others?  We have to apply this logic to
           -- -plugin-package too, and it's more consistent if the switch in
           -- behavior is based off of
           -- -hide-all-packages/-hide-all-plugin-packages depending on what
           -- flag is in question.
           vm_cleared | no_hide_others = vm
Edward Z. Yang's avatar
Edward Z. Yang committed
793 794 795
                      -- NB: renamings never clear
                      | (_:_) <- rns = vm
                      | otherwise = Map.filterWithKey
796
                            (\k uv -> k == mkUnit p
Edward Z. Yang's avatar
Edward Z. Yang committed
797
                                   || First (Just n) /= uv_package_name uv) vm
798 799
         _ -> panic "applyPackageFlag"

800
    HidePackage str ->
801
       case findPackages prec_map pkg_db (PackageArg str) pkgs unusable of
Edward Z. Yang's avatar
Edward Z. Yang committed
802 803
         Left ps  -> packageFlagErr dflags flag ps
         Right ps -> return vm'
804
          where vm' = foldl' (flip Map.delete) vm (map mkUnit ps)
Edward Z. Yang's avatar
Edward Z. Yang committed
805 806 807 808

-- | Like 'selectPackages', but doesn't return a list of unmatched
-- packages.  Furthermore, any packages it returns are *renamed*
-- if the 'UnitArg' has a renaming associated with it.
Sylvain Henry's avatar
Sylvain Henry committed
809 810 811 812
findPackages :: UnitPrecedenceMap
             -> ClosureUnitInfoMap -> PackageArg -> [UnitInfo]
             -> UnusableUnits
             -> Either [(UnitInfo, UnusableUnitReason)]
813
                [UnitInfo]
814
findPackages prec_map pkg_db arg pkgs unusable
Edward Z. Yang's avatar
Edward Z. Yang committed
815 816 817 818
  = let ps = mapMaybe (finder arg) pkgs
    in if null ps
        then Left (mapMaybe (\(x,y) -> finder arg x >>= \x' -> return (x',y))
                            (Map.elems unusable))
819
        else Right (sortByPreference prec_map ps)
Edward Z. Yang's avatar
Edward Z. Yang committed
820 821
  where
    finder (PackageArg str) p
Sylvain Henry's avatar
Sylvain Henry committed
822
      = if str == unitPackageIdString p || str == unitPackageNameString p
Edward Z. Yang's avatar
Edward Z. Yang committed
823 824 825
          then Just p
          else Nothing
    finder (UnitIdArg uid) p
826 827 828 829 830 831
      = case uid of
          RealUnit (Definite iuid)
            | iuid == unitId p
            -> Just p
          VirtUnit inst
            | indefUnit (instUnitInstanceOf inst) == unitId p
Sylvain Henry's avatar
Sylvain Henry committed
832
            -> Just (renameUnitInfo pkg_db (instUnitInsts inst) p)
833
          _ -> Nothing
Edward Z. Yang's avatar
Edward Z. Yang committed
834

Sylvain Henry's avatar
Sylvain Henry committed
835 836 837
selectPackages :: UnitPrecedenceMap -> PackageArg -> [UnitInfo]
               -> UnusableUnits
               -> Either [(UnitInfo, UnusableUnitReason)]
838
                  ([UnitInfo], [UnitInfo])
839
selectPackages prec_map arg pkgs unusable
Edward Z. Yang's avatar
Edward Z. Yang committed
840 841
  = let matches = matching arg
        (ps,rest) = partition matches pkgs
842 843
    in if null ps
        then Left (filter (matches.fst) (Map.elems unusable))
844
        else Right (sortByPreference prec_map ps, rest)
845

846
-- | Rename a 'UnitInfo' according to some module instantiation.
Sylvain Henry's avatar
Sylvain Henry committed
847 848
renameUnitInfo :: ClosureUnitInfoMap -> [(ModuleName, Module)] -> UnitInfo -> UnitInfo
renameUnitInfo pkg_map insts conf =
Edward Z. Yang's avatar
Edward Z. Yang committed
849
    let hsubst = listToUFM insts
850
        smod  = renameHoleModule' pkg_map hsubst
Sylvain Henry's avatar
Sylvain Henry committed
851
        new_insts = map (\(k,v) -> (k,smod v)) (unitInstantiations conf)
Edward Z. Yang's avatar
Edward Z. Yang committed
852
    in conf {
Sylvain Henry's avatar
Sylvain Henry committed
853 854 855
        unitInstantiations = new_insts,
        unitExposedModules = map (\(mod_name, mb_mod) -> (mod_name, fmap smod mb_mod))
                             (unitExposedModules conf)
Edward Z. Yang's avatar
Edward Z. Yang committed
856 857 858
    }


859 860
-- A package named on the command line can either include the
-- version, or just the name if it is unambiguous.
861
matchingStr :: String -> UnitInfo -> Bool
862
matchingStr str p
Sylvain Henry's avatar
Sylvain Henry committed
863 864
        =  str == unitPackageIdString p
        || str == unitPackageNameString p
865

866 867
matchingId :: UnitId -> UnitInfo -> Bool
matchingId uid p = uid == unitId p
868

869
matching :: PackageArg -> UnitInfo -> Bool
870
matching (PackageArg str) = matchingStr str
871
matching (UnitIdArg (RealUnit (Definite uid))) = matchingId uid
872
matching (UnitIdArg _)  = \_ -> False -- TODO: warn in this case
873

874 875
-- | This sorts a list of packages, putting "preferred" packages first.
-- See 'compareByPreference' for the semantics of "preference".
Sylvain Henry's avatar
Sylvain Henry committed
876
sortByPreference :: UnitPrecedenceMap -> [UnitInfo] -> [UnitInfo]
877 878 879 880 881 882 883 884 885 886 887
sortByPreference prec_map = sortBy (flip (compareByPreference prec_map))

-- | Returns 'GT' if @pkg@ should be preferred over @pkg'@ when picking
-- which should be "active".  Here is the order of preference:
--
--      1. First, prefer the latest version
--      2. If the versions are the same, prefer the package that
--      came in the latest package database.
--
-- Pursuant to #12518, we could change this policy to, for example, remove
-- the version preference, meaning that we would always prefer the packages
888
-- in later package database.
889
--
890 891 892 893 894 895
-- Instead, we use that preference based policy only when one of the packages
-- is integer-gmp and the other is integer-simple.
-- This currently only happens when we're looking up which concrete
-- package to use in place of @integer-wired-in@ and that two different
-- package databases supply a different integer library. For more about
-- the fake @integer-wired-in@ package, see Note [The integer library]
Sylvain Henry's avatar
Sylvain Henry committed
896
-- in the @GHC.Builtin.Names@ module.
897
compareByPreference
Sylvain Henry's avatar
Sylvain Henry committed
898
    :: UnitPrecedenceMap
899 900
    -> UnitInfo
    -> UnitInfo
901
    -> Ordering
902 903 904 905 906 907 908
compareByPreference prec_map pkg pkg'
  | Just prec  <- Map.lookup (unitId pkg)  prec_map
  , Just prec' <- Map.lookup (unitId pkg') prec_map
  , differentIntegerPkgs pkg pkg'
  = compare prec prec'

  | otherwise
Sylvain Henry's avatar
Sylvain Henry committed
909
  = case comparing unitPackageVersion pkg pkg' of
910 911 912 913 914 915 916 917 918
        GT -> GT
        EQ | Just prec  <- Map.lookup (unitId pkg)  prec_map
           , Just prec' <- Map.lookup (unitId pkg') prec_map
           -- Prefer the package from the later DB flag (i.e., higher
           -- precedence)
           -> compare prec prec'
           | otherwise
           -> EQ
        LT -> LT
Ian Lynagh's avatar
Ian Lynagh committed
919

Sylvain Henry's avatar
Sylvain Henry committed
920
  where isIntegerPkg p = unitPackageNameString p `elem`
921 922 923
          ["integer-simple", "integer-gmp"]
        differentIntegerPkgs p p' =
          isIntegerPkg p && isIntegerPkg p' &&
Sylvain Henry's avatar
Sylvain Henry committed
924
          (unitPackageName p /= unitPackageName p')
925

Ian Lynagh's avatar
Ian Lynagh committed
926
comparing :: Ord a => (t -> a) -> t -> t -> Ordering
927 928
comparing f a b = f a `compare` f b

Ian Lynagh's avatar
Ian Lynagh committed
929 930
packageFlagErr :: DynFlags
               -> PackageFlag
Sylvain Henry's avatar
Sylvain Henry committed
931
               -> [(UnitInfo, UnusableUnitReason)]
932
               -> IO a
933
packageFlagErr dflags flag reasons
934 935 936 937
  = packageFlagErr' dflags (pprFlag flag) reasons

trustFlagErr :: DynFlags
             -> TrustFlag
Sylvain Henry's avatar
Sylvain Henry committed
938
             -> [(UnitInfo, UnusableUnitReason)]
939 940 941 942 943 944
             -> IO a
trustFlagErr dflags flag reasons
  = packageFlagErr' dflags (pprTrustFlag flag) reasons

packageFlagErr' :: DynFlags
               -> SDoc
Sylvain Henry's avatar
Sylvain Henry committed
945
               -> [(UnitInfo, UnusableUnitReason)]
946 947
               -> IO a
packageFlagErr' dflags flag_doc reasons
948
  = throwGhcExceptionIO (CmdLineError (showSDoc dflags $ err))
949
  where err = text "cannot satisfy " <> flag_doc <>
950
                (if null reasons then Outputable.empty else text ": ") $$
951 952 953
              nest 4 (ppr_reasons $$
                      text "(use -v for more information)")
        ppr_reasons = vcat (map ppr_reason reasons)
954
        ppr_reason (p, reason) =
955
            pprReason (ppr (unitId p) <+> text "is") reason
956

957 958 959
pprFlag :: PackageFlag -> SDoc
pprFlag flag = case flag of
    HidePackage p   -> text "-hide-package " <> text p
960
    ExposePackage doc _ _ -> text doc
961

962 963 964 965 966
pprTrustFlag :: TrustFlag -> SDoc
pprTrustFlag flag = case flag of
    TrustPackage p    -> text "-trust " <> text p
    DistrustPackage p -> text "-distrust " <> text p

967
-- -----------------------------------------------------------------------------
968
-- Wired-in units
969
--
970
-- See Note [Wired-in units] in GHC.Unit.Module
971

Sylvain Henry's avatar
Sylvain Henry committed
972
type WiringMap = Map UnitId UnitId
973

974 975
findWiredInPackages
   :: DynFlags
Sylvain Henry's avatar
Sylvain Henry committed
976
   -> UnitPrecedenceMap
977
   -> [UnitInfo]           -- database
978
   -> VisibilityMap             -- info on what packages are visible
979
                                -- for wired in selection
980
   -> IO ([UnitInfo],  -- package database updated for wired in
Sylvain Henry's avatar
Sylvain Henry committed
981
          WiringMap)   -- map from unit id to wired identity
982

983
findWiredInPackages dflags prec_map pkgs vis_map = do
Simon Marlow's avatar
Simon Marlow committed
984
  -- Now we must find our wired-in packages, and rename them to
985
  -- their canonical names (eg. base-1.0 ==> base), as described