de344b7ea5e8cb73d8704393116e74f012d4c7c2
[ghc-hetmet.git] / ghc / compiler / main / MkIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4
5 \section[MkIface]{Print an interface for a module}
6
7 \begin{code}
8 module MkIface ( 
9         mkFinalIface,
10         pprModDetails, pprIface, pprUsage,
11         ifaceTyThing,
12   ) where
13
14 #include "HsVersions.h"
15
16 import HsSyn
17 import HsCore           ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
18 import HsTypes          ( toHsTyVars )
19 import TysPrim          ( alphaTyVars )
20 import BasicTypes       ( NewOrData(..), Activation(..),
21                           Version, initialVersion, bumpVersion 
22                         )
23 import NewDemand        ( isTopSig )
24 import RnMonad
25 import RnHsSyn          ( RenamedInstDecl, RenamedTyClDecl )
26 import HscTypes         ( VersionInfo(..), ModIface(..), ModDetails(..),
27                           ModuleLocation(..), GhciMode(..), FixityEnv, lookupFixity,
28                           IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
29                           TyThing(..), DFunId, Avails, TypeEnv,
30                           WhatsImported(..), GenAvailInfo(..), 
31                           ImportVersion, AvailInfo, Deprecations(..),
32                           lookupVersion, typeEnvIds
33                         )
34
35 import CmdLineOpts
36 import Id               ( idType, idInfo, isImplicitId, idCgInfo,
37                           isLocalId, idName,
38                         )
39 import DataCon          ( dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
40 import IdInfo           -- Lots
41 import Var              ( Var )
42 import CoreSyn          ( CoreRule(..), IdCoreRule )
43 import CoreFVs          ( ruleLhsFreeNames )
44 import CoreUnfold       ( neverUnfold, unfoldingTemplate )
45 import PprCore          ( pprIdCoreRule )
46 import Name             ( getName, nameModule, toRdrName, isGlobalName, 
47                           nameIsLocalOrFrom, Name, NamedThing(..) )
48 import NameEnv
49 import NameSet
50 import OccName          ( pprOccName )
51 import TyCon
52 import Class            ( classExtraBigSig, classTyCon, DefMeth(..) )
53 import FieldLabel       ( fieldLabelType )
54 import TcType           ( tcSplitSigmaTy, tidyTopType, deNoteType, namesOfDFunHead )
55 import SrcLoc           ( noSrcLoc )
56 import Outputable
57 import Module           ( ModuleName )
58 import Util             ( sortLt, dropList )
59 import ErrUtils         ( dumpIfSet_dyn )
60
61 import Monad            ( when )
62 import Maybe            ( catMaybes )
63 import IO               ( IOMode(..), openFile, hClose )
64 \end{code}
65
66
67 %************************************************************************
68 %*                                                                      *
69 \subsection{Completing an interface}
70 %*                                                                      *
71 %************************************************************************
72
73 \begin{code}
74
75
76
77 mkFinalIface :: GhciMode
78              -> DynFlags
79              -> ModuleLocation
80              -> Maybe ModIface          -- The old interface, if we have it
81              -> ModIface                -- The new one, minus the decls and versions
82              -> ModDetails              -- The ModDetails for this module
83              -> IO ModIface             -- The new one, complete with decls and versions
84 -- mkFinalIface 
85 --      a) completes the interface
86 --      b) writes it out to a file if necessary
87
88 mkFinalIface ghci_mode dflags location maybe_old_iface 
89         new_iface@ModIface{ mi_module=mod }
90         new_details@ModDetails{ md_insts=insts, 
91                                 md_rules=rules,
92                                 md_types=types }
93   = do  { 
94                 -- Add the new declarations, and the is-orphan flag
95           let iface_w_decls = new_iface { mi_decls = new_decls,
96                                           mi_orphan = orphan_mod }
97
98                 -- Add version information
99         ; let (final_iface, maybe_diffs) = _scc_ "versioninfo" addVersionInfo maybe_old_iface iface_w_decls
100
101                 -- Write the interface file, if necessary
102         ; when (must_write_hi_file maybe_diffs)
103                (writeIface hi_file_path final_iface)
104
105                 -- Debug printing
106         ; write_diffs dflags final_iface maybe_diffs
107
108         ; orphan_mod `seq`
109           return final_iface }
110
111   where
112      must_write_hi_file Nothing       = False
113      must_write_hi_file (Just _diffs) = ghci_mode /= Interactive
114                 -- We must write a new .hi file if there are some changes
115                 -- and we're not in interactive mode
116                 -- maybe_diffs = 'Nothing' means that even the usages havn't changed, 
117                 --     so there's no need to write a new interface file.  But even if 
118                 --     the usages have changed, the module version may not have.
119
120      hi_file_path = ml_hi_file location
121      new_decls    = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
122      inst_dcls    = map ifaceInstance insts
123      ty_cls_dcls  = foldNameEnv ifaceTyThing_acc [] types
124      rule_dcls    = map ifaceRule rules
125      orphan_mod   = isOrphanModule mod new_details
126
127 write_diffs :: DynFlags -> ModIface -> Maybe SDoc -> IO ()
128 write_diffs dflags new_iface Nothing
129   = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
130        dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
131
132 write_diffs dflags new_iface (Just sdoc_diffs)
133   = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
134        dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
135 \end{code}
136
137 \begin{code}
138 isOrphanModule :: Module -> ModDetails -> Bool
139 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
140   = any orphan_inst insts || any orphan_rule rules
141   where
142     orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
143     orphan_rule rule    = no_locals (ruleLhsFreeNames rule)
144     no_locals names     = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
145 \end{code}
146
147 Implicit Ids and class tycons aren't included in interface files, so
148 we miss them out of the accumulating parameter here.
149
150 \begin{code}
151 ifaceTyThing_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
152 ifaceTyThing_acc (AnId   id) so_far | isImplicitId id = so_far
153 ifaceTyThing_acc (ATyCon id) so_far | isClassTyCon id = so_far
154 ifaceTyThing_acc other so_far = ifaceTyThing other : so_far
155 \end{code}
156
157 Convert *any* TyThing into a RenamedTyClDecl.  Used both for
158 generating interface files and for the ':info' command in GHCi.
159
160 \begin{code}
161 ifaceTyThing :: TyThing -> RenamedTyClDecl
162 ifaceTyThing (AClass clas) = cls_decl
163   where
164     cls_decl = ClassDecl { tcdCtxt      = toHsContext sc_theta,
165                            tcdName      = getName clas,
166                            tcdTyVars    = toHsTyVars clas_tyvars,
167                            tcdFDs       = toHsFDs clas_fds,
168                            tcdSigs      = map toClassOpSig op_stuff,
169                            tcdMeths     = Nothing, 
170                            tcdSysNames  = sys_names,
171                            tcdLoc       = noSrcLoc }
172
173     (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
174     tycon     = classTyCon clas
175     data_con  = head (tyConDataCons tycon)
176     sys_names = mkClassDeclSysNames (getName tycon, getName data_con, 
177                                      getName (dataConId data_con), map getName sc_sels)
178
179     toClassOpSig (sel_id, def_meth)
180         = ASSERT(sel_tyvars == clas_tyvars)
181           ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
182         where
183           (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
184           def_meth' = case def_meth of
185                          NoDefMeth  -> NoDefMeth
186                          GenDefMeth -> GenDefMeth
187                          DefMeth id -> DefMeth (getName id)
188
189 ifaceTyThing (ATyCon tycon) = ty_decl
190   where
191     ty_decl | isSynTyCon tycon
192             = TySynonym { tcdName   = getName tycon,
193                           tcdTyVars = toHsTyVars tyvars,
194                           tcdSynRhs = toHsType syn_ty,
195                           tcdLoc    = noSrcLoc }
196
197             | isAlgTyCon tycon
198             = TyData {  tcdND     = new_or_data,
199                         tcdCtxt   = toHsContext (tyConTheta tycon),
200                         tcdName   = getName tycon,
201                         tcdTyVars = toHsTyVars tyvars,
202                         tcdCons   = map ifaceConDecl (tyConDataCons tycon),
203                         tcdNCons  = tyConFamilySize tycon,
204                         tcdDerivs = Nothing,
205                         tcdSysNames  = map getName (tyConGenIds tycon),
206                         tcdLoc       = noSrcLoc }
207
208             | isForeignTyCon tycon
209             = ForeignType { tcdName    = getName tycon,
210                             tcdExtName = Nothing,
211                             tcdFoType  = DNType,        -- The only case at present
212                             tcdLoc     = noSrcLoc }
213
214             | isPrimTyCon tycon || isFunTyCon tycon
215                 -- needed in GHCi for ':info Int#', for example
216             = TyData {  tcdND     = DataType,
217                         tcdCtxt   = [],
218                         tcdName   = getName tycon,
219                         tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
220                         tcdCons   = [],
221                         tcdNCons  = 0,
222                         tcdDerivs = Nothing,
223                         tcdSysNames  = [],
224                         tcdLoc       = noSrcLoc }
225
226             | otherwise = pprPanic "ifaceTyThing" (ppr tycon)
227
228     tyvars      = tyConTyVars tycon
229     (_, syn_ty) = getSynTyConDefn tycon
230     new_or_data | isNewTyCon tycon = NewType
231                 | otherwise        = DataType
232
233     ifaceConDecl data_con 
234         = ConDecl (getName data_con) (getName (dataConId data_con))
235                   (toHsTyVars ex_tyvars)
236                   (toHsContext ex_theta)
237                   details noSrcLoc
238         where
239           (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
240           field_labels   = dataConFieldLabels data_con
241           strict_marks   = dropList ex_theta (dataConStrictMarks data_con)
242                                 -- The 'drop' is because dataConStrictMarks
243                                 -- includes the existential dictionaries
244           details | null field_labels
245                   = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
246                     VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
247
248                   | otherwise
249                   = RecCon (zipWith mk_field strict_marks field_labels)
250
251     mk_field strict_mark field_label
252         = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
253
254 ifaceTyThing (AnId id) = iface_sig
255   where
256     iface_sig = IfaceSig { tcdName   = getName id, 
257                            tcdType   = toHsType id_type,
258                            tcdIdInfo = hs_idinfo,
259                            tcdLoc    =  noSrcLoc }
260
261     id_type = idType id
262     id_info = idInfo id
263     cg_info = idCgInfo id
264     arity_info = arityInfo id_info
265     caf_info   = cgCafInfo cg_info
266
267     hs_idinfo | opt_OmitInterfacePragmas
268               = []
269               | otherwise
270               = catMaybes [arity_hsinfo,  caf_hsinfo,
271                            strict_hsinfo, wrkr_hsinfo,
272                            unfold_hsinfo] 
273
274     ------------  Arity  --------------
275     arity_hsinfo | arity_info == 0 = Nothing
276                  | otherwise       = Just (HsArity arity_info)
277
278     ------------ Caf Info --------------
279     caf_hsinfo = case caf_info of
280                    NoCafRefs -> Just HsNoCafRefs
281                    _other    -> Nothing
282
283     ------------  Strictness  --------------
284         -- No point in explicitly exporting TopSig
285     strict_hsinfo = case newStrictnessInfo id_info of
286                         Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
287                         _other                        -> Nothing
288
289     ------------  Worker  --------------
290     work_info   = workerInfo id_info
291     has_worker  = case work_info of { HasWorker _ _ -> True; other -> False }
292     wrkr_hsinfo = case work_info of
293                     HasWorker work_id wrap_arity -> 
294                         Just (HsWorker (getName work_id) wrap_arity)
295                     NoWorker -> Nothing
296
297     ------------  Unfolding  --------------
298         -- The unfolding is redundant if there is a worker
299     unfold_info = unfoldingInfo id_info
300     inline_prag = inlinePragInfo id_info
301     rhs         = unfoldingTemplate unfold_info
302     unfold_hsinfo |  neverUnfold unfold_info 
303                   || has_worker = Nothing
304                   | otherwise   = Just (HsUnfold inline_prag (toUfExpr rhs))
305 \end{code}
306
307 \begin{code}
308 ifaceInstance :: DFunId -> RenamedInstDecl
309 ifaceInstance dfun_id
310   = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc                      
311   where
312     tidy_ty = tidyTopType (deNoteType (idType dfun_id))
313                 -- The deNoteType is very important.   It removes all type
314                 -- synonyms from the instance type in interface files.
315                 -- That in turn makes sure that when reading in instance decls
316                 -- from interface files that the 'gating' mechanism works properly.
317                 -- Otherwise you could have
318                 --      type Tibble = T Int
319                 --      instance Foo Tibble where ...
320                 -- and this instance decl wouldn't get imported into a module
321                 -- that mentioned T but not Tibble.
322
323 ifaceRule :: IdCoreRule -> RuleDecl Name pat
324 ifaceRule (id, BuiltinRule _ _)
325   = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
326
327 ifaceRule (id, Rule name act bndrs args rhs)
328   = IfaceRule name act (map toUfBndr bndrs) (getName id)
329               (map toUfExpr args) (toUfExpr rhs) noSrcLoc
330
331 bogusIfaceRule :: (NamedThing a) => a -> RuleDecl Name pat
332 bogusIfaceRule id
333   = IfaceRule SLIT("bogus") NeverActive [] (getName id) [] (UfVar (getName id)) noSrcLoc
334 \end{code}
335
336
337 %************************************************************************
338 %*                                                                      *
339 \subsection{Checking if the new interface is up to date
340 %*                                                                      *
341 %************************************************************************
342
343 \begin{code}
344 addVersionInfo :: Maybe ModIface                -- The old interface, read from M.hi
345                -> ModIface                      -- The new interface decls
346                -> (ModIface, Maybe SDoc)        -- Nothing => no change; no need to write new Iface
347                                                 -- Just mi => Here is the new interface to write
348                                                 --            with correct version numbers
349
350 -- NB: the fixities, declarations, rules are all assumed
351 -- to be sorted by increasing order of hsDeclName, so that 
352 -- we can compare for equality
353
354 addVersionInfo Nothing new_iface
355 -- No old interface, so definitely write a new one!
356   = (new_iface, Just (text "No old interface available"))
357
358 addVersionInfo (Just old_iface@(ModIface { mi_version  = old_version, 
359                                            mi_decls    = old_decls,
360                                            mi_fixities = old_fixities,
361                                            mi_deprecs  = old_deprecs }))
362                new_iface@(ModIface { mi_decls    = new_decls,
363                                      mi_fixities = new_fixities,
364                                      mi_deprecs  = new_deprecs })
365
366   | no_output_change && no_usage_change
367   = (new_iface, Nothing)
368         -- don't return the old iface because it may not have an
369         -- mi_globals field set to anything reasonable.
370
371   | otherwise           -- Add updated version numbers
372   = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
373     (final_iface, Just pp_diffs)
374         
375   where
376     final_iface = new_iface { mi_version = new_version }
377     old_mod_vers = vers_module  old_version
378     new_version = VersionInfo { vers_module  = bumpVersion no_output_change old_mod_vers,
379                                 vers_exports = bumpVersion no_export_change (vers_exports old_version),
380                                 vers_rules   = bumpVersion no_rule_change   (vers_rules   old_version),
381                                 vers_decls   = tc_vers }
382
383     no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
384     no_usage_change  = mi_usages old_iface == mi_usages new_iface
385
386     no_export_change = mi_exports old_iface == mi_exports new_iface             -- Kept sorted
387     no_rule_change   = dcl_rules old_decls  == dcl_rules  new_decls             -- Ditto
388     no_deprec_change = old_deprecs          == new_deprecs
389
390         -- Fill in the version number on the new declarations by looking at the old declarations.
391         -- Set the flag if anything changes. 
392         -- Assumes that the decls are sorted by hsDeclName.
393     (no_tc_change,  pp_tc_diffs,  tc_vers) = diffDecls old_version old_fixities new_fixities
394                                                        (dcl_tycl old_decls) (dcl_tycl new_decls)
395     pp_diffs = vcat [pp_tc_diffs,
396                      pp_change no_export_change "Export list",
397                      pp_change no_rule_change   "Rules",
398                      pp_change no_deprec_change "Deprecations",
399                      pp_change no_usage_change  "Usages"]
400     pp_change True  what = empty
401     pp_change False what = text what <+> ptext SLIT("changed")
402
403 diffDecls :: VersionInfo                                -- Old version
404           -> FixityEnv -> FixityEnv                     -- Old and new fixities
405           -> [RenamedTyClDecl] -> [RenamedTyClDecl]     -- Old and new decls
406           -> (Bool,             -- True <=> no change
407               SDoc,             -- Record of differences
408               NameEnv Version)  -- New version map
409
410 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
411           old_fixities new_fixities old new
412   = diff True empty emptyNameEnv old new
413   where
414         -- When seeing if two decls are the same, 
415         -- remember to check whether any relevant fixity has changed
416     eq_tc  d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
417     same_fixity n = lookupFixity old_fixities n == lookupFixity new_fixities n
418
419     diff ok_so_far pp new_vers []  []      = (ok_so_far, pp, new_vers)
420     diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers          ods []
421     diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new []  nds
422         where
423           new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
424                 -- When adding a new item, start from the old module version
425                 -- This way, if you have version 4 of f, then delete f, then add f again,
426                 -- you'll get version 6 of f, which will (correctly) force recompilation of
427                 -- clients
428
429     diff ok_so_far pp new_vers (od:ods) (nd:nds)
430         = case od_name `compare` nd_name of
431                 LT -> diff False (pp $$ only_old od) new_vers ods      (nd:nds)
432                 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
433                 EQ | od `eq_tc` nd -> diff ok_so_far pp                    new_vers           ods nds
434                    | otherwise     -> diff False     (pp $$ changed od nd) new_vers_with_diff ods nds
435         where
436           od_name = tyClDeclName od
437           nd_name = tyClDeclName nd
438           new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
439           old_version = lookupVersion old_decls_vers od_name
440
441     only_old d    = ptext SLIT("Only in old iface:") <+> ppr d
442     only_new d    = ptext SLIT("Only in new iface:") <+> ppr d
443     changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$ 
444                                                          (ptext SLIT("New:")  <+> ppr nd))
445 \end{code}
446
447
448
449 %************************************************************************
450 %*                                                                      *
451 \subsection{Writing ModDetails}
452 %*                                                                      *
453 %************************************************************************
454
455 \begin{code}
456 pprModDetails :: ModDetails -> SDoc
457 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
458   = vcat [ dump_types dfun_ids type_env
459          , dump_insts dfun_ids
460          , dump_rules rules]
461           
462 dump_types :: [Var] -> TypeEnv -> SDoc
463 dump_types dfun_ids type_env
464   = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
465   where
466     ids = [id | id <- typeEnvIds type_env, want_sig id]
467     want_sig id | opt_PprStyle_Debug = True
468                 | otherwise          = isLocalId id && 
469                                        isGlobalName (idName id) && 
470                                        not (id `elem` dfun_ids)
471         -- isLocalId ignores data constructors, records selectors etc
472         -- The isGlobalName ignores local dictionary and method bindings
473         -- that the type checker has invented.  User-defined things have
474         -- Global names.
475
476 dump_insts :: [Var] -> SDoc
477 dump_insts []       = empty
478 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
479
480 dump_sigs :: [Var] -> SDoc
481 dump_sigs ids
482         -- Print type signatures
483         -- Convert to HsType so that we get source-language style printing
484         -- And sort by RdrName
485   = vcat $ map ppr_sig $ sortLt lt_sig $
486     [ (toRdrName id, toHsType (idType id))
487     | id <- ids ]
488   where
489     lt_sig (n1,_) (n2,_) = n1 < n2
490     ppr_sig (n,t)        = ppr n <+> dcolon <+> ppr t
491
492 dump_rules :: [IdCoreRule] -> SDoc
493 dump_rules [] = empty
494 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
495                       nest 4 (vcat (map pprIdCoreRule rs)),
496                       ptext SLIT("#-}")]
497 \end{code}
498
499
500 %************************************************************************
501 %*                                                                      *
502 \subsection{Writing an interface file}
503 %*                                                                      *
504 %************************************************************************
505
506 \begin{code}
507 writeIface :: FilePath -> ModIface -> IO ()
508 writeIface hi_path mod_iface
509   = do  { if_hdl <- openFile hi_path WriteMode
510         ; printForIface if_hdl from_this_mod (pprIface mod_iface)
511         ; hClose if_hdl
512         }
513   where
514         -- Print names unqualified if they are from this module
515     from_this_mod n = nameModule n == this_mod
516     this_mod = mi_module mod_iface
517          
518 pprIface :: ModIface -> SDoc
519 pprIface iface
520  = vcat [ ptext SLIT("__interface")
521                 <+> doubleQuotes (ptext (mi_package iface))
522                 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
523                 <+> pp_sub_vers
524                 <+> (if mi_orphan iface then char '!' else empty)
525                 <+> int opt_HiVersion
526                 <+> ptext SLIT("where")
527
528         , vcat (map pprExport (mi_exports iface))
529         , vcat (map pprUsage (mi_usages iface))
530
531         , pprFixities (mi_fixities iface) (dcl_tycl decls)
532         , pprIfaceDecls (vers_decls version_info) decls
533         , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
534         ]
535   where
536     version_info = mi_version iface
537     decls        = mi_decls iface
538     exp_vers     = vers_exports version_info
539     rule_vers    = vers_rules version_info
540
541     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
542                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
543 \end{code}
544
545 When printing export lists, we print like this:
546         Avail   f               f
547         AvailTC C [C, x, y]     C(x,y)
548         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
549
550 \begin{code}
551 pprExport :: (ModuleName, Avails) -> SDoc
552 pprExport (mod, items)
553  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
554   where
555     pp_avail :: AvailInfo -> SDoc
556     pp_avail (Avail name)                    = pprOcc name
557     pp_avail (AvailTC _ [])                  = empty
558     pp_avail (AvailTC n (n':ns)) | n==n'     = pprOcc n             <> pp_export ns
559                                  | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
560     
561     pp_export []    = empty
562     pp_export names = braces (hsep (map pprOcc names))
563
564 pprOcc :: Name -> SDoc  -- Print the occurrence name only
565 pprOcc n = pprOccName (nameOccName n)
566 \end{code}
567
568
569 \begin{code}
570 pprUsage :: ImportVersion Name -> SDoc
571 pprUsage (m, has_orphans, is_boot, whats_imported)
572   = hsep [ptext SLIT("import"), ppr m, 
573           pp_orphan, pp_boot,
574           pp_versions whats_imported
575     ] <> semi
576   where
577     pp_orphan | has_orphans = char '!'
578               | otherwise   = empty
579     pp_boot   | is_boot     = char '@'
580               | otherwise   = empty
581
582         -- Importing the whole module is indicated by an empty list
583     pp_versions NothingAtAll                = empty
584     pp_versions (Everything v)              = dcolon <+> int v
585     pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr 
586                                               <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
587
588     pp_export_version Nothing  = empty
589     pp_export_version (Just v) = int v
590 \end{code}
591
592 \begin{code}
593 pprIfaceDecls :: NameEnv Int -> IfaceDecls -> SDoc
594 pprIfaceDecls version_map decls
595   = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
596          , vcat (map ppr_decl (dcl_tycl decls))
597          ]
598   where
599     ppr_decl d  = ppr_vers d <+> ppr d <> semi
600
601         -- Print the version for the decl
602     ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
603                    Nothing -> empty
604                    Just v  -> int v
605 \end{code}
606
607 \begin{code}
608 pprFixities :: (Outputable a)
609             => NameEnv a
610             -> [TyClDecl Name pat]
611             -> SDoc
612 pprFixities fixity_map decls
613   = hsep [ ppr fix <+> ppr n 
614          | d <- decls, 
615            (n,_) <- tyClDeclNames d, 
616            Just fix <- [lookupNameEnv fixity_map n]] <> semi
617
618 -- Disgusting to print these two together, but that's 
619 -- the way the interface parser currently expects them.
620 pprRulesAndDeprecs :: (Outputable a) => [a] -> Deprecations -> SDoc
621 pprRulesAndDeprecs [] NoDeprecs = empty
622 pprRulesAndDeprecs rules deprecs
623   = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
624   where
625     pp_rules []    = empty
626     pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
627
628     pp_deprecs NoDeprecs = empty
629     pp_deprecs deprecs   = ptext SLIT("__D") <+> guts
630                           where
631                             guts = case deprecs of
632                                         DeprecAll txt  -> doubleQuotes (ptext txt)
633                                         DeprecSome env -> ppr_deprec_env env
634
635 ppr_deprec_env :: NameEnv (Name, FAST_STRING) -> SDoc
636 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
637                    where
638                      pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)
639 \end{code}