State.hs 93.6 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

Sylvain Henry's avatar
Sylvain Henry committed
5
-- | Unit manipulation
6
module GHC.Unit.State (
7
        module GHC.Unit.Info,
8 9

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

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

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

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

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

Sylvain Henry's avatar
Sylvain Henry committed
55 56 57 58 59 60 61 62 63
        -- * Module hole substitution
        ShHoleSubst,
        renameHoleUnit,
        renameHoleModule,
        renameHoleUnit',
        renameHoleModule',
        instUnitToUnit,
        instModuleToModule,

64
        -- * Utils
65 66 67
        mkIndefUnitId,
        updateIndefUnitId,
        unwireUnit,
68
        pprFlag,
Sylvain Henry's avatar
Sylvain Henry committed
69 70
        pprUnits,
        pprUnitsSimple,
71
        pprModuleMap,
Sylvain Henry's avatar
Sylvain Henry committed
72 73
        homeUnitIsIndefinite,
        homeUnitIsDefinite,
74
    )
75 76 77
where

#include "HsVersions.h"
78

79
import GHC.Prelude
80

81
import GHC.Platform
82
import GHC.Unit.Database
83
import GHC.Unit.Info
84 85
import GHC.Unit.Types
import GHC.Unit.Module
Sylvain Henry's avatar
Sylvain Henry committed
86
import GHC.Driver.Session
Sylvain Henry's avatar
Sylvain Henry committed
87
import GHC.Driver.Ways
Sylvain Henry's avatar
Sylvain Henry committed
88 89 90
import GHC.Types.Unique.FM
import GHC.Types.Unique.DFM
import GHC.Types.Unique.Set
Sylvain Henry's avatar
Sylvain Henry committed
91
import GHC.Types.Unique.DSet
92 93 94 95
import GHC.Utils.Misc
import GHC.Utils.Panic
import GHC.Utils.Outputable as Outputable
import GHC.Data.Maybe
96

97
import System.Environment ( getEnv )
98 99
import GHC.Data.FastString
import GHC.Utils.Error  ( debugTraceMsg, MsgDoc, dumpIfSet_dyn,
Sylvain Henry's avatar
Sylvain Henry committed
100
                          withTiming, DumpFormat (..) )
101
import GHC.Utils.Exception
102

Simon Marlow's avatar
Simon Marlow committed
103
import System.Directory
104
import System.FilePath as FilePath
Simon Marlow's avatar
Simon Marlow committed
105
import Control.Monad
106
import Data.Graph (stronglyConnComp, SCC(..))
107
import Data.Char ( toUpper )
108
import Data.List as List
109
import Data.Map (Map)
110
import Data.Set (Set)
Edward Z. Yang's avatar
Edward Z. Yang committed
111
import Data.Monoid (First(..))
112
import qualified Data.Semigroup as Semigroup
113
import qualified Data.Map as Map
114
import qualified Data.Map.Strict as MapStrict
115
import qualified Data.Set as Set
Simon Marlow's avatar
Simon Marlow committed
116

117
-- ---------------------------------------------------------------------------
Sylvain Henry's avatar
Sylvain Henry committed
118
-- The Unit state
119

Sylvain Henry's avatar
Sylvain Henry committed
120 121
-- | Unit state is all stored in 'DynFlags', including the details of
-- all units, which units are exposed, and which modules they
122 123
-- provide.
--
Sylvain Henry's avatar
Sylvain Henry committed
124 125
-- The unit state is computed by 'initUnits', and kept in DynFlags.
-- It is influenced by various command-line flags:
126
--
127 128 129
--   * @-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.
130
--
131
--   * @-hide-package <pkg>@ causes @<pkg>@ to become hidden.
132
--
133 134
--   * (there are a few more flags, check below for their semantics)
--
Sylvain Henry's avatar
Sylvain Henry committed
135
-- The unit state has the following properties.
136
--
Sylvain Henry's avatar
Sylvain Henry committed
137 138
--   * Let @exposedUnits@ be the set of packages thus exposed.
--     Let @depExposedUnits@ be the transitive closure from @exposedUnits@ of
139 140
--     their dependencies.
--
Gabor Greif's avatar
Gabor Greif committed
141
--   * When searching for a module from a preload import declaration,
Sylvain Henry's avatar
Sylvain Henry committed
142
--     only the exposed modules in @exposedUnits@ are valid.
143 144
--
--   * When searching for a module from an implicit import, all modules
Sylvain Henry's avatar
Sylvain Henry committed
145
--     from @depExposedUnits@ are valid.
146
--
147
--   * When linking in a compilation manager mode, we link in packages the
148 149
--     program depends on (the compiler knows this list by the
--     time it gets to the link step).  Also, we link in all packages
150
--     which were mentioned with preload @-package@ flags on the command-line,
Ian Lynagh's avatar
Ian Lynagh committed
151
--     or are a transitive dependency of same, or are \"base\"\/\"rts\".
152
--     The reason for this is that we might need packages which don't
153 154 155 156 157
--     contain any Haskell modules, and therefore won't be discovered
--     by the normal mechanism of dependency tracking.

