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(..))
55 import Control.Monad (when)
62 %************************************************************************
64 loadSrcInterface, loadOrphanModules, loadHomeInterface
66 These three are called from TcM-land
68 %************************************************************************
71 -- | Load the interface corresponding to an @import@ directive in
72 -- source code. On a failure, fail in the monad with an error message.
73 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
74 loadSrcInterface doc mod want_boot = do
75 -- We must first find which Module this import refers to. This involves
76 -- calling the Finder, which as a side effect will search the filesystem
77 -- and create a ModLocation. If successful, loadIface will read the
78 -- interface; it will call the Finder again, but the ModLocation will be
79 -- cached from the first search.
81 res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
84 mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
86 Failed err -> failWithTc err
87 Succeeded iface -> return iface
89 let dflags = hsc_dflags hsc_env in
90 failWithTc (cannotFindInterface dflags mod err)
92 -- | Load interfaces for a collection of orphan modules.
93 loadOrphanModules :: [Module] -- the modules
94 -> Bool -- these are family instance-modules
96 loadOrphanModules mods isFamInstMod
97 | null mods = returnM ()
98 | otherwise = initIfaceTcRn $
99 do { traceIf (text "Loading orphan modules:" <+>
104 load mod = loadSysInterface (mk_doc mod) mod
106 | isFamInstMod = ppr mod <+> ptext SLIT("is a family-instance module")
107 | otherwise = ppr mod <+> ptext SLIT("is a orphan-instance module")
109 -- | Loads the interface for a given Name.
110 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
111 loadInterfaceForName doc name
114 -- Should not be called with a name from the module being compiled
115 this_mod <- getModule
116 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
118 initIfaceTcRn $ loadSysInterface doc (nameModule name)
121 -- | An 'IfM' function to load the home interface for a wired-in thing,
122 -- so that we're sure that we see its instance declarations and rules
123 loadWiredInHomeIface :: Name -> IfM lcl ()
124 loadWiredInHomeIface name
125 = ASSERT( isWiredInName name )
126 do loadSysInterface doc (nameModule name); return ()
128 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
130 -- | A wrapper for 'loadInterface' that throws an exception if it fails
131 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
132 loadSysInterface doc mod_name
133 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
135 Failed err -> ghcError (ProgramError (showSDoc err))
136 Succeeded iface -> return iface }
140 %*********************************************************
144 The main function to load an interface
145 for an imported module, and put it in
146 the External Package State
148 %*********************************************************
151 loadInterface :: SDoc -> Module -> WhereFrom
152 -> IfM lcl (MaybeErr Message ModIface)
154 -- loadInterface looks in both the HPT and PIT for the required interface
155 -- If not found, it loads it, and puts it in the PIT (always).
157 -- If it can't find a suitable interface file, we
158 -- a) modify the PackageIfaceTable to have an empty entry
159 -- (to avoid repeated complaints)
160 -- b) return (Left message)
162 -- It's not necessarily an error for there not to be an interface
163 -- file -- perhaps the module has changed, and that interface
166 loadInterface doc_str mod from
167 = do { -- Read the state
168 (eps,hpt) <- getEpsAndHpt
170 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
172 -- Check whether we have the interface already
174 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
176 -> returnM (Succeeded iface) ; -- Already loaded
177 -- The (src_imp == mi_boot iface) test checks that the already-loaded
178 -- interface isn't a boot iface. This can conceivably happen,
179 -- if an earlier import had a before we got to real imports. I think.
182 let { hi_boot_file = case from of
183 ImportByUser usr_boot -> usr_boot
184 ImportBySystem -> sys_boot
186 ; mb_dep = lookupUFM (eps_is_boot eps) (moduleName mod)
187 ; sys_boot = case mb_dep of
188 Just (_, is_boot) -> is_boot
190 -- The boot-ness of the requested interface,
191 } -- based on the dependencies in directly-imported modules
193 -- READ THE MODULE IN
194 ; read_result <- findAndReadIface doc_str mod hi_boot_file
195 ; case read_result of {
197 { let fake_iface = emptyModIface mod
199 ; updateEps_ $ \eps ->
200 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
201 -- Not found, so add an empty iface to
202 -- the EPS map so that we don't look again
204 ; returnM (Failed err) } ;
207 Succeeded (iface, file_path) -- Sanity check:
208 | ImportBySystem <- from, -- system-importing...
209 modulePackageId (mi_module iface) == thisPackage dflags,
210 -- a home-package module...
211 Nothing <- mb_dep -- that we know nothing about
212 -> returnM (Failed (badDepMsg mod))
217 loc_doc = text file_path
219 initIfaceLcl mod loc_doc $ do
221 -- Load the new ModIface into the External Package State
222 -- Even home-package interfaces loaded by loadInterface
223 -- (which only happens in OneShot mode; in Batch/Interactive
224 -- mode, home-package modules are loaded one by one into the HPT)
225 -- are put in the EPS.
227 -- The main thing is to add the ModIface to the PIT, but
229 -- IfaceDecls, IfaceInst, IfaceFamInst, IfaceRules, IfaceVectInfo
230 -- out of the ModIface and put them into the big EPS pools
232 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
233 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
234 -- If we do loadExport first the wrong info gets into the cache (unless we
235 -- explicitly tag each export which seems a bit of a bore)
237 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
238 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
239 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
240 ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
241 ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
243 ; let { final_iface = iface {
244 mi_decls = panic "No mi_decls in PIT",
245 mi_insts = panic "No mi_insts in PIT",
246 mi_fam_insts = panic "No mi_fam_insts in PIT",
247 mi_rules = panic "No mi_rules in PIT"
249 ; new_eps_vect_info =
251 vectInfoCCVar = mkNameSet
252 (ifaceVectInfoCCVar . mi_vect_info $ iface)
256 ; updateEps_ $ \ eps ->
258 eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
259 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
260 eps_rule_base = extendRuleBaseList (eps_rule_base eps)
262 eps_inst_env = extendInstEnvList (eps_inst_env eps)
264 eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
266 eps_vect_info = plusVectInfo (eps_vect_info eps)
271 extendFamInstEnvList emptyFamInstEnv
274 extendModuleEnv (eps_mod_fam_inst_env eps)
277 eps_stats = addEpsInStats (eps_stats eps)
278 (length new_eps_decls)
279 (length new_eps_insts) (length new_eps_rules) }
281 ; return (Succeeded final_iface)
285 = hang (ptext SLIT("Interface file inconsistency:"))
286 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned is needed,"),
287 ptext SLIT("but is not among the dependencies of interfaces directly imported by the module being compiled")])
289 -----------------------------------------------------
290 -- Loading type/class/value decls
291 -- We pass the full Module name here, replete with
292 -- its package info, so that we can build a Name for
293 -- each binder with the right package info in it
294 -- All subsequent lookups, including crucially lookups during typechecking
295 -- the declaration itself, will find the fully-glorious Name
297 -- We handle ATs specially. They are not main declarations, but also not
298 -- implict things (in particular, adding them to `implicitTyThings' would mess
299 -- things up in the renaming/type checking of source programs).
300 -----------------------------------------------------
302 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
303 addDeclsToPTE pte things = extendNameEnvList pte things
306 -> [(Version, IfaceDecl)]
307 -> IfL [(Name,TyThing)]
308 loadDecls ignore_prags ver_decls
309 = do { mod <- getIfModule
310 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
311 ; return (concat thingss)
314 loadDecl :: Bool -- Don't load pragmas into the decl pool
316 -> (Version, IfaceDecl)
317 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
318 -- TyThings are forkM'd thunks
319 loadDecl ignore_prags mod (_version, decl)
320 = do { -- Populate the name cache with final versions of all
321 -- the names associated with the decl
322 main_name <- mk_new_bndr mod (ifName decl)
323 -- ; traceIf (text "Loading decl for " <> ppr main_name)
324 ; implicit_names <- mapM (mk_new_bndr mod) (ifaceDeclSubBndrs decl)
326 -- Typecheck the thing, lazily
327 -- NB. Firstly, the laziness is there in case we never need the
328 -- declaration (in one-shot mode), and secondly it is there so that
329 -- we don't look up the occurrence of a name before calling mk_new_bndr
330 -- on the binder. This is important because we must get the right name
331 -- which includes its nameParent.
333 ; thing <- forkM doc $ do { bumpDeclStats main_name
334 ; tcIfaceDecl ignore_prags decl }
336 -- Populate the type environment with the implicitTyThings too.
338 -- Note [Tricky iface loop]
339 -- ~~~~~~~~~~~~~~~~~~~~~~~~
340 -- The delicate point here is that 'mini-env' should be
341 -- buildable from 'thing' without demanding any of the things 'forkM'd
342 -- by tcIfaceDecl. For example
343 -- class C a where { data T a; op :: T a -> Int }
344 -- We return the bindings
345 -- [("C", <cls>), ("T", lookup env "T"), ("op", lookup env "op")]
346 -- The call (lookup env "T") must return the tycon T without first demanding
347 -- op; because getting the latter will look up T, hence loop.
349 -- Of course, there is no reason in principle why (lookup env "T") should demand
350 -- anything do to with op, but take care:
351 -- (a) implicitTyThings, and
352 -- (b) getOccName of all the things returned by implicitThings,
353 -- must not depend on any of the nested type-checks
355 -- All a bit too finely-balanced for my liking.
357 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
358 lookup n = case lookupOccEnv mini_env (getOccName n) of
361 pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
363 ; returnM $ (main_name, thing) : [(n, lookup n) | n <- implicit_names]
365 -- We build a list from the *known* names, with (lookup n) thunks
366 -- as the TyThings. That way we can extend the PTE without poking the
369 -- mk_new_bndr allocates in the name cache the final canonical
370 -- name for the thing, with the correct
373 -- imported name, to fix the module correctly in the cache
375 = newGlobalBinder mod occ
376 (importedSrcLoc (showSDoc (ppr (moduleName mod))))
377 -- ToDo: qualify with the package name if necessary
379 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
381 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
383 = do { traceIf (text "Loading decl for" <+> ppr name)
384 ; updateEps_ (\eps -> let stats = eps_stats eps
385 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
390 %*********************************************************
392 \subsection{Reading an interface file}
394 %*********************************************************
397 findAndReadIface :: SDoc -> Module
398 -> IsBootInterface -- True <=> Look for a .hi-boot file
399 -- False <=> Look for .hi file
400 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
401 -- Nothing <=> file not found, or unreadable, or illegible
402 -- Just x <=> successfully found and parsed
404 -- It *doesn't* add an error to the monad, because
405 -- sometimes it's ok to fail... see notes with loadInterface
407 findAndReadIface doc_str mod hi_boot_file
408 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
410 then ptext SLIT("[boot]")
412 ptext SLIT("interface for"),
414 nest 4 (ptext SLIT("reason:") <+> doc_str)])
416 -- Check for GHC.Prim, and return its static interface
419 then returnM (Succeeded (ghcPrimIface,
420 "<built in interface for GHC.Prim>"))
424 ; hsc_env <- getTopEnv
425 ; mb_found <- ioToIOEnv (findExactModule hsc_env mod)
428 err | notFound err -> do
429 { traceIf (ptext SLIT("...not found"))
431 ; returnM (Failed (cannotFindInterface dflags
432 (moduleName mod) err)) } ;
435 -- Found file, so read it
436 { let { file_path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc) }
438 ; if thisPackage dflags == modulePackageId mod
439 && not (isOneShot (ghcMode dflags))
440 then returnM (Failed (homeModError mod loc))
443 ; traceIf (ptext SLIT("readIFace") <+> text file_path)
444 ; read_result <- readIface mod file_path hi_boot_file
445 ; case read_result of
446 Failed err -> returnM (Failed (badIfaceFile file_path err))
448 | mi_module iface /= mod ->
449 return (Failed (wrongIfaceModErr iface mod file_path))
451 returnM (Succeeded (iface, file_path))
452 -- Don't forget to fill in the package name...
455 notFound (Found _ _) = False
459 @readIface@ tries just the one file.
462 readIface :: Module -> FilePath -> IsBootInterface
463 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
464 -- Failed err <=> file not found, or unreadable, or illegible
465 -- Succeeded iface <=> successfully found and parsed
467 readIface wanted_mod file_path is_hi_boot_file
468 = do { dflags <- getDOpts
469 ; res <- tryMostM $ readBinIface file_path
472 | wanted_mod == actual_mod -> return (Succeeded iface)
473 | otherwise -> return (Failed err)
475 actual_mod = mi_module iface
476 err = hiModuleNameMismatchWarn wanted_mod actual_mod
478 Left exn -> return (Failed (text (showException exn)))
483 %*********************************************************
485 Wired-in interface for GHC.Prim
487 %*********************************************************
490 initExternalPackageState :: ExternalPackageState
491 initExternalPackageState
493 eps_is_boot = emptyUFM,
494 eps_PIT = emptyPackageIfaceTable,
495 eps_PTE = emptyTypeEnv,
496 eps_inst_env = emptyInstEnv,
497 eps_fam_inst_env = emptyFamInstEnv,
498 eps_rule_base = mkRuleBase builtinRules,
499 -- Initialise the EPS rule pool with the built-in rules
502 eps_vect_info = noVectInfo,
503 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
504 , n_insts_in = 0, n_insts_out = 0
505 , n_rules_in = length builtinRules, n_rules_out = 0 }
510 %*********************************************************
512 Wired-in interface for GHC.Prim
514 %*********************************************************
517 ghcPrimIface :: ModIface
519 = (emptyModIface gHC_PRIM) {
520 mi_exports = [(gHC_PRIM, ghcPrimExports)],
522 mi_fixities = fixities,
523 mi_fix_fn = mkIfaceFixCache fixities
526 fixities = [(getOccName seqId, Fixity 0 InfixR)]
530 %*********************************************************
532 \subsection{Statistics}
534 %*********************************************************
537 ifaceStats :: ExternalPackageState -> SDoc
539 = hcat [text "Renamer stats: ", msg]
541 stats = eps_stats eps
543 [int (n_ifaces_in stats) <+> text "interfaces read",
544 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
545 int (n_decls_in stats), text "read"],
546 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
547 int (n_insts_in stats), text "read"],
548 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
549 int (n_rules_in stats), text "read"]
554 %************************************************************************
558 %************************************************************************
561 -- | Read binary interface, and print it out
562 showIface :: HscEnv -> FilePath -> IO ()
563 showIface hsc_env filename = do
564 -- skip the version check; we don't want to worry about profiled vs.
565 -- non-profiled interfaces, for example.
566 writeIORef v_IgnoreHiWay True
567 iface <- initTcRnIf 's' hsc_env () () $ readBinIface filename
568 printDump (pprModIface iface)
572 pprModIface :: ModIface -> SDoc
575 = vcat [ ptext SLIT("interface")
576 <+> ppr (mi_module iface) <+> pp_boot
577 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
578 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
579 <+> (if mi_finsts iface then ptext SLIT("[family instance module]") else empty)
580 <+> integer opt_HiVersion
581 <+> ptext SLIT("where")
582 , vcat (map pprExport (mi_exports iface))
583 , pprDeps (mi_deps iface)
584 , vcat (map pprUsage (mi_usages iface))
585 , pprFixities (mi_fixities iface)
586 , vcat (map pprIfaceDecl (mi_decls iface))
587 , vcat (map ppr (mi_insts iface))
588 , vcat (map ppr (mi_fam_insts iface))
589 , vcat (map ppr (mi_rules iface))
590 , pprDeprecs (mi_deprecs iface)
593 pp_boot | mi_boot iface = ptext SLIT("[boot]")
596 exp_vers = mi_exp_vers iface
597 rule_vers = mi_rule_vers iface
599 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
600 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
603 When printing export lists, we print like this:
605 AvailTC C [C, x, y] C(x,y)
606 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
609 pprExport :: IfaceExport -> SDoc
610 pprExport (mod, items)
611 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
613 pp_avail :: GenAvailInfo OccName -> SDoc
614 pp_avail (Avail occ) = ppr occ
615 pp_avail (AvailTC _ []) = empty
616 pp_avail (AvailTC n (n':ns))
617 | n==n' = ppr n <> pp_export ns
618 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
621 pp_export names = braces (hsep (map ppr names))
623 pprUsage :: Usage -> SDoc
625 = hsep [ptext SLIT("import"), ppr (usg_name usage),
627 pp_export_version (usg_exports usage),
628 int (usg_rules usage),
629 pp_versions (usg_entities usage) ]
631 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
632 pp_export_version Nothing = empty
633 pp_export_version (Just v) = int v
635 pprDeps :: Dependencies -> SDoc
636 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs,
637 dep_finsts = finsts })
638 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
639 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
640 ptext SLIT("orphans:") <+> fsep (map ppr orphs),
641 ptext SLIT("family instance modules:") <+> fsep (map ppr finsts)
644 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
645 ppr_boot True = text "[boot]"
646 ppr_boot False = empty
648 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
649 pprIfaceDecl (ver, decl)
650 = ppr_vers ver <+> ppr decl
652 -- Print the version for the decl
653 ppr_vers v | v == initialVersion = empty
656 pprFixities :: [(OccName, Fixity)] -> SDoc
657 pprFixities [] = empty
658 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
660 pprFix (occ,fix) = ppr fix <+> ppr occ
662 pprDeprecs NoDeprecs = empty
663 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
664 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
666 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
670 %*********************************************************
674 %*********************************************************
677 badIfaceFile file err
678 = vcat [ptext SLIT("Bad interface file:") <+> text file,
681 hiModuleNameMismatchWarn :: Module -> Module -> Message
682 hiModuleNameMismatchWarn requested_mod read_mod =
683 withPprStyle defaultUserStyle $
684 -- we want the Modules below to be qualified with package names,
685 -- so reset the PrintUnqualified setting.
686 hsep [ ptext SLIT("Something is amiss; requested module ")
688 , ptext SLIT("differs from name found in the interface file")
692 wrongIfaceModErr iface mod_name file_path
693 = sep [ptext SLIT("Interface file") <+> iface_file,
694 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
695 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
696 sep [ptext SLIT("Probable cause: the source code which generated"),
698 ptext SLIT("has an incompatible module name")
701 where iface_file = doubleQuotes (text file_path)
703 homeModError mod location
704 = ptext SLIT("attempting to use module ") <> quotes (ppr mod)
705 <> (case ml_hs_file location of
706 Just file -> space <> parens (text file)
708 <+> ptext SLIT("which is not loaded")