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