2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Dealing with interface files}
8 loadInterface, loadHomeInterface, loadWiredInHomeIface,
9 loadSrcInterface, loadSysInterface, loadOrphanModules,
10 findAndReadIface, readIface, -- Used when reading the module's old interface
11 loadDecls, ifaceStats, discardDeclPrags,
12 initExternalPackageState
15 #include "HsVersions.h"
17 import {-# SOURCE #-} TcIface( tcIfaceDecl, tcIfaceRule, tcIfaceInst )
19 import Packages ( PackageState(..), PackageIdH(..), isHomePackage )
20 import DynFlags ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ),
22 import IfaceSyn ( IfaceDecl(..), IfaceConDecl(..), IfaceClassOp(..),
23 IfaceConDecls(..), IfaceIdInfo(..) )
24 import IfaceEnv ( newGlobalBinder )
25 import HscTypes ( ModIface(..), TyThing, emptyModIface, EpsStats(..),
26 addEpsInStats, ExternalPackageState(..),
27 PackageTypeEnv, emptyTypeEnv, HscEnv(..),
28 lookupIfaceByModule, emptyPackageIfaceTable,
29 IsBootInterface, mkIfaceFixCache,
33 import BasicTypes ( Version, Fixity(..), FixityDirection(..),
37 import PrelNames ( gHC_PRIM )
38 import PrelInfo ( ghcPrimExports )
39 import PrelRules ( builtinRules )
40 import Rules ( extendRuleBaseList, mkRuleBase )
41 import InstEnv ( emptyInstEnv, extendInstEnvList )
42 import Name ( Name {-instance NamedThing-}, getOccName,
43 nameModule, isInternalName, isWiredInName )
46 import Module ( Module, ModLocation(ml_hi_file), emptyModuleEnv,
48 extendModuleEnv, lookupModuleEnv, moduleUserString
50 import OccName ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc, mkClassDataConOcc,
51 mkSuperDictSelOcc, mkDataConWrapperOcc, mkDataConWorkerOcc )
52 import SrcLoc ( importedSrcLoc )
53 import Maybes ( MaybeErr(..) )
54 import FastString ( mkFastString )
55 import ErrUtils ( Message )
56 import Finder ( findModule, findPackageModule, FindResult(..), cantFindError )
58 import BinIface ( readBinIface )
59 import Panic ( ghcError, tryMost, showException, GhcException(..) )
64 %************************************************************************
66 loadSrcInterface, loadOrphanModules, loadHomeInterface
68 These three are called from TcM-land
70 %************************************************************************
73 loadSrcInterface :: SDoc -> Module -> IsBootInterface -> RnM ModIface
74 -- This is called for each 'import' declaration in the source code
75 -- On a failure, fail in the monad with an error message
77 loadSrcInterface doc mod want_boot
78 = do { mb_iface <- initIfaceTcRn $
79 loadInterface doc mod (ImportByUser want_boot)
81 Failed err -> failWithTc (elaborate err)
82 Succeeded iface -> return iface
85 elaborate err = hang (ptext SLIT("Failed to load interface for") <+>
86 quotes (ppr mod) <> colon) 4 err
89 loadOrphanModules :: [Module] -> TcM ()
90 loadOrphanModules mods
91 | null mods = returnM ()
92 | otherwise = initIfaceTcRn $
93 do { traceIf (text "Loading orphan modules:" <+>
98 load mod = loadSysInterface (mk_doc mod) mod
99 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
102 loadHomeInterface :: SDoc -> Name -> TcRn ModIface
103 loadHomeInterface doc name
104 = ASSERT2( not (isInternalName name), ppr name <+> parens doc )
105 initIfaceTcRn $ loadSysInterface doc (nameModule name)
108 loadWiredInHomeIface :: Name -> IfM lcl ()
109 -- A IfM function to load the home interface for a wired-in thing,
110 -- so that we're sure that we see its instance declarations and rules
111 loadWiredInHomeIface name
112 = ASSERT( isWiredInName name )
113 do { loadSysInterface doc (nameModule name); return () }
115 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
118 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
119 -- A wrapper for loadInterface that Throws an exception if it fails
120 loadSysInterface doc mod_name
121 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
123 Failed err -> ghcError (ProgramError (showSDoc err))
124 Succeeded iface -> return iface }
128 %*********************************************************
132 The main function to load an interface
133 for an imported module, and put it in
134 the External Package State
136 %*********************************************************
139 loadInterface :: SDoc -> Module -> WhereFrom
140 -> IfM lcl (MaybeErr Message ModIface)
142 -- If it can't find a suitable interface file, we
143 -- a) modify the PackageIfaceTable to have an empty entry
144 -- (to avoid repeated complaints)
145 -- b) return (Left message)
147 -- It's not necessarily an error for there not to be an interface
148 -- file -- perhaps the module has changed, and that interface
151 loadInterface doc_str mod from
152 = do { -- Read the state
153 (eps,hpt) <- getEpsAndHpt
155 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
157 -- Check whether we have the interface already
158 ; case lookupIfaceByModule hpt (eps_PIT eps) mod of {
160 -> returnM (Succeeded iface) ; -- Already loaded
161 -- The (src_imp == mi_boot iface) test checks that the already-loaded
162 -- interface isn't a boot iface. This can conceivably happen,
163 -- if an earlier import had a before we got to real imports. I think.
166 { let { hi_boot_file = case from of
167 ImportByUser usr_boot -> usr_boot
168 ImportBySystem -> sys_boot
170 ; mb_dep = lookupModuleEnv (eps_is_boot eps) mod
171 ; sys_boot = case mb_dep of
172 Just (_, is_boot) -> is_boot
174 -- The boot-ness of the requested interface,
175 } -- based on the dependencies in directly-imported modules
177 -- READ THE MODULE IN
178 ; let explicit | ImportByUser _ <- from = True
180 ; read_result <- findAndReadIface explicit doc_str mod hi_boot_file
182 ; case read_result of {
184 { let fake_iface = emptyModIface HomePackage mod
186 ; updateEps_ $ \eps ->
187 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
188 -- Not found, so add an empty iface to
189 -- the EPS map so that we don't look again
191 ; returnM (Failed err) } ;
194 Succeeded (iface, file_path) -- Sanity check:
195 | ImportBySystem <- from, -- system-importing...
196 isHomePackage (mi_package iface), -- ...a home-package module
197 Nothing <- mb_dep -- ...that we know nothing about
198 -> returnM (Failed (badDepMsg mod))
203 loc_doc = text file_path <+> colon
205 initIfaceLcl mod loc_doc $ do
207 -- Load the new ModIface into the External Package State
208 -- Even home-package interfaces loaded by loadInterface
209 -- (which only happens in OneShot mode; in Batch/Interactive
210 -- mode, home-package modules are loaded one by one into the HPT)
211 -- are put in the EPS.
213 -- The main thing is to add the ModIface to the PIT, but
215 -- IfaceDecls, IfaceInst, IfaceRules
216 -- out of the ModIface and put them into the big EPS pools
218 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
219 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
220 -- If we do loadExport first the wrong info gets into the cache (unless we
221 -- explicitly tag each export which seems a bit of a bore)
223 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
224 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
225 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
226 ; new_eps_rules <- if ignore_prags
228 else mapM tcIfaceRule (mi_rules iface)
230 ; let { final_iface = iface { mi_decls = panic "No mi_decls in PIT",
231 mi_insts = panic "No mi_insts in PIT",
232 mi_rules = panic "No mi_rules in PIT" } }
234 ; updateEps_ $ \ eps ->
235 eps { eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
236 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
237 eps_rule_base = extendRuleBaseList (eps_rule_base eps) new_eps_rules,
238 eps_inst_env = extendInstEnvList (eps_inst_env eps) new_eps_insts,
239 eps_stats = addEpsInStats (eps_stats eps) (length new_eps_decls)
240 (length new_eps_insts) (length new_eps_rules) }
242 ; return (Succeeded final_iface)
246 = hang (ptext SLIT("Interface file inconsistency:"))
247 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned,"),
248 ptext SLIT("but does not appear in the dependencies of the interface")])
250 -----------------------------------------------------
251 -- Loading type/class/value decls
252 -- We pass the full Module name here, replete with
253 -- its package info, so that we can build a Name for
254 -- each binder with the right package info in it
255 -- All subsequent lookups, including crucially lookups during typechecking
256 -- the declaration itself, will find the fully-glorious Name
257 -----------------------------------------------------
259 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
260 addDeclsToPTE pte things = extendNameEnvList pte things
263 -> [(Version, IfaceDecl)]
264 -> IfL [(Name,TyThing)]
265 loadDecls ignore_prags ver_decls
266 = do { mod <- getIfModule
267 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
268 ; return (concat thingss)
271 loadDecl :: Bool -- Don't load pragmas into the decl pool
273 -> (Version, IfaceDecl)
274 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
275 -- TyThings are forkM'd thunks
276 loadDecl ignore_prags mod (_version, decl)
277 = do { -- Populate the name cache with final versions of all
278 -- the names associated with the decl
279 main_name <- mk_new_bndr mod Nothing (ifName decl)
280 ; implicit_names <- mapM (mk_new_bndr mod (Just main_name)) (ifaceDeclSubBndrs decl)
282 -- Typecheck the thing, lazily
283 -- NB. firstly, the laziness is there in case we never need the
284 -- declaration (in one-shot mode), and secondly it is there so that
285 -- we don't look up the occurrence of a name before calling mk_new_bndr
286 -- on the binder. This is important because we must get the right name
287 -- which includes its nameParent.
288 ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
289 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
290 lookup n = case lookupOccEnv mini_env (getOccName n) of
292 Nothing -> pprPanic "loadDecl" (ppr main_name <+> ppr n)
294 ; returnM ((main_name, thing) : [(n, lookup n) | n <- implicit_names]) }
295 -- We build a list from the *known* names, with (lookup n) thunks
296 -- as the TyThings. That way we can extend the PTE without poking the
299 stripped_decl | ignore_prags = discardDeclPrags decl
302 -- mk_new_bndr allocates in the name cache the final canonical
303 -- name for the thing, with the correct
306 -- imported name, to fix the module correctly in the cache
307 mk_new_bndr mod mb_parent occ
308 = newGlobalBinder mod occ mb_parent
309 (importedSrcLoc (moduleUserString mod))
311 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
313 discardDeclPrags :: IfaceDecl -> IfaceDecl
314 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
315 discardDeclPrags decl = decl
317 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
319 = do { traceIf (text "Loading decl for" <+> ppr name)
320 ; updateEps_ (\eps -> let stats = eps_stats eps
321 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
325 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
326 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
327 -- Deeply revolting, because it has to predict what gets bound,
328 -- especially the question of whether there's a wrapper for a datacon
330 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, ifSigs = sigs })
331 = [tc_occ, dc_occ, dcww_occ] ++
332 [op | IfaceClassOp op _ _ <- sigs] ++
333 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
335 n_ctxt = length sc_ctxt
337 tc_occ = mkClassTyConOcc cls_occ
338 dc_occ = mkClassDataConOcc cls_occ
339 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
340 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
341 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
343 ifaceDeclSubBndrs (IfaceData {ifCons = IfAbstractTyCon})
346 ifaceDeclSubBndrs (IfaceData {ifCons = IfNewTyCon (IfVanillaCon { ifConOcc = con_occ,
347 ifConFields = fields})})
348 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
349 -- Wrapper, no worker; see MkId.mkDataConIds
351 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
352 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
353 ++ concatMap dc_occs cons
355 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
356 fld_occs (IfGadtCon {}) = []
358 | has_wrapper = [con_occ, work_occ, wrap_occ]
359 | otherwise = [con_occ, work_occ]
361 con_occ = ifConOcc con_decl
362 strs = ifConStricts con_decl
363 wrap_occ = mkDataConWrapperOcc con_occ
364 work_occ = mkDataConWorkerOcc con_occ
365 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
366 -- ToDo: may miss strictness in existential dicts
368 ifaceDeclSubBndrs _other = []
373 %*********************************************************
375 \subsection{Reading an interface file}
377 %*********************************************************
380 findAndReadIface :: Bool -- True <=> explicit user import
382 -> IsBootInterface -- True <=> Look for a .hi-boot file
383 -- False <=> Look for .hi file
384 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
385 -- Nothing <=> file not found, or unreadable, or illegible
386 -- Just x <=> successfully found and parsed
388 -- It *doesn't* add an error to the monad, because
389 -- sometimes it's ok to fail... see notes with loadInterface
391 findAndReadIface explicit doc_str mod_name hi_boot_file
392 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
394 then ptext SLIT("[boot]")
396 ptext SLIT("interface for"),
397 ppr mod_name <> semi],
398 nest 4 (ptext SLIT("reason:") <+> doc_str)])
400 -- Check for GHC.Prim, and return its static interface
402 ; let base_pkg = basePackageId (pkgState dflags)
403 ; if mod_name == gHC_PRIM
404 then returnM (Succeeded (ghcPrimIface{ mi_package = base_pkg },
405 "<built in interface for GHC.Prim>"))
409 ; hsc_env <- getTopEnv
410 ; mb_found <- ioToIOEnv (findHiFile hsc_env explicit mod_name hi_boot_file)
413 { traceIf (ptext SLIT("...not found"))
415 ; returnM (Failed (cantFindError dflags mod_name err)) } ;
417 Succeeded (file_path, pkg) -> do
419 -- Found file, so read it
420 { traceIf (ptext SLIT("readIFace") <+> text file_path)
421 ; read_result <- readIface mod_name file_path hi_boot_file
422 ; case read_result of
423 Failed err -> returnM (Failed (badIfaceFile file_path err))
425 | mi_module iface /= mod_name ->
426 return (Failed (wrongIfaceModErr iface mod_name file_path))
428 returnM (Succeeded (iface{mi_package=pkg}, file_path))
429 -- Don't forget to fill in the package name...
432 findHiFile :: HscEnv -> Bool -> Module -> IsBootInterface
433 -> IO (MaybeErr FindResult (FilePath, PackageIdH))
434 findHiFile hsc_env explicit mod_name hi_boot_file
436 -- In interactive or --make mode, we are *not allowed* to demand-load
437 -- a home package .hi file. So don't even look for them.
438 -- This helps in the case where you are sitting in eg. ghc/lib/std
439 -- and start up GHCi - it won't complain that all the modules it tries
440 -- to load are found in the home location.
441 let { home_allowed = isOneShot (ghcMode (hsc_dflags hsc_env)) } ;
442 maybe_found <- if home_allowed
443 then findModule hsc_env mod_name explicit
444 else findPackageModule hsc_env mod_name explicit;
447 Found loc pkg -> return (Succeeded (path, pkg))
449 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
451 err -> return (Failed err)
455 @readIface@ tries just the one file.
458 readIface :: Module -> String -> IsBootInterface
459 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
460 -- Failed err <=> file not found, or unreadable, or illegible
461 -- Succeeded iface <=> successfully found and parsed
463 readIface wanted_mod file_path is_hi_boot_file
464 = do { dflags <- getDOpts
466 { res <- tryMost (readBinIface file_path)
469 | wanted_mod == actual_mod -> return (Succeeded iface)
470 | otherwise -> return (Failed err)
472 actual_mod = mi_module iface
473 err = hiModuleNameMismatchWarn wanted_mod actual_mod
475 Left exn -> return (Failed (text (showException exn)))
480 %*********************************************************
482 Wired-in interface for GHC.Prim
484 %*********************************************************
487 initExternalPackageState :: ExternalPackageState
488 initExternalPackageState
490 eps_is_boot = emptyModuleEnv,
491 eps_PIT = emptyPackageIfaceTable,
492 eps_PTE = emptyTypeEnv,
493 eps_inst_env = emptyInstEnv,
494 eps_rule_base = mkRuleBase builtinRules,
495 -- Initialise the EPS rule pool with the built-in rules
496 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
497 , n_insts_in = 0, n_insts_out = 0
498 , n_rules_in = length builtinRules, n_rules_out = 0 }
503 %*********************************************************
505 Wired-in interface for GHC.Prim
507 %*********************************************************
510 ghcPrimIface :: ModIface
512 = (emptyModIface HomePackage gHC_PRIM) {
513 mi_exports = [(gHC_PRIM, ghcPrimExports)],
515 mi_fixities = fixities,
516 mi_fix_fn = mkIfaceFixCache fixities
519 fixities = [(getOccName seqId, Fixity 0 InfixR)]
523 %*********************************************************
525 \subsection{Statistics}
527 %*********************************************************
530 ifaceStats :: ExternalPackageState -> SDoc
532 = hcat [text "Renamer stats: ", msg]
534 stats = eps_stats eps
536 [int (n_ifaces_in stats) <+> text "interfaces read",
537 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
538 int (n_decls_in stats), text "read"],
539 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
540 int (n_insts_in stats), text "read"],
541 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
542 int (n_rules_in stats), text "read"]
547 %*********************************************************
551 %*********************************************************
554 badIfaceFile file err
555 = vcat [ptext SLIT("Bad interface file:") <+> text file,
558 hiModuleNameMismatchWarn :: Module -> Module -> Message
559 hiModuleNameMismatchWarn requested_mod read_mod =
560 hsep [ ptext SLIT("Something is amiss; requested module name")
562 , ptext SLIT("differs from name found in the interface file")
566 wrongIfaceModErr iface mod_name file_path
567 = sep [ptext SLIT("Interface file") <+> iface_file,
568 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
569 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
570 sep [ptext SLIT("Probable cause: the source code which generated"),
572 ptext SLIT("has an incompatible module name")
575 where iface_file = doubleQuotes (text file_path)