-- Notes on DLLs
-- ~~~~~~~~~~~~~
158 159 160 161
-- 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
162 163 164
-- When compiling A, we record in B's Module value whether it's
-- in a different DLL, by setting the DLL flag.

165
-- | Given a module name, there may be multiple ways it came into scope,
166 167 168
-- 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!
169
data ModuleOrigin =
170 171 172 173
    -- | 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
174
    -- | Module is unavailable because the package is unusable.
Sylvain Henry's avatar
Sylvain Henry committed
175
  | ModUnusable UnusableUnitReason
176 177 178 179 180 181
    -- | 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.
Sylvain Henry's avatar
Sylvain Henry committed
182
        fromOrigUnit :: Maybe Bool
183 184
        -- | Is the module available from a reexport of an exposed package?
        -- There could be multiple.
185
      , fromExposedReexport :: [UnitInfo]
186
        -- | Is the module available from a reexport of a hidden package?
187
      , fromHiddenReexport :: [UnitInfo]
188 189 190 191 192 193
        -- | Did the module export come from a package flag? (ToDo: track
        -- more information.
      , fromPackageFlag :: Bool
      }

instance Outputable ModuleOrigin where
194
    ppr ModHidden = text "hidden module"
195
    ppr (ModUnusable _) = text "unusable module"
196 197 198 199 200 201 202 203
    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" <+>
204
                    sep (map (ppr . mkUnit) res)]) ++
205 206 207
        (if null rhs
            then []
            else [text "hidden reexport by" <+>
208
                    sep (map (ppr . mkUnit) res)]) ++
209 210 211
        (if f then [text "package flag"] else [])
        ))

212 213 214 215
-- | 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
216

217
-- | Smart constructor for a module which is in @reexported-modules@.  Takes
218
-- as an argument whether or not the reexporting package is exposed, and
219 220
-- also its 'UnitInfo'.
fromReexportedModules :: Bool -> UnitInfo -> ModuleOrigin
221 222
fromReexportedModules True pkg = ModOrigin Nothing [pkg] [] False
fromReexportedModules False pkg = ModOrigin Nothing [] [pkg] False
223 224 225 226 227

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

228 229 230 231 232 233 234 235 236 237
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"

238 239
instance Monoid ModuleOrigin where
    mempty = ModOrigin Nothing [] [] False
240
    mappend = (Semigroup.<>)
241 242 243

-- | Is the name from the import actually visible? (i.e. does it cause
-- ambiguity, or is it only relevant when we're making suggestions?)
244 245
originVisible :: ModuleOrigin -> Bool
originVisible ModHidden = False
246
originVisible (ModUnusable _) = False
247 248 249 250 251 252 253
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
254

255 256
type PreloadUnitClosure = UniqSet UnitId

257 258
-- | 'UniqFM' map from 'Unit' to a 'UnitVisibility'.
type VisibilityMap = Map Unit UnitVisibility
Edward Z. Yang's avatar
Edward Z. Yang committed
259 260

-- | 'UnitVisibility' records the various aspects of visibility of a particular
261
-- 'Unit'.
Edward Z. Yang's avatar
Edward Z. Yang committed
262 263 264 265 266 267 268
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
269
      -- ^ The package name associated with the 'Unit'.  This is used
Edward Z. Yang's avatar
Edward Z. Yang committed
270 271
      -- to implement legacy behavior where @-package foo-0.1@ implicitly
      -- hides any packages named @foo@
272
    , uv_requirements :: Map ModuleName (Set InstantiatedModule)
Edward Z. Yang's avatar
Edward Z. Yang committed
273 274 275 276 277 278 279
      -- ^ 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.)
    }
280

Edward Z. Yang's avatar
Edward Z. Yang committed
281 282 283 284 285 286 287 288
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)
289 290 291 292 293 294 295 296 297 298 299

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
300 301 302 303 304 305 306 307
instance Monoid UnitVisibility where
    mempty = UnitVisibility
             { uv_expose_all = False
             , uv_renamings = []
             , uv_package_name = First Nothing
             , uv_requirements = Map.empty
             , uv_explicit = False
             }
308
    mappend = (Semigroup.<>)
309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

-- | Unit configuration
data UnitConfig = UnitConfig
   { unitConfigPlatformArchOs :: !PlatformMini  -- ^ Platform
   , unitConfigWays           :: !(Set Way)     -- ^ Ways to use
   , unitConfigProgramName    :: !String
      -- ^ Name of the compiler (e.g. "GHC", "GHCJS"). Used to fetch environment
      -- variables such as "GHC[JS]_PACKAGE_PATH".

   , unitConfigGlobalDB :: !FilePath    -- ^ Path to global DB
   , unitConfigGHCDir   :: !FilePath    -- ^ Main GHC dir: contains settings, etc.
   , unitConfigDBName   :: !String      -- ^ User DB name (e.g. "package.conf.d")

   , unitConfigAutoLink       :: ![UnitId] -- ^ Units to link automatically (e.g. base, rts)
   , unitConfigDistrustAll    :: !Bool     -- ^ Distrust all units by default
   , unitConfigHideAll        :: !Bool     -- ^ Hide all units by default
   , unitConfigHideAllPlugins :: !Bool     -- ^ Hide all plugins units by default

   , unitConfigAllowVirtualUnits :: !Bool
      -- ^ Allow the use of virtual units instantiated on-the-fly (see Note
      -- [About units] in GHC.Unit). This should only be used when we are
      -- type-checking an indefinite unit (not producing any code).

333 334 335 336 337
   , unitConfigDBCache      :: Maybe [UnitDatabase UnitId]
      -- ^ Cache of databases to use, in the order they were specified on the
      -- command line (later databases shadow earlier ones).
      -- If Nothing, databases will be found using `unitConfigFlagsDB`.

338 339 340 341 342 343 344 345
   -- command-line flags
   , unitConfigFlagsDB      :: [PackageDBFlag]     -- ^ Unit databases flags
   , unitConfigFlagsExposed :: [PackageFlag]       -- ^ Exposed units
   , unitConfigFlagsIgnored :: [IgnorePackageFlag] -- ^ Ignored units
   , unitConfigFlagsTrusted :: [TrustFlag]         -- ^ Trusted units
   , unitConfigFlagsPlugins :: [PackageFlag]       -- ^ Plugins exposed units
   }

