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