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,
46 mkClassDataConOcc, mkSuperDictSelOcc,
47 mkDataConWrapperOcc, mkDataConWorkerOcc )
48 import SrcLoc ( importedSrcLoc )
49 import Maybes ( MaybeErr(..) )
50 import ErrUtils ( Message )
51 import Finder ( findImportedModule, findExactModule,
52 FindResult(..), cannotFindInterface )
55 import BinIface ( readBinIface )
56 import Panic ( ghcError, tryMost, showException, GhcException(..) )
61 %************************************************************************
63 loadSrcInterface, loadOrphanModules, loadHomeInterface
65 These three are called from TcM-land
67 %************************************************************************
70 -- | Load the interface corresponding to an @import@ directive in
71 -- source code. On a failure, fail in the monad with an error message.
72 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
73 loadSrcInterface doc mod want_boot = do
74 -- We must first find which Module this import refers to. This involves
75 -- calling the Finder, which as a side effect will search the filesystem
76 -- and create a ModLocation. If successful, loadIface will read the
77 -- interface; it will call the Finder again, but the ModLocation will be
78 -- cached from the first search.
80 res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
83 mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
85 Failed err -> failWithTc err
86 Succeeded iface -> return iface
88 let dflags = hsc_dflags hsc_env in
89 failWithTc (cannotFindInterface dflags mod err)
91 -- | Load interfaces for a collection of orphan modules.
92 loadOrphanModules :: [Module] -> TcM ()
93 loadOrphanModules mods
94 | null mods = returnM ()
95 | otherwise = initIfaceTcRn $
96 do { traceIf (text "Loading orphan modules:" <+>
101 load mod = loadSysInterface (mk_doc mod) mod
102 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
104 -- | Loads the interface for a given Name.
105 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
106 loadInterfaceForName doc name
109 -- Should not be called with a name from the module being compiled
110 this_mod <- getModule
111 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
113 initIfaceTcRn $ loadSysInterface doc (nameModule name)
116 -- | An 'IfM' function to load the home interface for a wired-in thing,
117 -- so that we're sure that we see its instance declarations and rules
118 loadWiredInHomeIface :: Name -> IfM lcl ()
119 loadWiredInHomeIface name
120 = ASSERT( isWiredInName name )
121 do loadSysInterface doc (nameModule name); return ()
123 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
125 -- | A wrapper for 'loadInterface' that throws an exception if it fails
126 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
127 loadSysInterface doc mod_name
128 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
130 Failed err -> ghcError (ProgramError (showSDoc err))
131 Succeeded iface -> return iface }
135 %*********************************************************
139 The main function to load an interface
140 for an imported module, and put it in
141 the External Package State
143 %*********************************************************
146 loadInterface :: SDoc -> Module -> WhereFrom
147 -> IfM lcl (MaybeErr Message ModIface)
149 -- If it can't find a suitable interface file, we
150 -- a) modify the PackageIfaceTable to have an empty entry
151 -- (to avoid repeated complaints)
152 -- b) return (Left message)
154 -- It's not necessarily an error for there not to be an interface
155 -- file -- perhaps the module has changed, and that interface
158 loadInterface doc_str mod from
159 = do { -- Read the state
160 (eps,hpt) <- getEpsAndHpt
162 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
164 -- Check whether we have the interface already
166 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
168 -> returnM (Succeeded iface) ; -- Already loaded
169 -- The (src_imp == mi_boot iface) test checks that the already-loaded
170 -- interface isn't a boot iface. This can conceivably happen,
171 -- if an earlier import had a before we got to real imports. I think.
174 { let { hi_boot_file = case from of
175 ImportByUser usr_boot -> usr_boot
176 ImportBySystem -> sys_boot
178 ; mb_dep = lookupUFM (eps_is_boot eps) (moduleName mod)
179 ; sys_boot = case mb_dep of
180 Just (_, is_boot) -> is_boot
182 -- The boot-ness of the requested interface,
183 } -- based on the dependencies in directly-imported modules
185 -- READ THE MODULE IN
186 ; read_result <- findAndReadIface doc_str mod hi_boot_file
188 ; case read_result of {
190 { let fake_iface = emptyModIface mod
192 ; updateEps_ $ \eps ->
193 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
194 -- Not found, so add an empty iface to
195 -- the EPS map so that we don't look again
197 ; returnM (Failed err) } ;
200 Succeeded (iface, file_path) -- Sanity check:
201 | ImportBySystem <- from, -- system-importing...
202 modulePackageId (mi_module iface) == thisPackage dflags,
203 -- a home-package module...
204 Nothing <- mb_dep -- that we know nothing about
205 -> returnM (Failed (badDepMsg mod))
210 loc_doc = text file_path
212 initIfaceLcl mod loc_doc $ do
214 -- Load the new ModIface into the External Package State
215 -- Even home-package interfaces loaded by loadInterface
216 -- (which only happens in OneShot mode; in Batch/Interactive
217 -- mode, home-package modules are loaded one by one into the HPT)
218 -- are put in the EPS.
220 -- The main thing is to add the ModIface to the PIT, but
222 -- IfaceDecls, IfaceInst, IfaceRules
223 -- out of the ModIface and put them into the big EPS pools
225 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
226 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
227 -- If we do loadExport first the wrong info gets into the cache (unless we
228 -- explicitly tag each export which seems a bit of a bore)
230 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
231 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
232 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
233 ; new_eps_rules <- if ignore_prags
235 else mapM tcIfaceRule (mi_rules iface)
237 ; let { final_iface = iface { mi_decls = panic "No mi_decls in PIT",
238 mi_insts = panic "No mi_insts in PIT",
239 mi_rules = panic "No mi_rules in PIT" } }
241 ; updateEps_ $ \ eps ->
242 eps { eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
243 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
244 eps_rule_base = extendRuleBaseList (eps_rule_base eps) new_eps_rules,
245 eps_inst_env = extendInstEnvList (eps_inst_env eps) new_eps_insts,
246 eps_stats = addEpsInStats (eps_stats eps) (length new_eps_decls)
247 (length new_eps_insts) (length new_eps_rules) }
249 ; return (Succeeded final_iface)
253 = hang (ptext SLIT("Interface file inconsistency:"))
254 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned,"),
255 ptext SLIT("but does not appear in the dependencies of the interface")])
257 -----------------------------------------------------
258 -- Loading type/class/value decls
259 -- We pass the full Module name here, replete with
260 -- its package info, so that we can build a Name for
261 -- each binder with the right package info in it
262 -- All subsequent lookups, including crucially lookups during typechecking
263 -- the declaration itself, will find the fully-glorious Name
264 -----------------------------------------------------
266 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
267 addDeclsToPTE pte things = extendNameEnvList pte things
270 -> [(Version, IfaceDecl)]
271 -> IfL [(Name,TyThing)]
272 loadDecls ignore_prags ver_decls
273 = do { mod <- getIfModule
274 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
275 ; return (concat thingss)
278 loadDecl :: Bool -- Don't load pragmas into the decl pool
280 -> (Version, IfaceDecl)
281 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
282 -- TyThings are forkM'd thunks
283 loadDecl ignore_prags mod (_version, decl)
284 = do { -- Populate the name cache with final versions of all
285 -- the names associated with the decl
286 main_name <- mk_new_bndr mod Nothing (ifName decl)
287 ; implicit_names <- mapM (mk_new_bndr mod (Just main_name)) (ifaceDeclSubBndrs decl)
289 -- Typecheck the thing, lazily
290 -- NB. firstly, the laziness is there in case we never need the
291 -- declaration (in one-shot mode), and secondly it is there so that
292 -- we don't look up the occurrence of a name before calling mk_new_bndr
293 -- on the binder. This is important because we must get the right name
294 -- which includes its nameParent.
295 ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
296 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
297 lookup n = case lookupOccEnv mini_env (getOccName n) of
299 Nothing -> pprPanic "loadDecl" (ppr main_name <+> ppr n)
301 ; returnM ((main_name, thing) : [(n, lookup n) | n <- implicit_names]) }
302 -- We build a list from the *known* names, with (lookup n) thunks
303 -- as the TyThings. That way we can extend the PTE without poking the
306 stripped_decl | ignore_prags = discardDeclPrags decl
309 -- mk_new_bndr allocates in the name cache the final canonical
310 -- name for the thing, with the correct
313 -- imported name, to fix the module correctly in the cache
314 mk_new_bndr mod mb_parent occ
315 = newGlobalBinder mod occ mb_parent
316 (importedSrcLoc (showSDoc (ppr (moduleName mod))))
317 -- ToDo: qualify with the package name if necessary
319 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
321 discardDeclPrags :: IfaceDecl -> IfaceDecl
322 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
323 discardDeclPrags decl = decl
325 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
327 = do { traceIf (text "Loading decl for" <+> ppr name)
328 ; updateEps_ (\eps -> let stats = eps_stats eps
329 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
333 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
334 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
335 -- Deeply revolting, because it has to predict what gets bound,
336 -- especially the question of whether there's a wrapper for a datacon
338 ifaceDeclSubBndrs IfaceClass { ifCtxt = sc_ctxt,
341 = [tc_occ, dc_occ, dcww_occ] ++
342 [op | IfaceClassOp op _ _ <- sigs] ++
343 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
345 n_ctxt = length sc_ctxt
347 tc_occ = mkClassTyConOcc cls_occ
348 dc_occ = mkClassDataConOcc cls_occ
349 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
350 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
351 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
353 ifaceDeclSubBndrs IfaceData {ifCons = IfAbstractTyCon}
356 ifaceDeclSubBndrs IfaceData {ifCons = IfNewTyCon (IfVanillaCon {
358 ifConFields = fields})}
359 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
360 -- Wrapper, no worker; see MkId.mkDataConIds
362 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
363 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
364 ++ concatMap dc_occs cons
366 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
367 fld_occs (IfGadtCon {}) = []
369 | has_wrapper = [con_occ, work_occ, wrap_occ]
370 | otherwise = [con_occ, work_occ]
372 con_occ = ifConOcc con_decl
373 strs = ifConStricts con_decl
374 wrap_occ = mkDataConWrapperOcc con_occ
375 work_occ = mkDataConWorkerOcc con_occ
376 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
377 -- ToDo: may miss strictness in existential dicts
379 ifaceDeclSubBndrs _other = []
384 %*********************************************************
386 \subsection{Reading an interface file}
388 %*********************************************************
391 findAndReadIface :: SDoc -> Module
392 -> IsBootInterface -- True <=> Look for a .hi-boot file
393 -- False <=> Look for .hi file
394 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
395 -- Nothing <=> file not found, or unreadable, or illegible
396 -- Just x <=> successfully found and parsed
398 -- It *doesn't* add an error to the monad, because
399 -- sometimes it's ok to fail... see notes with loadInterface
401 findAndReadIface doc_str mod hi_boot_file
402 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
404 then ptext SLIT("[boot]")
406 ptext SLIT("interface for"),
408 nest 4 (ptext SLIT("reason:") <+> doc_str)])
410 -- Check for GHC.Prim, and return its static interface
413 then returnM (Succeeded (ghcPrimIface,
414 "<built in interface for GHC.Prim>"))
418 ; hsc_env <- getTopEnv
419 ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
422 { traceIf (ptext SLIT("...not found"))
424 ; returnM (Failed (cannotFindInterface dflags
425 (moduleName mod) err)) } ;
427 Succeeded file_path -> do
429 -- Found file, so read it
430 { traceIf (ptext SLIT("readIFace") <+> text file_path)
431 ; read_result <- readIface mod file_path hi_boot_file
432 ; case read_result of
433 Failed err -> returnM (Failed (badIfaceFile file_path err))
435 | mi_module iface /= mod ->
436 return (Failed (wrongIfaceModErr iface mod file_path))
438 returnM (Succeeded (iface, file_path))
439 -- Don't forget to fill in the package name...
442 findHiFile :: HscEnv -> Module -> IsBootInterface
443 -> IO (MaybeErr FindResult FilePath)
444 findHiFile hsc_env mod hi_boot_file
446 maybe_found <- findExactModule hsc_env mod
448 Found loc mod -> return (Succeeded path)
450 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
451 err -> return (Failed err)
454 @readIface@ tries just the one file.
457 readIface :: Module -> FilePath -> IsBootInterface
458 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
459 -- Failed err <=> file not found, or unreadable, or illegible
460 -- Succeeded iface <=> successfully found and parsed
462 readIface wanted_mod file_path is_hi_boot_file
463 = do { dflags <- getDOpts
465 { res <- tryMost (readBinIface file_path)
468 | wanted_mod == actual_mod -> return (Succeeded iface)
469 | otherwise -> return (Failed err)
471 actual_mod = mi_module iface
472 err = hiModuleNameMismatchWarn wanted_mod actual_mod
474 Left exn -> return (Failed (text (showException exn)))
479 %*********************************************************
481 Wired-in interface for GHC.Prim
483 %*********************************************************
486 initExternalPackageState :: ExternalPackageState
487 initExternalPackageState
489 eps_is_boot = emptyUFM,
490 eps_PIT = emptyPackageIfaceTable,
491 eps_PTE = emptyTypeEnv,
492 eps_inst_env = emptyInstEnv,
493 eps_rule_base = mkRuleBase builtinRules,
494 -- Initialise the EPS rule pool with the built-in rules
495 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
496 , n_insts_in = 0, n_insts_out = 0
497 , n_rules_in = length builtinRules, n_rules_out = 0 }
502 %*********************************************************
504 Wired-in interface for GHC.Prim
506 %*********************************************************
509 ghcPrimIface :: ModIface
511 = (emptyModIface gHC_PRIM) {
512 mi_exports = [(gHC_PRIM, ghcPrimExports)],
514 mi_fixities = fixities,
515 mi_fix_fn = mkIfaceFixCache fixities
518 fixities = [(getOccName seqId, Fixity 0 InfixR)]
522 %*********************************************************
524 \subsection{Statistics}
526 %*********************************************************
529 ifaceStats :: ExternalPackageState -> SDoc
531 = hcat [text "Renamer stats: ", msg]
533 stats = eps_stats eps
535 [int (n_ifaces_in stats) <+> text "interfaces read",
536 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
537 int (n_decls_in stats), text "read"],
538 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
539 int (n_insts_in stats), text "read"],
540 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
541 int (n_rules_in stats), text "read"]
546 %*********************************************************
550 %*********************************************************
553 badIfaceFile file err
554 = vcat [ptext SLIT("Bad interface file:") <+> text file,
557 hiModuleNameMismatchWarn :: Module -> Module -> Message
558 hiModuleNameMismatchWarn requested_mod read_mod =
559 withPprStyle defaultUserStyle $
560 -- we want the Modules below to be qualified with package names,
561 -- so reset the PrintUnqualified setting.
562 hsep [ ptext SLIT("Something is amiss; requested module ")
564 , ptext SLIT("differs from name found in the interface file")
568 wrongIfaceModErr iface mod_name file_path
569 = sep [ptext SLIT("Interface file") <+> iface_file,
570 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
571 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
572 sep [ptext SLIT("Probable cause: the source code which generated"),
574 ptext SLIT("has an incompatible module name")
577 where iface_file = doubleQuotes (text file_path)