b63849d9d7911d9804e6c9f91f18c8673452c722
[ghc-hetmet.git] / ghc / compiler / iface / LoadIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Dealing with interface files}
5
6 \begin{code}
7 module LoadIface (
8         loadHomeInterface, loadInterface,
9         loadSrcInterface, loadOrphanModules, loadHiBootInterface,
10         readIface,      -- Used when reading the module's old interface
11         predInstGates, ifaceInstGates, ifaceStats, discardDeclPrags,
12         initExternalPackageState
13    ) where
14
15 #include "HsVersions.h"
16
17 import {-# SOURCE #-}   TcIface( tcIfaceDecl )
18
19 import Packages         ( PackageState(..), PackageIdH(..), isHomePackage )
20 import DriverState      ( v_GhcMode, isCompManagerMode )
21 import CmdLineOpts      ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ) )
22 import IfaceSyn         ( IfaceDecl(..), IfaceConDecl(..), IfaceClassOp(..),
23                           IfaceConDecls(..), IfaceInst(..), IfaceRule(..),
24                           IfaceExpr(..), IfaceTyCon(..), IfaceIdInfo(..), 
25                           IfaceType(..), IfacePredType(..), IfaceExtName,
26                           mkIfaceExtName )
27 import IfaceEnv         ( newGlobalBinder, lookupIfaceExt, lookupIfaceTc,
28                           lookupOrig )
29 import HscTypes         ( ModIface(..), TyThing, emptyModIface, EpsStats(..),
30                           addEpsInStats, ExternalPackageState(..),
31                           PackageTypeEnv, emptyTypeEnv,  
32                           lookupIfaceByModule, emptyPackageIfaceTable,
33                           IsBootInterface, mkIfaceFixCache, Gated,
34                           implicitTyThings, addRulesToPool, addInstsToPool,
35                           availNames
36                          )
37
38 import BasicTypes       ( Version, Fixity(..), FixityDirection(..),
39                           isMarkedStrict )
40 import TcType           ( Type, tcSplitTyConApp_maybe )
41 import Type             ( funTyCon )
42 import TcRnMonad
43
44 import PrelNames        ( gHC_PRIM )
45 import PrelInfo         ( ghcPrimExports )
46 import PrelRules        ( builtinRules )
47 import Rules            ( emptyRuleBase )
48 import InstEnv          ( emptyInstEnv )
49 import Name             ( Name {-instance NamedThing-}, getOccName,
50                           nameModule, isInternalName )
51 import NameEnv
52 import MkId             ( seqId )
53 import Module           ( Module, ModLocation(ml_hi_file), emptyModuleEnv, 
54                           addBootSuffix_maybe,
55                           extendModuleEnv, lookupModuleEnv, moduleUserString
56                         )
57 import OccName          ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc, mkClassDataConOcc,
58                           mkSuperDictSelOcc, mkDataConWrapperOcc, mkDataConWorkerOcc )
59 import Class            ( Class, className )
60 import TyCon            ( tyConName )
61 import SrcLoc           ( importedSrcLoc )
62 import Maybes           ( mapCatMaybes, MaybeErr(..) )
63 import FastString       ( mkFastString )
64 import ErrUtils         ( Message )
65 import Finder           ( findModule, findPackageModule,  FindResult(..), cantFindError )
66 import Outputable
67 import BinIface         ( readBinIface )
68 import Panic            ( ghcError, tryMost, showException, GhcException(..) )
69 import List             ( nub )
70
71 import DATA_IOREF       ( readIORef )
72 \end{code}
73
74
75 %************************************************************************
76 %*                                                                      *
77                 loadSrcInterface, loadOrphanModules
78
79                 These two are called from TcM-land      
80 %*                                                                      *
81 %************************************************************************
82
83 \begin{code}
84 loadSrcInterface :: SDoc -> Module -> IsBootInterface -> RnM ModIface
85 -- This is called for each 'import' declaration in the source code
86 -- On a failure, fail in the monad with an error message
87
88 loadSrcInterface doc mod_name want_boot
89   = do  { mb_iface <- initIfaceTcRn $ loadInterface doc mod_name 
90                                            (ImportByUser want_boot)
91         ; case mb_iface of
92             Failed err      -> failWithTc (elaborate err) 
93             Succeeded iface -> return iface
94         }
95   where
96     elaborate err = hang (ptext SLIT("Failed to load interface for") <+> 
97                          quotes (ppr mod_name) <> colon) 4 err
98
99 loadHiBootInterface :: TcRn [Name]
100 -- Load the hi-boot iface for the module being compiled,
101 -- if it indeed exists in the transitive closure of imports
102 -- Return the list of names exported by the hi-boot file
103 loadHiBootInterface
104   = do  { eps <- getEps
105         ; mod <- getModule
106
107         ; traceIf (text "loadHiBootInterface" <+> ppr mod)
108
109         -- We're read all the direct imports by now, so eps_is_boot will
110         -- record if any of our imports mention us by way of hi-boot file
111         ; case lookupModuleEnv (eps_is_boot eps) mod of {
112             Nothing             -> return [] ;  -- The typical case
113
114             Just (_, False) ->          -- Someone below us imported us!
115                 -- This is a loop with no hi-boot in the way
116                 failWithTc (moduleLoop mod) ;
117
118             Just (mod_nm, True) ->      -- There's a hi-boot interface below us
119                 
120
121     do  {       -- Load it (into the PTE), and return the exported names
122           iface <- loadSrcInterface (mk_doc mod_nm) mod_nm True
123         ; sequenceM [ lookupOrig mod_nm occ
124                     | (mod,avails) <- mi_exports iface, 
125                       avail <- avails, occ <- availNames avail]
126     }}}
127   where
128     mk_doc mod = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
129                  <+> ptext SLIT("to compare against the Real Thing")
130
131     moduleLoop mod = ptext SLIT("Circular imports: module") <+> quotes (ppr mod) 
132                      <+> ptext SLIT("depends on itself")
133
134 loadOrphanModules :: [Module] -> TcM ()
135 loadOrphanModules mods
136   | null mods = returnM ()
137   | otherwise = initIfaceTcRn $
138                 do { traceIf (text "Loading orphan modules:" <+> 
139                                  fsep (map ppr mods))
140                    ; mappM_ load mods
141                    ; returnM () }
142   where
143     load mod   = loadSysInterface (mk_doc mod) mod
144     mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
145 \end{code}
146
147 %*********************************************************
148 %*                                                      *
149                 loadHomeInterface
150                 Called from Iface-land
151 %*                                                      *
152 %*********************************************************
153
154 \begin{code}
155 loadHomeInterface :: SDoc -> Name -> IfM lcl ModIface
156 loadHomeInterface doc name
157   = ASSERT2( not (isInternalName name), ppr name <+> parens doc )
158     loadSysInterface doc (nameModule name)
159
160 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
161 -- A wrapper for loadInterface that Throws an exception if it fails
162 loadSysInterface doc mod_name
163   = do  { mb_iface <- loadInterface doc mod_name ImportBySystem
164         ; case mb_iface of 
165             Failed err      -> ghcError (ProgramError (showSDoc err))
166             Succeeded iface -> return iface }
167 \end{code}
168
169
170 %*********************************************************
171 %*                                                      *
172                 loadInterface
173
174         The main function to load an interface
175         for an imported module, and put it in
176         the External Package State
177 %*                                                      *
178 %*********************************************************
179
180 \begin{code}
181 loadInterface :: SDoc -> Module -> WhereFrom 
182               -> IfM lcl (MaybeErr Message ModIface)
183 -- If it can't find a suitable interface file, we
184 --      a) modify the PackageIfaceTable to have an empty entry
185 --              (to avoid repeated complaints)
186 --      b) return (Left message)
187 --
188 -- It's not necessarily an error for there not to be an interface
189 -- file -- perhaps the module has changed, and that interface 
190 -- is no longer used
191
192 loadInterface doc_str mod from
193   = do  {       -- Read the state
194           (eps,hpt) <- getEpsAndHpt
195
196         ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
197
198                 -- Check whether we have the interface already
199         ; case lookupIfaceByModule hpt (eps_PIT eps) mod of {
200             Just iface 
201                 -> returnM (Succeeded iface) ;  -- Already loaded
202                         -- The (src_imp == mi_boot iface) test checks that the already-loaded
203                         -- interface isn't a boot iface.  This can conceivably happen,
204                         -- if an earlier import had a before we got to real imports.   I think.
205             other -> do
206
207         { let { hi_boot_file = case from of
208                                 ImportByUser usr_boot -> usr_boot
209                                 ImportBySystem        -> sys_boot
210
211               ; mb_dep   = lookupModuleEnv (eps_is_boot eps) mod
212               ; sys_boot = case mb_dep of
213                                 Just (_, is_boot) -> is_boot
214                                 Nothing           -> False
215                         -- The boot-ness of the requested interface, 
216               }         -- based on the dependencies in directly-imported modules
217
218         -- READ THE MODULE IN
219         ; let explicit | ImportByUser _ <- from = True
220                        | otherwise              = False
221         ; read_result <- findAndReadIface explicit doc_str mod hi_boot_file
222         ; dflags <- getDOpts
223         ; case read_result of {
224             Failed err -> do
225                 { let fake_iface = emptyModIface HomePackage mod
226
227                 ; updateEps_ $ \eps ->
228                         eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
229                         -- Not found, so add an empty iface to 
230                         -- the EPS map so that we don't look again
231                                 
232                 ; returnM (Failed err) } ;
233
234         -- Found and parsed!
235             Succeeded (iface, file_path)                        -- Sanity check:
236                 | ImportBySystem <- from,               --   system-importing...
237                   isHomePackage (mi_package iface),     --   ...a home-package module
238                   Nothing <- mb_dep                     --   ...that we know nothing about
239                 -> returnM (Failed (badDepMsg mod))
240
241                 | otherwise ->
242
243         let 
244             loc_doc = text file_path <+> colon
245         in 
246         initIfaceLcl mod loc_doc $ do
247
248         --      Load the new ModIface into the External Package State
249         -- Even home-package interfaces loaded by loadInterface 
250         --      (which only happens in OneShot mode; in Batch/Interactive 
251         --      mode, home-package modules are loaded one by one into the HPT)
252         -- are put in the EPS.
253         --
254         -- The main thing is to add the ModIface to the PIT, but
255         -- we also take the
256         --      IfaceDecls, IfaceInst, IfaceRules
257         -- out of the ModIface and put them into the big EPS pools
258
259         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
260         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
261         --     If we do loadExport first the wrong info gets into the cache (unless we
262         --      explicitly tag each export which seems a bit of a bore)
263
264         ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
265         ; new_eps_decls <- mapM (loadDecl ignore_prags) (mi_decls iface)
266         ; new_eps_insts <- mapM loadInst                (mi_insts iface)
267         ; new_eps_rules <- if ignore_prags 
268                            then return []
269                            else mapM loadRule (mi_rules iface)
270
271         ; let { final_iface = iface {   mi_decls = panic "No mi_decls in PIT",
272                                         mi_insts = panic "No mi_insts in PIT",
273                                         mi_rules = panic "No mi_rules in PIT" } }
274
275         ; updateEps_  $ \ eps -> 
276                 eps {   eps_PIT   = extendModuleEnv (eps_PIT eps) mod final_iface,
277                         eps_PTE   = addDeclsToPTE   (eps_PTE eps) new_eps_decls,
278                         eps_rules = addRulesToPool  (eps_rules eps) new_eps_rules,
279                         eps_insts = addInstsToPool  (eps_insts eps) new_eps_insts,
280                         eps_stats = addEpsInStats   (eps_stats eps) (length new_eps_decls)
281                                                     (length new_eps_insts) (length new_eps_rules) }
282
283         ; return (Succeeded final_iface)
284     }}}}
285
286 badDepMsg mod 
287   = hang (ptext SLIT("Interface file inconsistency:"))
288        2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned,"), 
289                ptext SLIT("but does not appear in the dependencies of the interface")])
290
291 -----------------------------------------------------
292 --      Loading type/class/value decls
293 -- We pass the full Module name here, replete with
294 -- its package info, so that we can build a Name for
295 -- each binder with the right package info in it
296 -- All subsequent lookups, including crucially lookups during typechecking
297 -- the declaration itself, will find the fully-glorious Name
298 -----------------------------------------------------
299
300 addDeclsToPTE :: PackageTypeEnv -> [[(Name,TyThing)]] -> PackageTypeEnv
301 addDeclsToPTE pte things = foldl extendNameEnvList pte things
302
303 loadDecl :: Bool                        -- Don't load pragmas into the decl pool
304           -> (Version, IfaceDecl)
305           -> IfL [(Name,TyThing)]       -- The list can be poked eagerly, but the
306                                         -- TyThings are forkM'd thunks
307 loadDecl ignore_prags (_version, decl)
308   = do  {       -- Populate the name cache with final versions of all 
309                 -- the names associated with the decl
310           mod <- getIfModule
311         ; main_name      <- mk_new_bndr mod Nothing (ifName decl)
312         ; implicit_names <- mapM (mk_new_bndr mod (Just main_name)) (ifaceDeclSubBndrs decl)
313
314         -- Typecheck the thing, lazily
315         ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
316         ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
317               lookup n = case lookupOccEnv mini_env (getOccName n) of
318                            Just thing -> thing
319                            Nothing    -> pprPanic "loadDecl" (ppr main_name <+> ppr n)
320
321         ; returnM ((main_name, thing) : [(n, lookup n) | n <- implicit_names]) }
322                 -- We build a list from the *known* names, with (lookup n) thunks
323                 -- as the TyThings.  That way we can extend the PTE without poking the
324                 -- thunks
325   where
326     stripped_decl | ignore_prags = discardDeclPrags decl
327                   | otherwise    = decl
328
329         -- mk_new_bndr allocates in the name cache the final canonical
330         -- name for the thing, with the correct 
331         --      * parent
332         --      * location
333         -- imported name, to fix the module correctly in the cache
334     mk_new_bndr mod mb_parent occ 
335         = newGlobalBinder mod occ mb_parent 
336                           (importedSrcLoc (moduleUserString mod))
337
338     doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
339
340 discardDeclPrags :: IfaceDecl -> IfaceDecl
341 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
342 discardDeclPrags decl                                  = decl
343
344 bumpDeclStats :: Name -> IfL ()         -- Record that one more declaration has actually been used
345 bumpDeclStats name
346   = do  { traceIf (text "Loading decl for" <+> ppr name)
347         ; updateEps_ (\eps -> let stats = eps_stats eps
348                               in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
349         }
350
351 -----------------
352 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
353 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
354 -- Deeply revolting, because it has to predict what gets bound,
355 -- especially the question of whether there's a wrapper for a datacon
356
357 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, ifSigs = sigs })
358   = [tc_occ, dc_occ, dcww_occ] ++
359     [op | IfaceClassOp op _ _ <- sigs] ++
360     [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]] 
361   where
362     n_ctxt = length sc_ctxt
363     n_sigs = length sigs
364     tc_occ  = mkClassTyConOcc cls_occ
365     dc_occ  = mkClassDataConOcc cls_occ 
366     dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ  -- Newtypes have wrapper but no worker
367              | otherwise  = mkDataConWorkerOcc dc_occ   -- Otherwise worker but no wrapper
368     is_newtype = n_sigs + n_ctxt == 1                   -- Sigh 
369
370 ifaceDeclSubBndrs (IfaceData {ifCons = IfAbstractTyCon}) 
371   = []
372 -- Newtype
373 ifaceDeclSubBndrs (IfaceData {ifCons = IfNewTyCon (IfVanillaCon { ifConOcc = con_occ, 
374                                                                   ifConFields = fields})}) 
375   = fields ++ [con_occ, mkDataConWrapperOcc con_occ]    
376         -- Wrapper, no worker; see MkId.mkDataConIds
377
378 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon _ cons})
379   = nub (concatMap fld_occs cons)       -- Eliminate duplicate fields
380     ++ concatMap dc_occs cons
381   where
382     fld_occs (IfVanillaCon { ifConFields = fields }) = fields
383     fld_occs (IfGadtCon {})                          = []
384     dc_occs con_decl
385         | has_wrapper = [con_occ, work_occ, wrap_occ]
386         | otherwise   = [con_occ, work_occ]
387         where
388           con_occ = ifConOcc con_decl
389           strs    = ifConStricts con_decl
390           wrap_occ = mkDataConWrapperOcc con_occ
391           work_occ = mkDataConWorkerOcc con_occ
392           has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
393                 -- ToDo: may miss strictness in existential dicts
394
395 ifaceDeclSubBndrs _other                      = []
396
397 -----------------------------------------------------
398 --      Loading instance decls
399 -----------------------------------------------------
400
401 loadInst :: IfaceInst -> IfL (Name, Gated IfaceInst)
402
403 loadInst decl@(IfaceInst {ifInstHead = inst_ty})
404   = do  {
405         -- Find out what type constructors and classes are "gates" for the
406         -- instance declaration.  If all these "gates" are slurped in then
407         -- we should slurp the instance decl too.
408         -- 
409         -- We *don't* want to count names in the context part as gates, though.
410         -- For example:
411         --              instance Foo a => Baz (T a) where ...
412         --
413         -- Here the gates are Baz and T, but *not* Foo.
414         -- 
415         -- HOWEVER: functional dependencies make things more complicated
416         --      class C a b | a->b where ...
417         --      instance C Foo Baz where ...
418         -- Here, the gates are really only C and Foo, *not* Baz.
419         -- That is, if C and Foo are visible, even if Baz isn't, we must
420         -- slurp the decl.
421         --
422         -- Rather than take fundeps into account "properly", we just slurp
423         -- if C is visible and *any one* of the Names in the types
424         -- This is a slightly brutal approximation, but most instance decls
425         -- are regular H98 ones and it's perfect for them.
426         --
427         -- NOTICE that we rename the type before extracting its free
428         -- variables.  The free-variable finder for a renamed HsType 
429         -- does the Right Thing for built-in syntax like [] and (,).
430           let { (cls_ext, tc_exts) = ifaceInstGates inst_ty }
431         ; cls <- lookupIfaceExt cls_ext
432         ; tcs <- mapM lookupIfaceTc tc_exts
433         ; (mod, doc) <- getIfCtxt 
434         ; returnM (cls, (tcs, (mod, doc, decl)))
435         }
436
437 -----------------------------------------------------
438 --      Loading Rules
439 -----------------------------------------------------
440
441 loadRule :: IfaceRule -> IfL (Gated IfaceRule)
442 -- "Gate" the rule simply by a crude notion of the free vars of
443 -- the LHS.  It can be crude, because having too few free vars is safe.
444 loadRule decl@(IfaceRule {ifRuleHead = fn, ifRuleArgs = args})
445   = do  { names <- mapM lookupIfaceExt (fn : arg_fvs)
446         ; (mod, doc) <- getIfCtxt 
447         ; returnM (names, (mod, doc, decl)) }
448   where
449     arg_fvs = [n | arg <- args, n <- crudeIfExprGblFvs arg]
450
451
452 ---------------------------
453 crudeIfExprGblFvs :: IfaceExpr -> [IfaceExtName]
454 -- A crude approximation to the free external names of an IfExpr
455 -- Returns a subset of the true answer
456 crudeIfExprGblFvs (IfaceType ty) = get_tcs ty
457 crudeIfExprGblFvs (IfaceExt v)   = [v]
458 crudeIfExprGblFvs other          = []   -- Well, I said it was crude
459
460 get_tcs :: IfaceType -> [IfaceExtName]
461 -- Get a crude subset of the TyCons of an IfaceType
462 get_tcs (IfaceTyVar _)      = []
463 get_tcs (IfaceAppTy t1 t2)  = get_tcs t1 ++ get_tcs t2
464 get_tcs (IfaceFunTy t1 t2)  = get_tcs t1 ++ get_tcs t2
465 get_tcs (IfaceForAllTy _ t) = get_tcs t
466 get_tcs (IfacePredTy st)    = case st of
467                                  IfaceClassP cl ts -> get_tcs_s ts
468                                  IfaceIParam _ t   -> get_tcs t
469 get_tcs (IfaceTyConApp (IfaceTc tc) ts) = tc : get_tcs_s ts
470 get_tcs (IfaceTyConApp other        ts) = get_tcs_s ts
471
472 -- The lists are always small => appending is fine
473 get_tcs_s :: [IfaceType] -> [IfaceExtName]
474 get_tcs_s tys = foldr ((++) . get_tcs) [] tys
475
476
477 ----------------
478 getIfCtxt :: IfL (Module, SDoc)
479 getIfCtxt = do { env <- getLclEnv; return (if_mod env, if_loc env) }
480 \end{code}
481
482
483 %*********************************************************
484 %*                                                      *
485                 Gating
486 %*                                                      *
487 %*********************************************************
488
489 Extract the gates of an instance declaration
490
491 \begin{code}
492 ifaceInstGates :: IfaceType -> (IfaceExtName, [IfaceTyCon])
493 -- Return the class, and the tycons mentioned in the rest of the head
494 -- We only pick the TyCon at the root of each type, to avoid
495 -- difficulties with overlap.  For example, suppose there are interfaces
496 -- in the pool for
497 --      C Int b
498 --      C a [b]
499 --      C a [T] 
500 -- Then, if we are trying to resolve (C Int x), we need the first
501 --       if we are trying to resolve (C x [y]), we need *both* the latter
502 --       two, even though T is not involved yet, so that we spot the overlap
503
504 ifaceInstGates (IfaceForAllTy _ t)                 = ifaceInstGates t
505 ifaceInstGates (IfaceFunTy _ t)                    = ifaceInstGates t
506 ifaceInstGates (IfacePredTy (IfaceClassP cls tys)) = (cls, instHeadTyconGates tys)
507 ifaceInstGates other = pprPanic "ifaceInstGates" (ppr other)
508         -- The other cases should not happen
509
510 instHeadTyconGates tys = mapCatMaybes root_tycon tys
511   where
512     root_tycon (IfaceFunTy _ _)      = Just (IfaceTc funTyConExtName)
513     root_tycon (IfaceTyConApp tc _)  = Just tc
514     root_tycon other                 = Nothing
515
516 funTyConExtName = mkIfaceExtName (tyConName funTyCon)
517
518
519 predInstGates :: Class -> [Type] -> (Name, [Name])
520 -- The same function, only this time on the predicate found in a dictionary
521 predInstGates cls tys
522   = (className cls, mapCatMaybes root_tycon tys)
523   where
524     root_tycon ty = case tcSplitTyConApp_maybe ty of
525                         Just (tc, _) -> Just (tyConName tc)
526                         Nothing      -> Nothing
527 \end{code}
528
529
530 %*********************************************************
531 %*                                                      *
532 \subsection{Reading an interface file}
533 %*                                                      *
534 %*********************************************************
535
536 \begin{code}
537 findAndReadIface :: Bool                -- True <=> explicit user import
538                  -> SDoc -> Module 
539                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
540                                         -- False <=> Look for .hi file
541                  -> IfM lcl (MaybeErr Message (ModIface, FilePath))
542         -- Nothing <=> file not found, or unreadable, or illegible
543         -- Just x  <=> successfully found and parsed 
544
545         -- It *doesn't* add an error to the monad, because 
546         -- sometimes it's ok to fail... see notes with loadInterface
547
548 findAndReadIface explicit doc_str mod_name hi_boot_file
549   = do  { traceIf (sep [hsep [ptext SLIT("Reading"), 
550                               if hi_boot_file 
551                                 then ptext SLIT("[boot]") 
552                                 else empty,
553                               ptext SLIT("interface for"), 
554                               ppr mod_name <> semi],
555                         nest 4 (ptext SLIT("reason:") <+> doc_str)])
556
557         -- Check for GHC.Prim, and return its static interface
558         ; dflags <- getDOpts
559         ; let base_pkg = basePackageId (pkgState dflags)
560         ; if mod_name == gHC_PRIM
561           then returnM (Succeeded (ghcPrimIface{ mi_package = base_pkg }, 
562                         "<built in interface for GHC.Prim>"))
563           else do
564
565         -- Look for the file
566         ; mb_found <- ioToIOEnv (findHiFile dflags explicit mod_name hi_boot_file)
567         ; case mb_found of {
568               Failed err -> do
569                 { traceIf (ptext SLIT("...not found"))
570                 ; dflags <- getDOpts
571                 ; returnM (Failed (cantFindError dflags mod_name err)) } ;
572
573               Succeeded (file_path, pkg) -> do 
574
575         -- Found file, so read it
576         { traceIf (ptext SLIT("readIFace") <+> text file_path)
577         ; read_result <- readIface mod_name file_path hi_boot_file
578         ; case read_result of
579             Failed err -> returnM (Failed (badIfaceFile file_path err))
580             Succeeded iface 
581                 | mi_module iface /= mod_name ->
582                   return (Failed (wrongIfaceModErr iface mod_name file_path))
583                 | otherwise ->
584                   returnM (Succeeded (iface{mi_package=pkg}, file_path))
585                         -- Don't forget to fill in the package name...
586         }}}
587
588 findHiFile :: DynFlags -> Bool -> Module -> IsBootInterface
589            -> IO (MaybeErr FindResult (FilePath, PackageIdH))
590 findHiFile dflags explicit mod_name hi_boot_file
591  = do { 
592         -- In interactive or --make mode, we are *not allowed* to demand-load
593         -- a home package .hi file.  So don't even look for them.
594         -- This helps in the case where you are sitting in eg. ghc/lib/std
595         -- and start up GHCi - it won't complain that all the modules it tries
596         -- to load are found in the home location.
597         ghci_mode <- readIORef v_GhcMode ;
598         let { home_allowed = not (isCompManagerMode ghci_mode) } ;
599         maybe_found <-  if home_allowed 
600                         then findModule        dflags mod_name explicit
601                         else findPackageModule dflags mod_name explicit;
602
603         case maybe_found of
604           Found loc pkg -> return (Succeeded (path, pkg))
605                         where
606                            path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
607
608           err -> return (Failed err)
609         }
610 \end{code}
611
612 @readIface@ tries just the one file.
613
614 \begin{code}
615 readIface :: Module -> String -> IsBootInterface 
616           -> IfM lcl (MaybeErr Message ModIface)
617         -- Failed err    <=> file not found, or unreadable, or illegible
618         -- Succeeded iface <=> successfully found and parsed 
619
620 readIface wanted_mod file_path is_hi_boot_file
621   = do  { dflags <- getDOpts
622         ; ioToIOEnv $ do
623         { res <- tryMost (readBinIface file_path)
624         ; case res of
625             Right iface 
626                 | wanted_mod == actual_mod -> return (Succeeded iface)
627                 | otherwise                -> return (Failed err)
628                 where
629                   actual_mod = mi_module iface
630                   err = hiModuleNameMismatchWarn wanted_mod actual_mod
631
632             Left exn    -> return (Failed (text (showException exn)))
633     }}
634 \end{code}
635
636
637 %*********************************************************
638 %*                                                       *
639         Wired-in interface for GHC.Prim
640 %*                                                       *
641 %*********************************************************
642
643 \begin{code}
644 initExternalPackageState :: ExternalPackageState
645 initExternalPackageState
646   = EPS { 
647       eps_is_boot    = emptyModuleEnv,
648       eps_PIT        = emptyPackageIfaceTable,
649       eps_PTE        = emptyTypeEnv,
650       eps_inst_env   = emptyInstEnv,
651       eps_rule_base  = emptyRuleBase,
652       eps_insts      = emptyNameEnv,
653       eps_rules      = addRulesToPool [] (map mk_gated_rule builtinRules),
654         -- Initialise the EPS rule pool with the built-in rules
655       eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
656                            , n_insts_in = 0, n_insts_out = 0
657                            , n_rules_in = length builtinRules, n_rules_out = 0 }
658     }
659   where
660     mk_gated_rule (fn_name, core_rule)
661         = ([fn_name], (nameModule fn_name, ptext SLIT("<built-in rule>"),
662            IfaceBuiltinRule (mkIfaceExtName fn_name) core_rule))
663 \end{code}
664
665
666 %*********************************************************
667 %*                                                       *
668         Wired-in interface for GHC.Prim
669 %*                                                       *
670 %*********************************************************
671
672 \begin{code}
673 ghcPrimIface :: ModIface
674 ghcPrimIface
675   = (emptyModIface HomePackage gHC_PRIM) {
676         mi_exports  = [(gHC_PRIM, ghcPrimExports)],
677         mi_decls    = [],
678         mi_fixities = fixities,
679         mi_fix_fn  = mkIfaceFixCache fixities
680     }           
681   where
682     fixities = [(getOccName seqId, Fixity 0 InfixR)]
683                         -- seq is infixr 0
684 \end{code}
685
686 %*********************************************************
687 %*                                                      *
688 \subsection{Statistics}
689 %*                                                      *
690 %*********************************************************
691
692 \begin{code}
693 ifaceStats :: ExternalPackageState -> SDoc
694 ifaceStats eps 
695   = hcat [text "Renamer stats: ", msg]
696   where
697     stats = eps_stats eps
698     msg = vcat 
699         [int (n_ifaces_in stats) <+> text "interfaces read",
700          hsep [ int (n_decls_out stats), text "type/class/variable imported, out of", 
701                 int (n_decls_in stats), text "read"],
702          hsep [ int (n_insts_out stats), text "instance decls imported, out of",  
703                 int (n_insts_in stats), text "read"],
704          hsep [ int (n_rules_out stats), text "rule decls imported, out of",  
705                 int (n_rules_in stats), text "read"]
706         ]
707 \end{code}    
708
709
710 %*********************************************************
711 %*                                                       *
712 \subsection{Errors}
713 %*                                                       *
714 %*********************************************************
715
716 \begin{code}
717 badIfaceFile file err
718   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
719           nest 4 err]
720
721 hiModuleNameMismatchWarn :: Module -> Module -> Message
722 hiModuleNameMismatchWarn requested_mod read_mod = 
723     hsep [ ptext SLIT("Something is amiss; requested module name")
724          , ppr requested_mod
725          , ptext SLIT("differs from name found in the interface file")
726          , ppr read_mod
727          ]
728
729 wrongIfaceModErr iface mod_name file_path 
730   = sep [ptext SLIT("Interface file") <+> iface_file,
731          ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
732          ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
733          sep [ptext SLIT("Probable cause: the source code which generated"),
734              nest 2 iface_file,
735              ptext SLIT("has an incompatible module name")
736             ]
737         ]
738   where iface_file = doubleQuotes (text file_path)
739 \end{code}