2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Dealing with interface files}
8 loadInterface, loadHomeInterface, 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 Packages ( PackageState(..), PackageIdH(..), isHomePackage )
20 import DynFlags ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ),
22 import IfaceSyn ( IfaceDecl(..), IfaceConDecl(..), IfaceClassOp(..),
23 IfaceConDecls(..), IfaceIdInfo(..) )
24 import IfaceEnv ( newGlobalBinder )
25 import HscTypes ( ModIface(..), TyThing, emptyModIface, EpsStats(..),
26 addEpsInStats, ExternalPackageState(..),
27 PackageTypeEnv, emptyTypeEnv, HscEnv(..),
28 lookupIfaceByModule, emptyPackageIfaceTable,
29 IsBootInterface, mkIfaceFixCache,
33 import BasicTypes ( Version, Fixity(..), FixityDirection(..),
37 import PrelNames ( gHC_PRIM )
38 import PrelInfo ( ghcPrimExports )
39 import PrelRules ( builtinRules )
40 import Rules ( extendRuleBaseList, mkRuleBase )
41 import InstEnv ( emptyInstEnv, extendInstEnvList )
42 import Name ( Name {-instance NamedThing-}, getOccName,
43 nameModule, nameIsLocalOrFrom, isWiredInName )
46 import Module ( Module, ModLocation(ml_hi_file), emptyModuleEnv,
48 extendModuleEnv, lookupModuleEnv, moduleString
50 import OccName ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc, mkClassDataConOcc,
51 mkSuperDictSelOcc, mkDataConWrapperOcc, mkDataConWorkerOcc )
52 import SrcLoc ( importedSrcLoc )
53 import Maybes ( MaybeErr(..) )
54 import FastString ( mkFastString )
55 import ErrUtils ( Message )
56 import Finder ( findModule, findPackageModule, FindResult(..), cantFindError )
58 import BinIface ( readBinIface )
59 import Panic ( ghcError, tryMost, showException, GhcException(..) )
64 %************************************************************************
66 loadSrcInterface, loadOrphanModules, loadHomeInterface
68 These three are called from TcM-land
70 %************************************************************************
73 loadSrcInterface :: SDoc -> Module -> IsBootInterface -> RnM ModIface
74 -- This is called for each 'import' declaration in the source code
75 -- On a failure, fail in the monad with an error message
77 loadSrcInterface doc mod want_boot
78 = do { mb_iface <- initIfaceTcRn $
79 loadInterface doc mod (ImportByUser want_boot)
81 Failed err -> failWithTc (elaborate err)
82 Succeeded iface -> return iface
85 elaborate err = hang (ptext SLIT("Failed to load interface for") <+>
86 quotes (ppr mod) <> colon) 4 err
89 loadOrphanModules :: [Module] -> TcM ()
90 loadOrphanModules mods
91 | null mods = returnM ()
92 | otherwise = initIfaceTcRn $
93 do { traceIf (text "Loading orphan modules:" <+>
98 load mod = loadSysInterface (mk_doc mod) mod
99 mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
102 loadHomeInterface :: SDoc -> Name -> TcRn ModIface
103 loadHomeInterface doc name
106 -- Should not be called with a name from the module being compiled
107 this_mod <- getModule
108 ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
110 initIfaceTcRn $ loadSysInterface doc (nameModule name)
114 loadWiredInHomeIface :: Name -> IfM lcl ()
115 -- A 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
118 = ASSERT( isWiredInName name )
119 do { loadSysInterface doc (nameModule name); return () }
121 doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
124 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
125 -- A wrapper for loadInterface that Throws an exception if it fails
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
164 ; case lookupIfaceByModule hpt (eps_PIT eps) mod of {
166 -> returnM (Succeeded iface) ; -- Already loaded
167 -- The (src_imp == mi_boot iface) test checks that the already-loaded
168 -- interface isn't a boot iface. This can conceivably happen,
169 -- if an earlier import had a before we got to real imports. I think.
172 { let { hi_boot_file = case from of
173 ImportByUser usr_boot -> usr_boot
174 ImportBySystem -> sys_boot
176 ; mb_dep = lookupModuleEnv (eps_is_boot eps) mod
177 ; sys_boot = case mb_dep of
178 Just (_, is_boot) -> is_boot
180 -- The boot-ness of the requested interface,
181 } -- based on the dependencies in directly-imported modules
183 -- READ THE MODULE IN
184 ; let explicit | ImportByUser _ <- from = True
186 ; read_result <- findAndReadIface explicit doc_str mod hi_boot_file
188 ; case read_result of {
190 { let fake_iface = emptyModIface HomePackage mod
192 ; updateEps_ $ \eps ->
193 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
194 -- Not found, so add an empty iface to
195 -- the EPS map so that we don't look again
197 ; returnM (Failed err) } ;
200 Succeeded (iface, file_path) -- Sanity check:
201 | ImportBySystem <- from, -- system-importing...
202 isHomePackage (mi_package iface), -- ...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 (moduleString mod))
317 doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
319 discardDeclPrags :: IfaceDecl -> IfaceDecl
320 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
321 discardDeclPrags decl = decl
323 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
325 = do { traceIf (text "Loading decl for" <+> ppr name)
326 ; updateEps_ (\eps -> let stats = eps_stats eps
327 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
331 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
332 -- *Excludes* the 'main' name, but *includes* the implicitly-bound names
333 -- Deeply revolting, because it has to predict what gets bound,
334 -- especially the question of whether there's a wrapper for a datacon
336 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, ifSigs = sigs })
337 = [tc_occ, dc_occ, dcww_occ] ++
338 [op | IfaceClassOp op _ _ <- sigs] ++
339 [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]]
341 n_ctxt = length sc_ctxt
343 tc_occ = mkClassTyConOcc cls_occ
344 dc_occ = mkClassDataConOcc cls_occ
345 dcww_occ | is_newtype = mkDataConWrapperOcc dc_occ -- Newtypes have wrapper but no worker
346 | otherwise = mkDataConWorkerOcc dc_occ -- Otherwise worker but no wrapper
347 is_newtype = n_sigs + n_ctxt == 1 -- Sigh
349 ifaceDeclSubBndrs (IfaceData {ifCons = IfAbstractTyCon})
352 ifaceDeclSubBndrs (IfaceData {ifCons = IfNewTyCon (IfVanillaCon { ifConOcc = con_occ,
353 ifConFields = fields})})
354 = fields ++ [con_occ, mkDataConWrapperOcc con_occ]
355 -- Wrapper, no worker; see MkId.mkDataConIds
357 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
358 = nub (concatMap fld_occs cons) -- Eliminate duplicate fields
359 ++ concatMap dc_occs cons
361 fld_occs (IfVanillaCon { ifConFields = fields }) = fields
362 fld_occs (IfGadtCon {}) = []
364 | has_wrapper = [con_occ, work_occ, wrap_occ]
365 | otherwise = [con_occ, work_occ]
367 con_occ = ifConOcc con_decl
368 strs = ifConStricts con_decl
369 wrap_occ = mkDataConWrapperOcc con_occ
370 work_occ = mkDataConWorkerOcc con_occ
371 has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
372 -- ToDo: may miss strictness in existential dicts
374 ifaceDeclSubBndrs _other = []
379 %*********************************************************
381 \subsection{Reading an interface file}
383 %*********************************************************
386 findAndReadIface :: Bool -- True <=> explicit user import
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 explicit doc_str mod_name hi_boot_file
398 = do { traceIf (sep [hsep [ptext SLIT("Reading"),
400 then ptext SLIT("[boot]")
402 ptext SLIT("interface for"),
403 ppr mod_name <> semi],
404 nest 4 (ptext SLIT("reason:") <+> doc_str)])
406 -- Check for GHC.Prim, and return its static interface
408 ; let base_pkg = basePackageId (pkgState dflags)
409 ; if mod_name == gHC_PRIM
410 then returnM (Succeeded (ghcPrimIface{ mi_package = base_pkg },
411 "<built in interface for GHC.Prim>"))
415 ; hsc_env <- getTopEnv
416 ; mb_found <- ioToIOEnv (findHiFile hsc_env explicit mod_name hi_boot_file)
419 { traceIf (ptext SLIT("...not found"))
421 ; returnM (Failed (cantFindError dflags mod_name err)) } ;
423 Succeeded (file_path, pkg) -> do
425 -- Found file, so read it
426 { traceIf (ptext SLIT("readIFace") <+> text file_path)
427 ; read_result <- readIface mod_name file_path hi_boot_file
428 ; case read_result of
429 Failed err -> returnM (Failed (badIfaceFile file_path err))
431 | mi_module iface /= mod_name ->
432 return (Failed (wrongIfaceModErr iface mod_name file_path))
434 returnM (Succeeded (iface{mi_package=pkg}, file_path))
435 -- Don't forget to fill in the package name...
438 findHiFile :: HscEnv -> Bool -> Module -> IsBootInterface
439 -> IO (MaybeErr FindResult (FilePath, PackageIdH))
440 findHiFile hsc_env explicit mod_name hi_boot_file
442 -- In interactive or --make mode, we are *not allowed* to demand-load
443 -- a home package .hi file. So don't even look for them.
444 -- This helps in the case where you are sitting in eg. ghc/lib/std
445 -- and start up GHCi - it won't complain that all the modules it tries
446 -- to load are found in the home location.
447 let { home_allowed = isOneShot (ghcMode (hsc_dflags hsc_env)) } ;
448 maybe_found <- if home_allowed
449 then findModule hsc_env mod_name explicit
450 else findPackageModule hsc_env mod_name explicit;
453 Found loc pkg -> return (Succeeded (path, pkg))
455 path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
457 err -> return (Failed err)
461 @readIface@ tries just the one file.
464 readIface :: Module -> String -> IsBootInterface
465 -> TcRnIf gbl lcl (MaybeErr Message ModIface)
466 -- Failed err <=> file not found, or unreadable, or illegible
467 -- Succeeded iface <=> successfully found and parsed
469 readIface wanted_mod file_path is_hi_boot_file
470 = do { dflags <- getDOpts
472 { res <- tryMost (readBinIface file_path)
475 | wanted_mod == actual_mod -> return (Succeeded iface)
476 | otherwise -> return (Failed err)
478 actual_mod = mi_module iface
479 err = hiModuleNameMismatchWarn wanted_mod actual_mod
481 Left exn -> return (Failed (text (showException exn)))
486 %*********************************************************
488 Wired-in interface for GHC.Prim
490 %*********************************************************
493 initExternalPackageState :: ExternalPackageState
494 initExternalPackageState
496 eps_is_boot = emptyModuleEnv,
497 eps_PIT = emptyPackageIfaceTable,
498 eps_PTE = emptyTypeEnv,
499 eps_inst_env = emptyInstEnv,
500 eps_rule_base = mkRuleBase builtinRules,
501 -- Initialise the EPS rule pool with the built-in rules
502 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
503 , n_insts_in = 0, n_insts_out = 0
504 , n_rules_in = length builtinRules, n_rules_out = 0 }
509 %*********************************************************
511 Wired-in interface for GHC.Prim
513 %*********************************************************
516 ghcPrimIface :: ModIface
518 = (emptyModIface HomePackage gHC_PRIM) {
519 mi_exports = [(gHC_PRIM, ghcPrimExports)],
521 mi_fixities = fixities,
522 mi_fix_fn = mkIfaceFixCache fixities
525 fixities = [(getOccName seqId, Fixity 0 InfixR)]
529 %*********************************************************
531 \subsection{Statistics}
533 %*********************************************************
536 ifaceStats :: ExternalPackageState -> SDoc
538 = hcat [text "Renamer stats: ", msg]
540 stats = eps_stats eps
542 [int (n_ifaces_in stats) <+> text "interfaces read",
543 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
544 int (n_decls_in stats), text "read"],
545 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
546 int (n_insts_in stats), text "read"],
547 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
548 int (n_rules_in stats), text "read"]
553 %*********************************************************
557 %*********************************************************
560 badIfaceFile file err
561 = vcat [ptext SLIT("Bad interface file:") <+> text file,
564 hiModuleNameMismatchWarn :: Module -> Module -> Message
565 hiModuleNameMismatchWarn requested_mod read_mod =
566 hsep [ ptext SLIT("Something is amiss; requested module name")
568 , ptext SLIT("differs from name found in the interface file")
572 wrongIfaceModErr iface mod_name file_path
573 = sep [ptext SLIT("Interface file") <+> iface_file,
574 ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
575 ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
576 sep [ptext SLIT("Probable cause: the source code which generated"),
578 ptext SLIT("has an incompatible module name")
581 where iface_file = doubleQuotes (text file_path)