346 347
initUnitConfig :: DynFlags -> UnitConfig
initUnitConfig dflags =
348 349 350 351 352 353
   let autoLink
         | not (gopt Opt_AutoLinkPackages dflags) = []
         -- By default we add base & rts to the preload units (when they are
         -- found in the unit database) except when we are building them
         | otherwise = filter (/= homeUnitId dflags) [baseUnitId, rtsUnitId]

354
   in UnitConfig
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
      { unitConfigPlatformArchOs = platformMini (targetPlatform dflags)
      , unitConfigProgramName    = programName dflags
      , unitConfigWays           = ways dflags

      , unitConfigGlobalDB       = globalPackageDatabasePath dflags
      , unitConfigGHCDir         = topDir dflags
      , unitConfigDBName         = "package.conf.d"

      , unitConfigAutoLink       = autoLink
      , unitConfigDistrustAll    = gopt Opt_DistrustAllPackages dflags
      , unitConfigHideAll        = gopt Opt_HideAllPackages dflags
      , unitConfigHideAllPlugins = gopt Opt_HideAllPluginPackages dflags

        -- when the home unit is indefinite, it means we are type-checking it
        -- only (not producing any code). Hence we can use virtual units
        -- instantiated on-the-fly (see Note [About units] in GHC.Unit)
      , unitConfigAllowVirtualUnits = homeUnitIsIndefinite dflags

373
      , unitConfigDBCache      = unitDatabases dflags
374 375 376 377 378
      , unitConfigFlagsDB      = packageDBFlags dflags
      , unitConfigFlagsExposed = packageFlags dflags
      , unitConfigFlagsIgnored = ignorePackageFlags dflags
      , unitConfigFlagsTrusted = trustFlags dflags
      , unitConfigFlagsPlugins = pluginPackageFlags dflags
379

380 381
      }

382 383 384 385 386 387
-- | 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 =
388
    Map ModuleName (Map Module ModuleOrigin)
389

Sylvain Henry's avatar
Sylvain Henry committed
390
data UnitState = UnitState {
391
  -- | A mapping of 'Unit' to 'UnitInfo'.  This list is adjusted
Sylvain Henry's avatar
Sylvain Henry committed
392
  -- so that only valid units are here.  'UnitInfo' reflects
393
  -- what was stored *on disk*, except for the 'trusted' flag, which
Sylvain Henry's avatar
Sylvain Henry committed
394
  -- is adjusted at runtime.  (In particular, some units in this map
395
  -- may have the 'exposed' flag be 'False'.)
Sylvain Henry's avatar
Sylvain Henry committed
396 397 398 399 400 401 402 403
  unitInfoMap :: UnitInfoMap,

  -- | 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]
  preloadClosure :: PreloadUnitClosure,
404

405
  -- | A mapping of 'PackageName' to 'IndefUnitId'.  This is used when
Edward Z. Yang's avatar
Edward Z. Yang committed
406
  -- users refer to packages in Backpack includes.
407
  packageNameMap            :: Map PackageName IndefUnitId,
Edward Z. Yang's avatar
Edward Z. Yang committed
408

409 410 411 412
  -- | A mapping from database unit keys to wired in unit ids.
  wireMap :: Map UnitId UnitId,

  -- | A mapping from wired in unit ids to unit keys from the database.
Sylvain Henry's avatar
Sylvain Henry committed
413
  unwireMap :: Map UnitId UnitId,
Edward Z. Yang's avatar
Edward Z. Yang committed
414

Sylvain Henry's avatar
Sylvain Henry committed
415 416 417
  -- | The units we're going to link in eagerly.  This list
  -- should be in reverse dependency order; that is, a unit
  -- is always mentioned before the units it depends on.
Sylvain Henry's avatar
Sylvain Henry committed
418
  preloadUnits      :: [UnitId],
419

Sylvain Henry's avatar
Sylvain Henry committed
420
  -- | Units which we explicitly depend on (from a command line flag).
421
  -- We'll use this to generate version macros.
Sylvain Henry's avatar
Sylvain Henry committed
422
  explicitUnits      :: [Unit],
423

424 425 426
  -- | 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.
