Flip direction of newtype coercions, fix some comments
[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
375 ifaceDeclSubBndrs (IfaceData {ifCons = IfDataTyCon cons})
376   = nub (concatMap ifConFields cons)    -- Eliminate duplicate fields
377     ++ concatMap dc_occs cons
378   where
379     dc_occs con_decl
380         | has_wrapper = [con_occ, work_occ, wrap_occ]
381         | otherwise   = [con_occ, work_occ]
382         where
383           con_occ = ifConOcc con_decl
384           strs    = ifConStricts con_decl
385           wrap_occ = mkDataConWrapperOcc con_occ
386           work_occ = mkDataConWorkerOcc con_occ
387           has_wrapper = any isMarkedStrict strs -- See MkId.mkDataConIds (sigh)
388                 -- ToDo: may miss strictness in existential dicts
389
390 ifaceDeclSubBndrs _other = []
391 \end{code}
392
393
394 %*********************************************************
395 %*                                                      *
396 \subsection{Reading an interface file}
397 %*                                                      *
398 %*********************************************************
399
400 \begin{code}
401 findAndReadIface :: SDoc -> Module
402                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
403                                         -- False <=> Look for .hi file
404                  -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
405         -- Nothing <=> file not found, or unreadable, or illegible
406         -- Just x  <=> successfully found and parsed 
407
408         -- It *doesn't* add an error to the monad, because 
409         -- sometimes it's ok to fail... see notes with loadInterface
410
411 findAndReadIface doc_str mod hi_boot_file
412   = do  { traceIf (sep [hsep [ptext SLIT("Reading"), 
413                               if hi_boot_file 
414                                 then ptext SLIT("[boot]") 
415                                 else empty,
416                               ptext SLIT("interface for"), 
417                               ppr mod <> semi],
418                         nest 4 (ptext SLIT("reason:") <+> doc_str)])
419
420         -- Check for GHC.Prim, and return its static interface
421         ; dflags <- getDOpts
422         ; if mod == gHC_PRIM
423           then returnM (Succeeded (ghcPrimIface, 
424                                    "<built in interface for GHC.Prim>"))
425           else do
426
427         -- Look for the file
428         ; hsc_env <- getTopEnv
429         ; mb_found <- ioToIOEnv (findHiFile hsc_env mod hi_boot_file)
430         ; case mb_found of {
431               Failed err -> do
432                 { traceIf (ptext SLIT("...not found"))
433                 ; dflags <- getDOpts
434                 ; returnM (Failed (cannotFindInterface dflags 
435                                         (moduleName mod) err)) } ;
436
437               Succeeded file_path -> do 
438
439         -- Found file, so read it
440         { traceIf (ptext SLIT("readIFace") <+> text file_path)
441         ; read_result <- readIface mod file_path hi_boot_file
442         ; case read_result of
443             Failed err -> returnM (Failed (badIfaceFile file_path err))
444             Succeeded iface 
445                 | mi_module iface /= mod ->
446                   return (Failed (wrongIfaceModErr iface mod file_path))
447                 | otherwise ->
448                   returnM (Succeeded (iface, file_path))
449                         -- Don't forget to fill in the package name...
450         }}}
451
452 findHiFile :: HscEnv -> Module -> IsBootInterface
453            -> IO (MaybeErr FindResult FilePath)
454 findHiFile hsc_env mod hi_boot_file
455   = do
456       maybe_found <- findExactModule hsc_env mod
457       case maybe_found of
458         Found loc mod -> return (Succeeded path)
459                 where
460                    path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)
461         err -> return (Failed err)
462 \end{code}
463
464 @readIface@ tries just the one file.
465
466 \begin{code}
467 readIface :: Module -> FilePath -> IsBootInterface 
468           -> TcRnIf gbl lcl (MaybeErr Message ModIface)
469         -- Failed err    <=> file not found, or unreadable, or illegible
470         -- Succeeded iface <=> successfully found and parsed 
471
472 readIface wanted_mod file_path is_hi_boot_file
473   = do  { dflags <- getDOpts
474         ; ioToIOEnv $ do
475         { res <- tryMost (readBinIface file_path)
476         ; case res of
477             Right iface 
478                 | wanted_mod == actual_mod -> return (Succeeded iface)
479                 | otherwise                -> return (Failed err)
480                 where
481                   actual_mod = mi_module iface
482                   err = hiModuleNameMismatchWarn wanted_mod actual_mod
483
484             Left exn    -> return (Failed (text (showException exn)))
485     }}
486 \end{code}
487
488
489 %*********************************************************
490 %*                                                       *
491         Wired-in interface for GHC.Prim
492 %*                                                       *
493 %*********************************************************
494
495 \begin{code}
496 initExternalPackageState :: ExternalPackageState
497 initExternalPackageState
498   = EPS { 
499       eps_is_boot    = emptyUFM,
500       eps_PIT        = emptyPackageIfaceTable,
501       eps_PTE        = emptyTypeEnv,
502       eps_inst_env   = emptyInstEnv,
503       eps_rule_base  = mkRuleBase builtinRules,
504         -- Initialise the EPS rule pool with the built-in rules
505       eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
506                            , n_insts_in = 0, n_insts_out = 0
507                            , n_rules_in = length builtinRules, n_rules_out = 0 }
508     }
509 \end{code}
510
511
512 %*********************************************************
513 %*                                                       *
514         Wired-in interface for GHC.Prim
515 %*                                                       *
516 %*********************************************************
517
518 \begin{code}
519 ghcPrimIface :: ModIface
520 ghcPrimIface
521   = (emptyModIface gHC_PRIM) {
522         mi_exports  = [(gHC_PRIM, ghcPrimExports)],
523         mi_decls    = [],
524         mi_fixities = fixities,
525         mi_fix_fn  = mkIfaceFixCache fixities
526     }           
527   where
528     fixities = [(getOccName seqId, Fixity 0 InfixR)]
529                         -- seq is infixr 0
530 \end{code}
531
532 %*********************************************************
533 %*                                                      *
534 \subsection{Statistics}
535 %*                                                      *
536 %*********************************************************
537
538 \begin{code}
539 ifaceStats :: ExternalPackageState -> SDoc
540 ifaceStats eps 
541   = hcat [text "Renamer stats: ", msg]
542   where
543     stats = eps_stats eps
544     msg = vcat 
545         [int (n_ifaces_in stats) <+> text "interfaces read",
546          hsep [ int (n_decls_out stats), text "type/class/variable imported, out of", 
547                 int (n_decls_in stats), text "read"],
548          hsep [ int (n_insts_out stats), text "instance decls imported, out of",  
549                 int (n_insts_in stats), text "read"],
550          hsep [ int (n_rules_out stats), text "rule decls imported, out of",  
551                 int (n_rules_in stats), text "read"]
552         ]
553 \end{code}    
554
555
556 %************************************************************************
557 %*                                                                      *
558                 Printing interfaces
559 %*                                                                      *
560 %************************************************************************
561
562 \begin{code}
563 showIface :: FilePath -> IO ()
564 -- Read binary interface, and print it out
565 showIface filename = do
566    -- skip the version check; we don't want to worry about profiled vs.
567    -- non-profiled interfaces, for example.
568    writeIORef v_IgnoreHiWay True
569    iface <- Binary.getBinFileWithDict filename
570    printDump (pprModIface iface)
571  where
572 \end{code}
573
574
575 \begin{code}
576 pprModIface :: ModIface -> SDoc
577 -- Show a ModIface
578 pprModIface iface
579  = vcat [ ptext SLIT("interface")
580                 <+> ppr (mi_module iface) <+> pp_boot 
581                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
582                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
583                 <+> int opt_HiVersion
584                 <+> ptext SLIT("where")
585         , vcat (map pprExport (mi_exports iface))
586         , pprDeps (mi_deps iface)
587         , vcat (map pprUsage (mi_usages iface))
588         , pprFixities (mi_fixities iface)
589         , vcat (map pprIfaceDecl (mi_decls iface))
590         , vcat (map ppr (mi_insts iface))
591         , vcat (map ppr (mi_rules iface))
592         , pprDeprecs (mi_deprecs iface)
593         ]
594   where
595     pp_boot | mi_boot iface = ptext SLIT("[boot]")
596             | otherwise     = empty
597
598     exp_vers  = mi_exp_vers iface
599     rule_vers = mi_rule_vers iface
600
601     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
602                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
603 \end{code}
604
605 When printing export lists, we print like this:
606         Avail   f               f
607         AvailTC C [C, x, y]     C(x,y)
608         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
609
610 \begin{code}
611 pprExport :: IfaceExport -> SDoc
612 pprExport (mod, items)
613  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
614   where
615     pp_avail :: GenAvailInfo OccName -> SDoc
616     pp_avail (Avail occ)    = ppr occ
617     pp_avail (AvailTC _ []) = empty
618     pp_avail (AvailTC n (n':ns)) 
619         | n==n'     = ppr n <> pp_export ns
620         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
621     
622     pp_export []    = empty
623     pp_export names = braces (hsep (map ppr names))
624
625 pprUsage :: Usage -> SDoc
626 pprUsage usage
627   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
628           int (usg_mod usage), 
629           pp_export_version (usg_exports usage),
630           int (usg_rules usage),
631           pp_versions (usg_entities usage) ]
632   where
633     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
634     pp_export_version Nothing  = empty
635     pp_export_version (Just v) = int v
636
637 pprDeps :: Dependencies -> SDoc
638 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
639   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
640           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
641           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
642         ]
643   where
644     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
645     ppr_boot True  = text "[boot]"
646     ppr_boot False = empty
647
648 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
649 pprIfaceDecl (ver, decl)
650   = ppr_vers ver <+> ppr decl
651   where
652         -- Print the version for the decl
653     ppr_vers v | v == initialVersion = empty
654                | otherwise           = int v
655
656 pprFixities :: [(OccName, Fixity)] -> SDoc
657 pprFixities []    = empty
658 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
659                   where
660                     pprFix (occ,fix) = ppr fix <+> ppr occ 
661
662 pprDeprecs NoDeprecs        = empty
663 pprDeprecs (DeprecAll txt)  = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
664 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
665                             where
666                               pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
667 \end{code}
668
669
670 %*********************************************************
671 %*                                                       *
672 \subsection{Errors}
673 %*                                                       *
674 %*********************************************************
675
676 \begin{code}
677 badIfaceFile file err
678   = vcat [ptext SLIT("Bad interface file:") <+> text file, 
679           nest 4 err]
680
681 hiModuleNameMismatchWarn :: Module -> Module -> Message
682 hiModuleNameMismatchWarn requested_mod read_mod = 
683   withPprStyle defaultUserStyle $
684     -- we want the Modules below to be qualified with package names,
685     -- so reset the PrintUnqualified setting.
686     hsep [ ptext SLIT("Something is amiss; requested module ")
687          , ppr requested_mod
688          , ptext SLIT("differs from name found in the interface file")
689          , ppr read_mod
690          ]
691
692 wrongIfaceModErr iface mod_name file_path 
693   = sep [ptext SLIT("Interface file") <+> iface_file,
694          ptext SLIT("contains module") <+> quotes (ppr (mi_module iface)) <> comma,
695          ptext SLIT("but we were expecting module") <+> quotes (ppr mod_name),
696          sep [ptext SLIT("Probable cause: the source code which generated"),
697              nest 2 iface_file,
698              ptext SLIT("has an incompatible module name")
699             ]
700         ]
701   where iface_file = doubleQuotes (text file_path)
702 \end{code}
703