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