b4178dbfe0cee609a695a2b183065195f62bba43
[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, mkIface, mkUsageInfo,
10         pprIface, 
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(..), FixitySig(..),
21                           Version, initialVersion, bumpVersion 
22                         )
23 import NewDemand        ( isTopSig )
24 import TcRnMonad
25 import TcRnTypes        ( ImportAvails(..) )
26 import RnHsSyn          ( RenamedInstDecl, RenamedTyClDecl )
27 import HscTypes         ( VersionInfo(..), ModIface(..), HomeModInfo(..),
28                           ModGuts(..), ModGuts, 
29                           GhciMode(..), HscEnv(..), Dependencies(..),
30                           FixityEnv, lookupFixity, collectFixities,
31                           IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
32                           TyThing(..), DFunId, 
33                           Avails, AvailInfo, GenAvailInfo(..), availName, 
34                           ExternalPackageState(..),
35                           ParsedIface(..), Usage(..),
36                           Deprecations(..), initialVersionInfo,
37                           lookupVersion, lookupIfaceByModName
38                         )
39
40 import CmdLineOpts
41 import Id               ( idType, idInfo, isImplicitId, idCgInfo )
42 import DataCon          ( dataConSig, dataConFieldLabels, dataConStrictMarks )
43 import IdInfo           -- Lots
44 import CoreSyn          ( CoreRule(..), IdCoreRule )
45 import CoreFVs          ( ruleLhsFreeNames )
46 import CoreUnfold       ( neverUnfold, unfoldingTemplate )
47 import Name             ( getName, nameModule, nameModule_maybe, nameOccName,
48                           nameIsLocalOrFrom, Name, NamedThing(..) )
49 import NameEnv
50 import NameSet
51 import OccName          ( OccName, pprOccName )
52 import TyCon            ( DataConDetails(..), tyConTyVars, tyConDataCons, tyConTheta,
53                           isFunTyCon, isPrimTyCon, isNewTyCon, isClassTyCon, 
54                           isSynTyCon, isAlgTyCon, isForeignTyCon,
55                           getSynTyConDefn, tyConGenInfo, tyConDataConDetails, tyConArity )
56 import Class            ( classExtraBigSig, classTyCon, DefMeth(..) )
57 import FieldLabel       ( fieldLabelType )
58 import TcType           ( tcSplitSigmaTy, tidyTopType, deNoteType, tyClsNamesOfDFunHead )
59 import SrcLoc           ( noSrcLoc )
60 import Module           ( Module, ModuleName, moduleNameFS, moduleName, isHomeModule,
61                           ModLocation(..), mkSysModuleNameFS, 
62                           ModuleEnv, emptyModuleEnv, foldModuleEnv, lookupModuleEnv,
63                           extendModuleEnv_C, elemModuleSet, moduleEnvElts, elemModuleEnv
64                         )
65 import Outputable
66 import Util             ( sortLt, dropList, seqList )
67 import Binary           ( getBinFileWithDict )
68 import BinIface         ( writeBinIface )
69 import ErrUtils         ( dumpIfSet_dyn )
70 import FiniteMap
71 import FastString
72
73 import Monad            ( when )
74 import Maybe            ( catMaybes, isJust, isNothing )
75 import Maybes           ( orElse )
76 import IO               ( putStrLn )
77 \end{code}
78
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection{Print out the contents of a binary interface}
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 showIface :: FilePath -> IO ()
88 showIface filename = do
89    parsed_iface <- Binary.getBinFileWithDict filename
90    let ParsedIface{
91       pi_mod=pi_mod, pi_pkg=pi_pkg, pi_vers=pi_vers,
92       pi_deps=pi_deps,
93       pi_orphan=pi_orphan, pi_usages=pi_usages,
94       pi_exports=pi_exports, pi_decls=pi_decls,
95       pi_fixity=pi_fixity, pi_insts=pi_insts,
96       pi_rules=pi_rules, pi_deprecs=pi_deprecs } = parsed_iface
97    putStrLn (showSDoc (vcat [
98         text "__interface" <+> doubleQuotes (ppr pi_pkg)
99            <+> ppr pi_mod <+> ppr pi_vers 
100            <+> (if pi_orphan then char '!' else empty)
101            <+> ptext SLIT("where"),
102         -- no instance Outputable (WhatsImported):
103         pprExports id (snd pi_exports),
104         pprDeps pi_deps,
105         pprUsages  id pi_usages,
106         hsep (map ppr_fix pi_fixity) <> semi,
107         vcat (map ppr_inst pi_insts),
108         vcat (map ppr_decl pi_decls),
109         ppr pi_rules
110         -- no instance Outputable (Either):
111         -- ppr pi_deprecs
112         ]))
113    where
114     ppr_fix (FixitySig n f _) = ppr f <+> ppr n
115     ppr_inst i  = ppr i <+> semi
116     ppr_decl (v,d)  = int v <+> ppr d <> semi
117 \end{code}
118
119 %************************************************************************
120 %*                                                                      *
121 \subsection{Completing an interface}
122 %*                                                                      *
123 %************************************************************************
124
125 \begin{code}
126 mkIface :: HscEnv
127         -> ModLocation
128         -> Maybe ModIface       -- The old interface, if we have it
129         -> ModGuts              -- The compiled, tidied module
130         -> IO ModIface          -- The new one, complete with decls and versions
131 -- mkFinalIface 
132 --      a) completes the interface
133 --      b) writes it out to a file if necessary
134
135 mkIface hsc_env location maybe_old_iface 
136         impl@ModGuts{ mg_module = this_mod,
137                       mg_usages = usages,
138                       mg_deps   = deps,
139                       mg_exports = exports,
140                       mg_rdr_env = rdr_env,
141                       mg_fix_env = fix_env,
142                       mg_deprecs = deprecs,
143                       mg_insts = insts, 
144                       mg_rules = rules,
145                       mg_types = types }
146   = do  {       -- Sort the exports to make them easier to compare for versions
147           let { my_exports = groupAvails this_mod exports ;
148
149                 iface_w_decls = ModIface { mi_module   = this_mod,
150                                            mi_package  = opt_InPackage,
151                                            mi_version  = initialVersionInfo,
152                                            mi_deps     = deps,
153                                            mi_usages   = usages,
154                                            mi_exports  = my_exports,
155                                            mi_decls    = new_decls,
156                                            mi_orphan   = orphan_mod,
157                                            mi_boot     = False,
158                                            mi_fixities = fix_env,
159                                            mi_globals  = Just rdr_env,
160                                            mi_deprecs  = deprecs } }
161
162                 -- Add version information
163         ; let (final_iface, maybe_diffs) = _scc_ "versioninfo" addVersionInfo maybe_old_iface iface_w_decls
164
165                 -- Write the interface file, if necessary
166         ; when (must_write_hi_file maybe_diffs)
167                 (writeBinIface hi_file_path final_iface)
168 --              (writeIface hi_file_path final_iface)
169
170                 -- Debug printing
171         ; write_diffs dflags final_iface maybe_diffs
172
173         ; orphan_mod `seq`
174           return final_iface }
175
176   where
177      dflags    = hsc_dflags hsc_env
178      ghci_mode = hsc_mode hsc_env
179
180      must_write_hi_file Nothing       = False
181      must_write_hi_file (Just _diffs) = ghci_mode /= Interactive
182                 -- We must write a new .hi file if there are some changes
183                 -- and we're not in interactive mode
184                 -- maybe_diffs = 'Nothing' means that even the usages havn't changed, 
185                 --     so there's no need to write a new interface file.  But even if 
186                 --     the usages have changed, the module version may not have.
187
188      hi_file_path = ml_hi_file location
189      new_decls    = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
190      inst_dcls    = map ifaceInstance insts
191      ty_cls_dcls  = foldNameEnv ifaceTyThing_acc [] types
192      rule_dcls    = map ifaceRule rules
193      orphan_mod   = isOrphanModule impl
194
195 write_diffs :: DynFlags -> ModIface -> Maybe SDoc -> IO ()
196 write_diffs dflags new_iface Nothing
197   = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
198        dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
199
200 write_diffs dflags new_iface (Just sdoc_diffs)
201   = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
202        dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
203 \end{code}
204
205 \begin{code}
206 isOrphanModule :: ModGuts -> Bool
207 isOrphanModule (ModGuts {mg_module = this_mod, mg_insts = insts, mg_rules = rules})
208   = any orphan_inst insts || any orphan_rule rules
209   where
210         -- A rule is an orphan if the LHS mentions nothing defined locally
211     orphan_inst dfun_id = no_locals (tyClsNamesOfDFunHead (idType dfun_id))
212         -- A instance is an orphan if its head mentions nothing defined locally
213     orphan_rule rule    = no_locals (ruleLhsFreeNames rule)
214
215     no_locals names     = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
216 \end{code}
217
218 Implicit Ids and class tycons aren't included in interface files, so
219 we miss them out of the accumulating parameter here.
220
221 \begin{code}
222 ifaceTyThing_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
223 ifaceTyThing_acc (AnId   id) so_far | isImplicitId id = so_far
224 ifaceTyThing_acc (ATyCon id) so_far | isClassTyCon id = so_far
225 ifaceTyThing_acc other so_far = ifaceTyThing other : so_far
226 \end{code}
227
228 Convert *any* TyThing into a RenamedTyClDecl.  Used both for
229 generating interface files and for the ':info' command in GHCi.
230
231 \begin{code}
232 ifaceTyThing :: TyThing -> RenamedTyClDecl
233 ifaceTyThing (AClass clas) = cls_decl
234   where
235     cls_decl = ClassDecl { tcdCtxt      = toHsContext sc_theta,
236                            tcdName      = getName clas,
237                            tcdTyVars    = toHsTyVars clas_tyvars,
238                            tcdFDs       = toHsFDs clas_fds,
239                            tcdSigs      = map toClassOpSig op_stuff,
240                            tcdMeths     = Nothing, 
241                            tcdLoc       = noSrcLoc }
242
243     (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
244     tycon     = classTyCon clas
245     data_con  = head (tyConDataCons tycon)
246
247     toClassOpSig (sel_id, def_meth)
248         = ASSERT(sel_tyvars == clas_tyvars)
249           ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
250         where
251           (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
252           def_meth' = case def_meth of
253                          NoDefMeth  -> NoDefMeth
254                          GenDefMeth -> GenDefMeth
255                          DefMeth id -> DefMeth (getName id)
256
257 ifaceTyThing (ATyCon tycon) = ty_decl
258   where
259     ty_decl | isSynTyCon tycon
260             = TySynonym { tcdName   = getName tycon,
261                           tcdTyVars = toHsTyVars tyvars,
262                           tcdSynRhs = toHsType syn_ty,
263                           tcdLoc    = noSrcLoc }
264
265             | isAlgTyCon tycon
266             = TyData {  tcdND      = new_or_data,
267                         tcdCtxt    = toHsContext (tyConTheta tycon),
268                         tcdName    = getName tycon,
269                         tcdTyVars  = toHsTyVars tyvars,
270                         tcdCons    = ifaceConDecls (tyConDataConDetails tycon),
271                         tcdDerivs  = Nothing,
272                         tcdGeneric = Just (isJust (tyConGenInfo tycon)),
273                                 -- Just True <=> has generic stuff
274                         tcdLoc     = noSrcLoc }
275
276             | isForeignTyCon tycon
277             = ForeignType { tcdName    = getName tycon,
278                             tcdExtName = Nothing,
279                             tcdFoType  = DNType,        -- The only case at present
280                             tcdLoc     = noSrcLoc }
281
282             | isPrimTyCon tycon || isFunTyCon tycon
283                 -- needed in GHCi for ':info Int#', for example
284             = TyData {  tcdND     = DataType,
285                         tcdCtxt   = [],
286                         tcdName   = getName tycon,
287                         tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
288                         tcdCons   = Unknown,
289                         tcdDerivs = Nothing,
290                         tcdGeneric  = Just False,
291                         tcdLoc       = noSrcLoc }
292
293             | otherwise = pprPanic "ifaceTyThing" (ppr tycon)
294
295     tyvars      = tyConTyVars tycon
296     (_, syn_ty) = getSynTyConDefn tycon
297     new_or_data | isNewTyCon tycon = NewType
298                 | otherwise        = DataType
299
300     ifaceConDecls Unknown       = Unknown
301     ifaceConDecls (HasCons n)   = HasCons n
302     ifaceConDecls (DataCons cs) = DataCons (map ifaceConDecl cs)
303
304     ifaceConDecl data_con 
305         = ConDecl (getName data_con)
306                   (toHsTyVars ex_tyvars)
307                   (toHsContext ex_theta)
308                   details noSrcLoc
309         where
310           (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
311           field_labels   = dataConFieldLabels data_con
312           strict_marks   = dropList ex_theta (dataConStrictMarks data_con)
313                                 -- The 'drop' is because dataConStrictMarks
314                                 -- includes the existential dictionaries
315           details | null field_labels
316                   = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
317                     PrefixCon (zipWith BangType strict_marks (map toHsType arg_tys))
318
319                   | otherwise
320                   = RecCon (zipWith mk_field strict_marks field_labels)
321
322     mk_field strict_mark field_label
323         = (getName field_label, BangType strict_mark (toHsType (fieldLabelType field_label)))
324
325 ifaceTyThing (AnId id) = iface_sig
326   where
327     iface_sig = IfaceSig { tcdName   = getName id, 
328                            tcdType   = toHsType id_type,
329                            tcdIdInfo = hs_idinfo,
330                            tcdLoc    =  noSrcLoc }
331
332     id_type = idType id
333     id_info = idInfo id
334     cg_info = idCgInfo id
335     arity_info = arityInfo id_info
336     caf_info   = cgCafInfo cg_info
337
338     hs_idinfo | opt_OmitInterfacePragmas
339               = []
340               | otherwise
341               = catMaybes [arity_hsinfo,  caf_hsinfo,
342                            strict_hsinfo, wrkr_hsinfo,
343                            unfold_hsinfo] 
344
345     ------------  Arity  --------------
346     arity_hsinfo | arity_info == 0 = Nothing
347                  | otherwise       = Just (HsArity arity_info)
348
349     ------------ Caf Info --------------
350     caf_hsinfo = case caf_info of
351                    NoCafRefs -> Just HsNoCafRefs
352                    _other    -> Nothing
353
354     ------------  Strictness  --------------
355         -- No point in explicitly exporting TopSig
356     strict_hsinfo = case newStrictnessInfo id_info of
357                         Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
358                         _other                        -> Nothing
359
360     ------------  Worker  --------------
361     work_info   = workerInfo id_info
362     has_worker  = case work_info of { HasWorker _ _ -> True; other -> False }
363     wrkr_hsinfo = case work_info of
364                     HasWorker work_id wrap_arity -> 
365                         Just (HsWorker (getName work_id) wrap_arity)
366                     NoWorker -> Nothing
367
368     ------------  Unfolding  --------------
369         -- The unfolding is redundant if there is a worker
370     unfold_info = unfoldingInfo id_info
371     inline_prag = inlinePragInfo id_info
372     rhs         = unfoldingTemplate unfold_info
373     unfold_hsinfo |  neverUnfold unfold_info 
374                   || has_worker = Nothing
375                   | otherwise   = Just (HsUnfold inline_prag (toUfExpr rhs))
376 \end{code}
377
378 \begin{code}
379 ifaceInstance :: DFunId -> RenamedInstDecl
380 ifaceInstance dfun_id
381   = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc                      
382   where
383     tidy_ty = tidyTopType (deNoteType (idType dfun_id))
384                 -- The deNoteType is very important.   It removes all type
385                 -- synonyms from the instance type in interface files.
386                 -- That in turn makes sure that when reading in instance decls
387                 -- from interface files that the 'gating' mechanism works properly.
388                 -- Otherwise you could have
389                 --      type Tibble = T Int
390                 --      instance Foo Tibble where ...
391                 -- and this instance decl wouldn't get imported into a module
392                 -- that mentioned T but not Tibble.
393
394 ifaceRule :: IdCoreRule -> RuleDecl Name
395 ifaceRule (id, BuiltinRule _ _)
396   = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
397
398 ifaceRule (id, Rule name act bndrs args rhs)
399   = IfaceRule name act (map toUfBndr bndrs) (getName id)
400               (map toUfExpr args) (toUfExpr rhs) noSrcLoc
401
402 bogusIfaceRule :: (NamedThing a) => a -> RuleDecl Name
403 bogusIfaceRule id
404   = IfaceRule FSLIT("bogus") NeverActive [] (getName id) [] (UfVar (getName id)) noSrcLoc
405 \end{code}
406
407
408 %*********************************************************
409 %*                                                      *
410 \subsection{Keeping track of what we've slurped, and version numbers}
411 %*                                                      *
412 %*********************************************************
413
414 mkUsageInfo figures out what the ``usage information'' for this
415 moudule is; that is, what it must record in its interface file as the
416 things it uses.  
417
418 We produce a line for every module B below the module, A, currently being
419 compiled:
420         import B <n> ;
421 to record the fact that A does import B indirectly.  This is used to decide
422 to look to look for B.hi rather than B.hi-boot when compiling a module that
423 imports A.  This line says that A imports B, but uses nothing in it.
424 So we'll get an early bale-out when compiling A if B's version changes.
425
426 The usage information records:
427
428 \begin{itemize}
429 \item   (a) anything reachable from its body code
430 \item   (b) any module exported with a @module Foo@
431 \item   (c) anything reachable from an exported item
432 \end{itemize}
433
434 Why (b)?  Because if @Foo@ changes then this module's export list
435 will change, so we must recompile this module at least as far as
436 making a new interface file --- but in practice that means complete
437 recompilation.
438
439 Why (c)?  Consider this:
440 \begin{verbatim}
441         module A( f, g ) where  |       module B( f ) where
442           import B( f )         |         f = h 3
443           g = ...               |         h = ...
444 \end{verbatim}
445
446 Here, @B.f@ isn't used in A.  Should we nevertheless record @B.f@ in
447 @A@'s usages?  Our idea is that we aren't going to touch A.hi if it is
448 *identical* to what it was before.  If anything about @B.f@ changes
449 than anyone who imports @A@ should be recompiled in case they use
450 @B.f@ (they'll get an early exit if they don't).  So, if anything
451 about @B.f@ changes we'd better make sure that something in A.hi
452 changes, and the convenient way to do that is to record the version
453 number @B.f@ in A.hi in the usage list.  If B.f changes that'll force a
454 complete recompiation of A, which is overkill but it's the only way to 
455 write a new, slightly different, A.hi.
456
457 But the example is tricker.  Even if @B.f@ doesn't change at all,
458 @B.h@ may do so, and this change may not be reflected in @f@'s version
459 number.  But with -O, a module that imports A must be recompiled if
460 @B.h@ changes!  So A must record a dependency on @B.h@.  So we treat
461 the occurrence of @B.f@ in the export list *just as if* it were in the
462 code of A, and thereby haul in all the stuff reachable from it.
463
464         *** Conclusion: if A mentions B.f in its export list,
465             behave just as if A mentioned B.f in its source code,
466             and slurp in B.f and all its transitive closure ***
467
468 [NB: If B was compiled with -O, but A isn't, we should really *still*
469 haul in all the unfoldings for B, in case the module that imports A *is*
470 compiled with -O.  I think this is the case.]
471
472 \begin{code}
473 mkUsageInfo :: HscEnv -> ExternalPackageState
474             -> ImportAvails -> EntityUsage
475             -> [Usage Name]
476
477 mkUsageInfo hsc_env eps
478             (ImportAvails { imp_mods = dir_imp_mods,
479                             imp_dep_mods = dep_mods })
480             used_names
481   = -- seq the list of Usages returned: occasionally these
482     -- don't get evaluated for a while and we can end up hanging on to
483     -- the entire collection of Ifaces.
484     usages `seqList` usages
485   where
486     usages = catMaybes [ mkUsage mod_name 
487                        | (mod_name,_) <- moduleEnvElts dep_mods]
488
489     hpt = hsc_HPT hsc_env
490     pit = eps_PIT eps
491     
492     import_all mod = case lookupModuleEnv dir_imp_mods mod of
493                         Just (_,imp_all) -> imp_all
494                         Nothing          -> False
495     
496     -- ent_map groups together all the things imported and used
497     -- from a particular module in this package
498     ent_map :: ModuleEnv [Name]
499     ent_map  = foldNameSet add_mv emptyModuleEnv used_names
500     add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [name]
501                    where
502                      mod = nameModule name
503                      add_item names _ = name:names
504     
505     -- We want to create a Usage for a home module if 
506     --  a) we used something from; has something in used_names
507     --  b) we imported all of it, even if we used nothing from it
508     --          (need to recompile if its export list changes: export_vers)
509     --  c) is a home-package orphan module (need to recompile if its
510     --          instance decls change: rules_vers)
511     mkUsage :: ModuleName -> Maybe (Usage Name)
512     mkUsage mod_name
513       |  isNothing maybe_iface  -- We can't depend on it if we didn't
514       || not (isHomeModule mod) -- even open the interface!
515       || (null used_names
516           && not all_imported
517           && not orphan_mod)
518       = Nothing                 -- Record no usage info
519     
520       | otherwise       
521       = Just (Usage { usg_name     = moduleName mod,
522                       usg_mod      = mod_vers,
523                       usg_exports  = export_vers,
524                       usg_entities = ent_vers,
525                       usg_rules    = rules_vers })
526       where
527         maybe_iface  = lookupIfaceByModName hpt pit mod_name
528                 -- In one-shot mode, the interfaces for home-package 
529                 -- modules accumulate in the PIT not HPT.  Sigh.
530
531         Just iface   = maybe_iface
532         mod          = mi_module iface
533         version_info = mi_version iface
534         orphan_mod   = mi_orphan iface
535         version_env  = vers_decls   version_info
536         mod_vers     = vers_module  version_info
537         rules_vers   = vers_rules   version_info
538         all_imported = import_all mod 
539         export_vers | all_imported = Just (vers_exports version_info)
540                     | otherwise    = Nothing
541     
542         -- The sort is to put them into canonical order
543         used_names = lookupModuleEnv ent_map mod `orElse` []
544         ent_vers = [(n, lookupVersion version_env n) 
545                    | n <- sortLt lt_occ used_names ]
546         lt_occ n1 n2 = nameOccName n1 < nameOccName n2
547 \end{code}
548
549 \begin{code}
550 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
551   -- Group by module and sort by occurrence
552   -- This keeps the list in canonical order
553 groupAvails this_mod avails 
554   = [ (mkSysModuleNameFS fs, sortLt lt avails)
555     | (fs,avails) <- fmToList groupFM
556     ]
557   where
558     groupFM :: FiniteMap FastString Avails
559         -- Deliberately use the FastString so we
560         -- get a canonical ordering
561     groupFM = foldl add emptyFM avails
562
563     add env avail = addToFM_C combine env mod_fs [avail']
564                   where
565                     mod_fs = moduleNameFS (moduleName avail_mod)
566                     avail_mod = case nameModule_maybe (availName avail) of
567                                           Just m  -> m
568                                           Nothing -> this_mod
569                     combine old _ = avail':old
570                     avail'        = sortAvail avail
571
572     a1 `lt` a2 = occ1 < occ2
573                where
574                  occ1  = nameOccName (availName a1)
575                  occ2  = nameOccName (availName a2)
576
577 sortAvail :: AvailInfo -> AvailInfo
578 -- Sort the sub-names into canonical order.
579 -- The canonical order has the "main name" at the beginning 
580 -- (if it's there at all)
581 sortAvail (Avail n) = Avail n
582 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
583                          | otherwise   = AvailTC n (    sortLt lt ns)
584                          where
585                            n1 `lt` n2 = nameOccName n1 < nameOccName n2
586 \end{code}
587
588 %************************************************************************
589 %*                                                                      *
590 \subsection{Checking if the new interface is up to date
591 %*                                                                      *
592 %************************************************************************
593
594 \begin{code}
595 addVersionInfo :: Maybe ModIface                -- The old interface, read from M.hi
596                -> ModIface                      -- The new interface decls
597                -> (ModIface, Maybe SDoc)        -- Nothing => no change; no need to write new Iface
598                                                 -- Just mi => Here is the new interface to write
599                                                 --            with correct version numbers
600
601 -- NB: the fixities, declarations, rules are all assumed
602 -- to be sorted by increasing order of hsDeclName, so that 
603 -- we can compare for equality
604
605 addVersionInfo Nothing new_iface
606 -- No old interface, so definitely write a new one!
607   = (new_iface, Just (text "No old interface available"))
608
609 addVersionInfo (Just old_iface@(ModIface { mi_version  = old_version, 
610                                            mi_decls    = old_decls,
611                                            mi_fixities = old_fixities,
612                                            mi_deprecs  = old_deprecs }))
613                new_iface@(ModIface { mi_decls    = new_decls,
614                                      mi_fixities = new_fixities,
615                                      mi_deprecs  = new_deprecs })
616
617   | no_output_change && no_usage_change
618   = (new_iface, Nothing)
619         -- don't return the old iface because it may not have an
620         -- mi_globals field set to anything reasonable.
621
622   | otherwise           -- Add updated version numbers
623   = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
624     (final_iface, Just pp_diffs)
625         
626   where
627     final_iface = new_iface { mi_version = new_version }
628     old_mod_vers = vers_module  old_version
629     new_version = VersionInfo { vers_module  = bumpVersion no_output_change old_mod_vers,
630                                 vers_exports = bumpVersion no_export_change (vers_exports old_version),
631                                 vers_rules   = bumpVersion no_rule_change   (vers_rules   old_version),
632                                 vers_decls   = tc_vers }
633
634     no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
635     no_usage_change  = mi_usages old_iface == mi_usages new_iface
636
637     no_export_change = mi_exports old_iface == mi_exports new_iface             -- Kept sorted
638     no_rule_change   = dcl_rules old_decls  == dcl_rules  new_decls             -- Ditto
639                      && dcl_insts old_decls == dcl_insts  new_decls
640     no_deprec_change = old_deprecs          == new_deprecs
641
642         -- Fill in the version number on the new declarations by looking at the old declarations.
643         -- Set the flag if anything changes. 
644         -- Assumes that the decls are sorted by hsDeclName.
645     (no_tc_change,  pp_tc_diffs,  tc_vers) = diffDecls old_version old_fixities new_fixities
646                                                        (dcl_tycl old_decls) (dcl_tycl new_decls)
647     pp_diffs = vcat [pp_tc_diffs,
648                      pp_change no_export_change "Export list",
649                      pp_change no_rule_change   "Rules",
650                      pp_change no_deprec_change "Deprecations",
651                      pp_change no_usage_change  "Usages"]
652     pp_change True  what = empty
653     pp_change False what = text what <+> ptext SLIT("changed")
654
655 diffDecls :: VersionInfo                                -- Old version
656           -> FixityEnv -> FixityEnv                     -- Old and new fixities
657           -> [RenamedTyClDecl] -> [RenamedTyClDecl]     -- Old and new decls
658           -> (Bool,             -- True <=> no change
659               SDoc,             -- Record of differences
660               NameEnv Version)  -- New version map
661
662 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
663           old_fixities new_fixities old new
664   = diff True empty emptyNameEnv old new
665   where
666         -- When seeing if two decls are the same, 
667         -- remember to check whether any relevant fixity has changed
668     eq_tc  d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
669     same_fixity n = lookupFixity old_fixities n == lookupFixity new_fixities n
670
671     diff ok_so_far pp new_vers []  []      = (ok_so_far, pp, new_vers)
672     diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers          ods []
673     diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new []  nds
674         where
675           new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
676                 -- When adding a new item, start from the old module version
677                 -- This way, if you have version 4 of f, then delete f, then add f again,
678                 -- you'll get version 6 of f, which will (correctly) force recompilation of
679                 -- clients
680
681     diff ok_so_far pp new_vers (od:ods) (nd:nds)
682         = case od_name `compare` nd_name of
683                 LT -> diff False (pp $$ only_old od) new_vers ods      (nd:nds)
684                 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
685                 EQ | od `eq_tc` nd -> diff ok_so_far pp                    new_vers           ods nds
686                    | otherwise     -> diff False     (pp $$ changed od nd) new_vers_with_diff ods nds
687         where
688           od_name = tyClDeclName od
689           nd_name = tyClDeclName nd
690           new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
691           old_version = lookupVersion old_decls_vers od_name
692
693     only_old d    = ptext SLIT("Only in old iface:") <+> ppr d
694     only_new d    = ptext SLIT("Only in new iface:") <+> ppr d
695     changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$ 
696                                                          (ptext SLIT("New:")  <+> ppr nd))
697 \end{code}
698
699
700 b%************************************************************************
701 %*                                                                      *
702 \subsection{Writing an interface file}
703 %*                                                                      *
704 %************************************************************************
705
706 \begin{code}
707 pprIface :: ModIface -> SDoc
708 pprIface iface
709  = vcat [ ptext SLIT("__interface")
710                 <+> doubleQuotes (ftext (mi_package iface))
711                 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
712                 <+> pp_sub_vers
713                 <+> (if mi_orphan iface then char '!' else empty)
714                 <+> int opt_HiVersion
715                 <+> ptext SLIT("where")
716
717         , pprExports nameOccName (mi_exports iface)
718         , pprDeps    (mi_deps iface)
719         , pprUsages  nameOccName (mi_usages iface)
720
721         , pprFixities (mi_fixities iface) (dcl_tycl decls)
722         , pprIfaceDecls (vers_decls version_info) decls
723         , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
724         ]
725   where
726     version_info = mi_version iface
727     decls        = mi_decls iface
728     exp_vers     = vers_exports version_info
729
730     rule_vers    = vers_rules version_info
731
732     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
733                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
734 \end{code}
735
736 When printing export lists, we print like this:
737         Avail   f               f
738         AvailTC C [C, x, y]     C(x,y)
739         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
740
741 \begin{code}
742 pprExports :: Eq a => (a -> OccName) -> [(ModuleName, [GenAvailInfo a])] -> SDoc
743 pprExports getOcc exports = vcat (map (pprExport getOcc) exports)
744
745 pprExport :: Eq a => (a -> OccName) -> (ModuleName, [GenAvailInfo a]) -> SDoc
746 pprExport getOcc (mod, items)
747  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
748   where
749     --pp_avail :: GenAvailInfo a -> SDoc
750     pp_avail (Avail name)                    = ppr (getOcc name)
751     pp_avail (AvailTC _ [])                  = empty
752     pp_avail (AvailTC n (n':ns)) 
753         | n==n'     = ppr (getOcc n) <> pp_export ns
754         | otherwise = ppr (getOcc n) <> char '|' <> pp_export (n':ns)
755     
756     pp_export []    = empty
757     pp_export names = braces (hsep (map (ppr.getOcc) names))
758
759 pprOcc :: Name -> SDoc  -- Print the occurrence name only
760 pprOcc n = pprOccName (nameOccName n)
761 \end{code}
762
763
764 \begin{code}
765 pprUsages :: (a -> OccName) -> [Usage a] -> SDoc
766 pprUsages getOcc usages = vcat (map (pprUsage getOcc) usages)
767
768 pprUsage :: (a -> OccName) -> Usage a -> SDoc
769 pprUsage getOcc usage
770   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
771           int (usg_mod usage), 
772           pp_export_version (usg_exports usage),
773           int (usg_rules usage),
774           pp_versions (usg_entities usage)
775     ] <> semi
776   where
777     pp_versions nvs = hsep [ ppr (getOcc n) <+> int v | (n,v) <- nvs ]
778
779     pp_export_version Nothing  = empty
780     pp_export_version (Just v) = int v
781
782
783 pprDeps :: Dependencies -> SDoc
784 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
785   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
786           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
787           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
788         ]
789   where
790     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
791    
792     ppr_boot   True  = text "[boot]"
793     ppr_boot   False = empty
794 \end{code}
795
796 \begin{code}
797 pprIfaceDecls :: NameEnv Int -> IfaceDecls -> SDoc
798 pprIfaceDecls version_map decls
799   = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
800          , vcat (map ppr_decl (dcl_tycl decls))
801          ]
802   where
803     ppr_decl d  = ppr_vers d <+> ppr d <> semi
804
805         -- Print the version for the decl
806     ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
807                    Nothing -> empty
808                    Just v  -> int v
809 \end{code}
810
811 \begin{code}
812 pprFixities :: FixityEnv
813             -> [TyClDecl Name]
814             -> SDoc
815 pprFixities fixity_map decls
816   = hsep [ ppr fix <+> ppr n 
817          | FixitySig n fix _ <- collectFixities fixity_map decls ] <> semi
818
819 -- Disgusting to print these two together, but that's 
820 -- the way the interface parser currently expects them.
821 pprRulesAndDeprecs :: (Outputable a) => [a] -> Deprecations -> SDoc
822 pprRulesAndDeprecs [] NoDeprecs = empty
823 pprRulesAndDeprecs rules deprecs
824   = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
825   where
826     pp_rules []    = empty
827     pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
828
829     pp_deprecs NoDeprecs = empty
830     pp_deprecs deprecs   = ptext SLIT("__D") <+> guts
831                           where
832                             guts = case deprecs of
833                                         DeprecAll txt  -> doubleQuotes (ftext txt)
834                                         DeprecSome env -> ppr_deprec_env env
835
836 ppr_deprec_env :: NameEnv (Name, FastString) -> SDoc
837 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
838                    where
839                      pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ftext txt)
840 \end{code}