427
  moduleNameProvidersMap    :: !ModuleNameProvidersMap,
428

429 430
  -- | A map, like 'moduleNameProvidersMap', but controlling plugin visibility.
  pluginModuleNameProvidersMap    :: !ModuleNameProvidersMap,
Edward Z. Yang's avatar
Edward Z. Yang committed
431 432 433 434 435 436 437 438

  -- | 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.
439 440 441 442 443 444 445
  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
446 447
  }

Sylvain Henry's avatar
Sylvain Henry committed
448 449
emptyUnitState :: UnitState
emptyUnitState = UnitState {
Sylvain Henry's avatar
Sylvain Henry committed
450 451
    unitInfoMap = Map.empty,
    preloadClosure = emptyUniqSet,
Edward Z. Yang's avatar
Edward Z. Yang committed
452
    packageNameMap = Map.empty,
453
    wireMap   = Map.empty,
Edward Z. Yang's avatar
Edward Z. Yang committed
454
    unwireMap = Map.empty,
Sylvain Henry's avatar
Sylvain Henry committed
455 456
    preloadUnits = [],
    explicitUnits = [],
457 458
    moduleNameProvidersMap = Map.empty,
    pluginModuleNameProvidersMap = Map.empty,
459 460
    requirementContext = Map.empty,
    allowVirtualUnits = False
461 462
    }

Sylvain Henry's avatar
Sylvain Henry committed
463 464 465 466
-- | Unit database
data UnitDatabase unit = UnitDatabase
   { unitDatabasePath  :: FilePath
   , unitDatabaseUnits :: [GenUnitInfo unit]
467 468
   }

Sylvain Henry's avatar
Sylvain Henry committed
469
type UnitInfoMap = Map UnitId UnitInfo
470

Sylvain Henry's avatar
Sylvain Henry committed
471
-- | Find the unit we know about with the given unit, if any
Sylvain Henry's avatar
Sylvain Henry committed
472
lookupUnit :: UnitState -> Unit -> Maybe UnitInfo
Sylvain Henry's avatar
Sylvain Henry committed
473 474
lookupUnit pkgs = lookupUnit' (allowVirtualUnits pkgs) (unitInfoMap pkgs) (preloadClosure pkgs)

Sylvain Henry's avatar
Sylvain Henry committed
475
-- | A more specialized interface, which doesn't require a 'UnitState' (so it
Sylvain Henry's avatar
Sylvain Henry committed
476 477 478 479 480 481 482 483
-- can be used while we're initializing 'DynFlags')
--
-- Parameters:
--    * a boolean specifying whether or not to look for on-the-fly renamed interfaces
--    * a 'UnitInfoMap'
--    * a 'PreloadUnitClosure'
lookupUnit' :: Bool -> UnitInfoMap -> PreloadUnitClosure -> Unit -> Maybe UnitInfo
lookupUnit' allowOnTheFlyInst pkg_map closure u = case u of
484
   HoleUnit   -> error "Hole unit"
485 486 487 488 489
   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
Sylvain Henry's avatar
Sylvain Henry committed
490
         fmap (renameUnitInfo pkg_map closure (instUnitInsts i))
