e165020947ce1ad3baadd06ced77f0cb4f7bf791
[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, idCafInfo )
42 import DataCon          ( dataConName, dataConSig, dataConFieldLabels,
43                           dataConStrictMarks, dataConWrapId )
44 import IdInfo           -- Lots
45 import CoreSyn          ( CoreRule(..), IdCoreRule )
46 import CoreFVs          ( ruleLhsFreeNames )
47 import CoreUnfold       ( neverUnfold, unfoldingTemplate )
48 import Name             ( getName, nameModule, nameModule_maybe, nameOccName,
49                           nameIsLocalOrFrom, Name, NamedThing(..) )
50 import NameEnv
51 import NameSet
52 import OccName          ( OccName, pprOccName )
53 import TyCon            ( DataConDetails(..), tyConTyVars, tyConDataCons, tyConTheta,
54                           isFunTyCon, isPrimTyCon, isNewTyCon, isClassTyCon, 
55                           isSynTyCon, isAlgTyCon, isForeignTyCon,
56                           getSynTyConDefn, tyConGenInfo, tyConDataConDetails, tyConArity )
57 import Class            ( classExtraBigSig, classTyCon )
58 import FieldLabel       ( fieldLabelType )
59 import TcType           ( tcSplitForAllTys, tcFunResultTy, tidyTopType, deNoteType, tyClsNamesOfDFunHead )
60 import SrcLoc           ( noSrcLoc )
61 import Module           ( Module, ModuleName, moduleNameFS, moduleName, isHomeModule,
62                           ModLocation(..), mkSysModuleNameFS, 
63                           ModuleEnv, emptyModuleEnv, lookupModuleEnv,
64                           extendModuleEnv_C, moduleEnvElts 
65                         )
66 import Outputable
67 import Util             ( sortLt, dropList, seqList )
68 import Binary           ( getBinFileWithDict )
69 import BinIface         ( writeBinIface, v_IgnoreHiVersion )
70 import ErrUtils         ( dumpIfSet_dyn )
71 import FiniteMap
72 import FastString
73
74 import DATA_IOREF       ( writeIORef )
75 import Monad            ( when )
76 import Maybe            ( catMaybes, isJust, isNothing )
77 import Maybes           ( orElse )
78 import IO               ( putStrLn )
79 \end{code}
80
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection{Print out the contents of a binary interface}
85 %*                                                                      *
86 %************************************************************************
87
88 \begin{code}
89 showIface :: FilePath -> IO ()
90 showIface filename = do
91    -- skip the version check; we don't want to worry about profiled vs.
92    -- non-profiled interfaces, for example.
93    writeIORef v_IgnoreHiVersion True
94    parsed_iface <- Binary.getBinFileWithDict filename
95    let ParsedIface{
96       pi_mod=pi_mod, pi_pkg=pi_pkg, pi_vers=pi_vers,
97       pi_deps=pi_deps,
98       pi_orphan=pi_orphan, pi_usages=pi_usages,
99       pi_exports=pi_exports, pi_decls=pi_decls,
100       pi_fixity=pi_fixity, pi_insts=pi_insts,
101       pi_rules=pi_rules, pi_deprecs=pi_deprecs } = parsed_iface
102    putStrLn (showSDoc (vcat [
103         text "__interface" <+> doubleQuotes (ppr pi_pkg)
104            <+> ppr pi_mod <+> ppr pi_vers 
105            <+> (if pi_orphan then char '!' else empty)
106            <+> ptext SLIT("where"),
107         -- no instance Outputable (WhatsImported):
108         pprExports id (snd pi_exports),
109         pprDeps pi_deps,
110         pprUsages  id pi_usages,
111         hsep (map ppr_fix pi_fixity) <> semi,
112         vcat (map ppr_inst pi_insts),
113         vcat (map ppr_decl pi_decls),
114         ppr pi_rules
115         -- no instance Outputable (Either):
116         -- ppr pi_deprecs
117         ]))
118    where
119     ppr_fix (FixitySig n f _) = ppr f <+> ppr n
120     ppr_inst i  = ppr i <+> semi
121     ppr_decl (v,d)  = int v <+> ppr d <> semi
122 \end{code}
123
124 %************************************************************************
125 %*                                                                      *
126 \subsection{Completing an interface}
127 %*                                                                      *
128 %************************************************************************
129
130 \begin{code}
131 mkIface :: HscEnv
132         -> ModLocation
133         -> Maybe ModIface       -- The old interface, if we have it
134         -> ModGuts              -- The compiled, tidied module
135         -> IO ModIface          -- The new one, complete with decls and versions
136 -- mkFinalIface 
137 --      a) completes the interface
138 --      b) writes it out to a file if necessary
139
140 mkIface hsc_env location maybe_old_iface 
141         impl@ModGuts{ mg_module = this_mod,
142                       mg_usages = usages,
143                       mg_deps   = deps,
144                       mg_exports = exports,
145                       mg_rdr_env = rdr_env,
146                       mg_fix_env = fix_env,
147                       mg_deprecs = deprecs,
148                       mg_insts = insts, 
149                       mg_rules = rules,
150                       mg_types = types }
151   = do  {       -- Sort the exports to make them easier to compare for versions
152           let { my_exports = groupAvails this_mod exports ;
153
154                 iface_w_decls = ModIface { mi_module   = this_mod,
155                                            mi_package  = opt_InPackage,
156                                            mi_version  = initialVersionInfo,
157                                            mi_deps     = deps,
158                                            mi_usages   = usages,
159                                            mi_exports  = my_exports,
160                                            mi_decls    = new_decls,
161                                            mi_orphan   = orphan_mod,
162                                            mi_boot     = False,
163                                            mi_fixities = fix_env,
164                                            mi_globals  = Just rdr_env,
165                                            mi_deprecs  = deprecs } }
166
167                 -- Add version information
168         ; let (final_iface, maybe_diffs) = _scc_ "versioninfo" addVersionInfo maybe_old_iface iface_w_decls
169
170                 -- Write the interface file, if necessary
171         ; when (must_write_hi_file maybe_diffs)
172                 (writeBinIface hi_file_path final_iface)
173 --              (writeIface hi_file_path final_iface)
174
175                 -- Debug printing
176         ; write_diffs dflags final_iface maybe_diffs
177
178         ; orphan_mod `seq`
179           return final_iface }
180
181   where
182      dflags    = hsc_dflags hsc_env
183      ghci_mode = hsc_mode hsc_env
184
185      must_write_hi_file Nothing       = False
186      must_write_hi_file (Just _diffs) = ghci_mode /= Interactive
187                 -- We must write a new .hi file if there are some changes
188                 -- and we're not in interactive mode
189                 -- maybe_diffs = 'Nothing' means that even the usages havn't changed, 
190                 --     so there's no need to write a new interface file.  But even if 
191                 --     the usages have changed, the module version may not have.
192
193      hi_file_path = ml_hi_file location
194      new_decls    = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
195      inst_dcls    = map ifaceInstance insts
196      ty_cls_dcls  = foldNameEnv ifaceTyThing_acc [] types
197      rule_dcls    = map ifaceRule rules
198      orphan_mod   = isOrphanModule impl
199
200 write_diffs :: DynFlags -> ModIface -> Maybe SDoc -> IO ()
201 write_diffs dflags new_iface Nothing
202   = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
203        dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
204
205 write_diffs dflags new_iface (Just sdoc_diffs)
206   = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
207        dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
208 \end{code}
209
210 \begin{code}
211 isOrphanModule :: ModGuts -> Bool
212 isOrphanModule (ModGuts {mg_module = this_mod, mg_insts = insts, mg_rules = rules})
213   = any orphan_inst insts || any orphan_rule rules
214   where
215         -- A rule is an orphan if the LHS mentions nothing defined locally
216     orphan_inst dfun_id = no_locals (tyClsNamesOfDFunHead (idType dfun_id))
217         -- A instance is an orphan if its head mentions nothing defined locally
218     orphan_rule rule    = no_locals (ruleLhsFreeNames rule)
219
220     no_locals names     = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
221 \end{code}
222
223 Implicit Ids and class tycons aren't included in interface files, so
224 we miss them out of the accumulating parameter here.
225
226 \begin{code}
227 ifaceTyThing_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
228 -- Don't put implicit things into the result
229 ifaceTyThing_acc (ADataCon dc) so_far                 = so_far
230 ifaceTyThing_acc (AnId   id) so_far | isImplicitId id = so_far
231 ifaceTyThing_acc (ATyCon id) so_far | isClassTyCon id = so_far
232 ifaceTyThing_acc other so_far = ifaceTyThing other : so_far
233 \end{code}
234
235 Convert *any* TyThing into a RenamedTyClDecl.  Used both for
236 generating interface files and for the ':info' command in GHCi.
237
238 \begin{code}
239 ifaceTyThing :: TyThing -> RenamedTyClDecl
240 ifaceTyThing (AClass clas) = cls_decl
241   where
242     cls_decl = ClassDecl { tcdCtxt      = toHsContext sc_theta,
243                            tcdName      = getName clas,
244                            tcdTyVars    = toHsTyVars clas_tyvars,
245                            tcdFDs       = toHsFDs clas_fds,
246                            tcdSigs      = map toClassOpSig op_stuff,
247                            tcdMeths     = Nothing, 
248                            tcdLoc       = noSrcLoc }
249
250     (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
251     tycon     = classTyCon clas
252     data_con  = head (tyConDataCons tycon)
253
254     toClassOpSig (sel_id, def_meth)
255         = ASSERT(sel_tyvars == clas_tyvars)
256           ClassOpSig (getName sel_id) def_meth (toHsType op_ty) noSrcLoc
257         where
258                 -- Be careful when splitting the type, because of things
259                 -- like         class Foo a where
260                 --                op :: (?x :: String) => a -> a
261                 -- and          class Baz a where
262                 --                op :: (Ord a) => a -> a
263           (sel_tyvars, rho_ty) = tcSplitForAllTys (idType sel_id)
264           op_ty                = tcFunResultTy rho_ty
265
266 ifaceTyThing (ATyCon tycon) = ty_decl
267   where
268     ty_decl | isSynTyCon tycon
269             = TySynonym { tcdName   = getName tycon,
270                           tcdTyVars = toHsTyVars tyvars,
271                           tcdSynRhs = toHsType syn_ty,
272                           tcdLoc    = noSrcLoc }
273
274             | isAlgTyCon tycon
275             = TyData {  tcdND      = new_or_data,
276                         tcdCtxt    = toHsContext (tyConTheta tycon),
277                         tcdName    = getName tycon,
278                         tcdTyVars  = toHsTyVars tyvars,
279                         tcdCons    = ifaceConDecls (tyConDataConDetails tycon),
280                         tcdDerivs  = Nothing,
281                         tcdGeneric = Just (isJust (tyConGenInfo tycon)),
282                                 -- Just True <=> has generic stuff
283                         tcdLoc     = noSrcLoc }
284
285             | isForeignTyCon tycon
286             = ForeignType { tcdName    = getName tycon,
287                             tcdExtName = Nothing,
288                             tcdFoType  = DNType,        -- The only case at present
289                             tcdLoc     = noSrcLoc }
290
291             | isPrimTyCon tycon || isFunTyCon tycon
292                 -- needed in GHCi for ':info Int#', for example
293             = TyData {  tcdND     = DataType,
294                         tcdCtxt   = [],
295                         tcdName   = getName tycon,
296                         tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
297                         tcdCons   = Unknown,
298                         tcdDerivs = Nothing,
299                         tcdGeneric  = Just False,
300                         tcdLoc       = noSrcLoc }
301
302             | otherwise = pprPanic "ifaceTyThing" (ppr tycon)
303
304     tyvars      = tyConTyVars tycon
305     (_, syn_ty) = getSynTyConDefn tycon
306     new_or_data | isNewTyCon tycon = NewType
307                 | otherwise        = DataType
308
309     ifaceConDecls Unknown       = Unknown
310     ifaceConDecls (HasCons n)   = HasCons n
311     ifaceConDecls (DataCons cs) = DataCons (map ifaceConDecl cs)
312
313     ifaceConDecl data_con 
314         = ConDecl (dataConName data_con)
315                   (toHsTyVars ex_tyvars)
316                   (toHsContext ex_theta)
317                   details noSrcLoc
318         where
319           (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
320           field_labels   = dataConFieldLabels data_con
321           strict_marks   = dropList ex_theta (dataConStrictMarks data_con)
322                                 -- The 'drop' is because dataConStrictMarks
323                                 -- includes the existential dictionaries
324           details | null field_labels
325                   = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
326                     PrefixCon (zipWith BangType strict_marks (map toHsType arg_tys))
327
328                   | otherwise
329                   = RecCon (zipWith mk_field strict_marks field_labels)
330
331     mk_field strict_mark field_label
332         = (getName field_label, BangType strict_mark (toHsType (fieldLabelType field_label)))
333
334 ifaceTyThing (AnId id) = iface_sig
335   where
336     iface_sig = IfaceSig { tcdName   = getName id, 
337                            tcdType   = toHsType id_type,
338                            tcdIdInfo = hs_idinfo,
339                            tcdLoc    =  noSrcLoc }
340
341     id_type = idType id
342     id_info = idInfo id
343     arity_info = arityInfo id_info
344     caf_info   = idCafInfo id
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         -- ToDo: do we need to sort into canonical order?
502
503     hpt = hsc_HPT hsc_env
504     pit = eps_PIT eps
505     
506     import_all mod = case lookupModuleEnv dir_imp_mods mod of
507                         Just (_,imp_all) -> imp_all
508                         Nothing          -> False
509     
510     -- ent_map groups together all the things imported and used
511     -- from a particular module in this package
512     ent_map :: ModuleEnv [Name]
513     ent_map  = foldNameSet add_mv emptyModuleEnv used_names
514     add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [name]
515                    where
516                      mod = nameModule name
517                      add_item names _ = name:names
518     
519     -- We want to create a Usage for a home module if 
520     --  a) we used something from; has something in used_names
521     --  b) we imported all of it, even if we used nothing from it
522     --          (need to recompile if its export list changes: export_vers)
523     --  c) is a home-package orphan module (need to recompile if its
524     --          instance decls change: rules_vers)
525     mkUsage :: ModuleName -> Maybe (Usage Name)
526     mkUsage mod_name
527       |  isNothing maybe_iface  -- We can't depend on it if we didn't
528       || not (isHomeModule mod) -- even open the interface!
529       || (null used_names
530           && not all_imported
531           && not orphan_mod)
532       = Nothing                 -- Record no usage info
533     
534       | otherwise       
535       = Just (Usage { usg_name     = moduleName mod,
536                       usg_mod      = mod_vers,
537                       usg_exports  = export_vers,
538                       usg_entities = ent_vers,
539                       usg_rules    = rules_vers })
540       where
541         maybe_iface  = lookupIfaceByModName hpt pit mod_name
542                 -- In one-shot mode, the interfaces for home-package 
543                 -- modules accumulate in the PIT not HPT.  Sigh.
544
545         Just iface   = maybe_iface
546         mod          = mi_module iface
547         version_info = mi_version iface
548         orphan_mod   = mi_orphan iface
549         version_env  = vers_decls   version_info
550         mod_vers     = vers_module  version_info
551         rules_vers   = vers_rules   version_info
552         all_imported = import_all mod 
553         export_vers | all_imported = Just (vers_exports version_info)
554                     | otherwise    = Nothing
555     
556         -- The sort is to put them into canonical order
557         used_names = lookupModuleEnv ent_map mod `orElse` []
558         ent_vers = [(n, lookupVersion version_env n) 
559                    | n <- sortLt lt_occ used_names ]
560         lt_occ n1 n2 = nameOccName n1 < nameOccName n2
561         -- ToDo: is '<' on OccNames the right thing; may differ between runs?
562 \end{code}
563
564 \begin{code}
565 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
566   -- Group by module and sort by occurrence
567   -- This keeps the list in canonical order
568 groupAvails this_mod avails 
569   = [ (mkSysModuleNameFS fs, sortLt lt avails)
570     | (fs,avails) <- fmToList groupFM
571     ]
572   where
573     groupFM :: FiniteMap FastString Avails
574         -- Deliberately use the FastString so we
575         -- get a canonical ordering
576     groupFM = foldl add emptyFM avails
577
578     add env avail = addToFM_C combine env mod_fs [avail']
579                   where
580                     mod_fs = moduleNameFS (moduleName avail_mod)
581                     avail_mod = case nameModule_maybe (availName avail) of
582                                           Just m  -> m
583                                           Nothing -> this_mod
584                     combine old _ = avail':old
585                     avail'        = sortAvail avail
586
587     a1 `lt` a2 = occ1 < occ2
588                where
589                  occ1  = nameOccName (availName a1)
590                  occ2  = nameOccName (availName a2)
591
592 sortAvail :: AvailInfo -> AvailInfo
593 -- Sort the sub-names into canonical order.
594 -- The canonical order has the "main name" at the beginning 
595 -- (if it's there at all)
596 sortAvail (Avail n) = Avail n
597 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
598                          | otherwise   = AvailTC n (    sortLt lt ns)
599                          where
600                            n1 `lt` n2 = nameOccName n1 < nameOccName n2
601 \end{code}
602
603 %************************************************************************
604 %*                                                                      *
605 \subsection{Checking if the new interface is up to date
606 %*                                                                      *
607 %************************************************************************
608
609 \begin{code}
610 addVersionInfo :: Maybe ModIface                -- The old interface, read from M.hi
611                -> ModIface                      -- The new interface decls
612                -> (ModIface, Maybe SDoc)        -- Nothing => no change; no need to write new Iface
613                                                 -- Just mi => Here is the new interface to write
614                                                 --            with correct version numbers
615
616 -- NB: the fixities, declarations, rules are all assumed
617 -- to be sorted by increasing order of hsDeclName, so that 
618 -- we can compare for equality
619
620 addVersionInfo Nothing new_iface
621 -- No old interface, so definitely write a new one!
622   = (new_iface, Just (text "No old interface available"))
623
624 addVersionInfo (Just old_iface@(ModIface { mi_version  = old_version, 
625                                            mi_decls    = old_decls,
626                                            mi_fixities = old_fixities,
627                                            mi_deprecs  = old_deprecs }))
628                new_iface@(ModIface { mi_decls    = new_decls,
629                                      mi_fixities = new_fixities,
630                                      mi_deprecs  = new_deprecs })
631
632   | no_output_change && no_usage_change
633   = (new_iface, Nothing)
634         -- don't return the old iface because it may not have an
635         -- mi_globals field set to anything reasonable.
636
637   | otherwise           -- Add updated version numbers
638   = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
639     (final_iface, Just pp_diffs)
640         
641   where
642     final_iface = new_iface { mi_version = new_version }
643     old_mod_vers = vers_module  old_version
644     new_version = VersionInfo { vers_module  = bumpVersion no_output_change old_mod_vers,
645                                 vers_exports = bumpVersion no_export_change (vers_exports old_version),
646                                 vers_rules   = bumpVersion no_rule_change   (vers_rules   old_version),
647                                 vers_decls   = tc_vers }
648
649     no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
650     no_usage_change  = mi_usages old_iface == mi_usages new_iface
651
652     no_export_change = mi_exports old_iface == mi_exports new_iface             -- Kept sorted
653     no_rule_change   = dcl_rules old_decls  == dcl_rules  new_decls             -- Ditto
654                      && dcl_insts old_decls == dcl_insts  new_decls
655     no_deprec_change = old_deprecs          == new_deprecs
656
657         -- Fill in the version number on the new declarations by looking at the old declarations.
658         -- Set the flag if anything changes. 
659         -- Assumes that the decls are sorted by hsDeclName.
660     (no_tc_change,  pp_tc_diffs,  tc_vers) = diffDecls old_version old_fixities new_fixities
661                                                        (dcl_tycl old_decls) (dcl_tycl new_decls)
662     pp_diffs = vcat [pp_tc_diffs,
663                      pp_change no_export_change "Export list",
664                      pp_change no_rule_change   "Rules",
665                      pp_change no_deprec_change "Deprecations",
666                      pp_change no_usage_change  "Usages"]
667     pp_change True  what = empty
668     pp_change False what = text what <+> ptext SLIT("changed")
669
670 diffDecls :: VersionInfo                                -- Old version
671           -> FixityEnv -> FixityEnv                     -- Old and new fixities
672           -> [RenamedTyClDecl] -> [RenamedTyClDecl]     -- Old and new decls
673           -> (Bool,             -- True <=> no change
674               SDoc,             -- Record of differences
675               NameEnv Version)  -- New version map
676
677 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
678           old_fixities new_fixities old new
679   = diff True empty emptyNameEnv old new
680   where
681         -- When seeing if two decls are the same, 
682         -- remember to check whether any relevant fixity has changed
683     eq_tc  d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
684     same_fixity n = lookupFixity old_fixities n == lookupFixity new_fixities n
685
686     diff ok_so_far pp new_vers []  []      = (ok_so_far, pp, new_vers)
687     diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers          ods []
688     diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new []  nds
689         where
690           new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
691                 -- When adding a new item, start from the old module version
692                 -- This way, if you have version 4 of f, then delete f, then add f again,
693                 -- you'll get version 6 of f, which will (correctly) force recompilation of
694                 -- clients
695
696     diff ok_so_far pp new_vers (od:ods) (nd:nds)
697         = case od_name `compare` nd_name of
698                 LT -> diff False (pp $$ only_old od) new_vers ods      (nd:nds)
699                 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
700                 EQ | od `eq_tc` nd -> diff ok_so_far pp                    new_vers           ods nds
701                    | otherwise     -> diff False     (pp $$ changed od nd) new_vers_with_diff ods nds
702         where
703           od_name = tyClDeclName od
704           nd_name = tyClDeclName nd
705           new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
706           old_version = lookupVersion old_decls_vers od_name
707
708     only_old d    = ptext SLIT("Only in old iface:") <+> ppr d
709     only_new d    = ptext SLIT("Only in new iface:") <+> ppr d
710     changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$ 
711                                                          (ptext SLIT("New:")  <+> ppr nd))
712 \end{code}
713
714
715 b%************************************************************************
716 %*                                                                      *
717 \subsection{Writing an interface file}
718 %*                                                                      *
719 %************************************************************************
720
721 \begin{code}
722 pprIface :: ModIface -> SDoc
723 pprIface iface
724  = vcat [ ptext SLIT("__interface")
725                 <+> doubleQuotes (ftext (mi_package iface))
726                 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
727                 <+> pp_sub_vers
728                 <+> (if mi_orphan iface then char '!' else empty)
729                 <+> int opt_HiVersion
730                 <+> ptext SLIT("where")
731
732         , pprExports nameOccName (mi_exports iface)
733         , pprDeps    (mi_deps iface)
734         , pprUsages  nameOccName (mi_usages iface)
735
736         , pprFixities (mi_fixities iface) (dcl_tycl decls)
737         , pprIfaceDecls (vers_decls version_info) decls
738         , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
739         ]
740   where
741     version_info = mi_version iface
742     decls        = mi_decls iface
743     exp_vers     = vers_exports version_info
744
745     rule_vers    = vers_rules version_info
746
747     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
748                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
749 \end{code}
750
751 When printing export lists, we print like this:
752         Avail   f               f
753         AvailTC C [C, x, y]     C(x,y)
754         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
755
756 \begin{code}
757 pprExports :: Eq a => (a -> OccName) -> [(ModuleName, [GenAvailInfo a])] -> SDoc
758 pprExports getOcc exports = vcat (map (pprExport getOcc) exports)
759
760 pprExport :: Eq a => (a -> OccName) -> (ModuleName, [GenAvailInfo a]) -> SDoc
761 pprExport getOcc (mod, items)
762  = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
763   where
764     --pp_avail :: GenAvailInfo a -> SDoc
765     pp_avail (Avail name)                    = ppr (getOcc name)
766     pp_avail (AvailTC _ [])                  = empty
767     pp_avail (AvailTC n (n':ns)) 
768         | n==n'     = ppr (getOcc n) <> pp_export ns
769         | otherwise = ppr (getOcc n) <> char '|' <> pp_export (n':ns)
770     
771     pp_export []    = empty
772     pp_export names = braces (hsep (map (ppr.getOcc) names))
773
774 pprOcc :: Name -> SDoc  -- Print the occurrence name only
775 pprOcc n = pprOccName (nameOccName n)
776 \end{code}
777
778
779 \begin{code}
780 pprUsages :: (a -> OccName) -> [Usage a] -> SDoc
781 pprUsages getOcc usages = vcat (map (pprUsage getOcc) usages)
782
783 pprUsage :: (a -> OccName) -> Usage a -> SDoc
784 pprUsage getOcc usage
785   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
786           int (usg_mod usage), 
787           pp_export_version (usg_exports usage),
788           int (usg_rules usage),
789           pp_versions (usg_entities usage)
790     ] <> semi
791   where
792     pp_versions nvs = hsep [ ppr (getOcc n) <+> int v | (n,v) <- nvs ]
793
794     pp_export_version Nothing  = empty
795     pp_export_version (Just v) = int v
796
797
798 pprDeps :: Dependencies -> SDoc
799 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
800   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
801           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
802           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
803         ]
804   where
805     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
806    
807     ppr_boot   True  = text "[boot]"
808     ppr_boot   False = empty
809 \end{code}
810
811 \begin{code}
812 pprIfaceDecls :: NameEnv Int -> IfaceDecls -> SDoc
813 pprIfaceDecls version_map decls
814   = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
815          , vcat (map ppr_decl (dcl_tycl decls))
816          ]
817   where
818     ppr_decl d  = ppr_vers d <+> ppr d <> semi
819
820         -- Print the version for the decl
821     ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
822                    Nothing -> empty
823                    Just v  -> int v
824 \end{code}
825
826 \begin{code}
827 pprFixities :: FixityEnv
828             -> [TyClDecl Name]
829             -> SDoc
830 pprFixities fixity_map decls
831   = hsep [ ppr fix <+> ppr n 
832          | FixitySig n fix _ <- collectFixities fixity_map decls ] <> semi
833
834 -- Disgusting to print these two together, but that's 
835 -- the way the interface parser currently expects them.
836 pprRulesAndDeprecs :: (Outputable a) => [a] -> Deprecations -> SDoc
837 pprRulesAndDeprecs [] NoDeprecs = empty
838 pprRulesAndDeprecs rules deprecs
839   = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
840   where
841     pp_rules []    = empty
842     pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
843
844     pp_deprecs NoDeprecs = empty
845     pp_deprecs deprecs   = ptext SLIT("__D") <+> guts
846                           where
847                             guts = case deprecs of
848                                         DeprecAll txt  -> doubleQuotes (ftext txt)
849                                         DeprecSome env -> ppr_deprec_env env
850
851 ppr_deprec_env :: NameEnv (Name, FastString) -> SDoc
852 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
853                    where
854                      pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ftext txt)
855 \end{code}