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