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