LoadIface.hs 53.6 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

Simon Marlow's avatar
Simon Marlow committed
5 6

Loading interface files
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

Simon Marlow's avatar
Simon Marlow committed
9
{-# LANGUAGE CPP, BangPatterns, RecordWildCards, NondecreasingIndentation #-}
10
{-# OPTIONS_GHC -fno-warn-orphans #-}
11
module LoadIface (
12 13 14 15
        -- Importing one thing
        tcLookupImported_maybe, importDecl,
        checkWiredInTyCon, ifCheckWiredInThing,

16
        -- RnM/TcM functions
Austin Seipp's avatar
Austin Seipp committed
17 18
        loadModuleInterface, loadModuleInterfaces,
        loadSrcInterface, loadSrcInterface_maybe,
19
        loadInterfaceForName, loadInterfaceForModule,
20 21

        -- IfM functions
Simon Peyton Jones's avatar
Simon Peyton Jones committed
22
        loadInterface,
23
        loadSysInterface, loadUserInterface, loadPluginInterface,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
24 25 26
        findAndReadIface, readIface,    -- Used when reading the module's old interface
        loadDecls,      -- Should move to TcIface and be renamed
        initExternalPackageState,
Edward Z. Yang's avatar
Edward Z. Yang committed
27
        moduleFreeHolesPrecise,
28
        needWiredInHomeIface, loadWiredInHomeIface,
29

Edward Z. Yang's avatar
Edward Z. Yang committed
30
        pprModIfaceSimple,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
31
        ifaceStats, pprModIface, showIface
32 33 34 35
   ) where

#include "HsVersions.h"

36 37
import GhcPrelude

Austin Seipp's avatar
Austin Seipp committed
38
import {-# SOURCE #-}   TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst,
39 40
                                 tcIfaceFamInst, tcIfaceVectInfo,
                                 tcIfaceAnnotations, tcIfaceCompleteSigs )
41

Simon Marlow's avatar
Simon Marlow committed
42
import DynFlags
43
import IfaceSyn
Simon Marlow's avatar
Simon Marlow committed
44 45 46 47
import IfaceEnv
import HscTypes

import BasicTypes hiding (SuccessFlag(..))
48
import TcRnMonad
Simon Marlow's avatar
Simon Marlow committed
49

Ian Lynagh's avatar
Ian Lynagh committed
50
import Constants
Simon Marlow's avatar
Simon Marlow committed
51 52
import PrelNames
import PrelInfo
53
import PrimOp   ( allThePrimOps, primOpFixity, primOpOcc )
54
import MkId     ( seqId )
55
import TysPrim  ( funTyConName )
Simon Marlow's avatar
Simon Marlow committed
56
import Rules
57
import TyCon
58
import Annotations
Simon Marlow's avatar
Simon Marlow committed
59 60 61
import InstEnv
import FamInstEnv
import Name
62
import NameEnv
63
import Avail
Simon Marlow's avatar
Simon Marlow committed
64
import Module
Simon Marlow's avatar
Simon Marlow committed
65 66 67
import Maybes
import ErrUtils
import Finder
68
import UniqFM
69
import SrcLoc
70
import Outputable
Simon Marlow's avatar
Simon Marlow committed
71 72
import BinIface
import Panic
Ian Lynagh's avatar
Ian Lynagh committed
73
import Util
74
import FastString
75
import Fingerprint
76
import Hooks
Adam Gundry's avatar
Adam Gundry committed
77
import FieldLabel
Edward Z. Yang's avatar
Edward Z. Yang committed
78 79
import RnModIface
import UniqDSet
Simon Marlow's avatar
Simon Marlow committed
80

Ian Lynagh's avatar
Ian Lynagh committed
81
import Control.Monad
82
import Control.Exception
83 84
import Data.IORef
import System.FilePath
85

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
{-
************************************************************************
*                                                                      *
*      tcImportDecl is the key function for "faulting in"              *
*      imported things
*                                                                      *
************************************************************************

The main idea is this.  We are chugging along type-checking source code, and
find a reference to GHC.Base.map.  We call tcLookupGlobal, which doesn't find
it in the EPS type envt.  So it
        1 loads GHC.Base.hi
        2 gets the decl for GHC.Base.map
        3 typechecks it via tcIfaceDecl
        4 and adds it to the type env in the EPS

Note that DURING STEP 4, we may find that map's type mentions a type
constructor that also

Notice that for imported things we read the current version from the EPS
mutable variable.  This is important in situations like
        ...$(e1)...$(e2)...
where the code that e1 expands to might import some defns that
also turn out to be needed by the code that e2 expands to.
-}

tcLookupImported_maybe :: Name -> TcM (MaybeErr MsgDoc TyThing)
-- Returns (Failed err) if we can't find the interface file for the thing
tcLookupImported_maybe name
  = do  { hsc_env <- getTopEnv
        ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
        ; case mb_thing of
            Just thing -> return (Succeeded thing)
            Nothing    -> tcImportDecl_maybe name }

tcImportDecl_maybe :: Name -> TcM (MaybeErr MsgDoc TyThing)
-- Entry point for *source-code* uses of importDecl
tcImportDecl_maybe name
  | Just thing <- wiredInNameTyThing_maybe name
  = do  { when (needWiredInHomeIface thing)
               (initIfaceTcRn (loadWiredInHomeIface name))
                -- See Note [Loading instances for wired-in things]
        ; return (Succeeded thing) }
  | otherwise
  = initIfaceTcRn (importDecl name)

importDecl :: Name -> IfM lcl (MaybeErr MsgDoc TyThing)
-- Get the TyThing for this Name from an interface file
-- It's not a wired-in thing -- the caller caught that
importDecl name
  = ASSERT( not (isWiredInName name) )
    do  { traceIf nd_doc

        -- Load the interface, which should populate the PTE
        ; mb_iface <- ASSERT2( isExternalName name, ppr name )
                      loadInterface nd_doc (nameModule name) ImportBySystem
        ; case mb_iface of {
                Failed err_msg  -> return (Failed err_msg) ;
                Succeeded _ -> do

        -- Now look it up again; this time we should find it
        { eps <- getEps
        ; case lookupTypeEnv (eps_PTE eps) name of
149
            Just thing -> return $ Succeeded thing
Simon Peyton Jones's avatar
Simon Peyton Jones committed
150
            Nothing    -> let doc = whenPprDebug (found_things_msg eps $$ empty)
151 152
                                    $$ not_found_msg
                          in return $ Failed doc
153 154
    }}}
  where
155 156
    nd_doc = text "Need decl for" <+> ppr name
    not_found_msg = hang (text "Can't find interface-file declaration for" <+>
157
                                pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
158 159
                       2 (vcat [text "Probable cause: bug in .hi-boot file, or inconsistent .hi file",
                                text "Use -ddump-if-trace to get an idea of which file caused the error"])
160 161 162 163 164
    found_things_msg eps =
        hang (text "Found the following declarations in" <+> ppr (nameModule name) <> colon)
           2 (vcat (map ppr $ filter is_interesting $ nameEnvElts $ eps_PTE eps))
      where
        is_interesting thing = nameModule name == nameModule (getName thing)
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187


{-
************************************************************************
*                                                                      *
           Checks for wired-in things
*                                                                      *
************************************************************************

Note [Loading instances for wired-in things]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to make sure that we have at least *read* the interface files
for any module with an instance decl or RULE that we might want.

* If the instance decl is an orphan, we have a whole separate mechanism
  (loadOrphanModules)

* If the instance decl is not an orphan, then the act of looking at the
  TyCon or Class will force in the defining module for the
  TyCon/Class, and hence the instance decl

* BUT, if the TyCon is a wired-in TyCon, we don't really need its interface;
  but we must make sure we read its interface in case it has instances or
188
  rules.  That is what LoadIface.loadWiredInHomeIface does.  It's called
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  from TcIface.{tcImportDecl, checkWiredInTyCon, ifCheckWiredInThing}

* HOWEVER, only do this for TyCons.  There are no wired-in Classes.  There
  are some wired-in Ids, but we don't want to load their interfaces. For
  example, Control.Exception.Base.recSelError is wired in, but that module
  is compiled late in the base library, and we don't want to force it to
  load before it's been compiled!

All of this is done by the type checker. The renamer plays no role.
(It used to, but no longer.)
-}

checkWiredInTyCon :: TyCon -> TcM ()
-- Ensure that the home module of the TyCon (and hence its instances)
-- are loaded. See Note [Loading instances for wired-in things]
-- It might not be a wired-in tycon (see the calls in TcUnify),
-- in which case this is a no-op.
checkWiredInTyCon tc
  | not (isWiredInName tc_name)
  = return ()
  | otherwise
  = do  { mod <- getModule
Simon Peyton Jones's avatar
Simon Peyton Jones committed
211
        ; traceIf (text "checkWiredInTyCon" <+> ppr tc_name $$ ppr mod)
212 213 214 215
        ; ASSERT( isExternalName tc_name )
          when (mod /= nameModule tc_name)
               (initIfaceTcRn (loadWiredInHomeIface tc_name))
                -- Don't look for (non-existent) Float.hi when
216
                -- compiling Float.hs, which mentions Float of course
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
                -- A bit yukky to call initIfaceTcRn here
        }
  where
    tc_name = tyConName tc

ifCheckWiredInThing :: TyThing -> IfL ()
-- Even though we are in an interface file, we want to make
-- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
-- Ditto want to ensure that RULES are loaded too
-- See Note [Loading instances for wired-in things]
ifCheckWiredInThing thing
  = do  { mod <- getIfModule
                -- Check whether we are typechecking the interface for this
                -- very module.  E.g when compiling the base library in --make mode
                -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
                -- the HPT, so without the test we'll demand-load it into the PIT!
                -- C.f. the same test in checkWiredInTyCon above
        ; let name = getName thing
        ; ASSERT2( isExternalName name, ppr name )
          when (needWiredInHomeIface thing && mod /= nameModule name)
               (loadWiredInHomeIface name) }

needWiredInHomeIface :: TyThing -> Bool
-- Only for TyCons; see Note [Loading instances for wired-in things]
needWiredInHomeIface (ATyCon {}) = True
needWiredInHomeIface _           = False


Austin Seipp's avatar
Austin Seipp committed
245 246 247
{-
************************************************************************
*                                                                      *
248
        loadSrcInterface, loadOrphanModules, loadInterfaceForName
249

Austin Seipp's avatar
Austin Seipp committed
250 251 252 253
                These three are called from TcM-land
*                                                                      *
************************************************************************
-}
254

Austin Seipp's avatar
Austin Seipp committed
255
-- | Load the interface corresponding to an @import@ directive in
Simon Marlow's avatar
Simon Marlow committed
256
-- source code.  On a failure, fail in the monad with an error message.
257 258 259 260
loadSrcInterface :: SDoc
                 -> ModuleName
                 -> IsBootInterface     -- {-# SOURCE #-} ?
                 -> Maybe FastString    -- "package", if any
261
                 -> RnM ModIface
262

263 264 265
loadSrcInterface doc mod want_boot maybe_pkg
  = do { res <- loadSrcInterface_maybe doc mod want_boot maybe_pkg
       ; case res of
266 267
           Failed err      -> failWithTc err
           Succeeded iface -> return iface }
268

269
-- | Like 'loadSrcInterface', but returns a 'MaybeErr'.
270 271 272 273
loadSrcInterface_maybe :: SDoc
                       -> ModuleName
                       -> IsBootInterface     -- {-# SOURCE #-} ?
                       -> Maybe FastString    -- "package", if any
274
                       -> RnM (MaybeErr MsgDoc ModIface)
275 276

loadSrcInterface_maybe doc mod want_boot maybe_pkg
Simon Marlow's avatar
Simon Marlow committed
277 278 279 280 281
  -- We must first find which Module this import refers to.  This involves
  -- calling the Finder, which as a side effect will search the filesystem
  -- and create a ModLocation.  If successful, loadIface will read the
  -- interface; it will call the Finder again, but the ModLocation will be
  -- cached from the first search.
282 283 284
  = do { hsc_env <- getTopEnv
       ; res <- liftIO $ findImportedModule hsc_env mod maybe_pkg
       ; case res of
285
           Found _ mod -> initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
286 287
           -- TODO: Make sure this error message is good
           err         -> return (Failed (cannotFindModule (hsc_dflags hsc_env) mod err)) }
288

Edward Z. Yang's avatar
Edward Z. Yang committed
289 290 291 292
-- | Load interface directly for a fully qualified 'Module'.  (This is a fairly
-- rare operation, but in particular it is used to load orphan modules
-- in order to pull their instances into the global package table and to
-- handle some operations in GHCi).
293 294 295 296 297 298
loadModuleInterface :: SDoc -> Module -> TcM ModIface
loadModuleInterface doc mod = initIfaceTcRn (loadSysInterface doc mod)

-- | Load interfaces for a collection of modules.
loadModuleInterfaces :: SDoc -> [Module] -> TcM ()
loadModuleInterfaces doc mods
299
  | null mods = return ()
300
  | otherwise = initIfaceTcRn (mapM_ load mods)
301
  where
302
    load mod = loadSysInterface (doc <+> parens (ppr mod)) mod
303

Simon Marlow's avatar
Simon Marlow committed
304
-- | Loads the interface for a given Name.
305 306
-- Should only be called for an imported name;
-- otherwise loadSysInterface may not find the interface
Simon Marlow's avatar
Simon Marlow committed
307 308
loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
loadInterfaceForName doc name
309 310 311 312 313
  = do { when debugIsOn $  -- Check pre-condition
         do { this_mod <- getModule
            ; MASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc ) }
      ; ASSERT2( isExternalName name, ppr name )
        initIfaceTcRn $ loadSysInterface doc (nameModule name) }
314 315 316 317 318 319 320 321 322 323

-- | Loads the interface for a given Module.
loadInterfaceForModule :: SDoc -> Module -> TcRn ModIface
loadInterfaceForModule doc m
  = do
    -- Should not be called with this module
    when debugIsOn $ do
      this_mod <- getModule
      MASSERT2( this_mod /= m, ppr m <+> parens doc )
    initIfaceTcRn $ loadSysInterface doc m
324

Austin Seipp's avatar
Austin Seipp committed
325 326 327
{-
*********************************************************
*                                                      *
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
328
                loadInterface
329

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
330 331 332
        The main function to load an interface
        for an imported module, and put it in
        the External Package State
Austin Seipp's avatar
Austin Seipp committed
333 334 335
*                                                      *
*********************************************************
-}
336

Simon Marlow's avatar
Simon Marlow committed
337
-- | An 'IfM' function to load the home interface for a wired-in thing,
338
-- so that we're sure that we see its instance declarations and rules
Simon Peyton Jones's avatar
Simon Peyton Jones committed
339
-- See Note [Loading instances for wired-in things]
Simon Marlow's avatar
Simon Marlow committed
340
loadWiredInHomeIface :: Name -> IfM lcl ()
341 342
loadWiredInHomeIface name
  = ASSERT( isWiredInName name )
343
    do _ <- loadSysInterface doc (nameModule name); return ()
344
  where
345
    doc = text "Need home interface for wired-in thing" <+> ppr name
346

347
------------------
348
-- | Loads a system interface and throws an exception if it fails
349
loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
350 351
loadSysInterface doc mod_name = loadInterfaceWithException doc mod_name ImportBySystem

352
------------------
353 354 355
-- | Loads a user interface and throws an exception if it fails. The first parameter indicates
-- whether we should import the boot variant of the module
loadUserInterface :: Bool -> SDoc -> Module -> IfM lcl ModIface
Austin Seipp's avatar
Austin Seipp committed
356
loadUserInterface is_boot doc mod_name
357
  = loadInterfaceWithException doc mod_name (ImportByUser is_boot)
358

359 360 361 362
loadPluginInterface :: SDoc -> Module -> IfM lcl ModIface
loadPluginInterface doc mod_name
  = loadInterfaceWithException doc mod_name ImportByPlugin

363
------------------
364 365 366
-- | A wrapper for 'loadInterface' that throws an exception if it fails
loadInterfaceWithException :: SDoc -> Module -> WhereFrom -> IfM lcl ModIface
loadInterfaceWithException doc mod_name where_from
Edward Z. Yang's avatar
Edward Z. Yang committed
367
  = withException (loadInterface doc mod_name where_from)
368

369
------------------
Simon Marlow's avatar
Simon Marlow committed
370
loadInterface :: SDoc -> Module -> WhereFrom
371
              -> IfM lcl (MaybeErr MsgDoc ModIface)
372

373
-- loadInterface looks in both the HPT and PIT for the required interface
Austin Seipp's avatar
Austin Seipp committed
374
-- If not found, it loads it, and puts it in the PIT (always).
375

376
-- If it can't find a suitable interface file, we
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
377 378 379
--      a) modify the PackageIfaceTable to have an empty entry
--              (to avoid repeated complaints)
--      b) return (Left message)
380 381
--
-- It's not necessarily an error for there not to be an interface
Austin Seipp's avatar
Austin Seipp committed
382
-- file -- perhaps the module has changed, and that interface
383
-- is no longer used
384

385
loadInterface doc_str mod from
Edward Z. Yang's avatar
Edward Z. Yang committed
386 387 388 389 390 391
  | isHoleModule mod
  -- Hole modules get special treatment
  = do dflags <- getDynFlags
       -- Redo search for our local hole module
       loadInterface doc_str (mkModule (thisPackage dflags) (moduleName mod)) from
  | otherwise
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
392 393
  = do  {       -- Read the state
          (eps,hpt) <- getEpsAndHpt
394
        ; gbl_env <- getGblEnv
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
395 396 397 398

        ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)

                -- Check whether we have the interface already
399
        ; dflags <- getDynFlags
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
400
        ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
Austin Seipp's avatar
Austin Seipp committed
401
            Just iface
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
402 403 404 405 406 407 408 409
                -> return (Succeeded iface) ;   -- Already loaded
                        -- The (src_imp == mi_boot iface) test checks that the already-loaded
                        -- interface isn't a boot iface.  This can conceivably happen,
                        -- if an earlier import had a before we got to real imports.   I think.
            _ -> do {

        -- READ THE MODULE IN
        ; read_result <- case (wantHiBootFile dflags eps mod from) of
410
                           Failed err             -> return (Failed err)
411 412 413 414 415 416 417 418
                           Succeeded hi_boot_file ->
                            -- Stoutly warn against an EPS-updating import
                            -- of one's own boot file! (one-shot only)
                            --See Note [Do not update EPS with your own hi-boot]
                            -- in MkIface.
                            WARN( hi_boot_file &&
                                  fmap fst (if_rec_types gbl_env) == Just mod,
                                  ppr mod )
Edward Z. Yang's avatar
Edward Z. Yang committed
419
                            computeInterface doc_str hi_boot_file mod
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
420 421 422 423 424 425
        ; case read_result of {
            Failed err -> do
                { let fake_iface = emptyModIface mod

                ; updateEps_ $ \eps ->
                        eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
Austin Seipp's avatar
Austin Seipp committed
426
                        -- Not found, so add an empty iface to
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
427
                        -- the EPS map so that we don't look again
Austin Seipp's avatar
Austin Seipp committed
428

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
429 430 431 432 433 434 435 436 437 438 439
                ; return (Failed err) } ;

        -- Found and parsed!
        -- We used to have a sanity check here that looked for:
        --  * System importing ..
        --  * a home package module ..
        --  * that we know nothing about (mb_dep == Nothing)!
        --
        -- But this is no longer valid because thNameToGhcName allows users to
        -- cause the system to load arbitrary interfaces (by supplying an appropriate
        -- Template Haskell original-name).
Edward Z. Yang's avatar
Edward Z. Yang committed
440
            Succeeded (iface, loc) ->
Austin Seipp's avatar
Austin Seipp committed
441
        let
Edward Z. Yang's avatar
Edward Z. Yang committed
442
            loc_doc = text loc
Austin Seipp's avatar
Austin Seipp committed
443
        in
Edward Z. Yang's avatar
Edward Z. Yang committed
444
        initIfaceLcl (mi_semantic_module iface) loc_doc (mi_boot iface) $ do
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
445

Simon Marlow's avatar
Simon Marlow committed
446 447
        dontLeakTheHPT $ do

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
448
        --      Load the new ModIface into the External Package State
Austin Seipp's avatar
Austin Seipp committed
449 450
        -- Even home-package interfaces loaded by loadInterface
        --      (which only happens in OneShot mode; in Batch/Interactive
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
451 452 453 454 455
        --      mode, home-package modules are loaded one by one into the HPT)
        -- are put in the EPS.
        --
        -- The main thing is to add the ModIface to the PIT, but
        -- we also take the
456
        --      IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules, IfaceVectInfo
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
457 458 459 460 461 462 463
        -- out of the ModIface and put them into the big EPS pools

        -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
        ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
        --     If we do loadExport first the wrong info gets into the cache (unless we
        --      explicitly tag each export which seems a bit of a bore)

ian@well-typed.com's avatar
ian@well-typed.com committed
464
        ; ignore_prags      <- goptM Opt_IgnoreInterfacePragmas
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
465 466 467 468 469
        ; new_eps_decls     <- loadDecls ignore_prags (mi_decls iface)
        ; new_eps_insts     <- mapM tcIfaceInst (mi_insts iface)
        ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
        ; new_eps_rules     <- tcIfaceRules ignore_prags (mi_rules iface)
        ; new_eps_anns      <- tcIfaceAnnotations (mi_anns iface)
470
        ; new_eps_vect_info <- tcIfaceVectInfo mod (mkNameEnv new_eps_decls) (mi_vect_info iface)
471
        ; new_eps_complete_sigs <- tcIfaceCompleteSigs (mi_complete_sigs iface)
472

Austin Seipp's avatar
Austin Seipp committed
473
        ; let { final_iface = iface {
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
474 475 476 477 478
                                mi_decls     = panic "No mi_decls in PIT",
                                mi_insts     = panic "No mi_insts in PIT",
                                mi_fam_insts = panic "No mi_fam_insts in PIT",
                                mi_rules     = panic "No mi_rules in PIT",
                                mi_anns      = panic "No mi_anns in PIT"
479 480
                              }
               }
481

Austin Seipp's avatar
Austin Seipp committed
482
        ; updateEps_  $ \ eps ->
Edward Z. Yang's avatar
Edward Z. Yang committed
483 484
           if elemModuleEnv mod (eps_PIT eps) || is_external_sig dflags iface
           then eps else
485
                eps {
486 487
                  eps_PIT          = extendModuleEnv (eps_PIT eps) mod final_iface,
                  eps_PTE          = addDeclsToPTE   (eps_PTE eps) new_eps_decls,
Austin Seipp's avatar
Austin Seipp committed
488
                  eps_rule_base    = extendRuleBaseList (eps_rule_base eps)
489
                                                        new_eps_rules,
490 491 492 493
                  eps_complete_matches
                                   = extendCompleteMatchMap
                                         (eps_complete_matches eps)
                                         new_eps_complete_sigs,
Austin Seipp's avatar
Austin Seipp committed
494
                  eps_inst_env     = extendInstEnvList (eps_inst_env eps)
495 496 497
                                                       new_eps_insts,
                  eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
                                                          new_eps_fam_insts,
Austin Seipp's avatar
Austin Seipp committed
498
                  eps_vect_info    = plusVectInfo (eps_vect_info eps)
499 500 501 502 503
                                                  new_eps_vect_info,
                  eps_ann_env      = extendAnnEnvList (eps_ann_env eps)
                                                      new_eps_anns,
                  eps_mod_fam_inst_env
                                   = let
Austin Seipp's avatar
Austin Seipp committed
504
                                       fam_inst_env =
505 506 507 508 509 510
                                         extendFamInstEnvList emptyFamInstEnv
                                                              new_eps_fam_insts
                                     in
                                     extendModuleEnv (eps_mod_fam_inst_env eps)
                                                     mod
                                                     fam_inst_env,
Austin Seipp's avatar
Austin Seipp committed
511
                  eps_stats        = addEpsInStats (eps_stats eps)
512 513 514
                                                   (length new_eps_decls)
                                                   (length new_eps_insts)
                                                   (length new_eps_rules) }
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
515 516

        ; return (Succeeded final_iface)
517 518
    }}}}

