00e9e7a26f86b915ebf1a6dbb16701c86cabc941
[ghc-hetmet.git] / compiler / iface / LoadIface.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Loading interface files
7
8 \begin{code}
9 module LoadIface (
10         loadInterface, loadInterfaceForName, loadWiredInHomeIface, 
11         loadSrcInterface, loadSysInterface, loadOrphanModules, 
12         findAndReadIface, readIface,    -- Used when reading the module's old interface
13         loadDecls,      -- Should move to TcIface and be renamed
14         initExternalPackageState,
15
16         ifaceStats, pprModIface, showIface
17    ) where
18
19 #include "HsVersions.h"
20
21 import {-# SOURCE #-}   TcIface( tcIfaceDecl, tcIfaceRules, tcIfaceInst, 
22                                  tcIfaceFamInst )
23
24 import DynFlags
25 import IfaceSyn
26 import IfaceEnv
27 import HscTypes
28
29 import BasicTypes hiding (SuccessFlag(..))
30 import TcRnMonad
31 import Type
32
33 import PrelNames
34 import PrelInfo
35 import PrelRules
36 import Rules
37 import InstEnv
38 import FamInstEnv
39 import Name
40 import NameEnv
41 import NameSet
42 import MkId
43 import Module
44 import OccName
45 import SrcLoc
46 import Maybes
47 import ErrUtils
48 import Finder
49 import UniqFM
50 import StaticFlags
51 import Outputable
52 import BinIface
53 import Panic
54
55 import Control.Monad (when)
56 import Data.List
57 import Data.Maybe
58 import Data.IORef
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64         loadSrcInterface, loadOrphanModules, loadHomeInterface
65
66                 These three are called from TcM-land    
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 -- | Load the interface corresponding to an @import@ directive in 
72 -- source code.  On a failure, fail in the monad with an error message.
73 loadSrcInterface :: SDoc -> ModuleName -> IsBootInterface -> RnM ModIface
74 loadSrcInterface doc mod want_boot  = do        
75   -- We must first find which Module this import refers to.  This involves
76   -- calling the Finder, which as a side effect will search the filesystem
77   -- and create a ModLocation.  If successful, loadIface will read the
78   -- interface; it will call the Finder again, but the ModLocation will be
79   -- cached from the first search.
80   hsc_env <- getTopEnv
81   res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
82   case res of
83     Found _ mod -> do
84       mb_iface <- initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot)
85       case mb_iface of
86         Failed err      -> failWithTc err
87         Succeeded iface -> return iface
88     err ->
89         let dflags = hsc_dflags hsc_env in
90         failWithTc (cannotFindInterface dflags mod err)
91
92 -- | Load interfaces for a collection of orphan modules.
93 loadOrphanModules :: [Module]         -- the modules
94                   -> Bool             -- these are family instance-modules
95                   -> TcM ()
96 loadOrphanModules mods isFamInstMod
97   | null mods = returnM ()
98   | otherwise = initIfaceTcRn $
99                 do { traceIf (text "Loading orphan modules:" <+> 
100                                  fsep (map ppr mods))
101                    ; mappM_ load mods
102                    ; returnM () }
103   where
104     load mod   = loadSysInterface (mk_doc mod) mod
105     mk_doc mod 
106       | isFamInstMod = ppr mod <+> ptext SLIT("is a family-instance module")
107       | otherwise    = ppr mod <+> ptext SLIT("is a orphan-instance module")
108
109 -- | Loads the interface for a given Name.
110 loadInterfaceForName :: SDoc -> Name -> TcRn ModIface
111 loadInterfaceForName doc name
112   = do  { 
113 #ifdef DEBUG
114                 -- Should not be called with a name from the module being compiled
115           this_mod <- getModule
116         ; ASSERT2( not (nameIsLocalOrFrom this_mod name), ppr name <+> parens doc )
117 #endif
118           initIfaceTcRn $ loadSysInterface doc (nameModule name)
119     }
120
121 -- | An 'IfM' function to load the home interface for a wired-in thing,
122 -- so that we're sure that we see its instance declarations and rules
123 loadWiredInHomeIface :: Name -> IfM lcl ()
124 loadWiredInHomeIface name
125   = ASSERT( isWiredInName name )
126     do loadSysInterface doc (nameModule name); return ()
127   where
128     doc = ptext SLIT("Need home interface for wired-in thing") <+> ppr name
129
130 -- | A wrapper for 'loadInterface' that throws an exception if it fails
131 loadSysInterface :: SDoc -> Module -> IfM lcl ModIface
132 loadSysInterface doc mod_name
133   = do  { mb_iface <- loadInterface doc mod_name ImportBySystem
134         ; case mb_iface of 
135             Failed err      -> ghcError (ProgramError (showSDoc err))
136             Succeeded iface -> return iface }
137 \end{code}
138
139
140 %*********************************************************
141 %*                                                      *
142                 loadInterface
143
144         The main function to load an interface
145         for an imported module, and put it in
146         the External Package State
147 %*                                                      *
148 %*********************************************************
149
150 \begin{code}
151 loadInterface :: SDoc -> Module -> WhereFrom
152               -> IfM lcl (MaybeErr Message ModIface)
153
154 -- loadInterface looks in both the HPT and PIT for the required interface
155 -- If not found, it loads it, and puts it in the PIT (always). 
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         ; case read_result of {
196             Failed err -> do
197                 { let fake_iface = emptyModIface mod
198
199                 ; updateEps_ $ \eps ->
200                         eps { eps_PIT = extendModuleEnv (eps_PIT eps) (mi_module fake_iface) fake_iface }
201                         -- Not found, so add an empty iface to 
202                         -- the EPS map so that we don't look again
203                                 
204                 ; returnM (Failed err) } ;
205
206         -- Found and parsed!
207             Succeeded (iface, file_path)        -- Sanity check:
208                 | ImportBySystem <- from,       --   system-importing...
209                   modulePackageId (mi_module iface) == thisPackage dflags,
210                                                 --   a home-package module...
211                   Nothing <- mb_dep             --   that we know nothing about
212                 -> returnM (Failed (badDepMsg mod))
213
214                 | otherwise ->
215
216         let 
217             loc_doc = text file_path
218         in 
219         initIfaceLcl mod loc_doc $ do
220
221         --      Load the new ModIface into the External Package State
222         -- Even home-package interfaces loaded by loadInterface 
223         --      (which only happens in OneShot mode; in Batch/Interactive 
224         --      mode, home-package modules are loaded one by one into the HPT)
225         -- are put in the EPS.
226         --
227         -- The main thing is to add the ModIface to the PIT, but
228         -- we also take the
229         --      IfaceDecls, IfaceInst, IfaceFamInst, IfaceRules, IfaceVectInfo
230         -- out of the ModIface and put them into the big EPS pools
231
232         -- NB: *first* we do loadDecl, so that the provenance of all the locally-defined
233         ---    names is done correctly (notably, whether this is an .hi file or .hi-boot file).
234         --     If we do loadExport first the wrong info gets into the cache (unless we
235         --      explicitly tag each export which seems a bit of a bore)
236
237         ; ignore_prags      <- doptM Opt_IgnoreInterfacePragmas
238         ; new_eps_decls     <- loadDecls ignore_prags (mi_decls iface)
239         ; new_eps_insts     <- mapM tcIfaceInst (mi_insts iface)
240         ; new_eps_fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
241         ; new_eps_rules     <- tcIfaceRules ignore_prags (mi_rules iface)
242
243         ; let { final_iface = iface {   
244                                 mi_decls     = panic "No mi_decls in PIT",
245                                 mi_insts     = panic "No mi_insts in PIT",
246                                 mi_fam_insts = panic "No mi_fam_insts in PIT",
247                                 mi_rules     = panic "No mi_rules in PIT"
248                               }
249               ; new_eps_vect_info =
250                   VectInfo {
251                     vectInfoCCVar = mkNameSet 
252                                      (ifaceVectInfoCCVar . mi_vect_info $ iface)
253                   }     
254                }
255
256         ; updateEps_  $ \ eps -> 
257             eps { 
258               eps_PIT          = extendModuleEnv (eps_PIT eps) mod final_iface,
259               eps_PTE          = addDeclsToPTE   (eps_PTE eps) new_eps_decls,
260               eps_rule_base    = extendRuleBaseList (eps_rule_base eps) 
261                                                     new_eps_rules,
262               eps_inst_env     = extendInstEnvList (eps_inst_env eps)  
263                                                    new_eps_insts,
264               eps_fam_inst_env = extendFamInstEnvList (eps_fam_inst_env eps)
265                                                       new_eps_fam_insts,
266               eps_vect_info    = plusVectInfo (eps_vect_info eps) 
267                                               new_eps_vect_info,
268               eps_mod_fam_inst_env
269                                = let
270                                    fam_inst_env = 
271                                      extendFamInstEnvList emptyFamInstEnv
272                                                           new_eps_fam_insts
273                                  in
274                                  extendModuleEnv (eps_mod_fam_inst_env eps)
275                                                  mod
276                                                  fam_inst_env,
277               eps_stats        = addEpsInStats (eps_stats eps) 
278                                                (length new_eps_decls)
279               (length new_eps_insts) (length new_eps_rules) }
280
281         ; return (Succeeded final_iface)
282     }}}}
283
284 badDepMsg mod 
285   = hang (ptext SLIT("Interface file inconsistency:"))
286        2 (sep [ptext SLIT("home-package module") <+> quotes (ppr mod) <+> ptext SLIT("is mentioned is needed,"), 
287                ptext SLIT("but is not among the dependencies of interfaces directly imported by the module being compiled")])
288
289 -----------------------------------------------------
290 --      Loading type/class/value decls
291 -- We pass the full Module name here, replete with
292 -- its package info, so that we can build a Name for
293 -- each binder with the right package info in it
294 -- All subsequent lookups, including crucially lookups during typechecking
295 -- the declaration itself, will find the fully-glorious Name
296 --
297 -- We handle ATs specially.  They are not main declarations, but also not
298 -- implict things (in particular, adding them to `implicitTyThings' would mess
299 -- things up in the renaming/type checking of source programs).
300 -----------------------------------------------------
301
302 addDeclsToPTE :: PackageTypeEnv -> [(Name,TyThing)] -> PackageTypeEnv
303 addDeclsToPTE pte things = extendNameEnvList pte things
304
305 loadDecls :: Bool
306           -> [(Version, IfaceDecl)]
307           -> IfL [(Name,TyThing)]
308 loadDecls ignore_prags ver_decls
309    = do { mod <- getIfModule
310         ; thingss <- mapM (loadDecl ignore_prags mod) ver_decls
311         ; return (concat thingss)
312         }
313
314 loadDecl :: Bool                    -- Don't load pragmas into the decl pool
315          -> Module
316           -> (Version, IfaceDecl)
317           -> IfL [(Name,TyThing)]   -- The list can be poked eagerly, but the
318                                     -- TyThings are forkM'd thunks
319 loadDecl ignore_prags mod (_version, decl)
320   = do  {       -- Populate the name cache with final versions of all 
321                 -- the names associated with the decl
322           main_name      <- mk_new_bndr mod (ifName decl)
323 --        ; traceIf (text "Loading decl for " <> ppr main_name)
324         ; implicit_names <- mapM (mk_new_bndr mod) (ifaceDeclSubBndrs decl)
325
326         -- Typecheck the thing, lazily
327         -- NB. Firstly, the laziness is there in case we never need the
328         -- declaration (in one-shot mode), and secondly it is there so that 
329         -- we don't look up the occurrence of a name before calling mk_new_bndr
330         -- on the binder.  This is important because we must get the right name
331         -- which includes its nameParent.
332
333         ; thing <- forkM doc $ do { bumpDeclStats main_name
334                                   ; tcIfaceDecl ignore_prags decl }
335
336         -- Populate the type environment with the implicitTyThings too.
337         -- 
338         -- Note [Tricky iface loop]
339         -- ~~~~~~~~~~~~~~~~~~~~~~~~
340         -- The delicate point here is that 'mini-env' should be
341         -- buildable from 'thing' without demanding any of the things 'forkM'd 
342         -- by tcIfaceDecl.  For example
343         --      class C a where { data T a; op :: T a -> Int }
344         -- We return the bindings
345         --      [("C", <cls>), ("T", lookup env "T"), ("op", lookup env "op")]
346         -- The call (lookup env "T") must return the tycon T without first demanding
347         -- op; because getting the latter will look up T, hence loop.
348         --
349         -- Of course, there is no reason in principle why (lookup env "T") should demand
350         -- anything do to with op, but take care: 
351         --      (a) implicitTyThings, and 
352         --      (b) getOccName of all the things returned by implicitThings, 
353         -- must not depend on any of the nested type-checks
354         -- 
355         -- All a bit too finely-balanced for my liking.
356
357         ; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
358               lookup n = case lookupOccEnv mini_env (getOccName n) of
359                            Just thing -> thing
360                            Nothing    -> 
361                              pprPanic "loadDecl" (ppr main_name <+> ppr n $$ ppr (decl))
362
363         ; returnM $ (main_name, thing) :  [(n, lookup n) | n <- implicit_names]
364         }
365                 -- We build a list from the *known* names, with (lookup n) thunks
366                 -- as the TyThings.  That way we can extend the PTE without poking the
367                 -- thunks
368   where
369         -- mk_new_bndr allocates in the name cache the final canonical
370         -- name for the thing, with the correct 
371         --      * parent
372         --      * location
373         -- imported name, to fix the module correctly in the cache
374     mk_new_bndr mod occ 
375         = newGlobalBinder mod occ 
376                           (importedSrcLoc (showSDoc (ppr (moduleName mod))))
377                         -- ToDo: qualify with the package name if necessary
378
379     doc = ptext SLIT("Declaration for") <+> ppr (ifName decl)
380
381 bumpDeclStats :: Name -> IfL ()         -- Record that one more declaration has actually been used
382 bumpDeclStats name
383   = do  { traceIf (text "Loading decl for" <+> ppr name)
384         ; updateEps_ (\eps -> let stats = eps_stats eps
385                               in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
386         }
387 \end{code}
388
389
390 %*********************************************************
391 %*                                                      *
392 \subsection{Reading an interface file}
393 %*                                                      *
394 %*********************************************************
395
396 \begin{code}
397 findAndReadIface :: SDoc -> Module
398                  -> IsBootInterface     -- True  <=> Look for a .hi-boot file
399                                         -- False <=> Look for .hi file
400                  -> TcRnIf gbl lcl (MaybeErr Message (ModIface, FilePath))
401         -- Nothing <=> file not found, or unreadable, or illegible
402         -- Just x  <=> successfully found and parsed 
403
404         -- It *doesn't* add an error to the monad, because 
405         -- sometimes it's ok to fail... see notes with loadInterface
406
407 findAndReadIface doc_str mod hi_boot_file
408   = do  { traceIf (sep [hsep [ptext SLIT("Reading"), 
409                               if hi_boot_file 
410                                 then ptext SLIT("[boot]") 
411                                 else empty,
412                               ptext SLIT("interface for"), 
413                               ppr mod <> semi],
414                         nest 4 (ptext SLIT("reason:") <+> doc_str)])
415
416         -- Check for GHC.Prim, and return its static interface
417         ; dflags <- getDOpts
418         ; if mod == gHC_PRIM
419           then returnM (Succeeded (ghcPrimIface, 
420                                    "<built in interface for GHC.Prim>"))
421           else do
422
423         -- Look for the file
424         ; hsc_env <- getTopEnv
425         ; mb_found <- ioToIOEnv (findExactModule hsc_env mod)
426         ; case mb_found of {
427               
428               err | notFound err -> do
429                 { traceIf (ptext SLIT("...not found"))
430                 ; dflags <- getDOpts
431                 ; returnM (Failed (cannotFindInterface dflags 
432                                         (moduleName mod) err)) } ;
433               Found loc mod -> do 
434
435         -- Found file, so read it
436         { let { file_path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc) }
437
438         ; if thisPackage dflags == modulePackageId mod
439                 && not (isOneShot (ghcMode dflags))
440             then returnM (Failed (homeModError mod loc))
441             else do {
442
443         ; traceIf (ptext SLIT("readIFace") <+> text file_path)
444         ; read_result <- readIface mod file_path hi_boot_file
445         ; case read_result of
446             Failed err -> returnM (Failed (badIfaceFile file_path err))
447             Succeeded iface 
448                 | mi_module iface /= mod ->
449                   return (Failed (wrongIfaceModErr iface mod file_path))
450                 | otherwise ->
451                   returnM (Succeeded (iface, file_path))
452                         -- Don't forget to fill in the package name...
453         }}}}
454
455 notFound (Found _ _) = False
456 notFound _ = True
457 \end{code}
458
459 @readIface@ tries just the one file.
460
461 \begin{code}
462 readIface :: Module -> FilePath -> IsBootInterface 
463           -> TcRnIf gbl lcl (MaybeErr Message ModIface)
464         -- Failed err    <=> file not found, or unreadable, or illegible
465         -- Succeeded iface <=> successfully found and parsed 
466
467 readIface wanted_mod file_path is_hi_boot_file
468   = do  { dflags <- getDOpts
469         ; res <- tryMostM $ readBinIface file_path
470         ; case res of
471             Right iface 
472                 | wanted_mod == actual_mod -> return (Succeeded iface)
473                 | otherwise                -> return (Failed err)
474                 where
475                   actual_mod = mi_module iface
476                   err = hiModuleNameMismatchWarn wanted_mod actual_mod
477
478             Left exn    -> return (Failed (text (showException exn)))
479     }
480 \end{code}
481
482
483 %*********************************************************
484 %*                                                       *
485         Wired-in interface for GHC.Prim
486 %*                                                       *
487 %*********************************************************
488
489 \begin{code}
490 initExternalPackageState :: ExternalPackageState
491 initExternalPackageState
492   = EPS { 
493       eps_is_boot      = emptyUFM,
494       eps_PIT          = emptyPackageIfaceTable,
495       eps_PTE          = emptyTypeEnv,
496       eps_inst_env     = emptyInstEnv,
497       eps_fam_inst_env = emptyFamInstEnv,
498       eps_rule_base    = mkRuleBase builtinRules,
499         -- Initialise the EPS rule pool with the built-in rules
500       eps_mod_fam_inst_env
501                        = emptyModuleEnv,
502       eps_vect_info    = noVectInfo,
503       eps_stats = EpsStats { n_ifaces_in = 0, n_decls_in = 0, n_decls_out = 0
504                            , n_insts_in = 0, n_insts_out = 0
505                            , n_rules_in = length builtinRules, n_rules_out = 0 }
506     }
507 \end{code}
508
509
510 %*********************************************************
511 %*                                                       *
512         Wired-in interface for GHC.Prim
513 %*                                                       *
514 %*********************************************************
515
516 \begin{code}
517 ghcPrimIface :: ModIface
518 ghcPrimIface
519   = (emptyModIface gHC_PRIM) {
520         mi_exports  = [(gHC_PRIM, ghcPrimExports)],
521         mi_decls    = [],
522         mi_fixities = fixities,
523         mi_fix_fn  = mkIfaceFixCache fixities
524     }           
525   where
526     fixities = [(getOccName seqId, Fixity 0 InfixR)]
527                         -- seq is infixr 0
528 \end{code}
529
530 %*********************************************************
531 %*                                                      *
532 \subsection{Statistics}
533 %*                                                      *
534 %*********************************************************
535
536 \begin{code}
537 ifaceStats :: ExternalPackageState -> SDoc
538 ifaceStats eps 
539   = hcat [text "Renamer stats: ", msg]
540   where
541     stats = eps_stats eps
542     msg = vcat 
543         [int (n_ifaces_in stats) <+> text "interfaces read",
544          hsep [ int (n_decls_out stats), text "type/class/variable imported, out of", 
545                 int (n_decls_in stats), text "read"],
546          hsep [ int (n_insts_out stats), text "instance decls imported, out of",  
547                 int (n_insts_in stats), text "read"],
548          hsep [ int (n_rules_out stats), text "rule decls imported, out of",  
549                 int (n_rules_in stats), text "read"]
550         ]
551 \end{code}
552
553
554 %************************************************************************
555 %*                                                                      *
556                 Printing interfaces
557 %*                                                                      *
558 %************************************************************************
559
560 \begin{code}
561 -- | Read binary interface, and print it out
562 showIface :: HscEnv -> FilePath -> IO ()
563 showIface hsc_env filename = do
564    -- skip the version check; we don't want to worry about profiled vs.
565    -- non-profiled interfaces, for example.
566    writeIORef v_IgnoreHiWay True
567    iface <- initTcRnIf 's' hsc_env () () $ readBinIface  filename
568    printDump (pprModIface iface)
569 \end{code}
570
571 \begin{code}
572 pprModIface :: ModIface -> SDoc
573 -- Show a ModIface
574 pprModIface iface
575  = vcat [ ptext SLIT("interface")
576                 <+> ppr (mi_module iface) <+> pp_boot 
577                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
578                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
579                 <+> (if mi_finsts iface then ptext SLIT("[family instance module]") else empty)
580                 <+> integer opt_HiVersion
581                 <+> ptext SLIT("where")
582         , vcat (map pprExport (mi_exports iface))
583         , pprDeps (mi_deps iface)
584         , vcat (map pprUsage (mi_usages iface))
585         , pprFixities (mi_fixities iface)
586         , vcat (map pprIfaceDecl (mi_decls iface))
587         , vcat (map ppr (mi_insts iface))
588         , vcat (map ppr (mi_fam_insts iface))
589         , vcat (map ppr (mi_rules iface))
590         , pprDeprecs (mi_deprecs iface)
591         ]
592   where
593     pp_boot | mi_boot iface = ptext SLIT("[boot]")
594             | otherwise     = empty
595
596     exp_vers  = mi_exp_vers iface
597     rule_vers = mi_rule_vers iface
598
599     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
600                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
601 \end{code}
602
603 When printing export lists, we print like this:
604         Avail   f               f
605         AvailTC C [C, x, y]     C(x,y)
606         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
607
608 \begin{code}
609 pprExport :: IfaceExport -> SDoc
610 pprExport (mod, items)
611  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
612   where
613     pp_avail :: GenAvailInfo OccName -> SDoc
614     pp_avail (Avail occ)    = ppr occ
615     pp_avail (AvailTC _ []) = empty
616     pp_avail (AvailTC n (n':ns)) 
617         | n==n'     = ppr n <> pp_export ns
618         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
619     
620     pp_export []    = empty
621     pp_export names = braces (hsep (map ppr names))
622
623 pprUsage :: Usage -> SDoc
624 pprUsage usage
625   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
626           int (usg_mod usage), 
627           pp_export_version (usg_exports usage),
628           int (usg_rules usage),
629           pp_versions (usg_entities usage) ]
630   where
631     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
632     pp_export_version Nothing  = empty
633     pp_export_version (Just v) = int v
634
635 pprDeps :: Dependencies -> SDoc
636 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs,
637                 dep_finsts = finsts })
638   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
639           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
640           ptext SLIT("orphans:") <+> fsep (map ppr orphs),
641           ptext SLIT("family instance modules:") <+> fsep (map ppr finsts)
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
703 homeModError mod location
704   = ptext SLIT("attempting to use module ") <> quotes (ppr mod)
705     <> (case ml_hs_file location of
706            Just file -> space <> parens (text file)
707            Nothing   -> empty)
708     <+> ptext SLIT("which is not loaded")
709 \end{code}
710