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