2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Dealing with interface files}
8 loadInterface, loadInterfaceForName, 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 DynFlags ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ) )
20 import IfaceSyn ( IfaceDecl(..), IfaceConDecl(..), IfaceClassOp(..),
21 IfaceConDecls(..), IfaceIdInfo(..) )
22 import IfaceEnv ( newGlobalBinder )
23 import HscTypes ( ModIface(..), TyThing, emptyModIface, EpsStats(..),
24 addEpsInStats, ExternalPackageState(..),
25 PackageTypeEnv, emptyTypeEnv, HscEnv(..),
26 lookupIfaceByModule, emptyPackageIfaceTable,
27 IsBootInterface, mkIfaceFixCache,
31 import BasicTypes ( Version, Fixity(..), FixityDirection(..),
35 import PrelNames ( gHC_PRIM )
36 import PrelInfo ( ghcPrimExports )
37 import PrelRules ( builtinRules )
38 import Rules ( extendRuleBaseList, mkRuleBase )
39 import InstEnv ( emptyInstEnv, extendInstEnvList )
40 import Name ( Name {-instance NamedThing-}, getOccName,
41 nameModule, nameIsLocalOrFrom, isWiredInName )
45 import OccName ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc, mkClassDataConOcc,
46 mkSuperDictSelOcc, mkDataConWrapperOcc, mkDataConWorkerOcc )
47 import SrcLoc ( importedSrcLoc )
48 import Maybes ( MaybeErr(..) )
49 import ErrUtils ( Message )
50 import Finder ( findImportedModule, findExactModule,
51 FindResult(..), cantFindError )
54 import BinIface ( readBinIface )
55 import Panic ( ghcError, tryMost, showException, GhcException(..) )
60 %************************************************************************
62 loadSrcInterface, loadOrphanModules, loadHomeInterface
64 These three are called from TcM-land
66 %************************************************************************
69 -- | Load the interface corresponding to an @import@ directive in
70 -- source code. On a failure, fail in the monad with an error message.
71 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
72 loadSrcInterface doc mod want_boot = do
73 -- We must first find which Module this import refers to. This involves
74 -- calling the Finder, which as a side effect will search the filesystem
75 -- and create a ModLocation. If successful, loadIface will read the
76 -- interface; it will call the Finder again, but the ModLocation will be
77 -- cached from the first search.
79 res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
82 mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
84 Failed err -> failWithTc (elaborate err)
85 Succeeded iface -> return iface
87 let dflags = hsc_dflags hsc_env in
88 failWithTc (elaborate (cantFindError dflags mod err))
90 elaborate err = hang (ptext SLIT("Failed to load interface for") <+>
91 quotes (ppr mod) <> colon) 4 err
93 -- | Load interfaces for a collection of orphan modules.
94 loadOrphanModules :: [Module] -> TcM ()
95 loadOrphanModules mods
96 | null mods = returnM ()
97 | otherwise = initIfaceTcRn $
98 do { traceIf (text "Loading orphan modules:" <+>
103 load mod = loadSysInterface (mk_doc mod) mod
104 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
106 -- | Loads the interface for a given Name.
107 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
108 loadInterfaceForName doc name
111 -- Should not be called with a name from the module being compiled
112 this_mod <- getModule
113 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
115 initIfaceTcRn $ loadSysInterface doc (nameModule name)
118 -- | An 'IfM' function to load the home interface for a wired-in thing,
119 -- so that we're sure that we see its instance declarations and rules
120 loadWiredInHomeIface :: Name -> IfM lcl ()
121 loadWiredInHomeIface name
122 = ASSERT( isWiredInName name )
123 do loadSysInterface doc (nameModule name); return ()
125 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
127 -- | A wrapper for 'loadInterface' that throws an exception if it fails
128 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
129 loadSysInterface doc mod_name
130 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
132 Failed err -> ghcError (ProgramError (showSDoc err))
133 Succeeded iface -> return iface }
137 %*********************************************************
141 The main function to load an interface
142 for an imported module, and put it in
143 the External Package State
145 %*********************************************************
148 loadInterface :: SDoc -> Module -> WhereFrom
149 -> IfM lcl (MaybeErr Message ModIface)
151 -- If it can't find a suitable interface file, we
152 -- a) modify the PackageIfaceTable to have an empty entry
153 -- (to avoid repeated complaints)
154 -- b) return (Left message)
156 -- It's not necessarily an error for there not to be an interface
157 -- file -- perhaps the module has changed, and that interface
160 loadInterface doc_str mod from
161 = do { -- Read the state
162 (eps,hpt) <- getEpsAndHpt
164 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
166 -- Check whether we have the interface already
168 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
170 -> returnM (Succeeded iface) ; -- Already loaded
171 -- The (src_imp == mi_boot iface) test checks that the already-loaded
172 -- interface isn't a boot iface. This can conceivably happen,
173 -- if an earlier import had a before we got to real imports. I think.
176 { let { hi_boot_file = case from of
177 ImportByUser usr_boot -> usr_boot
178 ImportBySystem -> sys_boot
180 ; mb_dep = lookupUFM (eps_is_boot eps) (moduleName mod)
181 ; sys_boot = case mb_dep of
182 Just (_, is_boot) -> is_boot
184 -- The boot-ness of the requested interface,
185 } -- based on the dependencies in directly-imported modules
187 -- READ THE MODULE IN
188 ; read_result <- findAndReadIface doc_str mod hi_boot_file
190 ; case read_result of {
192 { let fake_iface = emptyModIface mod
194 ; updateEps_ $ \eps ->
195 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
196 -- Not found, so add an empty iface to
197 -- the EPS map so that we don't look again
199 ; returnM (Failed err) } ;
202 Succeeded (iface, file_path) -- Sanity check:
203 | ImportBySystem <- from, -- system-importing...
204 modulePackageId (mi_module iface) == thisPackage dflags,
205 -- a home-package module...
206 Nothing <- mb_dep -- that we know nothing about
207 -> returnM (Failed (badDepMsg mod))
212 loc_doc = text file_path
214 initIfaceLcl mod loc_doc $ do
216 -- Load the new ModIface into the External Package State
217 -- Even home-package interfaces loaded by loadInterface
218 -- (which only happens in OneShot mode; in Batch/Interactive
219 -- mode, home-package modules are loaded one by one into the HPT)
220 -- are put in the EPS.
222 -- The main thing is to add the ModIface to the PIT, but
224 -- IfaceDecls, IfaceInst, IfaceRules
225 -- out of the ModIface and put them into the big EPS pools
227 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
228 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
229 -- If we do loadExport first the wrong info gets into the cache (unless we
230 -- explicitly tag each export which seems a bit of a bore)
232 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
233 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
234 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
235 ; new_eps_rules <- if ignore_prags
237 else mapM tcIfaceRule (mi_rules iface)
239 ; let { final_iface = iface { mi_decls = panic "No mi_decls in PIT",
240 mi_insts = panic "No mi_insts in PIT",
241 mi_rules = panic "No mi_rules in PIT" } }
243 ; updateEps_ $ \ eps ->
244 eps { eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
245 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
246 eps_rule_base = extendRuleBaseList (eps_rule_base eps) new_eps_rules,
247 eps_inst_env = extendInstEnvList (eps_inst_env eps) new_eps_insts,
248 eps_stats = addEpsInStats (eps_stats eps) (length new_eps_decls)
249 (length new_eps_insts) (length new_eps_rules) }
251 ; return (Succeeded final_iface)
255 = hang (ptext SLIT("Interface file inconsistency:"))
256 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned,"),
257 ptext SLIT("but does not appear in the dependencies of the interface")])
259 -----------------------------------------------------
260 -- Loading type/class/value decls
261 -- We pass the full Module name here, replete with
262 -- its package info, so that we can build a Name for
263 -- each binder with the right package info in it
264 -- All subsequent lookups, including crucially lookups during typechecking
265 -- the declaration itself, will find the fully-glorious Name
266 -----------------------------------------------------
268 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
269 addDeclsToPTE pte things = extendNameEnvList pte things
272 -> [(Version, IfaceDecl)]
273 -> IfL [(Name,TyThing)]
274 loadDecls ignore_prags ver_decls
275 = do { mod <- getIfModule
276 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
277 ; return (concat thingss)
280 loadDecl :: Bool -- Don't load pragmas into the decl pool
282 -> (Version, IfaceDecl)
283 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
284 -- TyThings are forkM'd thunks
285 loadDecl ignore_prags mod (_version, decl)
286 = do { -- Populate the name cache with final versions of all
287 -- the names associated with the decl
288 main_name <- mk_new_bndr mod Nothing (ifName decl)
289 ; implicit_names <- mapM (mk_new_bndr mod (Just main_name)) (ifaceDeclSubBndrs decl)
291 -- Typecheck the thing, lazily
292 -- NB. firstly, the laziness is there in case we never need the
293 -- declaration (in one-shot mode), and secondly it is there so that
294 -- we don't look up the occurrence of a name before calling mk_new_bndr
295 -- on the binder. This is important because we must get the right name
296 -- which includes its nameParent.
297 ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
298 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
299 lookup n = case lookupOccEnv mini_env (getOccName n) of
301 Nothing -> pprPanic "loadDecl" (ppr main_name <+> ppr n)
303 ; returnM ((main_name, thing) : [(n, lookup n) | n <- implicit_names]) }
304 -- We build a list from the *known* names, with (lookup n) thunks
305 -- as the TyThings. That way we can extend the PTE without poking the
308 stripped_decl | ignore_prags = discardDeclPrags decl
311 -- mk_new_bndr allocates in the name cache the final canonical
312 -- name for the thing, with the correct
315 -- imported name, to fix the module correctly in the cache
316 mk_new_bndr mod mb_parent occ
317 = newGlobalBinder mod occ mb_parent
318 (importedSrcLoc (showSDoc (pprModule mod)))
320 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
322 discardDeclPrags :: IfaceDecl -> IfaceDecl
323 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
324 discardDeclPrags decl = decl
326 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
328 = do { traceIf (text "Loading decl for" <+> ppr name)
329 ; updateEps_ (\eps -> let stats = eps_stats eps
330 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
334 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
335 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
336 -- Deeply revolting, because it has to predict what gets bound,
337 -- especially the question of whether there's a wrapper for a datacon
339 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, ifSigs = sigs })
340 = [tc_occ, dc_occ, dcww_occ] ++
341 [op | IfaceClassOp op _ _ <- sigs] ++
342 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
344 n_ctxt = length sc_ctxt
346 tc_occ = mkClassTyConOcc cls_occ
347 dc_occ = mkClassDataConOcc cls_occ
348 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
349 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
350 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
352 ifaceDeclSubBndrs (IfaceData {ifCons = IfAbstractTyCon})
355 ifaceDeclSubBndrs (IfaceData {ifCons = IfNewTyCon (IfVanillaCon { ifConOcc = con_occ,
356 ifConFields = fields})})
357 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
358 -- Wrapper, no worker; see MkId.mkDataConIds
360 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
361 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
362 ++ concatMap dc_occs cons
364 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
365 fld_occs (IfGadtCon {}) = []
367 | has_wrapper = [con_occ, work_occ, wrap_occ]
368 | otherwise = [con_occ, work_occ]
370 con_occ = ifConOcc con_decl
371 strs = ifConStricts con_decl
372 wrap_occ = mkDataConWrapperOcc con_occ
373 work_occ = mkDataConWorkerOcc con_occ
374 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
375 -- ToDo: may miss strictness in existential dicts
377 ifaceDeclSubBndrs _other = []
382 %*********************************************************
384 \subsection{Reading an interface file}
386 %*********************************************************
389 findAndReadIface :: SDoc -> Module
390 -> IsBootInterface -- True <=> Look for a .hi-boot file
391 -- False <=> Look for .hi file
392 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
393 -- Nothing <=> file not found, or unreadable, or illegible
394 -- Just x <=> successfully found and parsed
396 -- It *doesn't* add an error to the monad, because
397 -- sometimes it's ok to fail... see notes with loadInterface
399 findAndReadIface doc_str mod hi_boot_file
400 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
402 then ptext SLIT("[boot]")
404 ptext SLIT("interface for"),
406 nest 4 (ptext SLIT("reason:") <+> doc_str)])
408 -- Check for GHC.Prim, and return its static interface
411 then returnM (Succeeded (ghcPrimIface,
412 "<built in interface for GHC.Prim>"))
416 ; hsc_env <- getTopEnv
417 ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
420 { traceIf (ptext SLIT("...not found"))
422 ; returnM (Failed (cantFindError dflags (moduleName mod) err)) } ;
424 Succeeded file_path -> do
426 -- Found file, so read it
427 { traceIf (ptext SLIT("readIFace") <+> text file_path)
428 ; read_result <- readIface mod file_path hi_boot_file
429 ; case read_result of
430 Failed err -> returnM (Failed (badIfaceFile file_path err))
432 | mi_module iface /= mod ->
433 return (Failed (wrongIfaceModErr iface mod file_path))
435 returnM (Succeeded (iface, file_path))
436 -- Don't forget to fill in the package name...
439 findHiFile :: HscEnv -> Module -> IsBootInterface
440 -> IO (MaybeErr FindResult FilePath)
441 findHiFile hsc_env mod hi_boot_file
443 maybe_found <- findExactModule hsc_env mod
445 Found loc mod -> return (Succeeded path)
447 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
448 err -> return (Failed err)
451 @readIface@ tries just the one file.
454 readIface :: Module -> FilePath -> IsBootInterface
455 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
456 -- Failed err <=> file not found, or unreadable, or illegible
457 -- Succeeded iface <=> successfully found and parsed
459 readIface wanted_mod file_path is_hi_boot_file
460 = do { dflags <- getDOpts
462 { res <- tryMost (readBinIface file_path)
465 | wanted_mod == actual_mod -> return (Succeeded iface)
466 | otherwise -> return (Failed err)
468 actual_mod = mi_module iface
469 err = hiModuleNameMismatchWarn wanted_mod actual_mod
471 Left exn -> return (Failed (text (showException exn)))
476 %*********************************************************
478 Wired-in interface for GHC.Prim
480 %*********************************************************
483 initExternalPackageState :: ExternalPackageState
484 initExternalPackageState
486 eps_is_boot = emptyUFM,
487 eps_PIT = emptyPackageIfaceTable,
488 eps_PTE = emptyTypeEnv,
489 eps_inst_env = emptyInstEnv,
490 eps_rule_base = mkRuleBase builtinRules,
491 -- Initialise the EPS rule pool with the built-in rules
492 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
493 , n_insts_in = 0, n_insts_out = 0
494 , n_rules_in = length builtinRules, n_rules_out = 0 }
499 %*********************************************************
501 Wired-in interface for GHC.Prim
503 %*********************************************************
506 ghcPrimIface :: ModIface
508 = (emptyModIface gHC_PRIM) {
509 mi_exports = [(gHC_PRIM, ghcPrimExports)],
511 mi_fixities = fixities,
512 mi_fix_fn = mkIfaceFixCache fixities
515 fixities = [(getOccName seqId, Fixity 0 InfixR)]
519 %*********************************************************
521 \subsection{Statistics}
523 %*********************************************************
526 ifaceStats :: ExternalPackageState -> SDoc
528 = hcat [text "Renamer stats: ", msg]
530 stats = eps_stats eps
532 [int (n_ifaces_in stats) <+> text "interfaces read",
533 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
534 int (n_decls_in stats), text "read"],
535 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
536 int (n_insts_in stats), text "read"],
537 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
538 int (n_rules_in stats), text "read"]
543 %*********************************************************
547 %*********************************************************
550 badIfaceFile file err
551 = vcat [ptext SLIT("Bad interface file:") <+> text file,
554 hiModuleNameMismatchWarn :: Module -> Module -> Message
555 hiModuleNameMismatchWarn requested_mod read_mod =
556 withPprStyle defaultUserStyle $
557 -- we want the Modules below to be qualified with package names,
558 -- so reset the PrintUnqualified setting.
559 hsep [ ptext SLIT("Something is amiss; requested module ")
561 , ptext SLIT("differs from name found in the interface file")
565 wrongIfaceModErr iface mod_name file_path
566 = sep [ptext SLIT("Interface file") <+> iface_file,
567 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
568 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
569 sep [ptext SLIT("Probable cause: the source code which generated"),
571 ptext SLIT("has an incompatible module name")
574 where iface_file = doubleQuotes (text file_path)