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