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(..))
54 import Control.Monad (when)
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] -- the modules
93 -> Bool -- these are family instance-modules
95 loadOrphanModules mods isFamInstMod
96 | null mods = returnM ()
97 | otherwise = initIfaceTcRn $
98 do { traceIf (text "Loading orphan modules:" <+>
103 load mod = loadSysInterface (mk_doc mod) mod
105 | isFamInstMod = ppr mod <+> ptext SLIT("is a family-instance module")
106 | otherwise = ppr mod <+> ptext SLIT("is a orphan-instance module")
108 -- | Loads the interface for a given Name.
109 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
110 loadInterfaceForName doc name
113 -- Should not be called with a name from the module being compiled
114 this_mod <- getModule
115 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
117 initIfaceTcRn $ loadSysInterface doc (nameModule name)
120 -- | An 'IfM' function to load the home interface for a wired-in thing,
121 -- so that we're sure that we see its instance declarations and rules
122 loadWiredInHomeIface :: Name -> IfM lcl ()
123 loadWiredInHomeIface name
124 = ASSERT( isWiredInName name )
125 do loadSysInterface doc (nameModule name); return ()
127 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
129 -- | A wrapper for 'loadInterface' that throws an exception if it fails
130 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
131 loadSysInterface doc mod_name
132 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
134 Failed err -> ghcError (ProgramError (showSDoc err))
135 Succeeded iface -> return iface }
139 %*********************************************************
143 The main function to load an interface
144 for an imported module, and put it in
145 the External Package State
147 %*********************************************************
150 loadInterface :: SDoc -> Module -> WhereFrom
151 -> IfM lcl (MaybeErr Message ModIface)
153 -- loadInterface looks in both the HPT and PIT for the required interface
154 -- If not found, it loads it, and puts it in the PIT (always).
156 -- If it can't find a suitable interface file, we
157 -- a) modify the PackageIfaceTable to have an empty entry
158 -- (to avoid repeated complaints)
159 -- b) return (Left message)
161 -- It's not necessarily an error for there not to be an interface
162 -- file -- perhaps the module has changed, and that interface
165 loadInterface doc_str mod from
166 = do { -- Read the state
167 (eps,hpt) <- getEpsAndHpt
169 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
171 -- Check whether we have the interface already
173 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
175 -> returnM (Succeeded iface) ; -- Already loaded
176 -- The (src_imp == mi_boot iface) test checks that the already-loaded
177 -- interface isn't a boot iface. This can conceivably happen,
178 -- if an earlier import had a before we got to real imports. I think.
181 let { hi_boot_file = case from of
182 ImportByUser usr_boot -> usr_boot
183 ImportBySystem -> sys_boot
185 ; mb_dep = lookupUFM (eps_is_boot eps) (moduleName mod)
186 ; sys_boot = case mb_dep of
187 Just (_, is_boot) -> is_boot
189 -- The boot-ness of the requested interface,
190 } -- based on the dependencies in directly-imported modules
192 -- READ THE MODULE IN
193 ; read_result <- findAndReadIface doc_str mod hi_boot_file
194 ; case read_result of {
196 { let fake_iface = emptyModIface mod
198 ; updateEps_ $ \eps ->
199 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
200 -- Not found, so add an empty iface to
201 -- the EPS map so that we don't look again
203 ; returnM (Failed err) } ;
206 Succeeded (iface, file_path) -- Sanity check:
207 | ImportBySystem <- from, -- system-importing...
208 modulePackageId (mi_module iface) == thisPackage dflags,
209 -- a home-package module...
210 Nothing <- mb_dep -- that we know nothing about
211 -> returnM (Failed (badDepMsg mod))
216 loc_doc = text file_path
218 initIfaceLcl mod loc_doc $ do
220 -- Load the new ModIface into the External Package State
221 -- Even home-package interfaces loaded by loadInterface
222 -- (which only happens in OneShot mode; in Batch/Interactive
223 -- mode, home-package modules are loaded one by one into the HPT)
224 -- are put in the EPS.
226 -- The main thing is to add the ModIface to the PIT, but
228 -- IfaceDecls, IfaceInst, IfaceRules
229 -- out of the ModIface and put them into the big EPS pools
231 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
232 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
233 -- If we do loadExport first the wrong info gets into the cache (unless we
234 -- explicitly tag each export which seems a bit of a bore)
236 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
237 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
238 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
239 ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
240 ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
242 ; let { final_iface = iface {
243 mi_decls = panic "No mi_decls in PIT",
244 mi_insts = panic "No mi_insts in PIT",
245 mi_fam_insts = panic "No mi_fam_insts in PIT",
246 mi_rules = panic "No mi_rules in PIT"
249 ; updateEps_ $ \ eps ->
251 eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
252 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
253 eps_rule_base = extendRuleBaseList (eps_rule_base eps)
255 eps_inst_env = extendInstEnvList (eps_inst_env eps)
257 eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
262 extendFamInstEnvList emptyFamInstEnv
265 extendModuleEnv (eps_mod_fam_inst_env eps)
268 eps_stats = addEpsInStats (eps_stats eps)
269 (length new_eps_decls)
270 (length new_eps_insts) (length new_eps_rules) }
272 ; return (Succeeded final_iface)
276 = hang (ptext SLIT("Interface file inconsistency:"))
277 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned is needed,"),
278 ptext SLIT("but is not among the dependencies of interfaces directly imported by the module being compiled")])
280 -----------------------------------------------------
281 -- Loading type/class/value decls
282 -- We pass the full Module name here, replete with
283 -- its package info, so that we can build a Name for
284 -- each binder with the right package info in it
285 -- All subsequent lookups, including crucially lookups during typechecking
286 -- the declaration itself, will find the fully-glorious Name
288 -- We handle ATs specially. They are not main declarations, but also not
289 -- implict things (in particular, adding them to `implicitTyThings' would mess
290 -- things up in the renaming/type checking of source programs).
291 -----------------------------------------------------
293 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
294 addDeclsToPTE pte things = extendNameEnvList pte things
297 -> [(Version, IfaceDecl)]
298 -> IfL [(Name,TyThing)]
299 loadDecls ignore_prags ver_decls
300 = do { mod <- getIfModule
301 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
302 ; return (concat thingss)
305 loadDecl :: Bool -- Don't load pragmas into the decl pool
307 -> (Version, IfaceDecl)
308 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
309 -- TyThings are forkM'd thunks
310 loadDecl ignore_prags mod (_version, decl)
311 = do { -- Populate the name cache with final versions of all
312 -- the names associated with the decl
313 main_name <- mk_new_bndr mod (ifName decl)
314 -- ; traceIf (text "Loading decl for " <> ppr main_name)
315 ; implicit_names <- mapM (mk_new_bndr mod) (ifaceDeclSubBndrs decl)
317 -- Typecheck the thing, lazily
318 -- NB. Firstly, the laziness is there in case we never need the
319 -- declaration (in one-shot mode), and secondly it is there so that
320 -- we don't look up the occurrence of a name before calling mk_new_bndr
321 -- on the binder. This is important because we must get the right name
322 -- which includes its nameParent.
324 ; thing <- forkM doc $ do { bumpDeclStats main_name
325 ; tcIfaceDecl ignore_prags decl }
327 -- Populate the type environment with the implicitTyThings too.
329 -- Note [Tricky iface loop]
330 -- ~~~~~~~~~~~~~~~~~~~~~~~~
331 -- The delicate point here is that 'mini-env' should be
332 -- buildable from 'thing' without demanding any of the things 'forkM'd
333 -- by tcIfaceDecl. For example
334 -- class C a where { data T a; op :: T a -> Int }
335 -- We return the bindings
336 -- [("C", <cls>), ("T", lookup env "T"), ("op", lookup env "op")]
337 -- The call (lookup env "T") must return the tycon T without first demanding
338 -- op; because getting the latter will look up T, hence loop.
340 -- Of course, there is no reason in principle why (lookup env "T") should demand
341 -- anything do to with op, but take care:
342 -- (a) implicitTyThings, and
343 -- (b) getOccName of all the things returned by implicitThings,
344 -- must not depend on any of the nested type-checks
346 -- All a bit too finely-balanced for my liking.
348 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
349 lookup n = case lookupOccEnv mini_env (getOccName n) of
352 pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
354 ; returnM $ (main_name, thing) : [(n, lookup n) | n <- implicit_names]
356 -- We build a list from the *known* names, with (lookup n) thunks
357 -- as the TyThings. That way we can extend the PTE without poking the
360 -- mk_new_bndr allocates in the name cache the final canonical
361 -- name for the thing, with the correct
364 -- imported name, to fix the module correctly in the cache
366 = newGlobalBinder mod occ
367 (importedSrcLoc (showSDoc (ppr (moduleName mod))))
368 -- ToDo: qualify with the package name if necessary
370 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
372 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
374 = do { traceIf (text "Loading decl for" <+> ppr name)
375 ; updateEps_ (\eps -> let stats = eps_stats eps
376 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
381 %*********************************************************
383 \subsection{Reading an interface file}
385 %*********************************************************
388 findAndReadIface :: SDoc -> Module
389 -> IsBootInterface -- True <=> Look for a .hi-boot file
390 -- False <=> Look for .hi file
391 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
392 -- Nothing <=> file not found, or unreadable, or illegible
393 -- Just x <=> successfully found and parsed
395 -- It *doesn't* add an error to the monad, because
396 -- sometimes it's ok to fail... see notes with loadInterface
398 findAndReadIface doc_str mod hi_boot_file
399 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
401 then ptext SLIT("[boot]")
403 ptext SLIT("interface for"),
405 nest 4 (ptext SLIT("reason:") <+> doc_str)])
407 -- Check for GHC.Prim, and return its static interface
410 then returnM (Succeeded (ghcPrimIface,
411 "<built in interface for GHC.Prim>"))
415 ; hsc_env <- getTopEnv
416 ; mb_found <- ioToIOEnv (findExactModule hsc_env mod)
419 err | notFound err -> do
420 { traceIf (ptext SLIT("...not found"))
422 ; returnM (Failed (cannotFindInterface dflags
423 (moduleName mod) err)) } ;
426 -- Found file, so read it
427 { let { file_path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc) }
429 ; if thisPackage dflags == modulePackageId mod
430 && not (isOneShot (ghcMode dflags))
431 then returnM (Failed (homeModError mod loc))
434 ; traceIf (ptext SLIT("readIFace") <+> text file_path)
435 ; read_result <- readIface mod file_path hi_boot_file
436 ; case read_result of
437 Failed err -> returnM (Failed (badIfaceFile file_path err))
439 | mi_module iface /= mod ->
440 return (Failed (wrongIfaceModErr iface mod file_path))
442 returnM (Succeeded (iface, file_path))
443 -- Don't forget to fill in the package name...
446 notFound (Found _ _) = False
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
460 ; res <- tryMostM $ readBinIface file_path
463 | wanted_mod == actual_mod -> return (Succeeded iface)
464 | otherwise -> return (Failed err)
466 actual_mod = mi_module iface
467 err = hiModuleNameMismatchWarn wanted_mod actual_mod
469 Left exn -> return (Failed (text (showException exn)))
474 %*********************************************************
476 Wired-in interface for GHC.Prim
478 %*********************************************************
481 initExternalPackageState :: ExternalPackageState
482 initExternalPackageState
484 eps_is_boot = emptyUFM,
485 eps_PIT = emptyPackageIfaceTable,
486 eps_PTE = emptyTypeEnv,
487 eps_inst_env = emptyInstEnv,
488 eps_fam_inst_env = emptyFamInstEnv,
489 eps_rule_base = mkRuleBase builtinRules,
490 -- Initialise the EPS rule pool with the built-in rules
493 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
494 , n_insts_in = 0, n_insts_out = 0
495 , n_rules_in = length builtinRules, n_rules_out = 0 }
500 %*********************************************************
502 Wired-in interface for GHC.Prim
504 %*********************************************************
507 ghcPrimIface :: ModIface
509 = (emptyModIface gHC_PRIM) {
510 mi_exports = [(gHC_PRIM, ghcPrimExports)],
512 mi_fixities = fixities,
513 mi_fix_fn = mkIfaceFixCache fixities
516 fixities = [(getOccName seqId, Fixity 0 InfixR)]
520 %*********************************************************
522 \subsection{Statistics}
524 %*********************************************************
527 ifaceStats :: ExternalPackageState -> SDoc
529 = hcat [text "Renamer stats: ", msg]
531 stats = eps_stats eps
533 [int (n_ifaces_in stats) <+> text "interfaces read",
534 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
535 int (n_decls_in stats), text "read"],
536 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
537 int (n_insts_in stats), text "read"],
538 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
539 int (n_rules_in stats), text "read"]
544 %************************************************************************
548 %************************************************************************
551 -- | Read binary interface, and print it out
552 showIface :: HscEnv -> FilePath -> IO ()
553 showIface hsc_env filename = do
554 -- skip the version check; we don't want to worry about profiled vs.
555 -- non-profiled interfaces, for example.
556 writeIORef v_IgnoreHiWay True
557 iface <- initTcRnIf 's' hsc_env () () $ readBinIface filename
558 printDump (pprModIface iface)
562 pprModIface :: ModIface -> SDoc
565 = vcat [ ptext SLIT("interface")
566 <+> ppr (mi_module iface) <+> pp_boot
567 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
568 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
569 <+> (if mi_finsts iface then ptext SLIT("[family instance module]") else empty)
570 <+> integer opt_HiVersion
571 <+> ptext SLIT("where")
572 , vcat (map pprExport (mi_exports iface))
573 , pprDeps (mi_deps iface)
574 , vcat (map pprUsage (mi_usages iface))
575 , pprFixities (mi_fixities iface)
576 , vcat (map pprIfaceDecl (mi_decls iface))
577 , vcat (map ppr (mi_insts iface))
578 , vcat (map ppr (mi_fam_insts iface))
579 , vcat (map ppr (mi_rules iface))
580 , pprDeprecs (mi_deprecs iface)
583 pp_boot | mi_boot iface = ptext SLIT("[boot]")
586 exp_vers = mi_exp_vers iface
587 rule_vers = mi_rule_vers iface
589 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
590 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
593 When printing export lists, we print like this:
595 AvailTC C [C, x, y] C(x,y)
596 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
599 pprExport :: IfaceExport -> SDoc
600 pprExport (mod, items)
601 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
603 pp_avail :: GenAvailInfo OccName -> SDoc
604 pp_avail (Avail occ) = ppr occ
605 pp_avail (AvailTC _ []) = empty
606 pp_avail (AvailTC n (n':ns))
607 | n==n' = ppr n <> pp_export ns
608 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
611 pp_export names = braces (hsep (map ppr names))
613 pprUsage :: Usage -> SDoc
615 = hsep [ptext SLIT("import"), ppr (usg_name usage),
617 pp_export_version (usg_exports usage),
618 int (usg_rules usage),
619 pp_versions (usg_entities usage) ]
621 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
622 pp_export_version Nothing = empty
623 pp_export_version (Just v) = int v
625 pprDeps :: Dependencies -> SDoc
626 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs,
627 dep_finsts = finsts })
628 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
629 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
630 ptext SLIT("orphans:") <+> fsep (map ppr orphs),
631 ptext SLIT("family instance modules:") <+> fsep (map ppr finsts)
634 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
635 ppr_boot True = text "[boot]"
636 ppr_boot False = empty
638 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
639 pprIfaceDecl (ver, decl)
640 = ppr_vers ver <+> ppr decl
642 -- Print the version for the decl
643 ppr_vers v | v == initialVersion = empty
646 pprFixities :: [(OccName, Fixity)] -> SDoc
647 pprFixities [] = empty
648 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
650 pprFix (occ,fix) = ppr fix <+> ppr occ
652 pprDeprecs NoDeprecs = empty
653 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
654 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
656 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
660 %*********************************************************
664 %*********************************************************
667 badIfaceFile file err
668 = vcat [ptext SLIT("Bad interface file:") <+> text file,
671 hiModuleNameMismatchWarn :: Module -> Module -> Message
672 hiModuleNameMismatchWarn requested_mod read_mod =
673 withPprStyle defaultUserStyle $
674 -- we want the Modules below to be qualified with package names,
675 -- so reset the PrintUnqualified setting.
676 hsep [ ptext SLIT("Something is amiss; requested module ")
678 , ptext SLIT("differs from name found in the interface file")
682 wrongIfaceModErr iface mod_name file_path
683 = sep [ptext SLIT("Interface file") <+> iface_file,
684 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
685 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
686 sep [ptext SLIT("Probable cause: the source code which generated"),
688 ptext SLIT("has an incompatible module name")
691 where iface_file = doubleQuotes (text file_path)
693 homeModError mod location
694 = ptext SLIT("attempting to use module ") <> quotes (ppr mod)
695 <> (case ml_hs_file location of
696 Just file -> space <> parens (text file)
698 <+> ptext SLIT("which is not loaded")