2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Loading interface files
10 loadInterface, loadInterfaceForName, loadWiredInHomeIface,
11 loadSrcInterface, loadSysInterface, loadOrphanModules,
12 findAndReadIface, readIface, -- Used when reading the module's old interface
13 loadDecls, -- Should move to TcIface and be renamed
14 initExternalPackageState,
16 ifaceStats, pprModIface, showIface
19 #include "HsVersions.h"
21 import {-# SOURCE #-} TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst,
29 import BasicTypes hiding (SuccessFlag(..))
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 -- loadInterface looks in both the HPT and PIT for the required interface
149 -- If not found, it loads it, and puts it in the PIT (always).
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
189 ; case read_result of {
191 { let fake_iface = emptyModIface mod
193 ; updateEps_ $ \eps ->
194 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
195 -- Not found, so add an empty iface to
196 -- the EPS map so that we don't look again
198 ; returnM (Failed err) } ;
201 Succeeded (iface, file_path) -- Sanity check:
202 | ImportBySystem <- from, -- system-importing...
203 modulePackageId (mi_module iface) == thisPackage dflags,
204 -- a home-package module...
205 Nothing <- mb_dep -- that we know nothing about
206 -> returnM (Failed (badDepMsg mod))
211 loc_doc = text file_path
213 initIfaceLcl mod loc_doc $ do
215 -- Load the new ModIface into the External Package State
216 -- Even home-package interfaces loaded by loadInterface
217 -- (which only happens in OneShot mode; in Batch/Interactive
218 -- mode, home-package modules are loaded one by one into the HPT)
219 -- are put in the EPS.
221 -- The main thing is to add the ModIface to the PIT, but
223 -- IfaceDecls, IfaceInst, IfaceRules
224 -- out of the ModIface and put them into the big EPS pools
226 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
227 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
228 -- If we do loadExport first the wrong info gets into the cache (unless we
229 -- explicitly tag each export which seems a bit of a bore)
231 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
232 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
233 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
234 ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
235 ; new_eps_rules <- tcIfaceRules ignore_prags (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 ->
243 eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
244 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
245 eps_rule_base = extendRuleBaseList (eps_rule_base eps)
247 eps_inst_env = extendInstEnvList (eps_inst_env eps)
249 eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
251 eps_stats = addEpsInStats (eps_stats eps)
252 (length new_eps_decls)
253 (length new_eps_insts) (length new_eps_rules) }
255 ; return (Succeeded final_iface)
259 = hang (ptext SLIT("Interface file inconsistency:"))
260 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned is needed,"),
261 ptext SLIT("but is not among the dependencies of interfaces directly imported by the module being compiled")])
263 -----------------------------------------------------
264 -- Loading type/class/value decls
265 -- We pass the full Module name here, replete with
266 -- its package info, so that we can build a Name for
267 -- each binder with the right package info in it
268 -- All subsequent lookups, including crucially lookups during typechecking
269 -- the declaration itself, will find the fully-glorious Name
271 -- We handle ATs specially. They are not main declarations, but also not
272 -- implict things (in particular, adding them to `implicitTyThings' would mess
273 -- things up in the renaming/type checking of source programs).
274 -----------------------------------------------------
276 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
277 addDeclsToPTE pte things = extendNameEnvList pte things
280 -> [(Version, IfaceDecl)]
281 -> IfL [(Name,TyThing)]
282 loadDecls ignore_prags ver_decls
283 = do { mod <- getIfModule
284 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
285 ; return (concat thingss)
288 loadDecl :: Bool -- Don't load pragmas into the decl pool
290 -> (Version, IfaceDecl)
291 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
292 -- TyThings are forkM'd thunks
293 loadDecl ignore_prags mod (_version, decl)
294 = do { -- Populate the name cache with final versions of all
295 -- the names associated with the decl
296 main_name <- mk_new_bndr mod (ifName decl)
297 ; traceIf (text "Loading decl for " <> ppr main_name)
298 ; implicit_names <- mapM (mk_new_bndr mod) (ifaceDeclSubBndrs decl)
300 -- Typecheck the thing, lazily
301 -- NB. Firstly, the laziness is there in case we never need the
302 -- declaration (in one-shot mode), and secondly it is there so that
303 -- we don't look up the occurrence of a name before calling mk_new_bndr
304 -- on the binder. This is important because we must get the right name
305 -- which includes its nameParent.
307 ; thing <- forkM doc $ do { bumpDeclStats main_name
308 ; tcIfaceDecl ignore_prags decl }
310 -- Populate the type environment with the implicitTyThings too
311 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
312 lookup n = case lookupOccEnv mini_env (getOccName n) of
315 pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
317 ; returnM $ (main_name, thing) : [(n, lookup n) | n <- implicit_names]
319 -- We build a list from the *known* names, with (lookup n) thunks
320 -- as the TyThings. That way we can extend the PTE without poking the
323 -- mk_new_bndr allocates in the name cache the final canonical
324 -- name for the thing, with the correct
327 -- imported name, to fix the module correctly in the cache
329 = newGlobalBinder mod occ
330 (importedSrcLoc (showSDoc (ppr (moduleName mod))))
331 -- ToDo: qualify with the package name if necessary
333 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
335 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
337 = do { traceIf (text "Loading decl for" <+> ppr name)
338 ; updateEps_ (\eps -> let stats = eps_stats eps
339 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
344 %*********************************************************
346 \subsection{Reading an interface file}
348 %*********************************************************
351 findAndReadIface :: SDoc -> Module
352 -> IsBootInterface -- True <=> Look for a .hi-boot file
353 -- False <=> Look for .hi file
354 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
355 -- Nothing <=> file not found, or unreadable, or illegible
356 -- Just x <=> successfully found and parsed
358 -- It *doesn't* add an error to the monad, because
359 -- sometimes it's ok to fail... see notes with loadInterface
361 findAndReadIface doc_str mod hi_boot_file
362 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
364 then ptext SLIT("[boot]")
366 ptext SLIT("interface for"),
368 nest 4 (ptext SLIT("reason:") <+> doc_str)])
370 -- Check for GHC.Prim, and return its static interface
373 then returnM (Succeeded (ghcPrimIface,
374 "<built in interface for GHC.Prim>"))
378 ; hsc_env <- getTopEnv
379 ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
382 { traceIf (ptext SLIT("...not found"))
384 ; returnM (Failed (cannotFindInterface dflags
385 (moduleName mod) err)) } ;
387 Succeeded file_path -> do
389 -- Found file, so read it
390 { traceIf (ptext SLIT("readIFace") <+> text file_path)
391 ; read_result <- readIface mod file_path hi_boot_file
392 ; case read_result of
393 Failed err -> returnM (Failed (badIfaceFile file_path err))
395 | mi_module iface /= mod ->
396 return (Failed (wrongIfaceModErr iface mod file_path))
398 returnM (Succeeded (iface, file_path))
399 -- Don't forget to fill in the package name...
402 findHiFile :: HscEnv -> Module -> IsBootInterface
403 -> IO (MaybeErr FindResult FilePath)
404 findHiFile hsc_env mod hi_boot_file
406 maybe_found <- findExactModule hsc_env mod
408 Found loc mod -> return (Succeeded path)
410 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
411 err -> return (Failed err)
414 @readIface@ tries just the one file.
417 readIface :: Module -> FilePath -> IsBootInterface
418 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
419 -- Failed err <=> file not found, or unreadable, or illegible
420 -- Succeeded iface <=> successfully found and parsed
422 readIface wanted_mod file_path is_hi_boot_file
423 = do { dflags <- getDOpts
424 ; res <- tryMostM $ readBinIface file_path
427 | wanted_mod == actual_mod -> return (Succeeded iface)
428 | otherwise -> return (Failed err)
430 actual_mod = mi_module iface
431 err = hiModuleNameMismatchWarn wanted_mod actual_mod
433 Left exn -> return (Failed (text (showException exn)))
438 %*********************************************************
440 Wired-in interface for GHC.Prim
442 %*********************************************************
445 initExternalPackageState :: ExternalPackageState
446 initExternalPackageState
448 eps_is_boot = emptyUFM,
449 eps_PIT = emptyPackageIfaceTable,
450 eps_PTE = emptyTypeEnv,
451 eps_inst_env = emptyInstEnv,
452 eps_fam_inst_env = emptyFamInstEnv,
453 eps_rule_base = mkRuleBase builtinRules,
454 -- Initialise the EPS rule pool with the built-in rules
455 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
456 , n_insts_in = 0, n_insts_out = 0
457 , n_rules_in = length builtinRules, n_rules_out = 0 }
462 %*********************************************************
464 Wired-in interface for GHC.Prim
466 %*********************************************************
469 ghcPrimIface :: ModIface
471 = (emptyModIface gHC_PRIM) {
472 mi_exports = [(gHC_PRIM, ghcPrimExports)],
474 mi_fixities = fixities,
475 mi_fix_fn = mkIfaceFixCache fixities
478 fixities = [(getOccName seqId, Fixity 0 InfixR)]
482 %*********************************************************
484 \subsection{Statistics}
486 %*********************************************************
489 ifaceStats :: ExternalPackageState -> SDoc
491 = hcat [text "Renamer stats: ", msg]
493 stats = eps_stats eps
495 [int (n_ifaces_in stats) <+> text "interfaces read",
496 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
497 int (n_decls_in stats), text "read"],
498 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
499 int (n_insts_in stats), text "read"],
500 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
501 int (n_rules_in stats), text "read"]
506 %************************************************************************
510 %************************************************************************
513 -- | Read binary interface, and print it out
514 showIface :: HscEnv -> FilePath -> IO ()
515 showIface hsc_env filename = do
516 -- skip the version check; we don't want to worry about profiled vs.
517 -- non-profiled interfaces, for example.
518 writeIORef v_IgnoreHiWay True
519 iface <- initTcRnIf 's' hsc_env () () $ readBinIface filename
520 printDump (pprModIface iface)
524 pprModIface :: ModIface -> SDoc
527 = vcat [ ptext SLIT("interface")
528 <+> ppr (mi_module iface) <+> pp_boot
529 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
530 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
531 <+> int opt_HiVersion
532 <+> ptext SLIT("where")
533 , vcat (map pprExport (mi_exports iface))
534 , pprDeps (mi_deps iface)
535 , vcat (map pprUsage (mi_usages iface))
536 , pprFixities (mi_fixities iface)
537 , vcat (map pprIfaceDecl (mi_decls iface))
538 , vcat (map ppr (mi_insts iface))
539 , vcat (map ppr (mi_rules iface))
540 , pprDeprecs (mi_deprecs iface)
543 pp_boot | mi_boot iface = ptext SLIT("[boot]")
546 exp_vers = mi_exp_vers iface
547 rule_vers = mi_rule_vers iface
549 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
550 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
553 When printing export lists, we print like this:
555 AvailTC C [C, x, y] C(x,y)
556 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
559 pprExport :: IfaceExport -> SDoc
560 pprExport (mod, items)
561 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
563 pp_avail :: GenAvailInfo OccName -> SDoc
564 pp_avail (Avail occ) = ppr occ
565 pp_avail (AvailTC _ []) = empty
566 pp_avail (AvailTC n (n':ns))
567 | n==n' = ppr n <> pp_export ns
568 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
571 pp_export names = braces (hsep (map ppr names))
573 pprUsage :: Usage -> SDoc
575 = hsep [ptext SLIT("import"), ppr (usg_name usage),
577 pp_export_version (usg_exports usage),
578 int (usg_rules usage),
579 pp_versions (usg_entities usage) ]
581 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
582 pp_export_version Nothing = empty
583 pp_export_version (Just v) = int v
585 pprDeps :: Dependencies -> SDoc
586 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
587 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
588 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
589 ptext SLIT("orphans:") <+> fsep (map ppr orphs)
592 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
593 ppr_boot True = text "[boot]"
594 ppr_boot False = empty
596 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
597 pprIfaceDecl (ver, decl)
598 = ppr_vers ver <+> ppr decl
600 -- Print the version for the decl
601 ppr_vers v | v == initialVersion = empty
604 pprFixities :: [(OccName, Fixity)] -> SDoc
605 pprFixities [] = empty
606 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
608 pprFix (occ,fix) = ppr fix <+> ppr occ
610 pprDeprecs NoDeprecs = empty
611 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
612 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
614 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
618 %*********************************************************
622 %*********************************************************
625 badIfaceFile file err
626 = vcat [ptext SLIT("Bad interface file:") <+> text file,
629 hiModuleNameMismatchWarn :: Module -> Module -> Message
630 hiModuleNameMismatchWarn requested_mod read_mod =
631 withPprStyle defaultUserStyle $
632 -- we want the Modules below to be qualified with package names,
633 -- so reset the PrintUnqualified setting.
634 hsep [ ptext SLIT("Something is amiss; requested module ")
636 , ptext SLIT("differs from name found in the interface file")
640 wrongIfaceModErr iface mod_name file_path
641 = sep [ptext SLIT("Interface file") <+> iface_file,
642 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
643 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
644 sep [ptext SLIT("Probable cause: the source code which generated"),
646 ptext SLIT("has an incompatible module name")
649 where iface_file = doubleQuotes (text file_path)