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