Switch from recording IsBootInterface to recording full HscSource.
[ghc.git] / compiler / iface / LoadIface.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Loading interface files
7 -}
8
9 {-# LANGUAGE CPP #-}
10 {-# OPTIONS_GHC -fno-warn-orphans #-}
11 module LoadIface (
12 -- Importing one thing
13 tcLookupImported_maybe, importDecl,
14 checkWiredInTyCon, ifCheckWiredInThing,
15
16 -- RnM/TcM functions
17 loadModuleInterface, loadModuleInterfaces,
18 loadSrcInterface, loadSrcInterface_maybe,
19 loadInterfaceForName, loadInterfaceForModule,
20
21 -- IfM functions
22 loadInterface, loadWiredInHomeIface,
23 loadSysInterface, loadUserInterface, loadPluginInterface,
24 findAndReadIface, readIface, -- Used when reading the module's old interface
25 loadDecls, -- Should move to TcIface and be renamed
26 initExternalPackageState,
27
28 ifaceStats, pprModIface, showIface
29 ) where
30
31 #include "HsVersions.h"
32
33 import {-# SOURCE #-} TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst,
34 tcIfaceFamInst, tcIfaceVectInfo, tcIfaceAnnotations )
35
36 import DynFlags
37 import IfaceSyn
38 import IfaceEnv
39 import HscTypes
40
41 import BasicTypes hiding (SuccessFlag(..))
42 import TcRnMonad
43
44 import Constants
45 import PrelNames
46 import PrelInfo
47 import PrimOp ( allThePrimOps, primOpFixity, primOpOcc )
48 import MkId ( seqId )
49 import TysPrim ( funTyConName )
50 import Rules
51 import TyCon
52 import Annotations
53 import InstEnv
54 import FamInstEnv
55 import Name
56 import NameEnv
57 import Avail
58 import Module
59 import Maybes
60 import ErrUtils
61 import Finder
62 import UniqFM
63 import SrcLoc
64 import Outputable
65 import BinIface
66 import Panic
67 import Util
68 import FastString
69 import Fingerprint
70 import Hooks
71
72 import Control.Monad
73 import Data.IORef
74 import System.FilePath
75
76 {-
77 ************************************************************************
78 * *
79 * tcImportDecl is the key function for "faulting in" *
80 * imported things
81 * *
82 ************************************************************************
83
84 The main idea is this. We are chugging along type-checking source code, and
85 find a reference to GHC.Base.map. We call tcLookupGlobal, which doesn't find
86 it in the EPS type envt. So it
87 1 loads GHC.Base.hi
88 2 gets the decl for GHC.Base.map
89 3 typechecks it via tcIfaceDecl
90 4 and adds it to the type env in the EPS
91
92 Note that DURING STEP 4, we may find that map's type mentions a type
93 constructor that also
94
95 Notice that for imported things we read the current version from the EPS
96 mutable variable. This is important in situations like
97 ...$(e1)...$(e2)...
98 where the code that e1 expands to might import some defns that
99 also turn out to be needed by the code that e2 expands to.
100 -}
101
102 tcLookupImported_maybe :: Name -> TcM (MaybeErr MsgDoc TyThing)
103 -- Returns (Failed err) if we can't find the interface file for the thing
104 tcLookupImported_maybe name
105 = do { hsc_env <- getTopEnv
106 ; mb_thing <- liftIO (lookupTypeHscEnv hsc_env name)
107 ; case mb_thing of
108 Just thing -> return (Succeeded thing)
109 Nothing -> tcImportDecl_maybe name }
110
111 tcImportDecl_maybe :: Name -> TcM (MaybeErr MsgDoc TyThing)
112 -- Entry point for *source-code* uses of importDecl
113 tcImportDecl_maybe name
114 | Just thing <- wiredInNameTyThing_maybe name
115 = do { when (needWiredInHomeIface thing)
116 (initIfaceTcRn (loadWiredInHomeIface name))
117 -- See Note [Loading instances for wired-in things]
118 ; return (Succeeded thing) }
119 | otherwise
120 = initIfaceTcRn (importDecl name)
121
122 importDecl :: Name -> IfM lcl (MaybeErr MsgDoc TyThing)
123 -- Get the TyThing for this Name from an interface file
124 -- It's not a wired-in thing -- the caller caught that
125 importDecl name
126 = ASSERT( not (isWiredInName name) )
127 do { traceIf nd_doc
128
129 -- Load the interface, which should populate the PTE
130 ; mb_iface <- ASSERT2( isExternalName name, ppr name )
131 loadInterface nd_doc (nameModule name) ImportBySystem
132 ; case mb_iface of {
133 Failed err_msg -> return (Failed err_msg) ;
134 Succeeded _ -> do
135
136 -- Now look it up again; this time we should find it
137 { eps <- getEps
138 ; case lookupTypeEnv (eps_PTE eps) name of
139 Just thing -> return (Succeeded thing)
140 Nothing -> return (Failed not_found_msg)
141 }}}
142 where
143 nd_doc = ptext (sLit "Need decl for") <+> ppr name
144 not_found_msg = hang (ptext (sLit "Can't find interface-file declaration for") <+>
145 pprNameSpace (occNameSpace (nameOccName name)) <+> ppr name)
146 2 (vcat [ptext (sLit "Probable cause: bug in .hi-boot file, or inconsistent .hi file"),
147 ptext (sLit "Use -ddump-if-trace to get an idea of which file caused the error")])
148
149
150 {-
151 ************************************************************************
152 * *
153 Checks for wired-in things
154 * *
155 ************************************************************************
156
157 Note [Loading instances for wired-in things]
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 We need to make sure that we have at least *read* the interface files
160 for any module with an instance decl or RULE that we might want.
161
162 * If the instance decl is an orphan, we have a whole separate mechanism
163 (loadOrphanModules)
164
165 * If the instance decl is not an orphan, then the act of looking at the
166 TyCon or Class will force in the defining module for the
167 TyCon/Class, and hence the instance decl
168
169 * BUT, if the TyCon is a wired-in TyCon, we don't really need its interface;
170 but we must make sure we read its interface in case it has instances or
171 rules. That is what LoadIface.loadWiredInHomeInterface does. It's called
172 from TcIface.{tcImportDecl, checkWiredInTyCon, ifCheckWiredInThing}
173
174 * HOWEVER, only do this for TyCons. There are no wired-in Classes. There
175 are some wired-in Ids, but we don't want to load their interfaces. For
176 example, Control.Exception.Base.recSelError is wired in, but that module
177 is compiled late in the base library, and we don't want to force it to
178 load before it's been compiled!
179
180 All of this is done by the type checker. The renamer plays no role.
181 (It used to, but no longer.)
182 -}
183
184 checkWiredInTyCon :: TyCon -> TcM ()
185 -- Ensure that the home module of the TyCon (and hence its instances)
186 -- are loaded. See Note [Loading instances for wired-in things]
187 -- It might not be a wired-in tycon (see the calls in TcUnify),
188 -- in which case this is a no-op.
189 checkWiredInTyCon tc
190 | not (isWiredInName tc_name)
191 = return ()
192 | otherwise
193 = do { mod <- getModule
194 ; ASSERT( isExternalName tc_name )
195 when (mod /= nameModule tc_name)
196 (initIfaceTcRn (loadWiredInHomeIface tc_name))
197 -- Don't look for (non-existent) Float.hi when
198 -- compiling Float.hs, which mentions Float of course
199 -- A bit yukky to call initIfaceTcRn here
200 }
201 where
202 tc_name = tyConName tc
203
204 ifCheckWiredInThing :: TyThing -> IfL ()
205 -- Even though we are in an interface file, we want to make
206 -- sure the instances of a wired-in thing are loaded (imagine f :: Double -> Double)
207 -- Ditto want to ensure that RULES are loaded too
208 -- See Note [Loading instances for wired-in things]
209 ifCheckWiredInThing thing
210 = do { mod <- getIfModule
211 -- Check whether we are typechecking the interface for this
212 -- very module. E.g when compiling the base library in --make mode
213 -- we may typecheck GHC.Base.hi. At that point, GHC.Base is not in
214 -- the HPT, so without the test we'll demand-load it into the PIT!
215 -- C.f. the same test in checkWiredInTyCon above
216 ; let name = getName thing
217 ; ASSERT2( isExternalName name, ppr name )
218 when (needWiredInHomeIface thing && mod /= nameModule name)
219 (loadWiredInHomeIface name) }
220
221 needWiredInHomeIface :: TyThing -> Bool
222 -- Only for TyCons; see Note [Loading instances for wired-in things]
223 needWiredInHomeIface (ATyCon {}) = True
224 needWiredInHomeIface _ = False
225
226
227 {-
228 ************************************************************************
229 * *
230 loadSrcInterface, loadOrphanModules, loadInterfaceForName
231
232 These three are called from TcM-land
233 * *
234 ************************************************************************
235 -}
236
237 -- Note [Un-ambiguous multiple interfaces]
238 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
239 -- When a user writes an import statement, this usually causes a *single*
240 -- interface file to be loaded. However, the game is different when
241 -- signatures are being imported. Suppose in packages p and q we have
242 -- signatures:
243 --
244 -- module A where
245 -- foo :: Int
246 --
247 -- module A where
248 -- bar :: Int
249 --
250 -- If both packages are exposed and I am importing A, I should see a
251 -- "unified" signature:
252 --
253 -- module A where
254 -- foo :: Int
255 -- bar :: Int
256 --
257 -- The way we achieve this is having the module lookup for A load and return
258 -- multiple interface files, which we will then process as if there were
259 -- "multiple" imports:
260 --
261 -- import "p" A
262 -- import "q" A
263 --
264 -- Doing so does not cause any ambiguity, because any overlapping identifiers
265 -- are guaranteed to have the same name if the backing implementations of the
266 -- two signatures are the same (a condition which is checked by 'Packages'.)
267
268
269 -- | Load the interface corresponding to an @import@ directive in
270 -- source code. On a failure, fail in the monad with an error message.
271 -- See Note [Un-ambiguous multiple interfaces] for why the return type
272 -- is @[ModIface]@
273 loadSrcInterface :: SDoc
274 -> ModuleName
275 -> IsBootInterface -- {-# SOURCE #-} ?
276 -> Maybe FastString -- "package", if any
277 -> RnM [ModIface]
278
279 loadSrcInterface doc mod want_boot maybe_pkg
280 = do { res <- loadSrcInterface_maybe doc mod want_boot maybe_pkg
281 ; case res of
282 Failed err -> failWithTc err
283 Succeeded ifaces -> return ifaces }
284
285 -- | Like 'loadSrcInterface', but returns a 'MaybeErr'. See also
286 -- Note [Un-ambiguous multiple interfaces]
287 loadSrcInterface_maybe :: SDoc
288 -> ModuleName
289 -> IsBootInterface -- {-# SOURCE #-} ?
290 -> Maybe FastString -- "package", if any
291 -> RnM (MaybeErr MsgDoc [ModIface])
292
293 loadSrcInterface_maybe doc mod want_boot maybe_pkg
294 -- We must first find which Module this import refers to. This involves
295 -- calling the Finder, which as a side effect will search the filesystem
296 -- and create a ModLocation. If successful, loadIface will read the
297 -- interface; it will call the Finder again, but the ModLocation will be
298 -- cached from the first search.
299 = do { hsc_env <- getTopEnv
300 ; res <- liftIO $ findImportedModule hsc_env mod maybe_pkg
301 ; case res of
302 FoundModule (FoundHs { fr_mod = mod })
303 -> fmap (fmap (:[]))
304 . initIfaceTcRn
305 $ loadInterface doc mod (ImportByUser want_boot)
306 FoundSigs mods _backing
307 -> initIfaceTcRn $ do
308 ms <- forM mods $ \(FoundHs { fr_mod = mod }) ->
309 loadInterface doc mod (ImportByUser want_boot)
310 return (sequence ms)
311 err -> return (Failed (cannotFindInterface (hsc_dflags hsc_env) mod err)) }
312
313 -- | Load interface directly for a fully qualified 'Module'. (This is a fairly
314 -- rare operation, but in particular it is used to load orphan modules
315 -- in order to pull their instances into the global package table and to
316 -- handle some operations in GHCi).
317 loadModuleInterface :: SDoc -> Module -> TcM ModIface
318 loadModuleInterface doc mod = initIfaceTcRn (loadSysInterface doc mod)
319
320 -- | Load interfaces for a collection of modules.
321 loadModuleInterfaces :: SDoc -> [Module] -> TcM ()
322 loadModuleInterfaces doc mods
323 | null mods = return ()
324 | otherwise = initIfaceTcRn (mapM_ load mods)
325 where
326 load mod = loadSysInterface (doc <+> parens (ppr mod)) mod
327
328 -- | Loads the interface for a given Name.
329 -- Should only be called for an imported name;
330 -- otherwise loadSysInterface may not find the interface
331 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
332 loadInterfaceForName doc name
333 = do { when debugIsOn $ -- Check pre-condition
334 do { this_mod <- getModule
335 ; MASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc ) }
336 ; ASSERT2( isExternalName name, ppr name )
337 initIfaceTcRn $ loadSysInterface doc (nameModule name) }
338
339 -- | Loads the interface for a given Module.
340 loadInterfaceForModule :: SDoc -> Module -> TcRn ModIface
341 loadInterfaceForModule doc m
342 = do
343 -- Should not be called with this module
344 when debugIsOn $ do
345 this_mod <- getModule
346 MASSERT2( this_mod /= m, ppr m <+> parens doc )
347 initIfaceTcRn $ loadSysInterface doc m
348
349 {-
350 *********************************************************
351 * *
352 loadInterface
353
354 The main function to load an interface
355 for an imported module, and put it in
356 the External Package State
357 * *
358 *********************************************************
359 -}
360
361 -- | An 'IfM' function to load the home interface for a wired-in thing,
362 -- so that we're sure that we see its instance declarations and rules
363 -- See Note [Loading instances for wired-in things] in TcIface
364 loadWiredInHomeIface :: Name -> IfM lcl ()
365 loadWiredInHomeIface name
366 = ASSERT( isWiredInName name )
367 do _ <- loadSysInterface doc (nameModule name); return ()
368 where
369 doc = ptext (sLit "Need home interface for wired-in thing") <+> ppr name
370
371 ------------------
372 -- | Loads a system interface and throws an exception if it fails
373 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
374 loadSysInterface doc mod_name = loadInterfaceWithException doc mod_name ImportBySystem
375
376 ------------------
377 -- | Loads a user interface and throws an exception if it fails. The first parameter indicates
378 -- whether we should import the boot variant of the module
379 loadUserInterface :: Bool -> SDoc -> Module -> IfM lcl ModIface
380 loadUserInterface is_boot doc mod_name
381 = loadInterfaceWithException doc mod_name (ImportByUser is_boot)
382
383 loadPluginInterface :: SDoc -> Module -> IfM lcl ModIface
384 loadPluginInterface doc mod_name
385 = loadInterfaceWithException doc mod_name ImportByPlugin
386
387 ------------------
388 -- | A wrapper for 'loadInterface' that throws an exception if it fails
389 loadInterfaceWithException :: SDoc -> Module -> WhereFrom -> IfM lcl ModIface
390 loadInterfaceWithException doc mod_name where_from
391 = do { mb_iface <- loadInterface doc mod_name where_from
392 ; dflags <- getDynFlags
393 ; case mb_iface of
394 Failed err -> liftIO $ throwGhcExceptionIO (ProgramError (showSDoc dflags err))
395 Succeeded iface -> return iface }
396
397 ------------------
398 loadInterface :: SDoc -> Module -> WhereFrom
399 -> IfM lcl (MaybeErr MsgDoc ModIface)
400
401 -- loadInterface looks in both the HPT and PIT for the required interface
402 -- If not found, it loads it, and puts it in the PIT (always).
403
404 -- If it can't find a suitable interface file, we
405 -- a) modify the PackageIfaceTable to have an empty entry
406 -- (to avoid repeated complaints)
407 -- b) return (Left message)
408 --
409 -- It's not necessarily an error for there not to be an interface
410 -- file -- perhaps the module has changed, and that interface
411 -- is no longer used
412
413 loadInterface doc_str mod from
414 = do { -- Read the state
415 (eps,hpt) <- getEpsAndHpt
416 ; gbl_env <- getGblEnv
417
418 ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
419
420 -- Check whether we have the interface already
421 ; dflags <- getDynFlags
422 ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
423 Just iface
424 -> return (Succeeded iface) ; -- Already loaded
425 -- The (src_imp == mi_boot iface) test checks that the already-loaded
426 -- interface isn't a boot iface. This can conceivably happen,
427 -- if an earlier import had a before we got to real imports. I think.
428 _ -> do {
429
430 -- READ THE MODULE IN
431 ; read_result <- case (wantHiBootFile dflags eps mod from) of
432 Failed err -> return (Failed err)
433 Succeeded hi_boot_file ->
434 -- Stoutly warn against an EPS-updating import
435 -- of one's own boot file! (one-shot only)
436 --See Note [Do not update EPS with your own hi-boot]
437 -- in MkIface.
438 WARN( hi_boot_file &&
439 fmap fst (if_rec_types gbl_env) == Just mod,
440 ppr mod )
441 findAndReadIface doc_str mod hi_boot_file
442 ; case read_result of {
443 Failed err -> do
444 { let fake_iface = emptyModIface mod
445
446 ; updateEps_ $ \eps ->
447 eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
448 -- Not found, so add an empty iface to
449 -- the EPS map so that we don't look again
450
451 ; return (Failed err) } ;
452
453 -- Found and parsed!
454 -- We used to have a sanity check here that looked for:
455 -- * System importing ..
456 -- * a home package module ..
457 -- * that we know nothing about (mb_dep == Nothing)!
458 --
459 -- But this is no longer valid because thNameToGhcName allows users to
460 -- cause the system to load arbitrary interfaces (by supplying an appropriate
461 -- Template Haskell original-name).
462 Succeeded (iface, file_path) ->
463
464 let
465 loc_doc = text file_path
466 in
467 initIfaceLcl mod loc_doc $ do
468
469 -- Load the new ModIface into the External Package State
470 -- Even home-package interfaces loaded by loadInterface
471 -- (which only happens in OneShot mode; in Batch/Interactive
472 -- mode, home-package modules are loaded one by one into the HPT)
473 -- are put in the EPS.
474 --
475 -- The main thing is to add the ModIface to the PIT, but
476 -- we also take the
477 -- IfaceDecls, IfaceClsInst, IfaceFamInst, IfaceRules, IfaceVectInfo
478 -- out of the ModIface and put them into the big EPS pools
479
480 -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
481 --- names is done correctly (notably, whether this is an .hi file or .hi-boot file).
482 -- If we do loadExport first the wrong info gets into the cache (unless we
483 -- explicitly tag each export which seems a bit of a bore)
484
485 ; ignore_prags <- goptM Opt_IgnoreInterfacePragmas
486 ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
487 ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
488 ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
489 ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
490 ; new_eps_anns <- tcIfaceAnnotations (mi_anns iface)
491 ; new_eps_vect_info <- tcIfaceVectInfo mod (mkNameEnv new_eps_decls) (mi_vect_info iface)
492
493 ; let { final_iface = iface {
494 mi_decls = panic "No mi_decls in PIT",
495 mi_insts = panic "No mi_insts in PIT",
496 mi_fam_insts = panic "No mi_fam_insts in PIT",
497 mi_rules = panic "No mi_rules in PIT",
498 mi_anns = panic "No mi_anns in PIT"
499 }
500 }
501
502 ; updateEps_ $ \ eps ->
503 if elemModuleEnv mod (eps_PIT eps) then eps else
504 eps {
505 eps_PIT = extendModuleEnv (eps_PIT eps) mod final_iface,
506 eps_PTE = addDeclsToPTE (eps_PTE eps) new_eps_decls,
507 eps_rule_base = extendRuleBaseList (eps_rule_base eps)
508 new_eps_rules,
509 eps_inst_env = extendInstEnvList (eps_inst_env eps)
510 new_eps_insts,
511 eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
512 new_eps_fam_insts,
513 eps_vect_info = plusVectInfo (eps_vect_info eps)
514 new_eps_vect_info,
515 eps_ann_env = extendAnnEnvList (eps_ann_env eps)
516 new_eps_anns,
517 eps_mod_fam_inst_env
518 = let
519 fam_inst_env =
520 extendFamInstEnvList emptyFamInstEnv
521 new_eps_fam_insts
522 in
523 extendModuleEnv (eps_mod_fam_inst_env eps)
524 mod
525 fam_inst_env,
526 eps_stats = addEpsInStats (eps_stats eps)
527 (length new_eps_decls)
528 (length new_eps_insts)
529 (length new_eps_rules) }
530
531 ; return (Succeeded final_iface)
532 }}}}
533
534 wantHiBootFile :: DynFlags -> ExternalPackageState -> Module -> WhereFrom
535 -> MaybeErr MsgDoc IsBootInterface
536 -- Figure out whether we want Foo.hi or Foo.hi-boot
537 wantHiBootFile dflags eps mod from
538 = case from of
539 ImportByUser usr_boot
540 | usr_boot && not this_package
541 -> Failed (badSourceImport mod)
542 | otherwise -> Succeeded usr_boot
543
544 ImportByPlugin
545 -> Succeeded False
546
547 ImportBySystem
548 | not this_package -- If the module to be imported is not from this package
549 -> Succeeded False -- don't look it up in eps_is_boot, because that is keyed
550 -- on the ModuleName of *home-package* modules only.
551 -- We never import boot modules from other packages!
552
553 | otherwise
554 -> case lookupUFM (eps_is_boot eps) (moduleName mod) of
555 Just (_, is_boot) -> Succeeded is_boot
556 Nothing -> Succeeded False
557 -- The boot-ness of the requested interface,
558 -- based on the dependencies in directly-imported modules
559 where
560 this_package = thisPackage dflags == modulePackageKey mod
561
562 badSourceImport :: Module -> SDoc
563 badSourceImport mod
564 = hang (ptext (sLit "You cannot {-# SOURCE #-} import a module from another package"))
565 2 (ptext (sLit "but") <+> quotes (ppr mod) <+> ptext (sLit "is from package")
566 <+> quotes (ppr (modulePackageKey mod)))
567
568 -----------------------------------------------------
569 -- Loading type/class/value decls
570 -- We pass the full Module name here, replete with
571 -- its package info, so that we can build a Name for
572 -- each binder with the right package info in it
573 -- All subsequent lookups, including crucially lookups during typechecking
574 -- the declaration itself, will find the fully-glorious Name
575 --
576 -- We handle ATs specially. They are not main declarations, but also not
577 -- implicit things (in particular, adding them to `implicitTyThings' would mess
578 -- things up in the renaming/type checking of source programs).
579 -----------------------------------------------------
580
581 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
582 addDeclsToPTE pte things = extendNameEnvList pte things
583
584 loadDecls :: Bool
585 -> [(Fingerprint, IfaceDecl)]
586 -> IfL [(Name,TyThing)]
587 loadDecls ignore_prags ver_decls
588 = do { mod <- getIfModule
589 ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
590 ; return (concat thingss)
591 }
592
593 loadDecl :: Bool -- Don't load pragmas into the decl pool
594 -> Module
595 -> (Fingerprint, IfaceDecl)
596 -> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
597 -- TyThings are forkM'd thunks
598 loadDecl ignore_prags mod (_version, decl)
599 = do { -- Populate the name cache with final versions of all
600 -- the names associated with the decl
601 main_name <- lookupOrig mod (ifName decl)
602
603 -- Typecheck the thing, lazily
604 -- NB. Firstly, the laziness is there in case we never need the
605 -- declaration (in one-shot mode), and secondly it is there so that
606 -- we don't look up the occurrence of a name before calling mk_new_bndr
607 -- on the binder. This is important because we must get the right name
608 -- which includes its nameParent.
609
610 ; thing <- forkM doc $ do { bumpDeclStats main_name
611 ; tcIfaceDecl ignore_prags decl }
612
613 -- Populate the type environment with the implicitTyThings too.
614 --
615 -- Note [Tricky iface loop]
616 -- ~~~~~~~~~~~~~~~~~~~~~~~~
617 -- Summary: The delicate point here is that 'mini-env' must be
618 -- buildable from 'thing' without demanding any of the things
619 -- 'forkM'd by tcIfaceDecl.
620 --
621 -- In more detail: Consider the example
622 -- data T a = MkT { x :: T a }
623 -- The implicitTyThings of T are: [ <datacon MkT>, <selector x>]
624 -- (plus their workers, wrappers, coercions etc etc)
625 --
626 -- We want to return an environment
627 -- [ "MkT" -> <datacon MkT>, "x" -> <selector x>, ... ]
628 -- (where the "MkT" is the *Name* associated with MkT, etc.)
629 --
630 -- We do this by mapping the implicit_names to the associated
631 -- TyThings. By the invariant on ifaceDeclImplicitBndrs and
632 -- implicitTyThings, we can use getOccName on the implicit
633 -- TyThings to make this association: each Name's OccName should
634 -- be the OccName of exactly one implicitTyThing. So the key is
635 -- to define a "mini-env"
636 --
637 -- [ 'MkT' -> <datacon MkT>, 'x' -> <selector x>, ... ]
638 -- where the 'MkT' here is the *OccName* associated with MkT.
639 --
640 -- However, there is a subtlety: due to how type checking needs
641 -- to be staged, we can't poke on the forkM'd thunks inside the
642 -- implicitTyThings while building this mini-env.
643 -- If we poke these thunks too early, two problems could happen:
644 -- (1) When processing mutually recursive modules across
645 -- hs-boot boundaries, poking too early will do the
646 -- type-checking before the recursive knot has been tied,
647 -- so things will be type-checked in the wrong
648 -- environment, and necessary variables won't be in
649 -- scope.
650 --
651 -- (2) Looking up one OccName in the mini_env will cause
652 -- others to be looked up, which might cause that
653 -- original one to be looked up again, and hence loop.
654 --
655 -- The code below works because of the following invariant:
656 -- getOccName on a TyThing does not force the suspended type
657 -- checks in order to extract the name. For example, we don't
658 -- poke on the "T a" type of <selector x> on the way to
659 -- extracting <selector x>'s OccName. Of course, there is no
660 -- reason in principle why getting the OccName should force the
661 -- thunks, but this means we need to be careful in
662 -- implicitTyThings and its helper functions.
663 --
664 -- All a bit too finely-balanced for my liking.
665
666 -- This mini-env and lookup function mediates between the
667 --'Name's n and the map from 'OccName's to the implicit TyThings
668 ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
669 lookup n = case lookupOccEnv mini_env (getOccName n) of
670 Just thing -> thing
671 Nothing ->
672 pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
673
674 ; implicit_names <- mapM (lookupOrig mod) (ifaceDeclImplicitBndrs decl)
675
676 -- ; traceIf (text "Loading decl for " <> ppr main_name $$ ppr implicit_names)
677 ; return $ (main_name, thing) :
678 -- uses the invariant that implicit_names and
679 -- implicitTyThings are bijective
680 [(n, lookup n) | n <- implicit_names]
681 }
682 where
683 doc = ptext (sLit "Declaration for") <+> ppr (ifName decl)
684
685 bumpDeclStats :: Name -> IfL () -- Record that one more declaration has actually been used
686 bumpDeclStats name
687 = do { traceIf (text "Loading decl for" <+> ppr name)
688 ; updateEps_ (\eps -> let stats = eps_stats eps
689 in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
690 }
691
692 {-
693 *********************************************************
694 * *
695 \subsection{Reading an interface file}
696 * *
697 *********************************************************
698
699 Note [Home module load error]
700 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
701 If the sought-for interface is in the current package (as determined
702 by -package-name flag) then it jolly well should already be in the HPT
703 because we process home-package modules in dependency order. (Except
704 in one-shot mode; see notes with hsc_HPT decl in HscTypes).
705
706 It is possible (though hard) to get this error through user behaviour.
707 * Suppose package P (modules P1, P2) depends on package Q (modules Q1,
708 Q2, with Q2 importing Q1)
709 * We compile both packages.
710 * Now we edit package Q so that it somehow depends on P
711 * Now recompile Q with --make (without recompiling P).
712 * Then Q1 imports, say, P1, which in turn depends on Q2. So Q2
713 is a home-package module which is not yet in the HPT! Disaster.
714
715 This actually happened with P=base, Q=ghc-prim, via the AMP warnings.
716 See Trac #8320.
717 -}
718
719 findAndReadIface :: SDoc -> Module
720 -> IsBootInterface -- True <=> Look for a .hi-boot file
721 -- False <=> Look for .hi file
722 -> TcRnIf gbl lcl (MaybeErr MsgDoc (ModIface, FilePath))
723 -- Nothing <=> file not found, or unreadable, or illegible
724 -- Just x <=> successfully found and parsed
725
726 -- It *doesn't* add an error to the monad, because
727 -- sometimes it's ok to fail... see notes with loadInterface
728
729 findAndReadIface doc_str mod hi_boot_file
730 = do traceIf (sep [hsep [ptext (sLit "Reading"),
731 if hi_boot_file
732 then ptext (sLit "[boot]")
733 else Outputable.empty,
734 ptext (sLit "interface for"),
735 ppr mod <> semi],
736 nest 4 (ptext (sLit "reason:") <+> doc_str)])
737
738 -- Check for GHC.Prim, and return its static interface
739 if mod == gHC_PRIM
740 then do
741 iface <- getHooked ghcPrimIfaceHook ghcPrimIface
742 return (Succeeded (iface,
743 "<built in interface for GHC.Prim>"))
744 else do
745 dflags <- getDynFlags
746 -- Look for the file
747 hsc_env <- getTopEnv
748 mb_found <- liftIO (findExactModule hsc_env mod)
749 case mb_found of
750 FoundExact loc mod -> do
751
752 -- Found file, so read it
753 let file_path = addBootSuffix_maybe hi_boot_file
754 (ml_hi_file loc)
755
756 -- See Note [Home module load error]
757 if thisPackage dflags == modulePackageKey mod &&
758 not (isOneShot (ghcMode dflags))
759 then return (Failed (homeModError mod loc))
760 else do r <- read_file file_path
761 checkBuildDynamicToo r
762 return r
763 err -> do
764 traceIf (ptext (sLit "...not found"))
765 dflags <- getDynFlags
766 return (Failed (cannotFindInterface dflags
767 (moduleName mod)
768 (convFindExactResult err)))
769 where read_file file_path = do
770 traceIf (ptext (sLit "readIFace") <+> text file_path)
771 read_result <- readIface mod file_path
772 case read_result of
773 Failed err -> return (Failed (badIfaceFile file_path err))
774 Succeeded iface
775 | mi_module iface /= mod ->
776 return (Failed (wrongIfaceModErr iface mod file_path))
777 | otherwise ->
778 return (Succeeded (iface, file_path))
779 -- Don't forget to fill in the package name...
780 checkBuildDynamicToo (Succeeded (iface, filePath)) = do
781 dflags <- getDynFlags
782 whenGeneratingDynamicToo dflags $ withDoDynamicToo $ do
783 let ref = canGenerateDynamicToo dflags
784 dynFilePath = addBootSuffix_maybe hi_boot_file
785 $ replaceExtension filePath (dynHiSuf dflags)
786 r <- read_file dynFilePath
787 case r of
788 Succeeded (dynIface, _)
789 | mi_mod_hash iface == mi_mod_hash dynIface ->
790 return ()
791 | otherwise ->
792 do traceIf (text "Dynamic hash doesn't match")
793 liftIO $ writeIORef ref False
794 Failed err ->
795 do traceIf (text "Failed to load dynamic interface file:" $$ err)
796 liftIO $ writeIORef ref False
797 checkBuildDynamicToo _ = return ()
798
799 -- @readIface@ tries just the one file.
800
801 readIface :: Module -> FilePath
802 -> TcRnIf gbl lcl (MaybeErr MsgDoc ModIface)
803 -- Failed err <=> file not found, or unreadable, or illegible
804 -- Succeeded iface <=> successfully found and parsed
805
806 readIface wanted_mod file_path
807 = do { res <- tryMostM $
808 readBinIface CheckHiWay QuietBinIFaceReading file_path
809 ; case res of
810 Right iface
811 | wanted_mod == actual_mod -> return (Succeeded iface)
812 | otherwise -> return (Failed err)
813 where
814 actual_mod = mi_module iface
815 err = hiModuleNameMismatchWarn wanted_mod actual_mod
816
817 Left exn -> return (Failed (text (showException exn)))
818 }
819
820 {-
821 *********************************************************
822 * *
823 Wired-in interface for GHC.Prim
824 * *
825 *********************************************************
826 -}
827
828 initExternalPackageState :: ExternalPackageState
829 initExternalPackageState
830 = EPS {
831 eps_is_boot = emptyUFM,
832 eps_PIT = emptyPackageIfaceTable,
833 eps_PTE = emptyTypeEnv,
834 eps_inst_env = emptyInstEnv,
835 eps_fam_inst_env = emptyFamInstEnv,
836 eps_rule_base = mkRuleBase builtinRules,
837 -- Initialise the EPS rule pool with the built-in rules
838 eps_mod_fam_inst_env
839 = emptyModuleEnv,
840 eps_vect_info = noVectInfo,
841 eps_ann_env = emptyAnnEnv,
842 eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
843 , n_insts_in = 0, n_insts_out = 0
844 , n_rules_in = length builtinRules, n_rules_out = 0 }
845 }
846
847 {-
848 *********************************************************
849 * *
850 Wired-in interface for GHC.Prim
851 * *
852 *********************************************************
853 -}
854
855 ghcPrimIface :: ModIface
856 ghcPrimIface
857 = (emptyModIface gHC_PRIM) {
858 mi_exports = ghcPrimExports,
859 mi_decls = [],
860 mi_fixities = fixities,
861 mi_fix_fn = mkIfaceFixCache fixities
862 }
863 where
864 fixities = (getOccName seqId, Fixity 0 InfixR) -- seq is infixr 0
865 : (occName funTyConName, funTyFixity) -- trac #10145
866 : mapMaybe mkFixity allThePrimOps
867 mkFixity op = (,) (primOpOcc op) <$> primOpFixity op
868
869 {-
870 *********************************************************
871 * *
872 \subsection{Statistics}
873 * *
874 *********************************************************
875 -}
876
877 ifaceStats :: ExternalPackageState -> SDoc
878 ifaceStats eps
879 = hcat [text "Renamer stats: ", msg]
880 where
881 stats = eps_stats eps
882 msg = vcat
883 [int (n_ifaces_in stats) <+> text "interfaces read",
884 hsep [ int (n_decls_out stats), text "type/class/variable imported, out of",
885 int (n_decls_in stats), text "read"],
886 hsep [ int (n_insts_out stats), text "instance decls imported, out of",
887 int (n_insts_in stats), text "read"],
888 hsep [ int (n_rules_out stats), text "rule decls imported, out of",
889 int (n_rules_in stats), text "read"]
890 ]
891
892 {-
893 ************************************************************************
894 * *
895 Printing interfaces
896 * *
897 ************************************************************************
898 -}
899
900 -- | Read binary interface, and print it out
901 showIface :: HscEnv -> FilePath -> IO ()
902 showIface hsc_env filename = do
903 -- skip the hi way check; we don't want to worry about profiled vs.
904 -- non-profiled interfaces, for example.
905 iface <- initTcRnIf 's' hsc_env () () $
906 readBinIface IgnoreHiWay TraceBinIFaceReading filename
907 let dflags = hsc_dflags hsc_env
908 log_action dflags dflags SevDump noSrcSpan defaultDumpStyle (pprModIface iface)
909
910 pprModIface :: ModIface -> SDoc
911 -- Show a ModIface
912 pprModIface iface
913 = vcat [ ptext (sLit "interface")
914 <+> ppr (mi_module iface) <+> pp_hsc_src (mi_hsc_src iface)
915 <+> (if mi_orphan iface then ptext (sLit "[orphan module]") else Outputable.empty)
916 <+> (if mi_finsts iface then ptext (sLit "[family instance module]") else Outputable.empty)
917 <+> (if mi_hpc iface then ptext (sLit "[hpc]") else Outputable.empty)
918 <+> integer hiVersion
919 , nest 2 (text "interface hash:" <+> ppr (mi_iface_hash iface))
920 , nest 2 (text "ABI hash:" <+> ppr (mi_mod_hash iface))
921 , nest 2 (text "export-list hash:" <+> ppr (mi_exp_hash iface))
922 , nest 2 (text "orphan hash:" <+> ppr (mi_orphan_hash iface))
923 , nest 2 (text "flag hash:" <+> ppr (mi_flag_hash iface))
924 , nest 2 (text "sig of:" <+> ppr (mi_sig_of iface))
925 , nest 2 (text "used TH splices:" <+> ppr (mi_used_th iface))
926 , nest 2 (ptext (sLit "where"))
927 , ptext (sLit "exports:")
928 , nest 2 (vcat (map pprExport (mi_exports iface)))
929 , pprDeps (mi_deps iface)
930 , vcat (map pprUsage (mi_usages iface))
931 , vcat (map pprIfaceAnnotation (mi_anns iface))
932 , pprFixities (mi_fixities iface)
933 , vcat [ppr ver $$ nest 2 (ppr decl) | (ver,decl) <- mi_decls iface]
934 , vcat (map ppr (mi_insts iface))
935 , vcat (map ppr (mi_fam_insts iface))
936 , vcat (map ppr (mi_rules iface))
937 , pprVectInfo (mi_vect_info iface)
938 , ppr (mi_warns iface)
939 , pprTrustInfo (mi_trust iface)
940 , pprTrustPkg (mi_trust_pkg iface)
941 ]
942 where
943 pp_hsc_src HsBootFile = ptext (sLit "[boot]")
944 pp_hsc_src HsigFile = ptext (sLit "[hsig]")
945 pp_hsc_src HsSrcFile = Outputable.empty
946
947 {-
948 When printing export lists, we print like this:
949 Avail f f
950 AvailTC C [C, x, y] C(x,y)
951 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
952 -}
953
954 pprExport :: IfaceExport -> SDoc
955 pprExport (Avail n) = ppr n
956 pprExport (AvailTC _ []) = Outputable.empty
957 pprExport (AvailTC n (n':ns))
958 | n==n' = ppr n <> pp_export ns
959 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
960 where
961 pp_export [] = Outputable.empty
962 pp_export names = braces (hsep (map ppr names))
963
964 pprUsage :: Usage -> SDoc
965 pprUsage usage@UsagePackageModule{}
966 = pprUsageImport usage usg_mod
967 pprUsage usage@UsageHomeModule{}
968 = pprUsageImport usage usg_mod_name $$
969 nest 2 (
970 maybe Outputable.empty (\v -> text "exports: " <> ppr v) (usg_exports usage) $$
971 vcat [ ppr n <+> ppr v | (n,v) <- usg_entities usage ]
972 )
973 pprUsage usage@UsageFile{}
974 = hsep [ptext (sLit "addDependentFile"),
975 doubleQuotes (text (usg_file_path usage))]
976
977 pprUsageImport :: Outputable a => Usage -> (Usage -> a) -> SDoc
978 pprUsageImport usage usg_mod'
979 = hsep [ptext (sLit "import"), safe, ppr (usg_mod' usage),
980 ppr (usg_mod_hash usage)]
981 where
982 safe | usg_safe usage = ptext $ sLit "safe"
983 | otherwise = ptext $ sLit " -/ "
984
985 pprDeps :: Dependencies -> SDoc
986 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs,
987 dep_finsts = finsts })
988 = vcat [ptext (sLit "module dependencies:") <+> fsep (map ppr_mod mods),
989 ptext (sLit "package dependencies:") <+> fsep (map ppr_pkg pkgs),
990 ptext (sLit "orphans:") <+> fsep (map ppr orphs),
991 ptext (sLit "family instance modules:") <+> fsep (map ppr finsts)
992 ]
993 where
994 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
995 ppr_pkg (pkg,trust_req) = ppr pkg <>
996 (if trust_req then text "*" else Outputable.empty)
997 ppr_boot True = text "[boot]"
998 ppr_boot False = Outputable.empty
999
1000 pprFixities :: [(OccName, Fixity)] -> SDoc
1001 pprFixities [] = Outputable.empty
1002 pprFixities fixes = ptext (sLit "fixities") <+> pprWithCommas pprFix fixes
1003 where
1004 pprFix (occ,fix) = ppr fix <+> ppr occ
1005
1006 pprVectInfo :: IfaceVectInfo -> SDoc
1007 pprVectInfo (IfaceVectInfo { ifaceVectInfoVar = vars
1008 , ifaceVectInfoTyCon = tycons
1009 , ifaceVectInfoTyConReuse = tyconsReuse
1010 , ifaceVectInfoParallelVars = parallelVars
1011 , ifaceVectInfoParallelTyCons = parallelTyCons
1012 }) =
1013 vcat
1014 [ ptext (sLit "vectorised variables:") <+> hsep (map ppr vars)
1015 , ptext (sLit "vectorised tycons:") <+> hsep (map ppr tycons)
1016 , ptext (sLit "vectorised reused tycons:") <+> hsep (map ppr tyconsReuse)
1017 , ptext (sLit "parallel variables:") <+> hsep (map ppr parallelVars)
1018 , ptext (sLit "parallel tycons:") <+> hsep (map ppr parallelTyCons)
1019 ]
1020
1021 pprTrustInfo :: IfaceTrustInfo -> SDoc
1022 pprTrustInfo trust = ptext (sLit "trusted:") <+> ppr trust
1023
1024 pprTrustPkg :: Bool -> SDoc
1025 pprTrustPkg tpkg = ptext (sLit "require own pkg trusted:") <+> ppr tpkg
1026
1027 instance Outputable Warnings where
1028 ppr = pprWarns
1029
1030 pprWarns :: Warnings -> SDoc
1031 pprWarns NoWarnings = Outputable.empty
1032 pprWarns (WarnAll txt) = ptext (sLit "Warn all") <+> ppr txt
1033 pprWarns (WarnSome prs) = ptext (sLit "Warnings")
1034 <+> vcat (map pprWarning prs)
1035 where pprWarning (name, txt) = ppr name <+> ppr txt
1036
1037 pprIfaceAnnotation :: IfaceAnnotation -> SDoc
1038 pprIfaceAnnotation (IfaceAnnotation { ifAnnotatedTarget = target, ifAnnotatedValue = serialized })
1039 = ppr target <+> ptext (sLit "annotated by") <+> ppr serialized
1040
1041 {-
1042 *********************************************************
1043 * *
1044 \subsection{Errors}
1045 * *
1046 *********************************************************
1047 -}
1048
1049 badIfaceFile :: String -> SDoc -> SDoc
1050 badIfaceFile file err
1051 = vcat [ptext (sLit "Bad interface file:") <+> text file,
1052 nest 4 err]
1053
1054 hiModuleNameMismatchWarn :: Module -> Module -> MsgDoc
1055 hiModuleNameMismatchWarn requested_mod read_mod =
1056 -- ToDo: This will fail to have enough qualification when the package IDs
1057 -- are the same
1058 withPprStyle (mkUserStyle alwaysQualify AllTheWay) $
1059 -- we want the Modules below to be qualified with package names,
1060 -- so reset the PrintUnqualified setting.
1061 hsep [ ptext (sLit "Something is amiss; requested module ")
1062 , ppr requested_mod
1063 , ptext (sLit "differs from name found in the interface file")
1064 , ppr read_mod
1065 ]
1066
1067 wrongIfaceModErr :: ModIface -> Module -> String -> SDoc
1068 wrongIfaceModErr iface mod_name file_path
1069 = sep [ptext (sLit "Interface file") <+> iface_file,
1070 ptext (sLit "contains module") <+> quotes (ppr (mi_module iface)) <> comma,
1071 ptext (sLit "but we were expecting module") <+> quotes (ppr mod_name),
1072 sep [ptext (sLit "Probable cause: the source code which generated"),
1073 nest 2 iface_file,
1074 ptext (sLit "has an incompatible module name")
1075 ]
1076 ]
1077 where iface_file = doubleQuotes (text file_path)
1078
1079 homeModError :: Module -> ModLocation -> SDoc
1080 -- See Note [Home module load error]
1081 homeModError mod location
1082 = ptext (sLit "attempting to use module ") <> quotes (ppr mod)
1083 <> (case ml_hs_file location of
1084 Just file -> space <> parens (text file)
1085 Nothing -> Outputable.empty)
1086 <+> ptext (sLit "which is not loaded")