Simon Marlow's avatar
Simon Marlow committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566


-- Note [HPT space leak] (#15111)
--
-- In IfL, we defer some work until it is demanded using forkM, such
-- as building TyThings from IfaceDecls. These thunks are stored in
-- the ExternalPackageState, and they might never be poked.  If we're
-- not careful, these thunks will capture the state of the loaded
-- program when we read an interface file, and retain all that data
-- for ever.
--
-- Therefore, when loading a package interface file , we use a "clean"
-- version of the HscEnv with all the data about the currently loaded
-- program stripped out. Most of the fields can be panics because
-- we'll never read them, but hsc_HPT needs to be empty because this
-- interface will cause other interfaces to be loaded recursively, and
-- when looking up those interfaces we use the HPT in loadInterface.
-- We know that none of the interfaces below here can refer to
-- home-package modules however, so it's safe for the HPT to be empty.
--
dontLeakTheHPT :: IfL a -> IfL a
dontLeakTheHPT thing_inside = do
  let
    cleanTopEnv HscEnv{..} =
       let
         -- wrinkle: when we're typechecking in --backpack mode, the
         -- instantiation of a signature might reside in the HPT, so
         -- this case breaks the assumption that EPS interfaces only
         -- refer to other EPS interfaces. We can detect when we're in
         -- typechecking-only mode by using hscTarget==HscNothing, and
         -- in that case we don't empty the HPT.  (admittedly this is
         -- a bit of a hack, better suggestions welcome). A number of
         -- tests in testsuite/tests/backpack break without this
         -- tweak.
         !hpt | hscTarget hsc_dflags == HscNothing = hsc_HPT
              | otherwise = emptyHomePackageTable
       in
       HscEnv {  hsc_targets      = panic "cleanTopEnv: hsc_targets"
              ,  hsc_mod_graph    = panic "cleanTopEnv: hsc_mod_graph"
              ,  hsc_IC           = panic "cleanTopEnv: hsc_IC"
              ,  hsc_HPT          = hpt
              , .. }

  updTopEnv cleanTopEnv $ do
  !_ <- getTopEnv        -- force the updTopEnv
  thing_inside


