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,
342 [tc_occ, dc_occ, dcww_occ] ++
343 [op | IfaceClassOp op _ _ <- sigs] ++
344 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
346 n_ctxt = length sc_ctxt
348 tc_occ = mkClassTyConOcc cls_occ
349 dc_occ = mkClassDataConOcc cls_occ
350 co_occs | is_newtype = [mkNewTyCoOcc tc_occ]
352 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
353 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
354 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
356 ifaceDeclSubBndrs IfaceData {ifCons = IfAbstractTyCon}
359 ifaceDeclSubBndrs IfaceData {ifCons = IfNewTyCon (IfVanillaCon {
361 ifConFields = fields})}
362 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
363 -- Wrapper, no worker; see MkId.mkDataConIds
365 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
366 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
367 ++ concatMap dc_occs cons
369 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
370 fld_occs (IfGadtCon {}) = []
372 | has_wrapper = [con_occ, work_occ, wrap_occ]
373 | otherwise = [con_occ, work_occ]
375 con_occ = ifConOcc con_decl
376 strs = ifConStricts con_decl
377 wrap_occ = mkDataConWrapperOcc con_occ
378 work_occ = mkDataConWorkerOcc con_occ
379 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
380 -- ToDo: may miss strictness in existential dicts
382 ifaceDeclSubBndrs _other = []
387 %*********************************************************
389 \subsection{Reading an interface file}
391 %*********************************************************
394 findAndReadIface :: SDoc -> Module
395 -> IsBootInterface -- True <=> Look for a .hi-boot file
396 -- False <=> Look for .hi file
397 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
398 -- Nothing <=> file not found, or unreadable, or illegible
399 -- Just x <=> successfully found and parsed
401 -- It *doesn't* add an error to the monad, because
402 -- sometimes it's ok to fail... see notes with loadInterface
404 findAndReadIface doc_str mod hi_boot_file
405 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
407 then ptext SLIT("[boot]")
409 ptext SLIT("interface for"),
411 nest 4 (ptext SLIT("reason:") <+> doc_str)])
413 -- Check for GHC.Prim, and return its static interface
416 then returnM (Succeeded (ghcPrimIface,
417 "<built in interface for GHC.Prim>"))
421 ; hsc_env <- getTopEnv
422 ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
425 { traceIf (ptext SLIT("...not found"))
427 ; returnM (Failed (cannotFindInterface dflags
428 (moduleName mod) err)) } ;
430 Succeeded file_path -> do
432 -- Found file, so read it
433 { traceIf (ptext SLIT("readIFace") <+> text file_path)
434 ; read_result <- readIface mod file_path hi_boot_file
435 ; case read_result of
436 Failed err -> returnM (Failed (badIfaceFile file_path err))
438 | mi_module iface /= mod ->
439 return (Failed (wrongIfaceModErr iface mod file_path))
441 returnM (Succeeded (iface, file_path))
442 -- Don't forget to fill in the package name...
445 findHiFile :: HscEnv -> Module -> IsBootInterface
446 -> IO (MaybeErr FindResult FilePath)
447 findHiFile hsc_env mod hi_boot_file
449 maybe_found <- findExactModule hsc_env mod
451 Found loc mod -> return (Succeeded path)
453 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
454 err -> return (Failed err)
457 @readIface@ tries just the one file.
460 readIface :: Module -> FilePath -> IsBootInterface
461 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
462 -- Failed err <=> file not found, or unreadable, or illegible
463 -- Succeeded iface <=> successfully found and parsed
465 readIface wanted_mod file_path is_hi_boot_file
466 = do { dflags <- getDOpts
468 { res <- tryMost (readBinIface file_path)
471 | wanted_mod == actual_mod -> return (Succeeded iface)
472 | otherwise -> return (Failed err)
474 actual_mod = mi_module iface
475 err = hiModuleNameMismatchWarn wanted_mod actual_mod
477 Left exn -> return (Failed (text (showException exn)))
482 %*********************************************************
484 Wired-in interface for GHC.Prim
486 %*********************************************************
489 initExternalPackageState :: ExternalPackageState
490 initExternalPackageState
492 eps_is_boot = emptyUFM,
493 eps_PIT = emptyPackageIfaceTable,
494 eps_PTE = emptyTypeEnv,
495 eps_inst_env = emptyInstEnv,
496 eps_rule_base = mkRuleBase builtinRules,
497 -- Initialise the EPS rule pool with the built-in rules
498 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
499 , n_insts_in = 0, n_insts_out = 0
500 , n_rules_in = length builtinRules, n_rules_out = 0 }
505 %*********************************************************
507 Wired-in interface for GHC.Prim
509 %*********************************************************
512 ghcPrimIface :: ModIface
514 = (emptyModIface gHC_PRIM) {
515 mi_exports = [(gHC_PRIM, ghcPrimExports)],
517 mi_fixities = fixities,
518 mi_fix_fn = mkIfaceFixCache fixities
521 fixities = [(getOccName seqId, Fixity 0 InfixR)]
525 %*********************************************************
527 \subsection{Statistics}
529 %*********************************************************
532 ifaceStats :: ExternalPackageState -> SDoc
534 = hcat [text "Renamer stats: ", msg]
536 stats = eps_stats eps
538 [int (n_ifaces_in stats) <+> text "interfaces read",
539 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
540 int (n_decls_in stats), text "read"],
541 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
542 int (n_insts_in stats), text "read"],
543 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
544 int (n_rules_in stats), text "read"]
549 %*********************************************************
553 %*********************************************************
556 badIfaceFile file err
557 = vcat [ptext SLIT("Bad interface file:") <+> text file,
560 hiModuleNameMismatchWarn :: Module -> Module -> Message
561 hiModuleNameMismatchWarn requested_mod read_mod =
562 withPprStyle defaultUserStyle $
563 -- we want the Modules below to be qualified with package names,
564 -- so reset the PrintUnqualified setting.
565 hsep [ ptext SLIT("Something is amiss; requested module ")
567 , ptext SLIT("differs from name found in the interface file")
571 wrongIfaceModErr iface mod_name file_path
572 = sep [ptext SLIT("Interface file") <+> iface_file,
573 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
574 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
575 sep [ptext SLIT("Probable cause: the source code which generated"),
577 ptext SLIT("has an incompatible module name")
580 where iface_file = doubleQuotes (text file_path)