491 492 493 494 495 496 497 498
           (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
499

Sylvain Henry's avatar
Sylvain Henry committed
500
-- | Find the unit we know about with the given unit id, if any
Sylvain Henry's avatar
Sylvain Henry committed
501
lookupUnitId :: UnitState -> UnitId -> Maybe UnitInfo
Sylvain Henry's avatar
Sylvain Henry committed
502 503 504
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
505 506
lookupUnitId' :: UnitInfoMap -> UnitId -> Maybe UnitInfo
lookupUnitId' db uid = Map.lookup uid db
Sylvain Henry's avatar
Sylvain Henry committed
507 508


Sylvain Henry's avatar
Sylvain Henry committed
509
-- | Looks up the given unit in the unit state, panicing if it is not found
Sylvain Henry's avatar
Sylvain Henry committed
510
unsafeLookupUnit :: HasDebugCallStack => UnitState -> Unit -> UnitInfo
Sylvain Henry's avatar
Sylvain Henry committed
511 512 513 514
unsafeLookupUnit state u = case lookupUnit state u of
   Just info -> info
   Nothing   -> pprPanic "unsafeLookupUnit" (ppr u)

Sylvain Henry's avatar
Sylvain Henry committed
515
-- | Looks up the given unit id in the unit state, panicing if it is not found
Sylvain Henry's avatar
Sylvain Henry committed
516
unsafeLookupUnitId :: HasDebugCallStack => UnitState -> UnitId -> UnitInfo
Sylvain Henry's avatar
Sylvain Henry committed
517 518 519 520 521
unsafeLookupUnitId state uid = case lookupUnitId state uid of
   Just info -> info
   Nothing   -> pprPanic "unsafeLookupUnitId" (ppr uid)


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

Sylvain Henry's avatar
Sylvain Henry committed
527
-- | Search for units with a given package ID (e.g. \"foo-0.1\")
Sylvain Henry's avatar
Sylvain Henry committed
528
searchPackageId :: UnitState -> PackageId -> [UnitInfo]
Sylvain Henry's avatar
Sylvain Henry committed
529
searchPackageId pkgstate pid = filter ((pid ==) . unitPackageId)
530
                               (listUnitInfo pkgstate)
531

532 533 534 535 536 537 538 539 540
-- | 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
541 542
mkUnitInfoMap :: [UnitInfo] -> UnitInfoMap
mkUnitInfoMap infos = foldl' add Map.empty infos
Sylvain Henry's avatar
Sylvain Henry committed
543
  where
544
   mkVirt      p = virtualUnitId (mkInstantiatedUnit (unitInstanceOf p) (unitInstantiations p))
545 546
   add pkg_map p
      | not (null (unitInstantiations p))
547 548 549
      = Map.insert (mkVirt p) p
         $ Map.insert (unitId p) p
         $ pkg_map
550
      | otherwise
551
      = Map.insert (unitId p) p pkg_map
552

Sylvain Henry's avatar
Sylvain Henry committed
553 554 555
-- | Get a list of entries from the unit database.  NB: be careful with
-- this function, although all units in this map are "visible", this
-- does not imply that the exposed-modules of the unit are available
556
-- (they may have been thinned or renamed).
Sylvain Henry's avatar
Sylvain Henry committed
557
listUnitInfo :: UnitState -> [UnitInfo]
Sylvain Henry's avatar
Sylvain Henry committed
558
listUnitInfo state = Map.elems (unitInfoMap state)
559

560
-- ----------------------------------------------------------------------------
Sylvain Henry's avatar
Sylvain Henry committed
561
-- Loading the unit db files and building up the unit state
562

Sylvain Henry's avatar
Sylvain Henry committed
563 564
-- | Read the unit database files, and sets up various internal tables of
-- unit information, according to the unit-related flags on the
565
-- command-line (@-package@, @-hide-package@ etc.)
566
--
Sylvain Henry's avatar
Sylvain Henry committed
567
-- 'initUnits' can be called again subsequently after updating the
568
-- 'packageFlags' field of the 'DynFlags', and it will update the
Sylvain Henry's avatar
Sylvain Henry committed
569
-- 'unitState' in 'DynFlags'.
570
initUnits :: DynFlags -> IO DynFlags
571
initUnits dflags = do
572

573
  let forceUnitInfoMap (state, _) = unitInfoMap state `seq` ()
574 575
  let ctx     = initSDocContext dflags defaultUserStyle -- SDocContext used to render exception messages
  let printer = debugTraceMsg dflags                    -- printer for trace messages
576

577 578 579
  (state,dbs) <- withTiming dflags (text "initializing unit database")
                   forceUnitInfoMap
                   (mkUnitState ctx printer (initUnitConfig dflags))
580

581 582
  dumpIfSet_dyn (dflags { pprCols = 200 }) Opt_D_dump_mod_map "Module Map"
    FormatText (pprModuleMap (moduleNameProvidersMap state))
583

584
  let dflags'  = dflags
585
                  { unitDatabases = Just dbs -- databases are cached and never read again
586 587 588
                  , unitState     = state
                  }
      dflags'' = upd_wired_in_home_instantiations dflags'
589

590
  return dflags''
591 592

-- -----------------------------------------------------------------------------
Sylvain Henry's avatar
Sylvain Henry committed
593
-- Reading the unit database(s)
594

595 596 597 598 599
readUnitDatabases :: (Int -> SDoc -> IO ()) -> UnitConfig -> IO [UnitDatabase UnitId]
readUnitDatabases printer cfg = do
  conf_refs <- getUnitDbRefs cfg
  confs     <- liftM catMaybes $ mapM (resolveUnitDatabase cfg) conf_refs
  mapM (readUnitDatabase printer cfg) confs
600

601

602 603
getUnitDbRefs :: UnitConfig -> IO [PkgDbRef]
getUnitDbRefs cfg = do
604
  let system_conf_refs = [UserPkgDb, GlobalPkgDb]
605

606
  e_pkg_path <- tryIO (getEnv $ map toUpper (unitConfigProgramName cfg) ++ "_PACKAGE_PATH")
607 608 609
  let base_conf_refs = case e_pkg_path of
        Left _ -> system_conf_refs
        Right path
610
         | not (null path) && isSearchPathSeparator (last path)
611
         -> map PkgDbPath (splitSearchPath (init path)) ++ system_conf_refs
612
         | otherwise
613
         -> map PkgDbPath (splitSearchPath path)
614

615 616 617 618 619 620 621 622
  -- 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"
  --
623
  return $ reverse (foldr doFlag base_conf_refs (unitConfigFlagsDB cfg))
624 625 626 627 628 629
 where
  doFlag (PackageDB p) dbs = p : dbs
  doFlag NoUserPackageDB dbs = filter isNotUser dbs
  doFlag NoGlobalPackageDB dbs = filter isNotGlobal dbs
  doFlag ClearPackageDBs _ = []

630
  isNotUser UserPkgDb = False
631 632
  isNotUser _ = True

633
  isNotGlobal GlobalPkgDb = False
634
  isNotGlobal _ = True
635

636 637 638
-- | 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.
--
639
-- NB: This logic is reimplemented in Cabal, so if you change it,
640
-- make sure you update Cabal. (Or, better yet, dump it in the
641
-- compiler info so Cabal can use the info.)
642 643 644 645 646
resolveUnitDatabase :: UnitConfig -> PkgDbRef -> IO (Maybe FilePath)
resolveUnitDatabase cfg GlobalPkgDb = return $ Just (unitConfigGlobalDB cfg)
resolveUnitDatabase cfg UserPkgDb = runMaybeT $ do
  dir <- versionedAppDir (unitConfigProgramName cfg) (unitConfigPlatformArchOs cfg)
  let pkgconf = dir </> unitConfigDBName cfg
647 648
  exist <- tryMaybeT $ doesDirectoryExist pkgconf
  if exist then return pkgconf else mzero
Sylvain Henry's avatar
Sylvain Henry committed
649
resolveUnitDatabase _ (PkgDbPath name) = return $ Just name
650

651 652
readUnitDatabase :: (Int -> SDoc -> IO ()) -> UnitConfig -> FilePath -> IO (UnitDatabase UnitId)
readUnitDatabase printer cfg conf_file = do
653 654
  isdir <- doesDirectoryExist conf_file

655
  proto_pkg_configs <-
656
    if isdir
657
       then readDirStyleUnitInfo conf_file
658
       else do
659
            isfile <- doesFileExist conf_file
660
            if isfile
661
               then do
662
                 mpkgs <- tryReadOldFileStyleUnitInfo
663 664 665
                 case mpkgs of
                   Just pkgs -> return pkgs
                   Nothing   -> throwGhcExceptionIO $ InstallationError $
666 667 668 669
                      "ghc no longer supports single-file style package " ++
                      "databases (" ++ conf_file ++
                      ") use 'ghc-pkg init' to create the database with " ++
                      "the correct format."
670 671
               else throwGhcExceptionIO $ InstallationError $
                      "can't find a package database at " ++ conf_file
672

673
  let
674
      -- Fix #16360: remove trailing slash from conf_file before calculating pkgroot
675
      conf_file' = dropTrailingPathSeparator conf_file
676
      top_dir = unitConfigGHCDir cfg
677
      pkgroot = takeDirectory conf_file'
678
      pkg_configs1 = map (mungeUnitInfo top_dir pkgroot . mapUnitInfo (\(UnitKey x) -> UnitId x) unitIdFS . mkUnitKeyInfo)
679
                         proto_pkg_configs
680
  --
Sylvain Henry's avatar
Sylvain Henry committed
681
  return $ UnitDatabase conf_file' pkg_configs1
682
  where
683
    readDirStyleUnitInfo conf_dir = do
684
      let filename = conf_dir </> "package.cache"
685 686 687
      cache_exists <- doesFileExist filename
      if cache_exists
        then do
688
          printer 2 $ text "Using binary package database:" <+> text filename
689 690 691 692 693 694
          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.
695 696 697
          printer 2 $ text "There is no package.cache in"
                      <+> text conf_dir
                       <> text ", checking if the database is empty"
698 699 700 701
          db_empty <- all (not . isSuffixOf ".conf")
                   <$> getDirectoryContents conf_dir
          if db_empty
            then do
702 703 704
              printer 3 $ text "There are no .conf files in"
                          <+> text conf_dir <> text ", treating"
                          <+> text "package database as empty"
705 706 707 708 709 710
              return []
            else do
              throwGhcExceptionIO $ InstallationError $
                "there is no package.cache in " ++ conf_dir ++
                " even though package database is not empty"

711 712 713 714 715 716 717 718 719

    -- 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.
720
    tryReadOldFileStyleUnitInfo = do
721 722 723 724 725 726
      content <- readFile conf_file `catchIO` \_ -> return ""
      if take 2 content == "[]"
        then do
          let conf_dir = conf_file <.> "d"
          direxists <- doesDirectoryExist conf_dir
          if direxists
727
             then do printer 2 (text "Ignoring old file-style db and trying:" <+> text conf_dir)
728
                     liftM Just (readDirStyleUnitInfo conf_dir)
729 730
             else return (Just []) -- ghc-pkg will create it when it's updated
        else return Nothing
731

732 733
distrustAllUnits :: [UnitInfo] -> [UnitInfo]
distrustAllUnits pkgs = map distrust pkgs
734
  where
Sylvain Henry's avatar
Sylvain Henry committed
735
    distrust pkg = pkg{ unitIsTrusted = False }
736

737 738 739
mungeUnitInfo :: FilePath -> FilePath
                   -> UnitInfo -> UnitInfo
mungeUnitInfo top_dir pkgroot =
740
    mungeDynLibFields
741
  . mungeUnitInfoPaths top_dir pkgroot
742

743
mungeDynLibFields :: UnitInfo -> UnitInfo
744 745
mungeDynLibFields pkg =
    pkg {
Sylvain Henry's avatar
Sylvain Henry committed
746 747 748
      unitLibraryDynDirs = case unitLibraryDynDirs pkg of
         [] -> unitLibraryDirs pkg
         ds -> ds
749 750
    }

751
-- -----------------------------------------------------------------------------
Sylvain Henry's avatar
Sylvain Henry committed
752
-- Modify our copy of the unit database based on trust flags,
753 754 755
-- -trust and -distrust.

applyTrustFlag
756
   :: SDocContext
Sylvain Henry's avatar
Sylvain Henry committed
757 758
   -> UnitPrecedenceMap
   -> UnusableUnits
759
   -> [UnitInfo]
760
   -> TrustFlag
761
   -> IO [UnitInfo]
762
applyTrustFlag ctx prec_map unusable pkgs flag =
763 764 765 766
  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 ->
767
       case selectPackages prec_map (PackageArg str) pkgs unusable of
768
         Left ps       -> trustFlagErr ctx flag ps
769
         Right (ps,qs) -> return (map trust ps ++ qs)
Sylvain Henry's avatar
Sylvain Henry committed
770
          where trust p = p {unitIsTrusted=True}
771 772

    DistrustPackage str ->
773
       case selectPackages prec_map (PackageArg str) pkgs unusable of
774
         Left ps       -> trustFlagErr ctx flag ps
775
         Right (ps,qs) -> return (distrustAllUnits ps ++ qs)
776

Sylvain Henry's avatar
Sylvain Henry committed
777
-- | A little utility to tell if the home unit is indefinite
Edward Z. Yang's avatar
Edward Z. Yang committed
778
-- (if it is not, we should never use on-the-fly renaming.)
Sylvain Henry's avatar
Sylvain Henry committed
779 780 781 782 783 784 785
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
786

787
applyPackageFlag
788
   :: SDocContext
Sylvain Henry's avatar
Sylvain Henry committed
789
   -> UnitPrecedenceMap
Sylvain Henry's avatar
Sylvain Henry committed
790 791
   -> UnitInfoMap
   -> PreloadUnitClosure
Sylvain Henry's avatar
Sylvain Henry committed
792
   -> UnusableUnits
793 794
   -> Bool -- if False, if you expose a package, it implicitly hides
           -- any previously exposed packages with the same name
795
   -> [UnitInfo]
796
   -> VisibilityMap           -- Initially exposed
797
   -> PackageFlag               -- flag to apply
798
   -> IO VisibilityMap        -- Now exposed
799

800
applyPackageFlag ctx prec_map pkg_map closure unusable no_hide_others pkgs vm flag =
801
  case flag of
802
    ExposePackage _ arg (ModRenaming b rns) ->
Sylvain Henry's avatar
Sylvain Henry committed
803
       case findPackages prec_map pkg_map closure arg pkgs unusable of
804
         Left ps         -> packageFlagErr ctx flag ps
Edward Z. Yang's avatar
Edward Z. Yang committed
805
         Right (p:_) -> return vm'
806 807
          where
           n = fsPackageName p
Edward Z. Yang's avatar
Edward Z. Yang committed
808 809 810 811 812 813 814 815 816

           -- 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

817 818 819 820
           collectHoles uid = case uid of
             HoleUnit       -> Map.empty
             RealUnit {}    -> Map.empty -- definite units don't have holes
             VirtUnit indef ->
821
                  let local = [ Map.singleton
Edward Z. Yang's avatar
Edward Z. Yang committed
822
                                  (moduleName mod)
823 824
                                  (Set.singleton $ Module indef mod_name)
                              | (mod_name, mod) <- instUnitInsts indef
Edward Z. Yang's avatar
Edward Z. Yang committed
825
                              , isHoleModule mod ]
826 827
                      recurse = [ collectHoles (moduleUnit mod)
                                | (_, mod) <- instUnitInsts indef ]
Edward Z. Yang's avatar
Edward Z. Yang committed
828 829 830 831 832 833 834 835 836
                  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
                }
837
           vm' = Map.insertWith mappend (mkUnit p) uv vm_cleared
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
           -- 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
859 860 861
                      -- NB: renamings never clear
                      | (_:_) <- rns = vm
                      | otherwise = Map.filterWithKey
862
                            (\k uv -> k == mkUnit p
Edward Z. Yang's avatar
Edward Z. Yang committed
863
                                   || First (Just n) /= uv_package_name uv) vm
864 865
         _ -> panic "applyPackageFlag"

866
    HidePackage str ->
Sylvain Henry's avatar
Sylvain Henry committed
867
       case findPackages prec_map pkg_map closure (PackageArg str) pkgs unusable of
868
         Left ps  -> packageFlagErr ctx flag ps
Edward Z. Yang's avatar
Edward Z. Yang committed
869
         Right ps -> return vm'
870
          where vm' = foldl' (flip Map.delete) vm (map mkUnit ps)
Edward Z. Yang's avatar
Edward Z. Yang committed
871 872 873 874

-- | 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
875
findPackages :: UnitPrecedenceMap
Sylvain Henry's avatar
Sylvain Henry committed
876 877 878
             -> UnitInfoMap
             -> PreloadUnitClosure
             -> PackageArg -> [UnitInfo]
Sylvain Henry's avatar
Sylvain Henry committed
879 880
             -> UnusableUnits
             -> Either [(UnitInfo, UnusableUnitReason)]
881
                [UnitInfo]
Sylvain Henry's avatar
Sylvain Henry committed
882
findPackages prec_map pkg_map closure arg pkgs unusable
Edward Z. Yang's avatar
Edward Z. Yang committed
883 884 885 886
  = 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))
