0dbb17eb4e8e78b4fc548c1f94fe91fa74606eec
[ghc-hetmet.git] / compiler / iface / LoadIface.lhs
1
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Dealing with interface files}
5
6 \begin{code}
7 module LoadIface (
8         loadInterface, loadInterfaceForName, loadWiredInHomeIface, 
9         loadSrcInterface, loadSysInterface, loadOrphanModules, 
10         findAndReadIface, readIface,    -- Used when reading the module's old interface
11         loadDecls,      -- Should move to TcIface and be renamed
12         initExternalPackageState,
13
14         ifaceStats, pprModIface, showIface      -- Print the iface in Foo.hi
15    ) where
16
17 #include "HsVersions.h"
18
19 import {-# SOURCE #-}   TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst )
20
21 import DynFlags         ( DynFlags(..), DynFlag( Opt_IgnoreInterfacePragmas ) )
22 import IfaceSyn         ( IfaceDecl(..), IfaceConDecl(..), IfaceClassOp(..),
23                           IfaceConDecls(..), IfaceFamInst(..) )
24 import IfaceEnv         ( newGlobalBinder, lookupIfaceTc )
25 import HscTypes         ( ModIface(..), TyThing, IfaceExport, Usage(..), 
26                           Deprecs(..), Dependencies(..),
27                           emptyModIface, EpsStats(..), GenAvailInfo(..),
28                           addEpsInStats, ExternalPackageState(..),
29                           PackageTypeEnv, emptyTypeEnv,  HscEnv(..),
30                           lookupIfaceByModule, emptyPackageIfaceTable,
31                           IsBootInterface, mkIfaceFixCache, 
32                           implicitTyThings 
33                          )
34
35 import BasicTypes       ( Version, initialVersion,
36                           Fixity(..), FixityDirection(..), isMarkedStrict )
37 import TcRnMonad
38 import Type             ( TyThing(..) )
39
40 import PrelNames        ( gHC_PRIM )
41 import PrelInfo         ( ghcPrimExports )
42 import PrelRules        ( builtinRules )
43 import Rules            ( extendRuleBaseList, mkRuleBase )
44 import InstEnv          ( emptyInstEnv, extendInstEnvList )
45 import Name             ( Name {-instance NamedThing-}, getOccName,
46                           nameModule, nameIsLocalOrFrom, isWiredInName )
47 import NameEnv
48 import MkId             ( seqId )
49 import Module
50 import OccName          ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc,
51                           mkClassDataConOcc, mkSuperDictSelOcc,
52                           mkDataConWrapperOcc, mkDataConWorkerOcc,
53                           mkNewTyCoOcc, mkInstTyCoOcc ) 
54 import SrcLoc           ( importedSrcLoc )
55 import Maybes           ( MaybeErr(..) )
56 import ErrUtils         ( Message )
57 import Finder           ( findImportedModule, findExactModule,  
58                           FindResult(..), cannotFindInterface )
59 import UniqFM
60 import StaticFlags      ( opt_HiVersion )
61 import Outputable
62 import BinIface         ( readBinIface, v_IgnoreHiWay )
63 import Binary           ( getBinFileWithDict )
64 import Panic            ( ghcError, tryMost, showException, GhcException(..) )
65 import List             ( nub )
66 import Maybe            ( isJust )
67 import DATA_IOREF       ( writeIORef )
68 \end{code}
69
70
71 %************************************************************************
72 %*                                                                      *
73         loadSrcInterface, loadOrphanModules, loadHomeInterface
74
75                 These three are called from TcM-land    
76 %*                                                                      *
77 %************************************************************************
78
79 \begin{code}
80 -- | Load the interface corresponding to an @import@ directive in 
81 -- source code.  On a failure, fail in the monad with an error message.
82 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
83 loadSrcInterface doc mod want_boot  = do        
84   -- We must first find which Module this import refers to.  This involves
85   -- calling the Finder, which as a side effect will search the filesystem
86   -- and create a ModLocation.  If successful, loadIface will read the
87   -- interface; it will call the Finder again, but the ModLocation will be
88   -- cached from the first search.
89   hsc_env <- getTopEnv
90   res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
91   case res of
92     Found _ mod -> do
93       mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
94       case mb_iface of
95         Failed err      -> failWithTc err
96         Succeeded iface -> return iface
97     err ->
98         let dflags = hsc_dflags hsc_env in
99         failWithTc (cannotFindInterface dflags mod err)
100
101 -- | Load interfaces for a collection of orphan modules.
102 loadOrphanModules :: [Module] -> TcM ()
103 loadOrphanModules mods
104   | null mods = returnM ()
105   | otherwise = initIfaceTcRn $
106                 do { traceIf (text "Loading orphan modules:" <+> 
107                                  fsep (map ppr mods))
108                    ; mappM_ load mods
109                    ; returnM () }
110   where
111     load mod   = loadSysInterface (mk_doc mod) mod
112     mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
113
114 -- | Loads the interface for a given Name.
115 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
116 loadInterfaceForName doc name
117   = do  { 
118 #ifdef DEBUG
119                 -- Should not be called with a name from the module being compiled
120           this_mod <- getModule
121         ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
122 #endif
123           initIfaceTcRn $ loadSysInterface doc (nameModule name)
124     }
125
126 -- | An 'IfM' function to load the home interface for a wired-in thing,
127 -- so that we're sure that we see its instance declarations and rules
128 loadWiredInHomeIface :: Name -> IfM lcl ()
129 loadWiredInHomeIface name
130   = ASSERT( isWiredInName name )
131     do loadSysInterface doc (nameModule name); return ()
132   where
133     doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
134
135 -- | A wrapper for 'loadInterface' that throws an exception if it fails
136 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
137 loadSysInterface doc mod_name
138   = do  { mb_iface <- loadInterface doc mod_name ImportBySystem
139         ; case mb_iface of 
140             Failed err      -> ghcError (ProgramError (showSDoc err))
141             Succeeded iface -> return iface }
142 \end{code}
143
144
145 %*********************************************************
146 %*                                                      *
147                 loadInterface
148
149         The main function to load an interface
150         for an imported module, and put it in
151         the External Package State
152 %*                                                      *
153 %*********************************************************
154
155 \begin{code}
156 loadInterface :: SDoc -> Module -> WhereFrom
157               -> IfM lcl (MaybeErr Message ModIface)
158
159 -- loadInterface looks in both the HPT and PIT for the required interface
160 -- If not found, it loads it, and puts it in the PIT (always). 
161
162 -- If it can't find a suitable interface file, we
163 --      a) modify the PackageIfaceTable to have an empty entry
164 --              (to avoid repeated complaints)
165 --      b) return (Left message)
166 --
167 -- It's not necessarily an error for there not to be an interface
168 -- file -- perhaps the module has changed, and that interface 
169 -- is no longer used
170
171 loadInterface doc_str mod from
172   = do  {       -- Read the state
173           (eps,hpt) <- getEpsAndHpt
174
175         ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
176
177                 -- Check whether we have the interface already
178         ; dflags <- getDOpts
179         ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
180             Just iface 
181                 -> returnM (Succeeded iface) ;  -- Already loaded
182                         -- The (src_imp == mi_boot iface) test checks that the already-loaded
183                         -- interface isn't a boot iface.  This can conceivably happen,
184                         -- if an earlier import had a before we got to real imports.   I think.
185             other -> do
186
187         { let { hi_boot_file = case from of
188                                 ImportByUser usr_boot -> usr_boot
189                                 ImportBySystem        -> sys_boot
190
191               ; mb_dep   = lookupUFM (eps_is_boot eps) (moduleName mod)
192               ; sys_boot = case mb_dep of
193                                 Just (_, is_boot) -> is_boot
194                                 Nothing           -> False
195                         -- The boot-ness of the requested interface, 
196               }         -- based on the dependencies in directly-imported modules
197
198         -- READ THE MODULE IN
199         ; read_result <- findAndReadIface doc_str mod hi_boot_file
200         ; case read_result of {
201             Failed err -> do
202                 { let fake_iface = emptyModIface mod
203
204                 ; updateEps_ $ \eps ->
205                         eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
206                         -- Not found, so add an empty iface to 
207                         -- the EPS map so that we don't look again
208                                 
209                 ; returnM (Failed err) } ;
210
211         -- Found and parsed!
212             Succeeded (iface, file_path)        -- Sanity check:
213                 | ImportBySystem <- from,       --   system-importing...
214                   modulePackageId (mi_module iface) == thisPackage dflags,
215                                                 --   a home-package module...
216                   Nothing <- mb_dep             --   that we know nothing about
217                 -> returnM (Failed (badDepMsg mod))
218
219                 | otherwise ->
220
221         let 
222             loc_doc = text file_path
223         in 
224         initIfaceLcl mod loc_doc $ do
225
226         --      Load the new ModIface into the External Package State
227         -- Even home-package interfaces loaded by loadInterface 
228         --      (which only happens in OneShot mode; in Batch/Interactive 
229         --      mode, home-package modules are loaded one by one into the HPT)
230         -- are put in the EPS.
231         --
232         -- The main thing is to add the ModIface to the PIT, but
233         -- we also take the
234         --      IfaceDecls, IfaceInst, IfaceRules
235         -- out of the ModIface and put them into the big EPS pools
236
237         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
238         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
239         --     If we do loadExport first the wrong info gets into the cache (unless we
240         --      explicitly tag each export which seems a bit of a bore)
241
242         ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
243         ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
244         ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
245         ; new_eps_rules <- tcIfaceRules ignore_prags (mi_rules iface)
246
247         ; let { final_iface = iface {   mi_decls = panic "No mi_decls in PIT",
248                                         mi_insts = panic "No mi_insts in PIT",
249                                         mi_rules = panic "No mi_rules in PIT" } }
250
251         ; updateEps_  $ \ eps -> 
252             eps { eps_PIT       = extendModuleEnv (eps_PIT eps) mod final_iface,
253                   eps_PTE       = addDeclsToPTE   (eps_PTE eps) new_eps_decls,
254                   eps_rule_base = extendRuleBaseList (eps_rule_base eps) new_eps_rules,
255                   eps_inst_env  = extendInstEnvList  (eps_inst_env eps)  new_eps_insts,
256                   eps_stats     = addEpsInStats (eps_stats eps) (length new_eps_decls)
257                                                 (length new_eps_insts) (length new_eps_rules) }
258
259         ; return (Succeeded final_iface)
260     }}}}
261
262 badDepMsg mod 
263   = hang (ptext SLIT("Interface file inconsistency:"))
264        2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned is needed,"), 
265                ptext SLIT("but is not among the dependencies of interfaces directly imported by the module being compiled")])
266
267 -----------------------------------------------------
268 --      Loading type/class/value decls
269 -- We pass the full Module name here, replete with
270 -- its package info, so that we can build a Name for
271 -- each binder with the right package info in it
272 -- All subsequent lookups, including crucially lookups during typechecking
273 -- the declaration itself, will find the fully-glorious Name
274 --
275 -- We handle ATs specially.  They are not main declarations, but also not
276 -- implict things (in particular, adding them to `implicitTyThings' would mess
277 -- things up in the renaming/type checking of source programs).
278 -----------------------------------------------------
279
280 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
281 addDeclsToPTE pte things = extendNameEnvList pte things
282
283 loadDecls :: Bool
284           -> [(Version, IfaceDecl)]
285           -> IfL [(Name,TyThing)]
286 loadDecls ignore_prags ver_decls
287    = do { mod <- getIfModule
288         ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
289         ; return (concat thingss)
290         }
291
292 loadDecl :: Bool                    -- Don't load pragmas into the decl pool
293          -> Module
294           -> (Version, IfaceDecl)
295           -> IfL [(Name,TyThing)]   -- The list can be poked eagerly, but the
296                                     -- TyThings are forkM'd thunks
297 loadDecl ignore_prags mod (_version, decl)
298   = do  {       -- Populate the name cache with final versions of all 
299                 -- the names associated with the decl
300           main_name      <- mk_new_bndr mod Nothing (ifName decl)
301         ; parent_name    <- case ifFamily decl of  -- make family the parent
302                               Just famTyCon -> lookupIfaceTc famTyCon
303                               _             -> return main_name
304         ; implicit_names <- mapM (mk_new_bndr mod (Just parent_name)) 
305                                  (ifaceDeclSubBndrs decl)
306
307         -- Typecheck the thing, lazily
308         -- NB. Firstly, the laziness is there in case we never need the
309         -- declaration (in one-shot mode), and secondly it is there so that 
310         -- we don't look up the occurrence of a name before calling mk_new_bndr
311         -- on the binder.  This is important because we must get the right name
312         -- which includes its nameParent.
313
314         ; thing <- forkM doc $ do { bumpDeclStats main_name
315                                   ; tcIfaceDecl ignore_prags decl }
316
317         -- Populate the type environment with the implicitTyThings too
318         ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
319               lookup n = case lookupOccEnv mini_env (getOccName n) of
320                            Just thing -> thing
321                            Nothing    -> 
322                              pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
323
324         ; returnM $ (main_name, thing) :  [(n, lookup n) | n <- implicit_names]
325         }
326                 -- We build a list from the *known* names, with (lookup n) thunks
327                 -- as the TyThings.  That way we can extend the PTE without poking the
328                 -- thunks
329   where
330         -- mk_new_bndr allocates in the name cache the final canonical
331         -- name for the thing, with the correct 
332         --      * parent
333         --      * location
334         -- imported name, to fix the module correctly in the cache
335     mk_new_bndr mod mb_parent occ 
336         = newGlobalBinder mod occ mb_parent 
337                           (importedSrcLoc (showSDoc (ppr (moduleName mod))))
338                         -- ToDo: qualify with the package name if necessary
339
340     ifFamily (IfaceData {
341                 ifFamInst = Just (IfaceFamInst {ifFamInstTyCon = famTyCon})})
342                = Just famTyCon
343     ifFamily _ = Nothing
344
345     doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
346
347 bumpDeclStats :: Name -> IfL ()         -- Record that one more declaration has actually been used
348 bumpDeclStats name
349   = do  { traceIf (text "Loading decl for" <+> ppr name)
350         ; updateEps_ (\eps -> let stats = eps_stats eps
351                               in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
352         }
353
354 -----------------
355 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
356 --  *Excludes* the 'main' name, but *includes* the implicitly-bound names
357 -- Deeply revolting, because it has to predict what gets bound,
358 -- especially the question of whether there's a wrapper for a datacon
359 --
360 -- If you change this, make sure you change HscTypes.implicitTyThings in sync
361
362 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, 
363                                ifSigs = sigs, ifATs = ats })
364   = co_occs ++
365     [tc_occ, dc_occ, dcww_occ] ++
366     [op | IfaceClassOp op  _ _ <- sigs] ++
367     [ifName at | at <- ats ] ++
368     [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]] 
369   where
370     n_ctxt = length sc_ctxt
371     n_sigs = length sigs
372     tc_occ  = mkClassTyConOcc cls_occ
373     dc_occ  = mkClassDataConOcc cls_occ 
374     co_occs | is_newtype = [mkNewTyCoOcc tc_occ]
375             | otherwise  = []
376     dcww_occ -- | is_newtype = mkDataConWrapperOcc dc_occ       -- Newtypes have wrapper but no worker
377              | otherwise  = mkDataConWorkerOcc dc_occ   -- Otherwise worker but no wrapper
378     is_newtype = n_sigs + n_ctxt == 1                   -- Sigh 
379
380 ifaceDeclSubBndrs IfaceData {ifCons = IfAbstractTyCon}
381   = []
382 -- Newtype
383 ifaceDeclSubBndrs (IfaceData {ifName = tc_occ,
384                               ifCons = IfNewTyCon (
385                                          IfCon { ifConOcc = con_occ, 
386                                                            ifConFields = fields
387                                                          }),
388                               ifFamInst = famInst}) 
389   = fields ++ [con_occ, mkDataConWorkerOcc con_occ, mkNewTyCoOcc tc_occ]
390     ++ famInstCo famInst tc_occ
391
392 ifaceDeclSubBndrs (IfaceData {ifName = tc_occ,
393                               ifCons = IfDataTyCon cons, 
394                               ifFamInst = famInst})
395   = nub (concatMap ifConFields cons)    -- Eliminate duplicate fields
396     ++ concatMap dc_occs cons
397     ++ famInstCo famInst tc_occ
398   where
399     dc_occs con_decl
400         | has_wrapper = [con_occ, work_occ, wrap_occ]
401         | otherwise   = [con_occ, work_occ]
402         where
403           con_occ = ifConOcc con_decl
404           strs    = ifConStricts con_decl
405           wrap_occ = mkDataConWrapperOcc con_occ
406           work_occ = mkDataConWorkerOcc con_occ
407           has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
408                         || not (null . ifConEqSpec $ con_decl)
409                         || isJust famInst
410                 -- ToDo: may miss strictness in existential dicts
411
412 ifaceDeclSubBndrs _other = []
413
414 -- coercion for data/newtype family instances
415 famInstCo Nothing  baseOcc = []
416 famInstCo (Just _) baseOcc = [mkInstTyCoOcc baseOcc]
417 \end{code}
418
419
420 %*********************************************************
421 %*                                                      *
422 \subsection{Reading an interface file}
423 %*                                                      *
424 %*********************************************************
425
426 \begin{code}
427 findAndReadIface :: SDoc -> Module
428                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
429                                         -- False <=> Look for .hi file
430                  -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
431         -- Nothing <=> file not found, or unreadable, or illegible
432         -- Just x  <=> successfully found and parsed 
433
434         -- It *doesn't* add an error to the monad, because 
435         -- sometimes it's ok to fail... see notes with loadInterface
436
437 findAndReadIface doc_str mod hi_boot_file
438   = do  { traceIf (sep [hsep [ptext SLIT("Reading"), 
439                               if hi_boot_file 
440                                 then ptext SLIT("[boot]") 
441                                 else empty,
442                               ptext SLIT("interface for"), 
443                               ppr mod <> semi],
444                         nest 4 (ptext SLIT("reason:") <+> doc_str)])
445
446         -- Check for GHC.Prim, and return its static interface
447         ; dflags <- getDOpts
448         ; if mod == gHC_PRIM
449           then returnM (Succeeded (ghcPrimIface, 
450                                    "<built in interface for GHC.Prim>"))
451           else do
452
453         -- Look for the file
454         ; hsc_env <- getTopEnv
455         ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
456         ; case mb_found of {
457               Failed err -> do
458                 { traceIf (ptext SLIT("...not found"))
459                 ; dflags <- getDOpts
460                 ; returnM (Failed (cannotFindInterface dflags 
461                                         (moduleName mod) err)) } ;
462
463               Succeeded file_path -> do 
464
465         -- Found file, so read it
466         { traceIf (ptext SLIT("readIFace") <+> text file_path)
467         ; read_result <- readIface mod file_path hi_boot_file
468         ; case read_result of
469             Failed err -> returnM (Failed (badIfaceFile file_path err))
470             Succeeded iface 
471                 | mi_module iface /= mod ->
472                   return (Failed (wrongIfaceModErr iface mod file_path))
473                 | otherwise ->
474                   returnM (Succeeded (iface, file_path))
475                         -- Don't forget to fill in the package name...
476         }}}
477
478 findHiFile :: HscEnv -> Module -> IsBootInterface
479            -> IO (MaybeErr FindResult FilePath)
480 findHiFile hsc_env mod hi_boot_file
481   = do
482       maybe_found <- findExactModule hsc_env mod
483       case maybe_found of
484         Found loc mod -> return (Succeeded path)
485                 where
486                    path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
487         err -> return (Failed err)
488 \end{code}
489
490 @readIface@ tries just the one file.
491
492 \begin{code}
493 readIface :: Module -> FilePath -> IsBootInterface 
494           -> TcRnIf gbl lcl (MaybeErr Message ModIface)
495         -- Failed err    <=> file not found, or unreadable, or illegible
496         -- Succeeded iface <=> successfully found and parsed 
497
498 readIface wanted_mod file_path is_hi_boot_file
499   = do  { dflags <- getDOpts
500         ; ioToIOEnv $ do
501         { res <- tryMost (readBinIface file_path)
502         ; case res of
503             Right iface 
504                 | wanted_mod == actual_mod -> return (Succeeded iface)
505                 | otherwise                -> return (Failed err)
506                 where
507                   actual_mod = mi_module iface
508                   err = hiModuleNameMismatchWarn wanted_mod actual_mod
509
510             Left exn    -> return (Failed (text (showException exn)))
511     }}
512 \end{code}
513
514
515 %*********************************************************
516 %*                                                       *
517         Wired-in interface for GHC.Prim
518 %*                                                       *
519 %*********************************************************
520
521 \begin{code}
522 initExternalPackageState :: ExternalPackageState
523 initExternalPackageState
524   = EPS { 
525       eps_is_boot    = emptyUFM,
526       eps_PIT        = emptyPackageIfaceTable,
527       eps_PTE        = emptyTypeEnv,
528       eps_inst_env   = emptyInstEnv,
529       eps_rule_base  = mkRuleBase builtinRules,
530         -- Initialise the EPS rule pool with the built-in rules
531       eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
532                            , n_insts_in = 0, n_insts_out = 0
533                            , n_rules_in = length builtinRules, n_rules_out = 0 }
534     }
535 \end{code}
536
537
538 %*********************************************************
539 %*                                                       *
540         Wired-in interface for GHC.Prim
541 %*                                                       *
542 %*********************************************************
543
544 \begin{code}
545 ghcPrimIface :: ModIface
546 ghcPrimIface
547   = (emptyModIface gHC_PRIM) {
548         mi_exports  = [(gHC_PRIM, ghcPrimExports)],
549         mi_decls    = [],
550         mi_fixities = fixities,
551         mi_fix_fn  = mkIfaceFixCache fixities
552     }           
553   where
554     fixities = [(getOccName seqId, Fixity 0 InfixR)]
555                         -- seq is infixr 0
556 \end{code}
557
558 %*********************************************************
559 %*                                                      *
560 \subsection{Statistics}
561 %*                                                      *
562 %*********************************************************
563
564 \begin{code}
565 ifaceStats :: ExternalPackageState -> SDoc
566 ifaceStats eps 
567   = hcat [text "Renamer stats: ", msg]
568   where
569     stats = eps_stats eps
570     msg = vcat 
571         [int (n_ifaces_in stats) <+> text "interfaces read",
572          hsep [ int (n_decls_out stats), text "type/class/variable imported, out of", 
573                 int (n_decls_in stats), text "read"],
574          hsep [ int (n_insts_out stats), text "instance decls imported, out of",  
575                 int (n_insts_in stats), text "read"],
576          hsep [ int (n_rules_out stats), text "rule decls imported, out of",  
577                 int (n_rules_in stats), text "read"]
578         ]
579 \end{code}    
580
581
582 %************************************************************************
583 %*                                                                      *
584                 Printing interfaces
585 %*                                                                      *
586 %************************************************************************
587
588 \begin{code}
589 showIface :: FilePath -> IO ()
590 -- Read binary interface, and print it out
591 showIface filename = do
592    -- skip the version check; we don't want to worry about profiled vs.
593    -- non-profiled interfaces, for example.
594    writeIORef v_IgnoreHiWay True
595    iface <- Binary.getBinFileWithDict filename
596    printDump (pprModIface iface)
597  where
598 \end{code}
599
600
601 \begin{code}
602 pprModIface :: ModIface -> SDoc
603 -- Show a ModIface
604 pprModIface iface
605  = vcat [ ptext SLIT("interface")
606                 <+> ppr (mi_module iface) <+> pp_boot 
607                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
608                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
609                 <+> int opt_HiVersion
610                 <+> ptext SLIT("where")
611         , vcat (map pprExport (mi_exports iface))
612         , pprDeps (mi_deps iface)
613         , vcat (map pprUsage (mi_usages iface))
614         , pprFixities (mi_fixities iface)
615         , vcat (map pprIfaceDecl (mi_decls iface))
616         , vcat (map ppr (mi_insts iface))
617         , vcat (map ppr (mi_rules iface))
618         , pprDeprecs (mi_deprecs iface)
619         ]
620   where
621     pp_boot | mi_boot iface = ptext SLIT("[boot]")
622             | otherwise     = empty
623
624     exp_vers  = mi_exp_vers iface
625     rule_vers = mi_rule_vers iface
626
627     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
628                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
629 \end{code}
630
631 When printing export lists, we print like this:
632         Avail   f               f
633         AvailTC C [C, x, y]     C(x,y)
634         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
635
636 \begin{code}
637 pprExport :: IfaceExport -> SDoc
638 pprExport (mod, items)
639  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
640   where
641     pp_avail :: GenAvailInfo OccName -> SDoc
642     pp_avail (Avail occ)    = ppr occ
643     pp_avail (AvailTC _ []) = empty
644     pp_avail (AvailTC n (n':ns)) 
645         | n==n'     = ppr n <> pp_export ns
646         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
647     
648     pp_export []    = empty
649     pp_export names = braces (hsep (map ppr names))
650
651 pprUsage :: Usage -> SDoc
652 pprUsage usage
653   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
654           int (usg_mod usage), 
655           pp_export_version (usg_exports usage),
656           int (usg_rules usage),
657           pp_versions (usg_entities usage) ]
658   where
659     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
660     pp_export_version Nothing  = empty
661     pp_export_version (Just v) = int v
662
663 pprDeps :: Dependencies -> SDoc
664 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
665   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
666           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
667           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
668         ]
669   where
670     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
671     ppr_boot True  = text "[boot]"
672     ppr_boot False = empty
673
674 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
675 pprIfaceDecl (ver, decl)
676   = ppr_vers ver <+> ppr decl
677   where
678         -- Print the version for the decl
679     ppr_vers v | v == initialVersion = empty
680                | otherwise           = int v
681
682 pprFixities :: [(OccName, Fixity)] -> SDoc
683 pprFixities []    = empty
684 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
685                   where
686                     pprFix (occ,fix) = ppr fix <+> ppr occ 
687
688 pprDeprecs NoDeprecs        = empty
689 pprDeprecs (DeprecAll txt)  = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
690 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
691                             where
692                               pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
693 \end{code}
694
695
696 %*********************************************************
697 %*                                                       *
698 \subsection{Errors}
699 %*                                                       *
700 %*********************************************************
701
702 \begin{code}
703 badIfaceFile file err
704   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
705           nest 4 err]
706
707 hiModuleNameMismatchWarn :: Module -> Module -> Message
708 hiModuleNameMismatchWarn requested_mod read_mod = 
709   withPprStyle defaultUserStyle $
710     -- we want the Modules below to be qualified with package names,
711     -- so reset the PrintUnqualified setting.
712     hsep [ ptext SLIT("Something is amiss; requested module ")
713          , ppr requested_mod
714          , ptext SLIT("differs from name found in the interface file")
715          , ppr read_mod
716          ]
717
718 wrongIfaceModErr iface mod_name file_path 
719   = sep [ptext SLIT("Interface file") <+> iface_file,
720          ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
721          ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
722          sep [ptext SLIT("Probable cause: the source code which generated"),
723              nest 2 iface_file,
724              ptext SLIT("has an incompatible module name")
725             ]
726         ]
727   where iface_file = doubleQuotes (text file_path)
728 \end{code}
729