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, -- Should move to TcIface and be renamed
12 initExternalPackageState,
14 ifaceStats, pprModIface, showIface
17 #include "HsVersions.h"
19 import {-# SOURCE #-} TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst,
22 import DynFlags ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ) )
24 import IfaceEnv ( newGlobalBinder )
25 import HscTypes ( ModIface(..), TyThing, IfaceExport, Usage(..),
26 Deprecs(..), Dependencies(..),
27 emptyModIface, EpsStats(..), GenAvailInfo(..),
28 addEpsInStats, ExternalPackageState(..),
29 PackageTypeEnv, emptyTypeEnv, HscEnv(..),
30 lookupIfaceByModule, emptyPackageIfaceTable,
31 IsBootInterface, mkIfaceFixCache,
35 import BasicTypes ( Version, initialVersion,
36 Fixity(..), FixityDirection(..), isMarkedStrict )
38 import Type ( TyThing(..) )
40 import PrelNames ( gHC_PRIM )
41 import PrelInfo ( ghcPrimExports )
42 import PrelRules ( builtinRules )
43 import Rules ( extendRuleBaseList, mkRuleBase )
44 import InstEnv ( emptyInstEnv, extendInstEnvList )
45 import FamInstEnv ( emptyFamInstEnv, extendFamInstEnvList )
46 import Name ( Name {-instance NamedThing-}, getOccName,
47 nameModule, nameIsLocalOrFrom, isWiredInName )
51 import OccName ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc,
52 mkClassDataConOcc, mkSuperDictSelOcc,
53 mkDataConWrapperOcc, mkDataConWorkerOcc,
54 mkNewTyCoOcc, mkInstTyCoOcc )
55 import SrcLoc ( importedSrcLoc )
56 import Maybes ( MaybeErr(..) )
57 import ErrUtils ( Message )
58 import Finder ( findImportedModule, findExactModule,
59 FindResult(..), cannotFindInterface )
61 import StaticFlags ( opt_HiVersion )
63 import BinIface ( readBinIface, v_IgnoreHiWay )
65 import Panic ( ghcError, showException, GhcException(..) )
67 import Maybe ( isJust )
68 import DATA_IOREF ( writeIORef )
72 %************************************************************************
74 loadSrcInterface, loadOrphanModules, loadHomeInterface
76 These three are called from TcM-land
78 %************************************************************************
81 -- | Load the interface corresponding to an @import@ directive in
82 -- source code. On a failure, fail in the monad with an error message.
83 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
84 loadSrcInterface doc mod want_boot = do
85 -- We must first find which Module this import refers to. This involves
86 -- calling the Finder, which as a side effect will search the filesystem
87 -- and create a ModLocation. If successful, loadIface will read the
88 -- interface; it will call the Finder again, but the ModLocation will be
89 -- cached from the first search.
91 res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
94 mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
96 Failed err -> failWithTc err
97 Succeeded iface -> return iface
99 let dflags = hsc_dflags hsc_env in
100 failWithTc (cannotFindInterface dflags mod err)
102 -- | Load interfaces for a collection of orphan modules.
103 loadOrphanModules :: [Module] -> TcM ()
104 loadOrphanModules mods
105 | null mods = returnM ()
106 | otherwise = initIfaceTcRn $
107 do { traceIf (text "Loading orphan modules:" <+>
112 load mod = loadSysInterface (mk_doc mod) mod
113 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
115 -- | Loads the interface for a given Name.
116 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
117 loadInterfaceForName doc name
120 -- Should not be called with a name from the module being compiled
121 this_mod <- getModule
122 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
124 initIfaceTcRn $ loadSysInterface doc (nameModule name)
127 -- | An 'IfM' function to load the home interface for a wired-in thing,
128 -- so that we're sure that we see its instance declarations and rules
129 loadWiredInHomeIface :: Name -> IfM lcl ()
130 loadWiredInHomeIface name
131 = ASSERT( isWiredInName name )
132 do loadSysInterface doc (nameModule name); return ()
134 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
136 -- | A wrapper for 'loadInterface' that throws an exception if it fails
137 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
138 loadSysInterface doc mod_name
139 = do { mb_iface <- loadInterface doc mod_name ImportBySystem
141 Failed err -> ghcError (ProgramError (showSDoc err))
142 Succeeded iface -> return iface }
146 %*********************************************************
150 The main function to load an interface
151 for an imported module, and put it in
152 the External Package State
154 %*********************************************************
157 loadInterface :: SDoc -> Module -> WhereFrom
158 -> IfM lcl (MaybeErr Message ModIface)
160 -- loadInterface looks in both the HPT and PIT for the required interface
161 -- If not found, it loads it, and puts it in the PIT (always).
163 -- If it can't find a suitable interface file, we
164 -- a) modify the PackageIfaceTable to have an empty entry
165 -- (to avoid repeated complaints)
166 -- b) return (Left message)
168 -- It's not necessarily an error for there not to be an interface
169 -- file -- perhaps the module has changed, and that interface
172 loadInterface doc_str mod from
173 = do { -- Read the state
174 (eps,hpt) <- getEpsAndHpt
176 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
178 -- Check whether we have the interface already
180 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
182 -> returnM (Succeeded iface) ; -- Already loaded
183 -- The (src_imp == mi_boot iface) test checks that the already-loaded
184 -- interface isn't a boot iface. This can conceivably happen,
185 -- if an earlier import had a before we got to real imports. I think.
188 { let { hi_boot_file = case from of
189 ImportByUser usr_boot -> usr_boot
190 ImportBySystem -> sys_boot
192 ; mb_dep = lookupUFM (eps_is_boot eps) (moduleName mod)
193 ; sys_boot = case mb_dep of
194 Just (_, is_boot) -> is_boot
196 -- The boot-ness of the requested interface,
197 } -- based on the dependencies in directly-imported modules
199 -- READ THE MODULE IN
200 ; read_result <- findAndReadIface doc_str mod hi_boot_file
201 ; case read_result of {
203 { let fake_iface = emptyModIface mod
205 ; updateEps_ $ \eps ->
206 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
207 -- Not found, so add an empty iface to
208 -- the EPS map so that we don't look again
210 ; returnM (Failed err) } ;
213 Succeeded (iface, file_path) -- Sanity check:
214 | ImportBySystem <- from, -- system-importing...
215 modulePackageId (mi_module iface) == thisPackage dflags,
216 -- a home-package module...
217 Nothing <- mb_dep -- that we know nothing about
218 -> returnM (Failed (badDepMsg mod))
223 loc_doc = text file_path
225 initIfaceLcl mod loc_doc $ do
227 -- Load the new ModIface into the External Package State
228 -- Even home-package interfaces loaded by loadInterface
229 -- (which only happens in OneShot mode; in Batch/Interactive
230 -- mode, home-package modules are loaded one by one into the HPT)
231 -- are put in the EPS.
233 -- The main thing is to add the ModIface to the PIT, but
235 -- IfaceDecls, IfaceInst, IfaceRules
236 -- out of the ModIface and put them into the big EPS pools
238 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
239 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
240 -- If we do loadExport first the wrong info gets into the cache (unless we
241 -- explicitly tag each export which seems a bit of a bore)
243 ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
244 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
245 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
246 ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
247 ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
249 ; let { final_iface = iface { mi_decls = panic "No mi_decls in PIT",
250 mi_insts = panic "No mi_insts in PIT",
251 mi_rules = panic "No mi_rules in PIT" } }
253 ; updateEps_ $ \ eps ->
255 eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
256 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
257 eps_rule_base = extendRuleBaseList (eps_rule_base eps)
259 eps_inst_env = extendInstEnvList (eps_inst_env eps)
261 eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
263 eps_stats = addEpsInStats (eps_stats eps)
264 (length new_eps_decls)
265 (length new_eps_insts) (length new_eps_rules) }
267 ; return (Succeeded final_iface)
271 = hang (ptext SLIT("Interface file inconsistency:"))
272 2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned is needed,"),
273 ptext SLIT("but is not among the dependencies of interfaces directly imported by the module being compiled")])
275 -----------------------------------------------------
276 -- Loading type/class/value decls
277 -- We pass the full Module name here, replete with
278 -- its package info, so that we can build a Name for
279 -- each binder with the right package info in it
280 -- All subsequent lookups, including crucially lookups during typechecking
281 -- the declaration itself, will find the fully-glorious Name
283 -- We handle ATs specially. They are not main declarations, but also not
284 -- implict things (in particular, adding them to `implicitTyThings' would mess
285 -- things up in the renaming/type checking of source programs).
286 -----------------------------------------------------
288 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
289 addDeclsToPTE pte things = extendNameEnvList pte things
292 -> [(Version, IfaceDecl)]
293 -> IfL [(Name,TyThing)]
294 loadDecls ignore_prags ver_decls
295 = do { mod <- getIfModule
296 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
297 ; return (concat thingss)
300 loadDecl :: Bool -- Don't load pragmas into the decl pool
302 -> (Version, IfaceDecl)
303 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
304 -- TyThings are forkM'd thunks
305 loadDecl ignore_prags mod (_version, decl)
306 = do { -- Populate the name cache with final versions of all
307 -- the names associated with the decl
308 main_name <- mk_new_bndr mod (ifName decl)
309 ; traceIf (text "Loading decl for " <> ppr main_name)
310 ; implicit_names <- mapM (mk_new_bndr mod) (ifaceDeclSubBndrs decl)
312 -- Typecheck the thing, lazily
313 -- NB. Firstly, the laziness is there in case we never need the
314 -- declaration (in one-shot mode), and secondly it is there so that
315 -- we don't look up the occurrence of a name before calling mk_new_bndr
316 -- on the binder. This is important because we must get the right name
317 -- which includes its nameParent.
319 ; thing <- forkM doc $ do { bumpDeclStats main_name
320 ; tcIfaceDecl ignore_prags decl }
322 -- Populate the type environment with the implicitTyThings too
323 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
324 lookup n = case lookupOccEnv mini_env (getOccName n) of
327 pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
329 ; returnM $ (main_name, thing) : [(n, lookup n) | n <- implicit_names]
331 -- We build a list from the *known* names, with (lookup n) thunks
332 -- as the TyThings. That way we can extend the PTE without poking the
335 -- mk_new_bndr allocates in the name cache the final canonical
336 -- name for the thing, with the correct
339 -- imported name, to fix the module correctly in the cache
341 = newGlobalBinder mod occ
342 (importedSrcLoc (showSDoc (ppr (moduleName mod))))
343 -- ToDo: qualify with the package name if necessary
345 ifFamily (IfaceData {ifFamInst = Just (famTyCon, _)}) = Just famTyCon
348 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
350 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
352 = do { traceIf (text "Loading decl for" <+> ppr name)
353 ; updateEps_ (\eps -> let stats = eps_stats eps
354 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
359 %*********************************************************
361 \subsection{Reading an interface file}
363 %*********************************************************
366 findAndReadIface :: SDoc -> Module
367 -> IsBootInterface -- True <=> Look for a .hi-boot file
368 -- False <=> Look for .hi file
369 -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
370 -- Nothing <=> file not found, or unreadable, or illegible
371 -- Just x <=> successfully found and parsed
373 -- It *doesn't* add an error to the monad, because
374 -- sometimes it's ok to fail... see notes with loadInterface
376 findAndReadIface doc_str mod hi_boot_file
377 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
379 then ptext SLIT("[boot]")
381 ptext SLIT("interface for"),
383 nest 4 (ptext SLIT("reason:") <+> doc_str)])
385 -- Check for GHC.Prim, and return its static interface
388 then returnM (Succeeded (ghcPrimIface,
389 "<built in interface for GHC.Prim>"))
393 ; hsc_env <- getTopEnv
394 ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
397 { traceIf (ptext SLIT("...not found"))
399 ; returnM (Failed (cannotFindInterface dflags
400 (moduleName mod) err)) } ;
402 Succeeded file_path -> do
404 -- Found file, so read it
405 { traceIf (ptext SLIT("readIFace") <+> text file_path)
406 ; read_result <- readIface mod file_path hi_boot_file
407 ; case read_result of
408 Failed err -> returnM (Failed (badIfaceFile file_path err))
410 | mi_module iface /= mod ->
411 return (Failed (wrongIfaceModErr iface mod file_path))
413 returnM (Succeeded (iface, file_path))
414 -- Don't forget to fill in the package name...
417 findHiFile :: HscEnv -> Module -> IsBootInterface
418 -> IO (MaybeErr FindResult FilePath)
419 findHiFile hsc_env mod hi_boot_file
421 maybe_found <- findExactModule hsc_env mod
423 Found loc mod -> return (Succeeded path)
425 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
426 err -> return (Failed err)
429 @readIface@ tries just the one file.
432 readIface :: Module -> FilePath -> IsBootInterface
433 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
434 -- Failed err <=> file not found, or unreadable, or illegible
435 -- Succeeded iface <=> successfully found and parsed
437 readIface wanted_mod file_path is_hi_boot_file
438 = do { dflags <- getDOpts
439 ; res <- tryMostM $ readBinIface file_path
442 | wanted_mod == actual_mod -> return (Succeeded iface)
443 | otherwise -> return (Failed err)
445 actual_mod = mi_module iface
446 err = hiModuleNameMismatchWarn wanted_mod actual_mod
448 Left exn -> return (Failed (text (showException exn)))
453 %*********************************************************
455 Wired-in interface for GHC.Prim
457 %*********************************************************
460 initExternalPackageState :: ExternalPackageState
461 initExternalPackageState
463 eps_is_boot = emptyUFM,
464 eps_PIT = emptyPackageIfaceTable,
465 eps_PTE = emptyTypeEnv,
466 eps_inst_env = emptyInstEnv,
467 eps_fam_inst_env = emptyFamInstEnv,
468 eps_rule_base = mkRuleBase builtinRules,
469 -- Initialise the EPS rule pool with the built-in rules
470 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
471 , n_insts_in = 0, n_insts_out = 0
472 , n_rules_in = length builtinRules, n_rules_out = 0 }
477 %*********************************************************
479 Wired-in interface for GHC.Prim
481 %*********************************************************
484 ghcPrimIface :: ModIface
486 = (emptyModIface gHC_PRIM) {
487 mi_exports = [(gHC_PRIM, ghcPrimExports)],
489 mi_fixities = fixities,
490 mi_fix_fn = mkIfaceFixCache fixities
493 fixities = [(getOccName seqId, Fixity 0 InfixR)]
497 %*********************************************************
499 \subsection{Statistics}
501 %*********************************************************
504 ifaceStats :: ExternalPackageState -> SDoc
506 = hcat [text "Renamer stats: ", msg]
508 stats = eps_stats eps
510 [int (n_ifaces_in stats) <+> text "interfaces read",
511 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
512 int (n_decls_in stats), text "read"],
513 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
514 int (n_insts_in stats), text "read"],
515 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
516 int (n_rules_in stats), text "read"]
521 %************************************************************************
525 %************************************************************************
528 -- | Read binary interface, and print it out
529 showIface :: HscEnv -> FilePath -> IO ()
530 showIface hsc_env filename = do
531 -- skip the version check; we don't want to worry about profiled vs.
532 -- non-profiled interfaces, for example.
533 writeIORef v_IgnoreHiWay True
534 iface <- initTcRnIf 's' hsc_env () () $ readBinIface filename
535 printDump (pprModIface iface)
539 pprModIface :: ModIface -> SDoc
542 = vcat [ ptext SLIT("interface")
543 <+> ppr (mi_module iface) <+> pp_boot
544 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
545 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
546 <+> int opt_HiVersion
547 <+> ptext SLIT("where")
548 , vcat (map pprExport (mi_exports iface))
549 , pprDeps (mi_deps iface)
550 , vcat (map pprUsage (mi_usages iface))
551 , pprFixities (mi_fixities iface)
552 , vcat (map pprIfaceDecl (mi_decls iface))
553 , vcat (map ppr (mi_insts iface))
554 , vcat (map ppr (mi_rules iface))
555 , pprDeprecs (mi_deprecs iface)
558 pp_boot | mi_boot iface = ptext SLIT("[boot]")
561 exp_vers = mi_exp_vers iface
562 rule_vers = mi_rule_vers iface
564 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
565 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
568 When printing export lists, we print like this:
570 AvailTC C [C, x, y] C(x,y)
571 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
574 pprExport :: IfaceExport -> SDoc
575 pprExport (mod, items)
576 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
578 pp_avail :: GenAvailInfo OccName -> SDoc
579 pp_avail (Avail occ) = ppr occ
580 pp_avail (AvailTC _ []) = empty
581 pp_avail (AvailTC n (n':ns))
582 | n==n' = ppr n <> pp_export ns
583 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
586 pp_export names = braces (hsep (map ppr names))
588 pprUsage :: Usage -> SDoc
590 = hsep [ptext SLIT("import"), ppr (usg_name usage),
592 pp_export_version (usg_exports usage),
593 int (usg_rules usage),
594 pp_versions (usg_entities usage) ]
596 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
597 pp_export_version Nothing = empty
598 pp_export_version (Just v) = int v
600 pprDeps :: Dependencies -> SDoc
601 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
602 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
603 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
604 ptext SLIT("orphans:") <+> fsep (map ppr orphs)
607 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
608 ppr_boot True = text "[boot]"
609 ppr_boot False = empty
611 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
612 pprIfaceDecl (ver, decl)
613 = ppr_vers ver <+> ppr decl
615 -- Print the version for the decl
616 ppr_vers v | v == initialVersion = empty
619 pprFixities :: [(OccName, Fixity)] -> SDoc
620 pprFixities [] = empty
621 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
623 pprFix (occ,fix) = ppr fix <+> ppr occ
625 pprDeprecs NoDeprecs = empty
626 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
627 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
629 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
633 %*********************************************************
637 %*********************************************************
640 badIfaceFile file err
641 = vcat [ptext SLIT("Bad interface file:") <+> text file,
644 hiModuleNameMismatchWarn :: Module -> Module -> Message
645 hiModuleNameMismatchWarn requested_mod read_mod =
646 withPprStyle defaultUserStyle $
647 -- we want the Modules below to be qualified with package names,
648 -- so reset the PrintUnqualified setting.
649 hsep [ ptext SLIT("Something is amiss; requested module ")
651 , ptext SLIT("differs from name found in the interface file")
655 wrongIfaceModErr iface mod_name file_path
656 = sep [ptext SLIT("Interface file") <+> iface_file,
657 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
658 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
659 sep [ptext SLIT("Probable cause: the source code which generated"),
661 ptext SLIT("has an incompatible module name")
664 where iface_file = doubleQuotes (text file_path)