887
        else Right (sortByPreference prec_map ps)
Edward Z. Yang's avatar
Edward Z. Yang committed
888 889
  where
    finder (PackageArg str) p
Sylvain Henry's avatar
Sylvain Henry committed
890
      = if str == unitPackageIdString p || str == unitPackageNameString p
Edward Z. Yang's avatar
Edward Z. Yang committed
891 892 893
          then Just p
          else Nothing
    finder (UnitIdArg uid) p
894 895 896 897 898 899
      = 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
900
            -> Just (renameUnitInfo pkg_map closure (instUnitInsts inst) p)
901
          _ -> Nothing
Edward Z. Yang's avatar
Edward Z. Yang committed
902

Sylvain Henry's avatar
Sylvain Henry committed
903 904 905
selectPackages :: UnitPrecedenceMap -> PackageArg -> [UnitInfo]
               -> UnusableUnits
               -> Either [(UnitInfo, UnusableUnitReason)]
906
                  ([UnitInfo], [UnitInfo])
907
selectPackages prec_map arg pkgs unusable
Edward Z. Yang's avatar
Edward Z. Yang committed
908 909
  = let matches = matching arg
        (ps,rest) = partition matches pkgs
910 911
    in if null ps
        then Left (filter (matches.fst) (Map.elems unusable))
