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