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