c91aa63e1adf744e132be5c622646a018e338c29
[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(..), IfaceIdInfo(..) )
24 import IfaceEnv         ( newGlobalBinder )
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 import Class            ( classATs )
40
41 import PrelNames        ( gHC_PRIM )
42 import PrelInfo         ( ghcPrimExports )
43 import PrelRules        ( builtinRules )
44 import Rules            ( extendRuleBaseList, mkRuleBase )
45 import InstEnv          ( emptyInstEnv, extendInstEnvList )
46 import Name             ( Name {-instance NamedThing-}, getOccName,
47                           nameModule, nameIsLocalOrFrom, isWiredInName )
48 import NameEnv
49 import MkId             ( seqId )
50 import Module
51 import OccName          ( OccName, mkOccEnv, lookupOccEnv, mkClassTyConOcc,
52                           mkClassDataConOcc, mkSuperDictSelOcc,
53                           mkDataConWrapperOcc, mkDataConWorkerOcc,
54                           mkNewTyCoOcc, mkInstTyTcOcc, mkInstTyCoOcc ) 
55 import SrcLoc           ( importedSrcLoc )
56 import Maybes           ( MaybeErr(..) )
57 import ErrUtils         ( Message )
58 import Finder           ( findImportedModule, findExactModule,  
59                           FindResult(..), cannotFindInterface )
60 import UniqFM
61 import StaticFlags      ( opt_HiVersion )
62 import Outputable
63 import BinIface         ( readBinIface, v_IgnoreHiWay )
64 import Binary           ( getBinFileWithDict )
65 import Panic            ( ghcError, tryMost, showException, GhcException(..) )
66 import List             ( nub )
67 import Maybe            ( isJust )
68 import DATA_IOREF       ( writeIORef )
69 \end{code}
70
71
72 %************************************************************************
73 %*                                                                      *
74         loadSrcInterface, loadOrphanModules, loadHomeInterface
75
76                 These three are called from TcM-land    
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 -- | Load the interface corresponding to an @import@ directive in 
82 -- source code.  On a failure, fail in the monad with an error message.
83 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
84 loadSrcInterface doc mod want_boot  = do        
85   -- We must first find which Module this import refers to.  This involves
86   -- calling the Finder, which as a side effect will search the filesystem
87   -- and create a ModLocation.  If successful, loadIface will read the
88   -- interface; it will call the Finder again, but the ModLocation will be
89   -- cached from the first search.
90   hsc_env <- getTopEnv
91   res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
92   case res of
93     Found _ mod -> do
94       mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
95       case mb_iface of
96         Failed err      -> failWithTc err
97         Succeeded iface -> return iface
98     err ->
99         let dflags = hsc_dflags hsc_env in
100         failWithTc (cannotFindInterface dflags mod err)
101
102 -- | Load interfaces for a collection of orphan modules.
103 loadOrphanModules :: [Module] -> TcM ()
104 loadOrphanModules mods
105   | null mods = returnM ()
106   | otherwise = initIfaceTcRn $
107                 do { traceIf (text "Loading orphan modules:" <+> 
108                                  fsep (map ppr mods))
109                    ; mappM_ load mods
110                    ; returnM () }
111   where
112     load mod   = loadSysInterface (mk_doc mod) mod
113     mk_doc mod = ppr mod <+> ptext SLIT("is a orphan-instance module")
114
115 -- | Loads the interface for a given Name.
116 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
117 loadInterfaceForName doc name
118   = do  { 
119 #ifdef DEBUG
120                 -- Should not be called with a name from the module being compiled
121           this_mod <- getModule
122         ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
123 #endif
124           initIfaceTcRn $ loadSysInterface doc (nameModule name)
125     }
126
127 -- | An 'IfM' function to load the home interface for a wired-in thing,
128 -- so that we're sure that we see its instance declarations and rules
129 loadWiredInHomeIface :: Name -> IfM lcl ()
130 loadWiredInHomeIface name
131   = ASSERT( isWiredInName name )
132     do loadSysInterface doc (nameModule name); return ()
133   where
134     doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
135
136 -- | A wrapper for 'loadInterface' that throws an exception if it fails
137 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
138 loadSysInterface doc mod_name
139   = do  { mb_iface <- loadInterface doc mod_name ImportBySystem
140         ; case mb_iface of 
141             Failed err      -> ghcError (ProgramError (showSDoc err))
142             Succeeded iface -> return iface }
143 \end{code}
144
145
146 %*********************************************************
147 %*                                                      *
148                 loadInterface
149
150         The main function to load an interface
151         for an imported module, and put it in
152         the External Package State
153 %*                                                      *
154 %*********************************************************
155
156 \begin{code}
157 loadInterface :: SDoc -> Module -> WhereFrom
158               -> IfM lcl (MaybeErr Message ModIface)
159
160 -- If it can't find a suitable interface file, we
161 --      a) modify the PackageIfaceTable to have an empty entry
162 --              (to avoid repeated complaints)
163 --      b) return (Left message)
164 --
165 -- It's not necessarily an error for there not to be an interface
166 -- file -- perhaps the module has changed, and that interface 
167 -- is no longer used
168
169 loadInterface doc_str mod from
170   = do  {       -- Read the state
171           (eps,hpt) <- getEpsAndHpt
172
173         ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)
174
175                 -- Check whether we have the interface already
176         ; dflags <- getDOpts
177         ; case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of {
178             Just iface 
179                 -> returnM (Succeeded iface) ;  -- Already loaded
180                         -- The (src_imp == mi_boot iface) test checks that the already-loaded
181                         -- interface isn't a boot iface.  This can conceivably happen,
182                         -- if an earlier import had a before we got to real imports.   I think.
183             other -> do
184
185         { let { hi_boot_file = case from of
186                                 ImportByUser usr_boot -> usr_boot
187                                 ImportBySystem        -> sys_boot
188
189               ; mb_dep   = lookupUFM (eps_is_boot eps) (moduleName mod)
190               ; sys_boot = case mb_dep of
191                                 Just (_, is_boot) -> is_boot
192                                 Nothing           -> False
193                         -- The boot-ness of the requested interface, 
194               }         -- based on the dependencies in directly-imported modules
195
196         -- READ THE MODULE IN
197         ; read_result <- findAndReadIface doc_str mod hi_boot_file
198         ; dflags <- getDOpts
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         ; implicit_names <- mapM (mk_new_bndr mod (Just main_name)) 
303                                  (ifaceDeclSubBndrs decl)
304         ; at_names       <- mapM (mk_new_bndr mod  (Just main_name)) (atNames decl)
305
306         -- Typecheck the thing, lazily
307         -- NB. firstly, the laziness is there in case we never need the
308         -- declaration (in one-shot mode), and secondly it is there so that 
309         -- we don't look up the occurrence of a name before calling mk_new_bndr
310         -- on the binder.  This is important because we must get the right name
311         -- which includes its nameParent.
312         ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
313         ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
314               lookup n = case lookupOccEnv mini_env (getOccName n) of
315                            Just thing -> thing
316                            Nothing    -> 
317                              pprPanic "loadDecl" (ppr main_name <+> 
318                                                   ppr n $$ ppr (stripped_decl))
319
320         ; returnM $ (main_name, thing) :  [(n, lookup n) | n <- implicit_names]
321                                        ++ zip at_names (atThings thing)
322         }
323                 -- We build a list from the *known* names, with (lookup n) thunks
324                 -- as the TyThings.  That way we can extend the PTE without poking the
325                 -- thunks
326   where
327     stripped_decl | ignore_prags = discardDeclPrags decl
328                   | otherwise    = decl
329
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     atNames (IfaceClass {ifATs = ats}) = [ifName at | at <- ats]
341     atNames _                          = []
342
343     atThings (AClass cla) = [ATyCon at | at <- classATs cla]
344     atThings _            = []
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, 
368                                ifName = cls_occ, 
369                                ifSigs = sigs }
370   = co_occs ++
371     [tc_occ, dc_occ, dcww_occ] ++
372     [op | IfaceClassOp op _ _ <- sigs] ++
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 (_, _, index)) baseOcc = [mkInstTyTcOcc index baseOcc,
422                                           mkInstTyCoOcc index baseOcc]
423 \end{code}
424
425
426 %*********************************************************
427 %*                                                      *
428 \subsection{Reading an interface file}
429 %*                                                      *
430 %*********************************************************
431
432 \begin{code}
433 findAndReadIface :: SDoc -> Module
434                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
435                                         -- False <=> Look for .hi file
436                  -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
437         -- Nothing <=> file not found, or unreadable, or illegible
438         -- Just x  <=> successfully found and parsed 
439
440         -- It *doesn't* add an error to the monad, because 
441         -- sometimes it's ok to fail... see notes with loadInterface
442
443 findAndReadIface doc_str mod hi_boot_file
444   = do  { traceIf (sep [hsep [ptext SLIT("Reading"), 
445                               if hi_boot_file 
446                                 then ptext SLIT("[boot]") 
447                                 else empty,
448                               ptext SLIT("interface for"), 
449                               ppr mod <> semi],
450                         nest 4 (ptext SLIT("reason:") <+> doc_str)])
451
452         -- Check for GHC.Prim, and return its static interface
453         ; dflags <- getDOpts
454         ; if mod == gHC_PRIM
455           then returnM (Succeeded (ghcPrimIface, 
456                                    "<built in interface for GHC.Prim>"))
457           else do
458
459         -- Look for the file
460         ; hsc_env <- getTopEnv
461         ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
462         ; case mb_found of {
463               Failed err -> do
464                 { traceIf (ptext SLIT("...not found"))
465                 ; dflags <- getDOpts
466                 ; returnM (Failed (cannotFindInterface dflags 
467                                         (moduleName mod) err)) } ;
468
469               Succeeded file_path -> do 
470
471         -- Found file, so read it
472         { traceIf (ptext SLIT("readIFace") <+> text file_path)
473         ; read_result <- readIface mod file_path hi_boot_file
474         ; case read_result of
475             Failed err -> returnM (Failed (badIfaceFile file_path err))
476             Succeeded iface 
477                 | mi_module iface /= mod ->
478                   return (Failed (wrongIfaceModErr iface mod file_path))
479                 | otherwise ->
480                   returnM (Succeeded (iface, file_path))
481                         -- Don't forget to fill in the package name...
482         }}}
483
484 findHiFile :: HscEnv -> Module -> IsBootInterface
485            -> IO (MaybeErr FindResult FilePath)
486 findHiFile hsc_env mod hi_boot_file
487   = do
488       maybe_found <- findExactModule hsc_env mod
489       case maybe_found of
490         Found loc mod -> return (Succeeded path)
491                 where
492                    path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
493         err -> return (Failed err)
494 \end{code}
495
496 @readIface@ tries just the one file.
497
498 \begin{code}
499 readIface :: Module -> FilePath -> IsBootInterface 
500           -> TcRnIf gbl lcl (MaybeErr Message ModIface)
501         -- Failed err    <=> file not found, or unreadable, or illegible
502         -- Succeeded iface <=> successfully found and parsed 
503
504 readIface wanted_mod file_path is_hi_boot_file
505   = do  { dflags <- getDOpts
506         ; ioToIOEnv $ do
507         { res <- tryMost (readBinIface file_path)
508         ; case res of
509             Right iface 
510                 | wanted_mod == actual_mod -> return (Succeeded iface)
511                 | otherwise                -> return (Failed err)
512                 where
513                   actual_mod = mi_module iface
514                   err = hiModuleNameMismatchWarn wanted_mod actual_mod
515
516             Left exn    -> return (Failed (text (showException exn)))
517     }}
518 \end{code}
519
520
521 %*********************************************************
522 %*                                                       *
523         Wired-in interface for GHC.Prim
524 %*                                                       *
525 %*********************************************************
526
527 \begin{code}
528 initExternalPackageState :: ExternalPackageState
529 initExternalPackageState
530   = EPS { 
531       eps_is_boot    = emptyUFM,
532       eps_PIT        = emptyPackageIfaceTable,
533       eps_PTE        = emptyTypeEnv,
534       eps_inst_env   = emptyInstEnv,
535       eps_rule_base  = mkRuleBase builtinRules,
536         -- Initialise the EPS rule pool with the built-in rules
537       eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
538                            , n_insts_in = 0, n_insts_out = 0
539                            , n_rules_in = length builtinRules, n_rules_out = 0 }
540     }
541 \end{code}
542
543
544 %*********************************************************
545 %*                                                       *
546         Wired-in interface for GHC.Prim
547 %*                                                       *
548 %*********************************************************
549
550 \begin{code}
551 ghcPrimIface :: ModIface
552 ghcPrimIface
553   = (emptyModIface gHC_PRIM) {
554         mi_exports  = [(gHC_PRIM, ghcPrimExports)],
555         mi_decls    = [],
556         mi_fixities = fixities,
557         mi_fix_fn  = mkIfaceFixCache fixities
558     }           
559   where
560     fixities = [(getOccName seqId, Fixity 0 InfixR)]
561                         -- seq is infixr 0
562 \end{code}
563
564 %*********************************************************
565 %*                                                      *
566 \subsection{Statistics}
567 %*                                                      *
568 %*********************************************************
569
570 \begin{code}
571 ifaceStats :: ExternalPackageState -> SDoc
572 ifaceStats eps 
573   = hcat [text "Renamer stats: ", msg]
574   where
575     stats = eps_stats eps
576     msg = vcat 
577         [int (n_ifaces_in stats) <+> text "interfaces read",
578          hsep [ int (n_decls_out stats), text "type/class/variable imported, out of", 
579                 int (n_decls_in stats), text "read"],
580          hsep [ int (n_insts_out stats), text "instance decls imported, out of",  
581                 int (n_insts_in stats), text "read"],
582          hsep [ int (n_rules_out stats), text "rule decls imported, out of",  
583                 int (n_rules_in stats), text "read"]
584         ]
585 \end{code}    
586
587
588 %************************************************************************
589 %*                                                                      *
590                 Printing interfaces
591 %*                                                                      *
592 %************************************************************************
593
594 \begin{code}
595 showIface :: FilePath -> IO ()
596 -- Read binary interface, and print it out
597 showIface filename = do
598    -- skip the version check; we don't want to worry about profiled vs.
599    -- non-profiled interfaces, for example.
600    writeIORef v_IgnoreHiWay True
601    iface <- Binary.getBinFileWithDict filename
602    printDump (pprModIface iface)
603  where
604 \end{code}
605
606
607 \begin{code}
608 pprModIface :: ModIface -> SDoc
609 -- Show a ModIface
610 pprModIface iface
611  = vcat [ ptext SLIT("interface")
612                 <+> ppr (mi_module iface) <+> pp_boot 
613                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
614                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
615                 <+> int opt_HiVersion
616                 <+> ptext SLIT("where")
617         , vcat (map pprExport (mi_exports iface))
618         , pprDeps (mi_deps iface)
619         , vcat (map pprUsage (mi_usages iface))
620         , pprFixities (mi_fixities iface)
621         , vcat (map pprIfaceDecl (mi_decls iface))
622         , vcat (map ppr (mi_insts iface))
623         , vcat (map ppr (mi_rules iface))
624         , pprDeprecs (mi_deprecs iface)
625         ]
626   where
627     pp_boot | mi_boot iface = ptext SLIT("[boot]")
628             | otherwise     = empty
629
630     exp_vers  = mi_exp_vers iface
631     rule_vers = mi_rule_vers iface
632
633     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
634                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
635 \end{code}
636
637 When printing export lists, we print like this:
638         Avail   f               f
639         AvailTC C [C, x, y]     C(x,y)
640         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
641
642 \begin{code}
643 pprExport :: IfaceExport -> SDoc
644 pprExport (mod, items)
645  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
646   where
647     pp_avail :: GenAvailInfo OccName -> SDoc
648     pp_avail (Avail occ)    = ppr occ
649     pp_avail (AvailTC _ []) = empty
650     pp_avail (AvailTC n (n':ns)) 
651         | n==n'     = ppr n <> pp_export ns
652         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
653     
654     pp_export []    = empty
655     pp_export names = braces (hsep (map ppr names))
656
657 pprUsage :: Usage -> SDoc
658 pprUsage usage
659   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
660           int (usg_mod usage), 
661           pp_export_version (usg_exports usage),
662           int (usg_rules usage),
663           pp_versions (usg_entities usage) ]
664   where
665     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
666     pp_export_version Nothing  = empty
667     pp_export_version (Just v) = int v
668
669 pprDeps :: Dependencies -> SDoc
670 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
671   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
672           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
673           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
674         ]
675   where
676     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
677     ppr_boot True  = text "[boot]"
678     ppr_boot False = empty
679
680 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
681 pprIfaceDecl (ver, decl)
682   = ppr_vers ver <+> ppr decl
683   where
684         -- Print the version for the decl
685     ppr_vers v | v == initialVersion = empty
686                | otherwise           = int v
687
688 pprFixities :: [(OccName, Fixity)] -> SDoc
689 pprFixities []    = empty
690 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
691                   where
692                     pprFix (occ,fix) = ppr fix <+> ppr occ 
693
694 pprDeprecs NoDeprecs        = empty
695 pprDeprecs (DeprecAll txt)  = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
696 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
697                             where
698                               pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
699 \end{code}
700
701
702 %*********************************************************
703 %*                                                       *
704 \subsection{Errors}
705 %*                                                       *
706 %*********************************************************
707
708 \begin{code}
709 badIfaceFile file err
710   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
711           nest 4 err]
712
713 hiModuleNameMismatchWarn :: Module -> Module -> Message
714 hiModuleNameMismatchWarn requested_mod read_mod = 
715   withPprStyle defaultUserStyle $
716     -- we want the Modules below to be qualified with package names,
717     -- so reset the PrintUnqualified setting.
718     hsep [ ptext SLIT("Something is amiss; requested module ")
719          , ppr requested_mod
720          , ptext SLIT("differs from name found in the interface file")
721          , ppr read_mod
722          ]
723
724 wrongIfaceModErr iface mod_name file_path 
725   = sep [ptext SLIT("Interface file") <+> iface_file,
726          ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
727          ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
728          sep [ptext SLIT("Probable cause: the source code which generated"),
729              nest 2 iface_file,
730              ptext SLIT("has an incompatible module name")
731             ]
732         ]
733   where iface_file = doubleQuotes (text file_path)
734 \end{code}
735