2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Dealing with interface files}
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 noIfaceErr, -- used by CompManager too
16 #include "HsVersions.h"
18 import {-# SOURCE #-} TcIface( tcIfaceDecl )
20 import Packages ( PackageState(..), isHomeModule )
21 import DriverState ( v_GhcMode, isCompManagerMode )
22 import DriverUtil ( replaceFilenameSuffix )
23 import CmdLineOpts ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ) )
24 import Parser ( parseIface )
26 import IfaceSyn ( IfaceDecl(..), IfaceConDecl(..), IfaceClassOp(..),
27 IfaceConDecls(..), IfaceInst(..), IfaceRule(..),
28 IfaceExpr(..), IfaceTyCon(..), IfaceIdInfo(..),
29 IfaceType(..), IfacePredType(..), IfaceExtName,
31 import IfaceEnv ( newGlobalBinder, lookupIfaceExt, lookupIfaceTc,
33 import HscTypes ( ModIface(..), TyThing, emptyModIface, EpsStats(..),
34 addEpsInStats, ExternalPackageState(..),
35 PackageTypeEnv, emptyTypeEnv, IfacePackage(..),
36 lookupIfaceByModule, emptyPackageIfaceTable,
37 IsBootInterface, mkIfaceFixCache, Gated,
38 implicitTyThings, addRulesToPool, addInstsToPool,
42 import BasicTypes ( Version, Fixity(..), FixityDirection(..),
44 import TcType ( Type, tcSplitTyConApp_maybe )
45 import Type ( funTyCon )
48 import PrelNames ( gHC_PRIM )
49 import PrelInfo ( ghcPrimExports )
50 import PrelRules ( builtinRules )
51 import Rules ( emptyRuleBase )
52 import InstEnv ( emptyInstEnv )
53 import Name ( Name {-instance NamedThing-}, getOccName,
54 nameModule, isInternalName )
57 import Module ( Module, ModLocation(ml_hi_file), emptyModuleEnv,
58 extendModuleEnv, lookupModuleEnv, moduleUserString
60 import OccName ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc, mkClassDataConOcc,
61 mkSuperDictSelOcc, mkDataConWrapperOcc, mkDataConWorkerOcc )
62 import Class ( Class, className )
63 import TyCon ( tyConName )
64 import SrcLoc ( mkSrcLoc, importedSrcLoc )
65 import Maybes ( isJust, mapCatMaybes )
66 import StringBuffer ( hGetStringBuffer )
67 import FastString ( mkFastString )
68 import ErrUtils ( Message, mkLocMessage )
69 import Finder ( findModule, findPackageModule, FindResult(..),
70 hiBootExt, hiBootVerExt )
73 import BinIface ( readBinIface )
77 import DATA_IOREF ( readIORef )
83 %************************************************************************
85 loadSrcInterface, loadOrphanModules
87 These two are called from TcM-land
89 %************************************************************************
92 loadSrcInterface :: SDoc -> Module -> IsBootInterface -> RnM ModIface
93 -- This is called for each 'import' declaration in the source code
94 -- On a failure, fail in the monad with an error message
96 loadSrcInterface doc mod_name want_boot
97 = do { mb_iface <- initIfaceTcRn $ loadInterface doc mod_name
98 (ImportByUser want_boot)
100 Left err -> failWithTc (elaborate err)
101 Right iface -> return iface
104 elaborate err = hang (ptext SLIT("Failed to load interface for") <+>
105 quotes (ppr mod_name) <> colon) 4 err
107 loadHiBootInterface :: TcRn [Name]
108 -- Load the hi-boot iface for the module being compiled,
109 -- if it indeed exists in the transitive closure of imports
110 -- Return the list of names exported by the hi-boot file
115 ; traceIf (text "loadHiBootInterface" <+> ppr mod)
117 -- We're read all the direct imports by now, so eps_is_boot will
118 -- record if any of our imports mention us by way of hi-boot file
119 ; case lookupModuleEnv (eps_is_boot eps) mod of {
120 Nothing -> return [] ; -- The typical case
122 Just (_, False) -> -- Someone below us imported us!
123 -- This is a loop with no hi-boot in the way
124 failWithTc (moduleLoop mod) ;
126 Just (mod_nm, True) -> -- There's a hi-boot interface below us
129 do { -- Load it (into the PTE, and return the exported names
130 iface <- loadSrcInterface (mk_doc mod_nm) mod_nm True
131 ; sequenceM [ lookupOrig mod_nm occ
132 | (mod,avails) <- mi_exports iface,
133 avail <- avails, occ <- availNames avail]
136 mk_doc mod = ptext SLIT("Need the hi-boot interface for") <+> ppr mod
137 <+> ptext SLIT("to compare against the Real Thing")
139 moduleLoop mod = ptext SLIT("Circular imports: module") <+> quotes (ppr mod)
140 <+> ptext SLIT("depends on itself")
142 loadOrphanModules :: [Module] -> TcM ()
143 loadOrphanModules mods
144 | null mods = returnM ()
145 | otherwise = initIfaceTcRn $
146 do { traceIf (text "Loading orphan modules:" <+>
151 load mod = loadSysInterface (mk_doc mod) mod
152 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
155 %*********************************************************
158 Called from Iface-land
160 %*********************************************************
163 loadHomeInterface :: SDoc -> Name -> IfM lcl ModIface
164 loadHomeInterface doc name
165 = ASSERT2( not (isInternalName name), ppr name <+> parens doc )
166 loadSysInterface doc (nameModule name)
168 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
169 -- A wrapper for loadInterface that Throws an exception if it fails
170 loadSysInterface doc mod_name
171 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
173 Left err -> ghcError (ProgramError (showSDoc err))
174 Right iface -> return iface }
178 %*********************************************************
182 The main function to load an interface
183 for an imported module, and put it in
184 the External Package State
186 %*********************************************************
189 loadInterface :: SDoc -> Module -> WhereFrom
190 -> IfM lcl (Either Message ModIface)
191 -- If it can't find a suitable interface file, we
192 -- a) modify the PackageIfaceTable to have an empty entry
193 -- (to avoid repeated complaints)
194 -- b) return (Left message)
196 -- It's not necessarily an error for there not to be an interface
197 -- file -- perhaps the module has changed, and that interface
198 -- is no longer used -- but the caller can deal with that by
199 -- catching the exception
201 loadInterface doc_str mod_name from
202 = do { -- Read the state
203 (eps,hpt) <- getEpsAndHpt
205 ; traceIf (text "Considering whether to load" <+> ppr mod_name <+> ppr from)
207 -- Check whether we have the interface already
208 ; case lookupIfaceByModule hpt (eps_PIT eps) mod_name of {
210 -> returnM (Right iface) ; -- Already loaded
211 -- The (src_imp == mi_boot iface) test checks that the already-loaded
212 -- interface isn't a boot iface. This can conceivably happen,
213 -- if an earlier import had a before we got to real imports. I think.
216 { let { hi_boot_file = case from of
217 ImportByUser usr_boot -> usr_boot
218 ImportBySystem -> sys_boot
220 ; mb_dep = lookupModuleEnv (eps_is_boot eps) mod_name
221 ; sys_boot = case mb_dep of
222 Just (_, is_boot) -> is_boot
224 -- The boot-ness of the requested interface,
225 } -- based on the dependencies in directly-imported modules
227 -- READ THE MODULE IN
228 ; let explicit | ImportByUser _ <- from = True
230 ; read_result <- findAndReadIface explicit doc_str mod_name hi_boot_file
232 ; case read_result of {
234 { let fake_iface = emptyModIface ThisPackage mod_name
236 ; updateEps_ $ \eps ->
237 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
238 -- Not found, so add an empty iface to
239 -- the EPS map so that we don't look again
241 ; returnM (Left err) } ;
246 let { mod = mi_module iface } in
248 -- Sanity check. If we're system-importing a module we know nothing at all
249 -- about, it should be from a different package to this one
250 WARN( case from of { ImportBySystem -> True; other -> False } &&
251 not (isJust mb_dep) &&
252 isHomeModule dflags mod,
253 ppr mod $$ ppr mb_dep $$ ppr (eps_is_boot eps) )
255 initIfaceLcl mod_name $ do
256 -- Load the new ModIface into the External Package State
257 -- Even home-package interfaces loaded by loadInterface
258 -- (which only happens in OneShot mode; in Batch/Interactive
259 -- mode, home-package modules are loaded one by one into the HPT)
260 -- are put in the EPS.
262 -- The main thing is to add the ModIface to the PIT, but
264 -- IfaceDecls, IfaceInst, IfaceRules
265 -- out of the ModIface and put them into the big EPS pools
267 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
268 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
269 -- If we do loadExport first the wrong info gets into the cache (unless we
270 -- explicitly tag each export which seems a bit of a bore)
272 { ignore_prags <- doptM Opt_IgnoreInterfacePragmas
273 ; new_eps_decls <- loadDecls ignore_prags mod (mi_decls iface)
274 ; new_eps_rules <- loadRules ignore_prags mod_name (mi_rules iface)
275 ; new_eps_insts <- loadInsts mod_name (mi_insts iface)
277 ; let { final_iface = iface { mi_decls = panic "No mi_decls in PIT",
278 mi_insts = panic "No mi_insts in PIT",
279 mi_rules = panic "No mi_rules in PIT" } }
281 ; updateEps_ $ \ eps ->
282 eps { eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
283 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
284 eps_rules = addRulesToPool (eps_rules eps) new_eps_rules,
285 eps_insts = addInstsToPool (eps_insts eps) new_eps_insts,
286 eps_stats = addEpsInStats (eps_stats eps) (length new_eps_decls)
287 (length new_eps_insts) (length new_eps_rules) }
289 ; return (Right final_iface)
292 -----------------------------------------------------
293 -- Loading type/class/value decls
294 -- We pass the full Module name here, replete with
295 -- its package info, so that we can build a Name for
296 -- each binder with the right package info in it
297 -- All subsequent lookups, including crucially lookups during typechecking
298 -- the declaration itself, will find the fully-glorious Name
299 -----------------------------------------------------
301 addDeclsToPTE :: PackageTypeEnv -> [[(Name,TyThing)]] -> PackageTypeEnv
302 addDeclsToPTE pte things = foldl extendNameEnvList pte things
304 loadDecls :: Bool -- Don't load pragmas into the decl pool
306 -> [(Version, IfaceDecl)]
307 -> IfL [[(Name,TyThing)]] -- The list can be poked eagerly, but the
308 -- TyThings are forkM'd thunks
309 loadDecls ignore_prags mod decls = mapM (loadDecl ignore_prags mod) decls
311 loadDecl ignore_prags mod (_version, decl)
312 = do { -- Populate the name cache with final versions of all
313 -- the names associated with the decl
314 main_name <- mk_new_bndr Nothing (ifName decl)
315 ; implicit_names <- mapM (mk_new_bndr (Just main_name)) (ifaceDeclSubBndrs decl)
317 -- Typecheck the thing, lazily
318 ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
319 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
320 lookup n = case lookupOccEnv mini_env (getOccName n) of
322 Nothing -> pprPanic "loadDecl" (ppr main_name <+> ppr n)
324 ; returnM ((main_name, thing) : [(n, lookup n) | n <- implicit_names]) }
325 -- We build a list from the *known* names, with (lookup n) thunks
326 -- as the TyThings. That way we can extend the PTE without poking the
329 stripped_decl | ignore_prags = discardDeclPrags decl
332 -- mk_new_bndr allocates in the name cache the final canonical
333 -- name for the thing, with the correct
337 -- imported name, to fix the module correctly in the cache
338 mk_new_bndr mb_parent occ = newGlobalBinder mod occ mb_parent loc
339 loc = importedSrcLoc (moduleUserString mod)
340 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
342 discardDeclPrags :: IfaceDecl -> IfaceDecl
343 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
344 discardDeclPrags decl = decl
346 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
348 = do { traceIf (text "Loading decl for" <+> ppr name)
349 ; updateEps_ (\eps -> let stats = eps_stats eps
350 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
354 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
355 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
356 -- Deeply revolting, because it has to predict what gets bound,
357 -- especially the question of whether there's a wrapper for a datacon
359 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, ifSigs = sigs })
360 = [tc_occ, dc_occ, dcww_occ] ++
361 [op | IfaceClassOp op _ _ <- sigs] ++
362 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
364 n_ctxt = length sc_ctxt
366 tc_occ = mkClassTyConOcc cls_occ
367 dc_occ = mkClassDataConOcc cls_occ
368 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
369 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
370 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
372 ifaceDeclSubBndrs (IfaceData {ifCons = IfAbstractTyCon})
375 ifaceDeclSubBndrs (IfaceData {ifCons = IfNewTyCon (IfVanillaCon { ifConOcc = con_occ,
376 ifConFields = fields})})
377 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
378 -- Wrapper, no worker; see MkId.mkDataConIds
380 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon _ cons})
381 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
382 ++ concatMap dc_occs cons
384 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
385 fld_occs (IfGadtCon {}) = []
387 | has_wrapper = [con_occ, work_occ, wrap_occ]
388 | otherwise = [con_occ, work_occ]
390 con_occ = ifConOcc con_decl
391 strs = ifConStricts con_decl
392 wrap_occ = mkDataConWrapperOcc con_occ
393 work_occ = mkDataConWorkerOcc con_occ
394 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
395 -- ToDo: may miss strictness in existential dicts
397 ifaceDeclSubBndrs _other = []
399 -----------------------------------------------------
400 -- Loading instance decls
401 -----------------------------------------------------
403 loadInsts :: Module -> [IfaceInst] -> IfL [(Name, Gated IfaceInst)]
404 loadInsts mod decls = mapM (loadInstDecl mod) decls
406 loadInstDecl mod decl@(IfaceInst {ifInstHead = inst_ty})
408 -- Find out what type constructors and classes are "gates" for the
409 -- instance declaration. If all these "gates" are slurped in then
410 -- we should slurp the instance decl too.
412 -- We *don't* want to count names in the context part as gates, though.
414 -- instance Foo a => Baz (T a) where ...
416 -- Here the gates are Baz and T, but *not* Foo.
418 -- HOWEVER: functional dependencies make things more complicated
419 -- class C a b | a->b where ...
420 -- instance C Foo Baz where ...
421 -- Here, the gates are really only C and Foo, *not* Baz.
422 -- That is, if C and Foo are visible, even if Baz isn't, we must
425 -- Rather than take fundeps into account "properly", we just slurp
426 -- if C is visible and *any one* of the Names in the types
427 -- This is a slightly brutal approximation, but most instance decls
428 -- are regular H98 ones and it's perfect for them.
430 -- NOTICE that we rename the type before extracting its free
431 -- variables. The free-variable finder for a renamed HsType
432 -- does the Right Thing for built-in syntax like [] and (,).
433 let { (cls_ext, tc_exts) = ifaceInstGates inst_ty }
434 ; cls <- lookupIfaceExt cls_ext
435 ; tcs <- mapM lookupIfaceTc tc_exts
436 ; returnM (cls, (tcs, (mod,decl)))
439 -----------------------------------------------------
441 -----------------------------------------------------
443 loadRules :: Bool -- Don't load pragmas into the decl pool
445 -> [IfaceRule] -> IfL [Gated IfaceRule]
446 loadRules ignore_prags mod rules
447 | ignore_prags = returnM []
448 | otherwise = mapM (loadRule mod) rules
450 loadRule :: Module -> IfaceRule -> IfL (Gated IfaceRule)
451 -- "Gate" the rule simply by a crude notion of the free vars of
452 -- the LHS. It can be crude, because having too few free vars is safe.
453 loadRule mod decl@(IfaceRule {ifRuleHead = fn, ifRuleArgs = args})
454 = do { names <- mapM lookupIfaceExt (fn : arg_fvs)
455 ; returnM (names, (mod, decl)) }
457 arg_fvs = [n | arg <- args, n <- crudeIfExprGblFvs arg]
460 ---------------------------
461 crudeIfExprGblFvs :: IfaceExpr -> [IfaceExtName]
462 -- A crude approximation to the free external names of an IfExpr
463 -- Returns a subset of the true answer
464 crudeIfExprGblFvs (IfaceType ty) = get_tcs ty
465 crudeIfExprGblFvs (IfaceExt v) = [v]
466 crudeIfExprGblFvs other = [] -- Well, I said it was crude
468 get_tcs :: IfaceType -> [IfaceExtName]
469 -- Get a crude subset of the TyCons of an IfaceType
470 get_tcs (IfaceTyVar _) = []
471 get_tcs (IfaceAppTy t1 t2) = get_tcs t1 ++ get_tcs t2
472 get_tcs (IfaceFunTy t1 t2) = get_tcs t1 ++ get_tcs t2
473 get_tcs (IfaceForAllTy _ t) = get_tcs t
474 get_tcs (IfacePredTy st) = case st of
475 IfaceClassP cl ts -> get_tcs_s ts
476 IfaceIParam _ t -> get_tcs t
477 get_tcs (IfaceTyConApp (IfaceTc tc) ts) = tc : get_tcs_s ts
478 get_tcs (IfaceTyConApp other ts) = get_tcs_s ts
480 -- The lists are always small => appending is fine
481 get_tcs_s :: [IfaceType] -> [IfaceExtName]
482 get_tcs_s tys = foldr ((++) . get_tcs) [] tys
486 %*********************************************************
490 %*********************************************************
492 Extract the gates of an instance declaration
495 ifaceInstGates :: IfaceType -> (IfaceExtName, [IfaceTyCon])
496 -- Return the class, and the tycons mentioned in the rest of the head
497 -- We only pick the TyCon at the root of each type, to avoid
498 -- difficulties with overlap. For example, suppose there are interfaces
503 -- Then, if we are trying to resolve (C Int x), we need the first
504 -- if we are trying to resolve (C x [y]), we need *both* the latter
505 -- two, even though T is not involved yet, so that we spot the overlap
507 ifaceInstGates (IfaceForAllTy _ t) = ifaceInstGates t
508 ifaceInstGates (IfaceFunTy _ t) = ifaceInstGates t
509 ifaceInstGates (IfacePredTy (IfaceClassP cls tys)) = instHeadGates cls tys
510 ifaceInstGates other = pprPanic "ifaceInstGates" (ppr other)
511 -- The other cases should not happen
513 instHeadGates cls tys = (cls, mapCatMaybes root_tycon tys)
515 root_tycon (IfaceFunTy _ _) = Just (IfaceTc funTyConExtName)
516 root_tycon (IfaceTyConApp tc _) = Just tc
517 root_tycon other = Nothing
519 funTyConExtName = mkIfaceExtName (tyConName funTyCon)
522 predInstGates :: Class -> [Type] -> (Name, [Name])
523 -- The same function, only this time on the predicate found in a dictionary
524 predInstGates cls tys
525 = (className cls, mapCatMaybes root_tycon tys)
527 root_tycon ty = case tcSplitTyConApp_maybe ty of
528 Just (tc, _) -> Just (tyConName tc)
533 %*********************************************************
535 \subsection{Reading an interface file}
537 %*********************************************************
540 findAndReadIface :: Bool -- True <=> explicit user import
542 -> IsBootInterface -- True <=> Look for a .hi-boot file
543 -- False <=> Look for .hi file
544 -> IfM lcl (Either Message ModIface)
545 -- Nothing <=> file not found, or unreadable, or illegible
546 -- Just x <=> successfully found and parsed
548 -- It *doesn't* add an error to the monad, because
549 -- sometimes it's ok to fail... see notes with loadInterface
551 findAndReadIface explicit doc_str mod_name hi_boot_file
552 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
554 then ptext SLIT("[boot]")
556 ptext SLIT("interface for"),
557 ppr mod_name <> semi],
558 nest 4 (ptext SLIT("reason:") <+> doc_str)])
560 -- Check for GHC.Prim, and return its static interface
562 ; let base_id = basePackageId (pkgState dflags)
564 | Just id <- base_id = ExternalPackage id
565 | otherwise = ThisPackage
566 -- if basePackageId is Nothing, it means we must be
567 -- compiling the base package.
568 ; if mod_name == gHC_PRIM
569 then returnM (Right (ghcPrimIface{ mi_package = base_pkg }))
573 ; mb_found <- ioToIOEnv (findHiFile dflags explicit mod_name hi_boot_file)
576 { traceIf (ptext SLIT("...not found"))
578 ; returnM (Left (noIfaceErr dflags mod_name err)) } ;
580 Right (file_path,pkg) -> do
582 -- Found file, so read it
583 { traceIf (ptext SLIT("readIFace") <+> text file_path)
584 ; read_result <- readIface mod_name file_path hi_boot_file
585 ; case read_result of
586 Left err -> returnM (Left (badIfaceFile file_path err))
588 | mi_module iface /= mod_name ->
589 return (Left (wrongIfaceModErr iface mod_name file_path))
591 returnM (Right iface{mi_package=pkg})
592 -- don't forget to fill in the package name...
595 findHiFile :: DynFlags -> Bool -> Module -> IsBootInterface
596 -> IO (Either FindResult (FilePath, IfacePackage))
597 findHiFile dflags explicit mod_name hi_boot_file
599 -- In interactive or --make mode, we are *not allowed* to demand-load
600 -- a home package .hi file. So don't even look for them.
601 -- This helps in the case where you are sitting in eg. ghc/lib/std
602 -- and start up GHCi - it won't complain that all the modules it tries
603 -- to load are found in the home location.
604 ghci_mode <- readIORef v_GhcMode ;
605 let { home_allowed = hi_boot_file ||
606 not (isCompManagerMode ghci_mode) } ;
607 maybe_found <- if home_allowed
608 then findModule dflags mod_name explicit
609 else findPackageModule dflags mod_name explicit;
611 case maybe_found of {
612 Found loc pkg -> foundOk loc hi_boot_file pkg;
613 err -> return (Left err) ;
616 foundOk loc hi_boot_file pkg = do { -- Don't need module returned by finder
618 -- Return the path to M.hi, M.hi-boot, or M.hi-boot-n as appropriate
619 let { hi_path = ml_hi_file loc ;
620 hi_boot_path = replaceFilenameSuffix hi_path hiBootExt ;
621 hi_boot_ver_path = replaceFilenameSuffix hi_path hiBootVerExt
624 if not hi_boot_file then
625 return (Right (hi_path,pkg))
627 hi_ver_exists <- doesFileExist hi_boot_ver_path ;
628 if hi_ver_exists then return (Right (hi_boot_ver_path,pkg))
629 else return (Right (hi_boot_path,pkg))
633 @readIface@ tries just the one file.
636 readIface :: Module -> String -> IsBootInterface
637 -> IfM lcl (Either Message ModIface)
638 -- Left err <=> file not found, or unreadable, or illegible
639 -- Right iface <=> successfully found and parsed
641 readIface wanted_mod_name file_path is_hi_boot_file
642 = do { dflags <- getDOpts
643 ; ioToIOEnv (read_iface dflags wanted_mod_name file_path is_hi_boot_file) }
645 read_iface dflags wanted_mod file_path is_hi_boot_file
646 | is_hi_boot_file -- Read ascii
647 = do { res <- tryMost (hGetStringBuffer file_path) ;
649 Left exn -> return (Left (text (showException exn))) ;
651 case unP parseIface (mkPState buffer loc dflags) of
652 PFailed span err -> return (Left (mkLocMessage span err))
654 | wanted_mod == actual_mod -> return (Right iface)
655 | otherwise -> return (Left err)
657 actual_mod = mi_module iface
658 err = hiModuleNameMismatchWarn wanted_mod actual_mod
661 | otherwise -- Read binary
662 = do { res <- tryMost (readBinIface file_path)
664 Right iface -> return (Right iface)
665 Left exn -> return (Left (text (showException exn))) }
667 loc = mkSrcLoc (mkFastString file_path) 1 0
671 %*********************************************************
673 Wired-in interface for GHC.Prim
675 %*********************************************************
678 initExternalPackageState :: ExternalPackageState
679 initExternalPackageState
681 eps_is_boot = emptyModuleEnv,
682 eps_PIT = emptyPackageIfaceTable,
683 eps_PTE = emptyTypeEnv,
684 eps_inst_env = emptyInstEnv,
685 eps_rule_base = emptyRuleBase,
686 eps_insts = emptyNameEnv,
687 eps_rules = addRulesToPool [] (map mk_gated_rule builtinRules),
688 -- Initialise the EPS rule pool with the built-in rules
689 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
690 , n_insts_in = 0, n_insts_out = 0
691 , n_rules_in = length builtinRules, n_rules_out = 0 }
694 mk_gated_rule (fn_name, core_rule)
695 = ([fn_name], (nameModule fn_name, IfaceBuiltinRule (mkIfaceExtName fn_name) core_rule))
699 %*********************************************************
701 Wired-in interface for GHC.Prim
703 %*********************************************************
706 ghcPrimIface :: ModIface
708 = (emptyModIface ThisPackage gHC_PRIM) {
709 mi_exports = [(gHC_PRIM, ghcPrimExports)],
711 mi_fixities = fixities,
712 mi_fix_fn = mkIfaceFixCache fixities
715 fixities = [(getOccName seqId, Fixity 0 InfixR)]
719 %*********************************************************
721 \subsection{Statistics}
723 %*********************************************************
726 ifaceStats :: ExternalPackageState -> SDoc
728 = hcat [text "Renamer stats: ", msg]
730 stats = eps_stats eps
732 [int (n_ifaces_in stats) <+> text "interfaces read",
733 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
734 int (n_decls_in stats), text "read"],
735 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
736 int (n_insts_in stats), text "read"],
737 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
738 int (n_rules_in stats), text "read"]
743 %*********************************************************
747 %*********************************************************
750 badIfaceFile file err
751 = vcat [ptext SLIT("Bad interface file:") <+> text file,
754 hiModuleNameMismatchWarn :: Module -> Module -> Message
755 hiModuleNameMismatchWarn requested_mod read_mod =
756 hsep [ ptext SLIT("Something is amiss; requested module name")
758 , ptext SLIT("differs from name found in the interface file")
762 noIfaceErr dflags mod_name (PackageHidden pkg)
763 = ptext SLIT("Could not import") <+> quotes (ppr mod_name) <> colon
764 $$ ptext SLIT("it is a member of package") <+> quotes (ppr pkg) <> comma
765 <+> ptext SLIT("which is hidden")
767 noIfaceErr dflags mod_name (ModuleHidden pkg)
768 = ptext SLIT("Could not import") <+> quotes (ppr mod_name) <> colon
769 $$ ptext SLIT("it is hidden")
770 <+> parens (ptext SLIT("in package") <+> quotes (ppr pkg))
772 noIfaceErr dflags mod_name (NotFound files)
773 = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
777 | verbosity dflags < 3 =
778 text "(use -v to see a list of the files searched for)"
780 hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
782 wrongIfaceModErr iface mod_name file_path
783 = sep [ptext SLIT("Interface file") <+> iface_file,
784 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
785 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
786 sep [ptext SLIT("Probable cause: the source code which generated"),
788 ptext SLIT("has an incompatible module name")
791 where iface_file = doubleQuotes (text file_path)