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