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