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(..), cannotFindInterface )
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 err
85 Succeeded iface -> return iface
87 let dflags = hsc_dflags hsc_env in
88 failWithTc (cannotFindInterface dflags mod err)
90 -- | Load interfaces for a collection of orphan modules.
91 loadOrphanModules :: [Module] -> TcM ()
92 loadOrphanModules mods
93 | null mods = returnM ()
94 | otherwise = initIfaceTcRn $
95 do { traceIf (text "Loading orphan modules:" <+>
100 load mod = loadSysInterface (mk_doc mod) mod
101 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
103 -- | Loads the interface for a given Name.
104 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
105 loadInterfaceForName doc name
108 -- Should not be called with a name from the module being compiled
109 this_mod <- getModule
110 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
112 initIfaceTcRn $ loadSysInterface doc (nameModule name)
115 -- | An 'IfM' function to load the home interface for a wired-in thing,
116 -- so that we're sure that we see its instance declarations and rules
117 loadWiredInHomeIface :: Name -> IfM lcl ()
118 loadWiredInHomeIface name
119 = ASSERT( isWiredInName name )
120 do loadSysInterface doc (nameModule name); return ()
122 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
124 -- | A wrapper for 'loadInterface' that throws an exception if it fails
125 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
126 loadSysInterface doc mod_name
127 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
129 Failed err -> ghcError (ProgramError (showSDoc err))
130 Succeeded iface -> return iface }
134 %*********************************************************
138 The main function to load an interface
139 for an imported module, and put it in
140 the External Package State
142 %*********************************************************
145 loadInterface :: SDoc -> Module -> WhereFrom
146 -> IfM lcl (MaybeErr Message ModIface)
148 -- If it can't find a suitable interface file, we
149 -- a) modify the PackageIfaceTable to have an empty entry
150 -- (to avoid repeated complaints)
151 -- b) return (Left message)
153 -- It's not necessarily an error for there not to be an interface
154 -- file -- perhaps the module has changed, and that interface
157 loadInterface doc_str mod from
158 = do { -- Read the state
159 (eps,hpt) <- getEpsAndHpt
161 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
163 -- Check whether we have the interface already
165 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
167 -> returnM (Succeeded iface) ; -- Already loaded
168 -- The (src_imp == mi_boot iface) test checks that the already-loaded
169 -- interface isn't a boot iface. This can conceivably happen,
170 -- if an earlier import had a before we got to real imports. I think.
173 { let { hi_boot_file = case from of
174 ImportByUser usr_boot -> usr_boot
175 ImportBySystem -> sys_boot
177 ; mb_dep = lookupUFM (eps_is_boot eps) (moduleName mod)
178 ; sys_boot = case mb_dep of
179 Just (_, is_boot) -> is_boot
181 -- The boot-ness of the requested interface,
182 } -- based on the dependencies in directly-imported modules
184 -- READ THE MODULE IN
185 ; read_result <- findAndReadIface doc_str mod hi_boot_file
187 ; case read_result of {
189 { let fake_iface = emptyModIface mod
191 ; updateEps_ $ \eps ->
192 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
193 -- Not found, so add an empty iface to
194 -- the EPS map so that we don't look again
196 ; returnM (Failed err) } ;
199 Succeeded (iface, file_path) -- Sanity check:
200 | ImportBySystem <- from, -- system-importing...
201 modulePackageId (mi_module iface) == thisPackage dflags,
202 -- a home-package module...
203 Nothing <- mb_dep -- that we know nothing about
204 -> returnM (Failed (badDepMsg mod))
209 loc_doc = text file_path
211 initIfaceLcl mod loc_doc $ do
213 -- Load the new ModIface into the External Package State
214 -- Even home-package interfaces loaded by loadInterface
215 -- (which only happens in OneShot mode; in Batch/Interactive
216 -- mode, home-package modules are loaded one by one into the HPT)
217 -- are put in the EPS.
219 -- The main thing is to add the ModIface to the PIT, but
221 -- IfaceDecls, IfaceInst, IfaceRules
222 -- out of the ModIface and put them into the big EPS pools
224 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
225 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
226 -- If we do loadExport first the wrong info gets into the cache (unless we
227 -- explicitly tag each export which seems a bit of a bore)
229 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
230 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
231 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
232 ; new_eps_rules <- if ignore_prags
234 else mapM tcIfaceRule (mi_rules iface)
236 ; let { final_iface = iface { mi_decls = panic "No mi_decls in PIT",
237 mi_insts = panic "No mi_insts in PIT",
238 mi_rules = panic "No mi_rules in PIT" } }
240 ; updateEps_ $ \ eps ->
241 eps { eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
242 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
243 eps_rule_base = extendRuleBaseList (eps_rule_base eps) new_eps_rules,
244 eps_inst_env = extendInstEnvList (eps_inst_env eps) new_eps_insts,
245 eps_stats = addEpsInStats (eps_stats eps) (length new_eps_decls)
246 (length new_eps_insts) (length new_eps_rules) }
248 ; return (Succeeded final_iface)
252 = hang (ptext SLIT("Interface file inconsistency:"))
253 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned,"),
254 ptext SLIT("but does not appear in the dependencies of the interface")])
256 -----------------------------------------------------
257 -- Loading type/class/value decls
258 -- We pass the full Module name here, replete with
259 -- its package info, so that we can build a Name for
260 -- each binder with the right package info in it
261 -- All subsequent lookups, including crucially lookups during typechecking
262 -- the declaration itself, will find the fully-glorious Name
263 -----------------------------------------------------
265 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
266 addDeclsToPTE pte things = extendNameEnvList pte things
269 -> [(Version, IfaceDecl)]
270 -> IfL [(Name,TyThing)]
271 loadDecls ignore_prags ver_decls
272 = do { mod <- getIfModule
273 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
274 ; return (concat thingss)
277 loadDecl :: Bool -- Don't load pragmas into the decl pool
279 -> (Version, IfaceDecl)
280 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
281 -- TyThings are forkM'd thunks
282 loadDecl ignore_prags mod (_version, decl)
283 = do { -- Populate the name cache with final versions of all
284 -- the names associated with the decl
285 main_name <- mk_new_bndr mod Nothing (ifName decl)
286 ; implicit_names <- mapM (mk_new_bndr mod (Just main_name)) (ifaceDeclSubBndrs decl)
288 -- Typecheck the thing, lazily
289 -- NB. firstly, the laziness is there in case we never need the
290 -- declaration (in one-shot mode), and secondly it is there so that
291 -- we don't look up the occurrence of a name before calling mk_new_bndr
292 -- on the binder. This is important because we must get the right name
293 -- which includes its nameParent.
294 ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
295 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
296 lookup n = case lookupOccEnv mini_env (getOccName n) of
298 Nothing -> pprPanic "loadDecl" (ppr main_name <+> ppr n)
300 ; returnM ((main_name, thing) : [(n, lookup n) | n <- implicit_names]) }
301 -- We build a list from the *known* names, with (lookup n) thunks
302 -- as the TyThings. That way we can extend the PTE without poking the
305 stripped_decl | ignore_prags = discardDeclPrags decl
308 -- mk_new_bndr allocates in the name cache the final canonical
309 -- name for the thing, with the correct
312 -- imported name, to fix the module correctly in the cache
313 mk_new_bndr mod mb_parent occ
314 = newGlobalBinder mod occ mb_parent
315 (importedSrcLoc (showSDoc (ppr (moduleName mod))))
316 -- ToDo: qualify with the package name if necessary
318 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
320 discardDeclPrags :: IfaceDecl -> IfaceDecl
321 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
322 discardDeclPrags decl = decl
324 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
326 = do { traceIf (text "Loading decl for" <+> ppr name)
327 ; updateEps_ (\eps -> let stats = eps_stats eps
328 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
332 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
333 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
334 -- Deeply revolting, because it has to predict what gets bound,
335 -- especially the question of whether there's a wrapper for a datacon
337 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, ifSigs = sigs })
338 = [tc_occ, dc_occ, dcww_occ] ++
339 [op | IfaceClassOp op _ _ <- sigs] ++
340 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
342 n_ctxt = length sc_ctxt
344 tc_occ = mkClassTyConOcc cls_occ
345 dc_occ = mkClassDataConOcc cls_occ
346 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
347 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
348 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
350 ifaceDeclSubBndrs (IfaceData {ifCons = IfAbstractTyCon})
353 ifaceDeclSubBndrs (IfaceData {ifCons = IfNewTyCon (IfVanillaCon { ifConOcc = con_occ,
354 ifConFields = fields})})
355 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
356 -- Wrapper, no worker; see MkId.mkDataConIds
358 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
359 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
360 ++ concatMap dc_occs cons
362 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
363 fld_occs (IfGadtCon {}) = []
365 | has_wrapper = [con_occ, work_occ, wrap_occ]
366 | otherwise = [con_occ, work_occ]
368 con_occ = ifConOcc con_decl
369 strs = ifConStricts con_decl
370 wrap_occ = mkDataConWrapperOcc con_occ
371 work_occ = mkDataConWorkerOcc con_occ
372 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
373 -- ToDo: may miss strictness in existential dicts
375 ifaceDeclSubBndrs _other = []
380 %*********************************************************
382 \subsection{Reading an interface file}
384 %*********************************************************
387 findAndReadIface :: SDoc -> Module
388 -> IsBootInterface -- True <=> Look for a .hi-boot file
389 -- False <=> Look for .hi file
390 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
391 -- Nothing <=> file not found, or unreadable, or illegible
392 -- Just x <=> successfully found and parsed
394 -- It *doesn't* add an error to the monad, because
395 -- sometimes it's ok to fail... see notes with loadInterface
397 findAndReadIface doc_str mod hi_boot_file
398 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
400 then ptext SLIT("[boot]")
402 ptext SLIT("interface for"),
404 nest 4 (ptext SLIT("reason:") <+> doc_str)])
406 -- Check for GHC.Prim, and return its static interface
409 then returnM (Succeeded (ghcPrimIface,
410 "<built in interface for GHC.Prim>"))
414 ; hsc_env <- getTopEnv
415 ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
418 { traceIf (ptext SLIT("...not found"))
420 ; returnM (Failed (cannotFindInterface dflags
421 (moduleName mod) err)) } ;
423 Succeeded file_path -> do
425 -- Found file, so read it
426 { traceIf (ptext SLIT("readIFace") <+> text file_path)
427 ; read_result <- readIface mod file_path hi_boot_file
428 ; case read_result of
429 Failed err -> returnM (Failed (badIfaceFile file_path err))
431 | mi_module iface /= mod ->
432 return (Failed (wrongIfaceModErr iface mod file_path))
434 returnM (Succeeded (iface, file_path))
435 -- Don't forget to fill in the package name...
438 findHiFile :: HscEnv -> Module -> IsBootInterface
439 -> IO (MaybeErr FindResult FilePath)
440 findHiFile hsc_env mod hi_boot_file
442 maybe_found <- findExactModule hsc_env mod
444 Found loc mod -> return (Succeeded path)
446 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
447 err -> return (Failed err)
450 @readIface@ tries just the one file.
453 readIface :: Module -> FilePath -> IsBootInterface
454 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
455 -- Failed err <=> file not found, or unreadable, or illegible
456 -- Succeeded iface <=> successfully found and parsed
458 readIface wanted_mod file_path is_hi_boot_file
459 = do { dflags <- getDOpts
461 { res <- tryMost (readBinIface file_path)
464 | wanted_mod == actual_mod -> return (Succeeded iface)
465 | otherwise -> return (Failed err)
467 actual_mod = mi_module iface
468 err = hiModuleNameMismatchWarn wanted_mod actual_mod
470 Left exn -> return (Failed (text (showException exn)))
475 %*********************************************************
477 Wired-in interface for GHC.Prim
479 %*********************************************************
482 initExternalPackageState :: ExternalPackageState
483 initExternalPackageState
485 eps_is_boot = emptyUFM,
486 eps_PIT = emptyPackageIfaceTable,
487 eps_PTE = emptyTypeEnv,
488 eps_inst_env = emptyInstEnv,
489 eps_rule_base = mkRuleBase builtinRules,
490 -- Initialise the EPS rule pool with the built-in rules
491 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
492 , n_insts_in = 0, n_insts_out = 0
493 , n_rules_in = length builtinRules, n_rules_out = 0 }
498 %*********************************************************
500 Wired-in interface for GHC.Prim
502 %*********************************************************
505 ghcPrimIface :: ModIface
507 = (emptyModIface gHC_PRIM) {
508 mi_exports = [(gHC_PRIM, ghcPrimExports)],
510 mi_fixities = fixities,
511 mi_fix_fn = mkIfaceFixCache fixities
514 fixities = [(getOccName seqId, Fixity 0 InfixR)]
518 %*********************************************************
520 \subsection{Statistics}
522 %*********************************************************
525 ifaceStats :: ExternalPackageState -> SDoc
527 = hcat [text "Renamer stats: ", msg]
529 stats = eps_stats eps
531 [int (n_ifaces_in stats) <+> text "interfaces read",
532 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
533 int (n_decls_in stats), text "read"],
534 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
535 int (n_insts_in stats), text "read"],
536 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
537 int (n_rules_in stats), text "read"]
542 %*********************************************************
546 %*********************************************************
549 badIfaceFile file err
550 = vcat [ptext SLIT("Bad interface file:") <+> text file,
553 hiModuleNameMismatchWarn :: Module -> Module -> Message
554 hiModuleNameMismatchWarn requested_mod read_mod =
555 withPprStyle defaultUserStyle $
556 -- we want the Modules below to be qualified with package names,
557 -- so reset the PrintUnqualified setting.
558 hsep [ ptext SLIT("Something is amiss; requested module ")
560 , ptext SLIT("differs from name found in the interface file")
564 wrongIfaceModErr iface mod_name file_path
565 = sep [ptext SLIT("Interface file") <+> iface_file,
566 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
567 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
568 sep [ptext SLIT("Probable cause: the source code which generated"),
570 ptext SLIT("has an incompatible module name")
573 where iface_file = doubleQuotes (text file_path)