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