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