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