Edward Z. Yang's avatar
Edward Z. Yang committed
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
-- | Returns @True@ if a 'ModIface' comes from an external package.
-- In this case, we should NOT load it into the EPS; the entities
-- should instead come from the local merged signature interface.
is_external_sig :: DynFlags -> ModIface -> Bool
is_external_sig dflags iface =
    -- It's a signature iface...
    mi_semantic_module iface /= mi_module iface &&
    -- and it's not from the local package
    moduleUnitId (mi_module iface) /= thisPackage dflags

-- | This is an improved version of 'findAndReadIface' which can also
-- handle the case when a user requests @p[A=<B>]:M@ but we only
-- have an interface for @p[A=<A>]:M@ (the indefinite interface.
-- If we are not trying to build code, we load the interface we have,
-- *instantiating it* according to how the holes are specified.
-- (Of course, if we're actually building code, this is a hard error.)
--
-- In the presence of holes, 'computeInterface' has an important invariant:
-- to load module M, its set of transitively reachable requirements must
-- have an up-to-date local hi file for that requirement.  Note that if
-- we are loading the interface of a requirement, this does not
-- apply to the requirement itself; e.g., @p[A=<A>]:A@ does not require
-- A.hi to be up-to-date (and indeed, we MUST NOT attempt to read A.hi, unless
-- we are actually typechecking p.)
computeInterface ::
       SDoc -> IsBootInterface -> Module
    -> TcRnIf gbl lcl (MaybeErr MsgDoc (ModIface, FilePath))
computeInterface doc_str hi_boot_file mod0 = do
    MASSERT( not (isHoleModule mod0) )
    dflags <- getDynFlags
    case splitModuleInsts mod0 of
598
        (imod, Just indef) | not (unitIdIsDefinite (thisPackage dflags)) -> do
599
            r <- findAndReadIface doc_str imod mod0 hi_boot_file
Edward Z. Yang's avatar
Edward Z. Yang committed
600 601 602
            case r of
                Succeeded (iface0, path) -> do
                    hsc_env <- getTopEnv
603 604 605 606 607 608
                    r <- liftIO $
                        rnModIface hsc_env (indefUnitIdInsts (indefModuleUnitId indef))
                                   Nothing iface0
                    case r of
                        Right x -> return (Succeeded (x, path))
                        Left errs -> liftIO . throwIO . mkSrcErr $ errs
Edward Z. Yang's avatar
Edward Z. Yang committed
609 610
                Failed err -> return (Failed err)
        (mod, _) ->
611
            findAndReadIface doc_str mod mod0 hi_boot_file
Edward Z. Yang's avatar
Edward Z. Yang committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

-- | Compute the signatures which must be compiled in order to
-- load the interface for a 'Module'.  The output of this function
-- is always a subset of 'moduleFreeHoles'; it is more precise
-- because in signature @p[A=<A>,B=<B>]:B@, although the free holes
-- are A and B, B might not depend on A at all!
--
-- If this is invoked on a signature, this does NOT include the
-- signature itself; e.g. precise free module holes of
-- @p[A=<A>,B=<B>]:B@ never includes B.
moduleFreeHolesPrecise
    :: SDoc -> Module
    -> TcRnIf gbl lcl (MaybeErr MsgDoc (UniqDSet ModuleName))
moduleFreeHolesPrecise doc_str mod
 | moduleIsDefinite mod = return (Succeeded emptyUniqDSet)
 | otherwise =
   case splitModuleInsts mod of
629 630
    (imod, Just indef) -> do
        let insts = indefUnitIdInsts (indefModuleUnitId indef)
Edward Z. Yang's avatar
Edward Z. Yang committed
631 632 633 634 635 636 637 638 639 640 641 642
        traceIf (text "Considering whether to load" <+> ppr mod <+>
                 text "to compute precise free module holes")
        (eps, hpt) <- getEpsAndHpt
        dflags <- getDynFlags
        case tryEpsAndHpt dflags eps hpt `firstJust` tryDepsCache eps imod insts of
            Just r -> return (Succeeded r)
            Nothing -> readAndCache imod insts
    (_, Nothing) -> return (Succeeded emptyUniqDSet)
  where
    tryEpsAndHpt dflags eps hpt =
        fmap mi_free_holes (lookupIfaceByModule dflags hpt (eps_PIT eps) mod)
    tryDepsCache eps imod insts =
643
        case lookupInstalledModuleEnv (eps_free_holes eps) imod of
Edward Z. Yang's avatar
Edward Z. Yang committed
644 645 646
            Just ifhs  -> Just (renameFreeHoles ifhs insts)
            _otherwise -> Nothing
    readAndCache imod insts = do
647
        mb_iface <- findAndReadIface (text "moduleFreeHolesPrecise" <+> doc_str) imod mod False
Edward Z. Yang's avatar
Edward Z. Yang committed
648 649 650 651 652
        case mb_iface of
            Succeeded (iface, _) -> do
                let ifhs = mi_free_holes iface
                -- Cache it
                updateEps_ (\eps ->
653
                    eps { eps_free_holes = extendInstalledModuleEnv (eps_free_holes eps) imod ifhs })
Edward Z. Yang's avatar
Edward Z. Yang committed
654 655 656
                return (Succeeded (renameFreeHoles ifhs insts))
            Failed err -> return (Failed err)

657
wantHiBootFile :: DynFlags -> ExternalPackageState -> Module -> WhereFrom
658
               -> MaybeErr MsgDoc IsBootInterface
659 660 661
-- Figure out whether we want Foo.hi or Foo.hi-boot
wantHiBootFile dflags eps mod from
  = case from of
Austin Seipp's avatar
Austin Seipp committed
662
       ImportByUser usr_boot
663 664 665 666
          | usr_boot && not this_package
          -> Failed (badSourceImport mod)
          | otherwise -> Succeeded usr_boot

667 668 669
       ImportByPlugin
          -> Succeeded False

670 671 672
       ImportBySystem
          | not this_package   -- If the module to be imported is not from this package
          -> Succeeded False   -- don't look it up in eps_is_boot, because that is keyed
Austin Seipp's avatar
Austin Seipp committed
673
                               -- on the ModuleName of *home-package* modules only.
674 675 676 677
                               -- We never import boot modules from other packages!

          | otherwise
          -> case lookupUFM (eps_is_boot eps) (moduleName mod) of
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
678 679
                Just (_, is_boot) -> Succeeded is_boot
                Nothing           -> Succeeded False
Austin Seipp's avatar
Austin Seipp committed
680
                     -- The boot-ness of the requested interface,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
681
                     -- based on the dependencies in directly-imported modules
682
  where
683
    this_package = thisPackage dflags == moduleUnitId mod
684 685 686

badSourceImport :: Module -> SDoc
badSourceImport mod
687 688
  = hang (text "You cannot {-# SOURCE #-} import a module from another package")
       2 (text "but" <+> quotes (ppr mod) <+> ptext (sLit "is from package")
689
          <+> quotes (ppr (moduleUnitId mod)))
690

691
-----------------------------------------------------
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
692
--      Loading type/class/value decls
693 694 695 696 697
-- We pass the full Module name here, replete with
-- its package info, so that we can build a Name for
-- each binder with the right package info in it
-- All subsequent lookups, including crucially lookups during typechecking
-- the declaration itself, will find the fully-glorious Name
698 699
--
-- We handle ATs specially.  They are not main declarations, but also not
Edward Z. Yang's avatar
Edward Z. Yang committed
700
-- implicit things (in particular, adding them to `implicitTyThings' would mess
701
-- things up in the renaming/type checking of source programs).
702 703
-----------------------------------------------------

704 705 706 707
addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
addDeclsToPTE pte things = extendNameEnvList pte things

loadDecls :: Bool
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
708 709
          -> [(Fingerprint, IfaceDecl)]
          -> IfL [(Name,TyThing)]
710
loadDecls ignore_prags ver_decls
711
   = do { thingss <- mapM (loadDecl ignore_prags) ver_decls
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
712 713 714 715 716 717 718
        ; return (concat thingss)
        }

loadDecl :: Bool                    -- Don't load pragmas into the decl pool
          -> (Fingerprint, IfaceDecl)
          -> IfL [(Name,TyThing)]   -- The list can be poked eagerly, but the
                                    -- TyThings are forkM'd thunks
719
loadDecl ignore_prags (_version, decl)
Austin Seipp's avatar
Austin Seipp committed
720
  = do  {       -- Populate the name cache with final versions of all
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
721
                -- the names associated with the decl
722
          let main_name = ifName decl
723

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
724 725
        -- Typecheck the thing, lazily
        -- NB. Firstly, the laziness is there in case we never need the
Austin Seipp's avatar
Austin Seipp committed
726
        -- declaration (in one-shot mode), and secondly it is there so that
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
727 728 729
        -- we don't look up the occurrence of a name before calling mk_new_bndr
        -- on the binder.  This is important because we must get the right name
        -- which includes its nameParent.
730

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
731 732
        ; thing <- forkM doc $ do { bumpDeclStats main_name
                                  ; tcIfaceDecl ignore_prags decl }
733

734
        -- Populate the type environment with the implicitTyThings too.
Austin Seipp's avatar
Austin Seipp committed
735
        --
736 737 738 739 740 741 742
        -- Note [Tricky iface loop]
        -- ~~~~~~~~~~~~~~~~~~~~~~~~
        -- Summary: The delicate point here is that 'mini-env' must be
        -- buildable from 'thing' without demanding any of the things
        -- 'forkM'd by tcIfaceDecl.
        --
        -- In more detail: Consider the example
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
743
        --      data T a = MkT { x :: T a }
744 745
        -- The implicitTyThings of T are:  [ <datacon MkT>, <selector x>]
        -- (plus their workers, wrappers, coercions etc etc)
Austin Seipp's avatar
Austin Seipp committed
746 747
        --
        -- We want to return an environment
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
748
        --      [ "MkT" -> <datacon MkT>, "x" -> <selector x>, ... ]
749 750
        -- (where the "MkT" is the *Name* associated with MkT, etc.)
        --
Edward Z. Yang's avatar
Edward Z. Yang committed
751
        -- We do this by mapping the implicit_names to the associated
752
        -- TyThings.  By the invariant on ifaceDeclImplicitBndrs and
753 754
        -- implicitTyThings, we can use getOccName on the implicit
        -- TyThings to make this association: each Name's OccName should
Edward Z. Yang's avatar
Edward Z. Yang committed
755
        -- be the OccName of exactly one implicitTyThing.  So the key is
756 757 758 759 760 761 762
        -- to define a "mini-env"
        --
        -- [ 'MkT' -> <datacon MkT>, 'x' -> <selector x>, ... ]
        -- where the 'MkT' here is the *OccName* associated with MkT.
        --
        -- However, there is a subtlety: due to how type checking needs
        -- to be staged, we can't poke on the forkM'd thunks inside the
Austin Seipp's avatar
Austin Seipp committed
763
        -- implicitTyThings while building this mini-env.
764 765 766 767 768 769 770
        -- If we poke these thunks too early, two problems could happen:
        --    (1) When processing mutually recursive modules across
        --        hs-boot boundaries, poking too early will do the
        --        type-checking before the recursive knot has been tied,
        --        so things will be type-checked in the wrong
        --        environment, and necessary variables won't be in
        --        scope.
Austin Seipp's avatar
Austin Seipp committed
771
        --
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        --    (2) Looking up one OccName in the mini_env will cause
        --        others to be looked up, which might cause that
        --        original one to be looked up again, and hence loop.
        --
        -- The code below works because of the following invariant:
        -- getOccName on a TyThing does not force the suspended type
        -- checks in order to extract the name. For example, we don't
        -- poke on the "T a" type of <selector x> on the way to
        -- extracting <selector x>'s OccName. Of course, there is no
        -- reason in principle why getting the OccName should force the
        -- thunks, but this means we need to be careful in
        -- implicitTyThings and its helper functions.
        --
        -- All a bit too finely-balanced for my liking.

        -- This mini-env and lookup function mediates between the
Thomas Schilling's avatar
Thomas Schilling committed
788
        --'Name's n and the map from 'OccName's to the implicit TyThings
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
789 790 791
        ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
              lookup n = case lookupOccEnv mini_env (getOccName n) of
                           Just thing -> thing
Austin Seipp's avatar
Austin Seipp committed
792
                           Nothing    ->
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
793
                             pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
794

795
        ; implicit_names <- mapM lookupIfaceTop (ifaceDeclImplicitBndrs decl)
796 797

--         ; traceIf (text "Loading decl for " <> ppr main_name $$ ppr implicit_names)
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
798
        ; return $ (main_name, thing) :
799
                      -- uses the invariant that implicit_names and
Edward Z. Yang's avatar
Edward Z. Yang committed
800
                      -- implicitTyThings are bijective
801
                      [(n, lookup n) | n <- implicit_names]
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
802
        }
803
  where
804
    doc = text "Declaration for" <+> ppr (ifName decl)
805

chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
806
bumpDeclStats :: Name -> IfL ()         -- Record that one more declaration has actually been used
807
bumpDeclStats name
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
808 809 810 811
  = do  { traceIf (text "Loading decl for" <+> ppr name)
        ; updateEps_ (\eps -> let stats = eps_stats eps
                              in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
        }
812

Austin Seipp's avatar
Austin Seipp committed
813 814 815
{-
*********************************************************
*                                                      *
816
\subsection{Reading an interface file}
Austin Seipp's avatar
Austin Seipp committed
817 818
*                                                      *
*********************************************************
819

820 821 822 823 824 825 826 827 828 829
Note [Home module load error]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the sought-for interface is in the current package (as determined
by -package-name flag) then it jolly well should already be in the HPT
because we process home-package modules in dependency order.  (Except
in one-shot mode; see notes with hsc_HPT decl in HscTypes).

It is possible (though hard) to get this error through user behaviour.
  * Suppose package P (modules P1, P2) depends on package Q (modules Q1,
    Q2, with Q2 importing Q1)
Austin Seipp's avatar
Austin Seipp committed
830
  * We compile both packages.
831
  * Now we edit package Q so that it somehow depends on P
Austin Seipp's avatar
Austin Seipp committed
832
  * Now recompile Q with --make (without recompiling P).
833 834 835 836 837
  * Then Q1 imports, say, P1, which in turn depends on Q2. So Q2
    is a home-package module which is not yet in the HPT!  Disaster.

This actually happened with P=base, Q=ghc-prim, via the AMP warnings.
See Trac #8320.
Austin Seipp's avatar
Austin Seipp committed
838
-}
839

840 841 842 843 844 845 846 847
findAndReadIface :: SDoc
                 -- The unique identifier of the on-disk module we're
                 -- looking for
                 -> InstalledModule
                 -- The *actual* module we're looking for.  We use
                 -- this to check the consistency of the requirements
                 -- of the module we read out.
                 -> Module
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
848 849
                 -> IsBootInterface     -- True  <=> Look for a .hi-boot file
                                        -- False <=> Look for .hi file
850
                 -> TcRnIf gbl lcl (MaybeErr MsgDoc (ModIface, FilePath))
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
851
        -- Nothing <=> file not found, or unreadable, or illegible
Austin Seipp's avatar
Austin Seipp committed
852
        -- Just x  <=> successfully found and parsed
853

Austin Seipp's avatar
Austin Seipp committed
854
        -- It *doesn't* add an error to the monad, because
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
855
        -- sometimes it's ok to fail... see notes with loadInterface
856
findAndReadIface doc_str mod wanted_mod_with_insts hi_boot_file
857
  = do traceIf (sep [hsep [text "Reading",
Austin Seipp's avatar
Austin Seipp committed
858
                           if hi_boot_file
859
                             then text "[boot]"
860
                             else Outputable.empty,
861
                           text "interface for",
862
                           ppr mod <> semi],
863
                     nest 4 (text "reason:" <+> doc_str)])
864 865

       -- Check for GHC.Prim, and return its static interface
866 867
       -- TODO: make this check a function
       if mod `installedModuleEq` gHC_PRIM
868 869 870
           then do
               iface <- getHooked ghcPrimIfaceHook ghcPrimIface
               return (Succeeded (iface,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
871
                                   "<built in interface for GHC.Prim>"))
872 873 874 875 876 877
           else do
               dflags <- getDynFlags
               -- Look for the file
               hsc_env <- getTopEnv
               mb_found <- liftIO (findExactModule hsc_env mod)
               case mb_found of
878
                   InstalledFound loc mod -> do
879 880 881 882
                       -- Found file, so read it
                       let file_path = addBootSuffix_maybe hi_boot_file
                                                           (ml_hi_file loc)

883
                       -- See Note [Home module load error]
884
                       if installedModuleUnitId mod `installedUnitIdEq` thisPackage dflags &&
885 886
                          not (isOneShot (ghcMode dflags))
                           then return (Failed (homeModError mod loc))
887 888 889
                           else do r <- read_file file_path
                                   checkBuildDynamicToo r
                                   return r
890
                   err -> do
891
                       traceIf (text "...not found")
892
                       dflags <- getDynFlags
Austin Seipp's avatar
Austin Seipp committed
893
                       return (Failed (cannotFindInterface dflags
894
                                           (installedModuleName mod) err))
895
    where read_file file_path = do
896
              traceIf (text "readIFace" <+> text file_path)
897 898 899 900 901 902 903 904 905 906 907
              -- Figure out what is recorded in mi_module.  If this is
              -- a fully definite interface, it'll match exactly, but
              -- if it's indefinite, the inside will be uninstantiated!
              dflags <- getDynFlags
              let wanted_mod =
                    case splitModuleInsts wanted_mod_with_insts of
                        (_, Nothing) -> wanted_mod_with_insts
                        (_, Just indef_mod) ->
                          indefModuleToModule dflags
                            (generalizeIndefModule indef_mod)
              read_result <- readIface wanted_mod file_path
908 909
              case read_result of
                Failed err -> return (Failed (badIfaceFile file_path err))
910
                Succeeded iface -> return (Succeeded (iface, file_path))
911
                            -- Don't forget to fill in the package name...
912 913
          checkBuildDynamicToo (Succeeded (iface, filePath)) = do
              dflags <- getDynFlags
Edward Z. Yang's avatar
Edward Z. Yang committed
914 915 916 917 918
              -- Indefinite interfaces are ALWAYS non-dynamic, and
              -- that's OK.
              let is_definite_iface = moduleIsDefinite (mi_module iface)
              when is_definite_iface $
                whenGeneratingDynamicToo dflags $ withDoDynamicToo $ do
919
                  let ref = canGenerateDynamicToo dflags
920 921
                      dynFilePath = addBootSuffix_maybe hi_boot_file
                                  $ replaceExtension filePath (dynHiSuf dflags)
922 923 924 925 926 927 928 929 930 931 932
                  r <- read_file dynFilePath
                  case r of
                      Succeeded (dynIface, _)
                       | mi_mod_hash iface == mi_mod_hash dynIface ->
                          return ()
                       | otherwise ->
                          do traceIf (text "Dynamic hash doesn't match")
                             liftIO $ writeIORef ref False
                      Failed err ->
                          do traceIf (text "Failed to load dynamic interface file:" $$ err)
                             liftIO $ writeIORef ref False
933
          checkBuildDynamicToo _ = return ()
934

Austin Seipp's avatar
Austin Seipp committed
935
-- @readIface@ tries just the one file.
936

937
readIface :: Module -> FilePath
938
          -> TcRnIf gbl lcl (MaybeErr MsgDoc ModIface)
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
939
        -- Failed err    <=> file not found, or unreadable, or illegible
Austin Seipp's avatar
Austin Seipp committed
940
        -- Succeeded iface <=> successfully found and parsed
941

942
readIface wanted_mod file_path
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
943
  = do  { res <- tryMostM $
944
                 readBinIface CheckHiWay QuietBinIFaceReading file_path
Sylvain Henry's avatar
Sylvain Henry committed
945
        ; dflags <- getDynFlags
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
946
        ; case res of