d4cd503ffef282b2c1c9b117732702ca0abf98dd
[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
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, 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         ; case read_result of {
199             Failed err -> do
200                 { let fake_iface = emptyModIface mod
201
202                 ; updateEps_ $ \eps ->
203                         eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
204                         -- Not found, so add an empty iface to 
205                         -- the EPS map so that we don't look again
206                                 
207                 ; returnM (Failed err) } ;
208
209         -- Found and parsed!
210             Succeeded (iface, file_path)        -- Sanity check:
211                 | ImportBySystem <- from,       --   system-importing...
212                   modulePackageId (mi_module iface) == thisPackage dflags,
213                                                 --   a home-package module...
214                   Nothing <- mb_dep             --   that we know nothing about
215                 -> returnM (Failed (badDepMsg mod))
216
217                 | otherwise ->
218
219         let 
220             loc_doc = text file_path
221         in 
222         initIfaceLcl mod loc_doc $ do
223
224         --      Load the new ModIface into the External Package State
225         -- Even home-package interfaces loaded by loadInterface 
226         --      (which only happens in OneShot mode; in Batch/Interactive 
227         --      mode, home-package modules are loaded one by one into the HPT)
228         -- are put in the EPS.
229         --
230         -- The main thing is to add the ModIface to the PIT, but
231         -- we also take the
232         --      IfaceDecls, IfaceInst, IfaceRules
233         -- out of the ModIface and put them into the big EPS pools
234
235         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
236         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
237         --     If we do loadExport first the wrong info gets into the cache (unless we
238         --      explicitly tag each export which seems a bit of a bore)
239
240         ; ignore_prags <- doptM Opt_IgnoreInterfacePragmas
241         ; new_eps_decls <- loadDecls ignore_prags (mi_decls iface)
242         ; new_eps_insts <- mapM tcIfaceInst (mi_insts iface)
243         ; new_eps_rules <- if ignore_prags 
244                            then return []
245                            else mapM tcIfaceRule (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,"), 
265                ptext SLIT("but does not appear in the dependencies of the interface")])
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         ; thing <- forkM doc (bumpDeclStats main_name >> tcIfaceDecl stripped_decl)
314         ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
315               lookup n = case lookupOccEnv mini_env (getOccName n) of
316                            Just thing -> thing
317                            Nothing    -> 
318                              pprPanic "loadDecl" (ppr main_name <+> 
319                                                   ppr n $$ ppr (stripped_decl))
320
321         ; returnM $ (main_name, thing) :  [(n, lookup n) | n <- implicit_names]
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     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 discardDeclPrags :: IfaceDecl -> IfaceDecl
348 discardDeclPrags decl@(IfaceId {ifIdInfo = HasInfo _}) = decl { ifIdInfo = NoInfo }
349 discardDeclPrags decl                                  = decl
350
351 bumpDeclStats :: Name -> IfL ()         -- Record that one more declaration has actually been used
352 bumpDeclStats name
353   = do  { traceIf (text "Loading decl for" <+> ppr name)
354         ; updateEps_ (\eps -> let stats = eps_stats eps
355                               in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
356         }
357
358 -----------------
359 ifaceDeclSubBndrs :: IfaceDecl -> [OccName]
360 --  *Excludes* the 'main' name, but *includes* the implicitly-bound names
361 -- Deeply revolting, because it has to predict what gets bound,
362 -- especially the question of whether there's a wrapper for a datacon
363 --
364 -- If you change this, make sure you change HscTypes.implicitTyThings in sync
365
366 ifaceDeclSubBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_occ, 
367                                ifSigs = sigs, ifATs = ats })
368   = co_occs ++
369     [tc_occ, dc_occ, dcww_occ] ++
370     [op | IfaceClassOp op  _ _ <- sigs] ++
371     [ifName at | at <- ats ] ++
372     [mkSuperDictSelOcc n cls_occ | n <- [1..n_ctxt]] 
373   where
374     n_ctxt = length sc_ctxt
375     n_sigs = length sigs
376     tc_occ  = mkClassTyConOcc cls_occ
377     dc_occ  = mkClassDataConOcc cls_occ 
378     co_occs | is_newtype = [mkNewTyCoOcc tc_occ]
379             | otherwise  = []
380     dcww_occ -- | is_newtype = mkDataConWrapperOcc dc_occ       -- Newtypes have wrapper but no worker
381              | otherwise  = mkDataConWorkerOcc dc_occ   -- Otherwise worker but no wrapper
382     is_newtype = n_sigs + n_ctxt == 1                   -- Sigh 
383
384 ifaceDeclSubBndrs IfaceData {ifCons = IfAbstractTyCon}
385   = []
386 -- Newtype
387 ifaceDeclSubBndrs (IfaceData {ifName = tc_occ,
388                               ifCons = IfNewTyCon (
389                                          IfCon { ifConOcc = con_occ, 
390                                                            ifConFields = fields
391                                                          }),
392                               ifFamInst = famInst}) 
393   = fields ++ [con_occ, mkDataConWorkerOcc con_occ, mkNewTyCoOcc tc_occ]
394     ++ famInstCo famInst tc_occ
395
396 ifaceDeclSubBndrs (IfaceData {ifName = tc_occ,
397                               ifCons = IfDataTyCon cons, 
398                               ifFamInst = famInst})
399   = nub (concatMap ifConFields cons)    -- Eliminate duplicate fields
400     ++ concatMap dc_occs cons
401     ++ famInstCo famInst tc_occ
402   where
403     dc_occs con_decl
404         | has_wrapper = [con_occ, work_occ, wrap_occ]
405         | otherwise   = [con_occ, work_occ]
406         where
407           con_occ = ifConOcc con_decl
408           strs    = ifConStricts con_decl
409           wrap_occ = mkDataConWrapperOcc con_occ
410           work_occ = mkDataConWorkerOcc con_occ
411           has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
412                         || not (null . ifConEqSpec $ con_decl)
413                         || isJust famInst
414                 -- ToDo: may miss strictness in existential dicts
415
416 ifaceDeclSubBndrs _other = []
417
418 -- coercion for data/newtype family instances
419 famInstCo Nothing  baseOcc = []
420 famInstCo (Just _) baseOcc = [mkInstTyCoOcc baseOcc]
421 \end{code}
422
423
424 %*********************************************************
425 %*                                                      *
426 \subsection{Reading an interface file}
427 %*                                                      *
428 %*********************************************************
429
430 \begin{code}
431 findAndReadIface :: SDoc -> Module
432                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
433                                         -- False <=> Look for .hi file
434                  -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
435         -- Nothing <=> file not found, or unreadable, or illegible
436         -- Just x  <=> successfully found and parsed 
437
438         -- It *doesn't* add an error to the monad, because 
439         -- sometimes it's ok to fail... see notes with loadInterface
440
441 findAndReadIface doc_str mod hi_boot_file
442   = do  { traceIf (sep [hsep [ptext SLIT("Reading"), 
443                               if hi_boot_file 
444                                 then ptext SLIT("[boot]") 
445                                 else empty,
446                               ptext SLIT("interface for"), 
447                               ppr mod <> semi],
448                         nest 4 (ptext SLIT("reason:") <+> doc_str)])
449
450         -- Check for GHC.Prim, and return its static interface
451         ; dflags <- getDOpts
452         ; if mod == gHC_PRIM
453           then returnM (Succeeded (ghcPrimIface, 
454                                    "<built in interface for GHC.Prim>"))
455           else do
456
457         -- Look for the file
458         ; hsc_env <- getTopEnv
459         ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
460         ; case mb_found of {
461               Failed err -> do
462                 { traceIf (ptext SLIT("...not found"))
463                 ; dflags <- getDOpts
464                 ; returnM (Failed (cannotFindInterface dflags 
465                                         (moduleName mod) err)) } ;
466
467               Succeeded file_path -> do 
468
469         -- Found file, so read it
470         { traceIf (ptext SLIT("readIFace") <+> text file_path)
471         ; read_result <- readIface mod file_path hi_boot_file
472         ; case read_result of
473             Failed err -> returnM (Failed (badIfaceFile file_path err))
474             Succeeded iface 
475                 | mi_module iface /= mod ->
476                   return (Failed (wrongIfaceModErr iface mod file_path))
477                 | otherwise ->
478                   returnM (Succeeded (iface, file_path))
479                         -- Don't forget to fill in the package name...
480         }}}
481
482 findHiFile :: HscEnv -> Module -> IsBootInterface
483            -> IO (MaybeErr FindResult FilePath)
484 findHiFile hsc_env mod hi_boot_file
485   = do
486       maybe_found <- findExactModule hsc_env mod
487       case maybe_found of
488         Found loc mod -> return (Succeeded path)
489                 where
490                    path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
491         err -> return (Failed err)
492 \end{code}
493
494 @readIface@ tries just the one file.
495
496 \begin{code}
497 readIface :: Module -> FilePath -> IsBootInterface 
498           -> TcRnIf gbl lcl (MaybeErr Message ModIface)
499         -- Failed err    <=> file not found, or unreadable, or illegible
500         -- Succeeded iface <=> successfully found and parsed 
501
502 readIface wanted_mod file_path is_hi_boot_file
503   = do  { dflags <- getDOpts
504         ; ioToIOEnv $ do
505         { res <- tryMost (readBinIface file_path)
506         ; case res of
507             Right iface 
508                 | wanted_mod == actual_mod -> return (Succeeded iface)
509                 | otherwise                -> return (Failed err)
510                 where
511                   actual_mod = mi_module iface
512                   err = hiModuleNameMismatchWarn wanted_mod actual_mod
513
514             Left exn    -> return (Failed (text (showException exn)))
515     }}
516 \end{code}
517
518
519 %*********************************************************
520 %*                                                       *
521         Wired-in interface for GHC.Prim
522 %*                                                       *
523 %*********************************************************
524
525 \begin{code}
526 initExternalPackageState :: ExternalPackageState
527 initExternalPackageState
528   = EPS { 
529       eps_is_boot    = emptyUFM,
530       eps_PIT        = emptyPackageIfaceTable,
531       eps_PTE        = emptyTypeEnv,
532       eps_inst_env   = emptyInstEnv,
533       eps_rule_base  = mkRuleBase builtinRules,
534         -- Initialise the EPS rule pool with the built-in rules
535       eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
536                            , n_insts_in = 0, n_insts_out = 0
537                            , n_rules_in = length builtinRules, n_rules_out = 0 }
538     }
539 \end{code}
540
541
542 %*********************************************************
543 %*                                                       *
544         Wired-in interface for GHC.Prim
545 %*                                                       *
546 %*********************************************************
547
548 \begin{code}
549 ghcPrimIface :: ModIface
550 ghcPrimIface
551   = (emptyModIface gHC_PRIM) {
552         mi_exports  = [(gHC_PRIM, ghcPrimExports)],
553         mi_decls    = [],
554         mi_fixities = fixities,
555         mi_fix_fn  = mkIfaceFixCache fixities
556     }           
557   where
558     fixities = [(getOccName seqId, Fixity 0 InfixR)]
559                         -- seq is infixr 0
560 \end{code}
561
562 %*********************************************************
563 %*                                                      *
564 \subsection{Statistics}
565 %*                                                      *
566 %*********************************************************
567
568 \begin{code}
569 ifaceStats :: ExternalPackageState -> SDoc
570 ifaceStats eps 
571   = hcat [text "Renamer stats: ", msg]
572   where
573     stats = eps_stats eps
574     msg = vcat 
575         [int (n_ifaces_in stats) <+> text "interfaces read",
576          hsep [ int (n_decls_out stats), text "type/class/variable imported, out of", 
577                 int (n_decls_in stats), text "read"],
578          hsep [ int (n_insts_out stats), text "instance decls imported, out of",  
579                 int (n_insts_in stats), text "read"],
580          hsep [ int (n_rules_out stats), text "rule decls imported, out of",  
581                 int (n_rules_in stats), text "read"]
582         ]
583 \end{code}    
584
585
586 %************************************************************************
587 %*                                                                      *
588                 Printing interfaces
589 %*                                                                      *
590 %************************************************************************
591
592 \begin{code}
593 showIface :: FilePath -> IO ()
594 -- Read binary interface, and print it out
595 showIface filename = do
596    -- skip the version check; we don't want to worry about profiled vs.
597    -- non-profiled interfaces, for example.
598    writeIORef v_IgnoreHiWay True
599    iface <- Binary.getBinFileWithDict filename
600    printDump (pprModIface iface)
601  where
602 \end{code}
603
604
605 \begin{code}
606 pprModIface :: ModIface -> SDoc
607 -- Show a ModIface
608 pprModIface iface
609  = vcat [ ptext SLIT("interface")
610                 <+> ppr (mi_module iface) <+> pp_boot 
611                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
612                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
613                 <+> int opt_HiVersion
614                 <+> ptext SLIT("where")
615         , vcat (map pprExport (mi_exports iface))
616         , pprDeps (mi_deps iface)
617         , vcat (map pprUsage (mi_usages iface))
618         , pprFixities (mi_fixities iface)
619         , vcat (map pprIfaceDecl (mi_decls iface))
620         , vcat (map ppr (mi_insts iface))
621         , vcat (map ppr (mi_rules iface))
622         , pprDeprecs (mi_deprecs iface)
623         ]
624   where
625     pp_boot | mi_boot iface = ptext SLIT("[boot]")
626             | otherwise     = empty
627
628     exp_vers  = mi_exp_vers iface
629     rule_vers = mi_rule_vers iface
630
631     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
632                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
633 \end{code}
634
635 When printing export lists, we print like this:
636         Avail   f               f
637         AvailTC C [C, x, y]     C(x,y)
638         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
639
640 \begin{code}
641 pprExport :: IfaceExport -> SDoc
642 pprExport (mod, items)
643  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
644   where
645     pp_avail :: GenAvailInfo OccName -> SDoc
646     pp_avail (Avail occ)    = ppr occ
647     pp_avail (AvailTC _ []) = empty
648     pp_avail (AvailTC n (n':ns)) 
649         | n==n'     = ppr n <> pp_export ns
650         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
651     
652     pp_export []    = empty
653     pp_export names = braces (hsep (map ppr names))
654
655 pprUsage :: Usage -> SDoc
656 pprUsage usage
657   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
658           int (usg_mod usage), 
659           pp_export_version (usg_exports usage),
660           int (usg_rules usage),
661           pp_versions (usg_entities usage) ]
662   where
663     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
664     pp_export_version Nothing  = empty
665     pp_export_version (Just v) = int v
666
667 pprDeps :: Dependencies -> SDoc
668 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
669   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
670           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
671           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
672         ]
673   where
674     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
675     ppr_boot True  = text "[boot]"
676     ppr_boot False = empty
677
678 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
679 pprIfaceDecl (ver, decl)
680   = ppr_vers ver <+> ppr decl
681   where
682         -- Print the version for the decl
683     ppr_vers v | v == initialVersion = empty
684                | otherwise           = int v
685
686 pprFixities :: [(OccName, Fixity)] -> SDoc
687 pprFixities []    = empty
688 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
689                   where
690                     pprFix (occ,fix) = ppr fix <+> ppr occ 
691
692 pprDeprecs NoDeprecs        = empty
693 pprDeprecs (DeprecAll txt)  = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
694 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
695                             where
696                               pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
697 \end{code}
698
699
700 %*********************************************************
701 %*                                                       *
702 \subsection{Errors}
703 %*                                                       *
704 %*********************************************************
705
706 \begin{code}
707 badIfaceFile file err
708   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
709           nest 4 err]
710
711 hiModuleNameMismatchWarn :: Module -> Module -> Message
712 hiModuleNameMismatchWarn requested_mod read_mod = 
713   withPprStyle defaultUserStyle $
714     -- we want the Modules below to be qualified with package names,
715     -- so reset the PrintUnqualified setting.
716     hsep [ ptext SLIT("Something is amiss; requested module ")
717          , ppr requested_mod
718          , ptext SLIT("differs from name found in the interface file")
719          , ppr read_mod
720          ]
721
722 wrongIfaceModErr iface mod_name file_path 
723   = sep [ptext SLIT("Interface file") <+> iface_file,
724          ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
725          ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
726          sep [ptext SLIT("Probable cause: the source code which generated"),
727              nest 2 iface_file,
728              ptext SLIT("has an incompatible module name")
729             ]
730         ]
731   where iface_file = doubleQuotes (text file_path)
732 \end{code}
733