912
        else Right (sortByPreference prec_map ps, rest)
913

914
-- | Rename a 'UnitInfo' according to some module instantiation.
Sylvain Henry's avatar
Sylvain Henry committed
915 916
renameUnitInfo :: UnitInfoMap -> PreloadUnitClosure -> [(ModuleName, Module)] -> UnitInfo -> UnitInfo
renameUnitInfo pkg_map closure insts conf =
Edward Z. Yang's avatar
Edward Z. Yang committed
917
    let hsubst = listToUFM insts
Sylvain Henry's avatar
Sylvain Henry committed
918
        smod  = renameHoleModule' pkg_map closure hsubst
Sylvain Henry's avatar
Sylvain Henry committed
919
        new_insts = map (\(k,v) -> (k,smod v)) (unitInstantiations conf)
Edward Z. Yang's avatar
Edward Z. Yang committed
920
    in conf {
Sylvain Henry's avatar
Sylvain Henry committed
921 922 923
        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
924 925 926
    }


927 928
-- A package named on the command line can either include the
-- version, or just the name if it is unambiguous.
929
matchingStr :: String -> UnitInfo -> Bool
930
matchingStr str p
Sylvain Henry's avatar
Sylvain Henry committed
931 932
        =  str == unitPackageIdString p
        || str == unitPackageNameString p
