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