933

934 935
matchingId :: UnitId -> UnitInfo -> Bool
matchingId uid p = uid == unitId p
936

937
matching :: PackageArg -> UnitInfo -> Bool
938
matching (PackageArg str) = matchingStr str
939
matching (UnitIdArg (RealUnit (Definite uid))) = matchingId uid
940
matching (UnitIdArg _)  = \_ -> False -- TODO: warn in this case
941

942 943
-- | This sorts a list of packages, putting "preferred" packages first.
-- See 'compareByPreference' for the semantics of "preference".
Sylvain Henry's avatar
Sylvain Henry committed
944
sortByPreference :: UnitPrecedenceMap -> [UnitInfo] -> [UnitInfo]
945 946 947 948 949 950 951 952 953 954
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
Sylvain Henry's avatar
Sylvain Henry committed
955 956
-- the version preference, meaning that we would always prefer the units
-- in later unit database.
957
compareByPreference
Sylvain Henry's avatar
Sylvain Henry committed
958
    :: UnitPrecedenceMap
959 960
    -> UnitInfo
    -> UnitInfo
961
    -> Ordering
962
compareByPreference prec_map pkg pkg'
Sylvain Henry's avatar
Sylvain Henry committed
963
  = case comparing unitPackageVersion pkg pkg' of
964 965 966
        GT -> GT
        EQ | Just prec  <- Map.lookup (unitId pkg)  prec_map
           , Just prec' <- Map.lookup (unitId pkg') prec_map
Sylvain Henry's avatar
Sylvain Henry committed
967
           -- Prefer the unit from the later DB flag (i.e., higher
968 969 970 971 972
           -- precedence)
           -> compare prec prec'
           | otherwise
           -> EQ
        LT -> LT
Ian Lynagh's avatar
Ian Lynagh committed
973 974

comparing :: Ord a => (t -> a) -> t -> t -> Ordering
975 976
comparing f a b = f a `compare` f b

977
packageFlagErr :: SDocContext
Ian Lynagh's avatar
Ian Lynagh committed
978
               -> PackageFlag
Sylvain Henry's avatar
Sylvain Henry committed
979
               -> [(UnitInfo, UnusableUnitReason)]
980
               -> IO a
981 982
packageFlagErr ctx flag reasons
  = packageFlagErr' ctx (pprFlag flag) reasons
983

984
trustFlagErr :: SDocContext
985
             -> TrustFlag
Sylvain Henry's avatar
Sylvain Henry committed
986
             -> [(UnitInfo, UnusableUnitReason)]
987
             -> IO a
988 989
trustFlagErr ctx