remove empty dir
[ghc-hetmet.git] / compiler / iface / MkIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4
5 \begin{code}
6 module MkIface ( 
7         pprModIface, showIface,         -- Print the iface in Foo.hi
8
9         mkUsageInfo,    -- Construct the usage info for a module
10
11         mkIface,        -- Build a ModIface from a ModGuts, 
12                         -- including computing version information
13
14         writeIfaceFile, -- Write the interface file
15
16         checkOldIface   -- See if recompilation is required, by
17                         -- comparing version information
18  ) where
19 \end{code}
20
21         -----------------------------------------------
22                 MkIface.lhs deals with versioning
23         -----------------------------------------------
24
25 Here's the version-related info in an interface file
26
27   module Foo 8          -- module-version 
28              3          -- export-list-version
29              2          -- rule-version
30     Usages:     -- Version info for what this compilation of Foo imported
31         Baz 3           -- Module version
32             [4]         -- The export-list version if Foo depended on it
33             (g,2)       -- Function and its version
34             (T,1)       -- Type and its version
35
36     <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
37                 -- The [2] says that f's unfolding 
38                 -- mentions verison 2 of Wib.t
39         
40         -----------------------------------------------
41                         Basic idea
42         -----------------------------------------------
43
44 Basic idea: 
45   * In the mi_usages information in an interface, we record the 
46     version number of each free variable of the module
47
48   * In mkIface, we compute the version number of each exported thing A.f
49     by comparing its A.f's info with its new info, and bumping its 
50     version number if it differs.  If A.f mentions B.g, and B.g's version
51     number has changed, then we count A.f as having changed too.
52
53   * In checkOldIface we compare the mi_usages for the module with
54     the actual version info for all each thing recorded in mi_usages
55
56
57 Fixities
58 ~~~~~~~~
59 We count A.f as changing if its fixity changes
60
61 Rules
62 ~~~~~
63 If a rule changes, we want to recompile any module that might be
64 affected by that rule.  For non-orphan rules, this is relatively easy.
65 If module M defines f, and a rule for f, just arrange that the version
66 number for M.f changes if any of the rules for M.f change.  Any module
67 that does not depend on M.f can't be affected by the rule-change
68 either.
69
70 Orphan rules (ones whose 'head function' is not defined in M) are
71 harder.  Here's what we do.
72
73   * We have a per-module orphan-rule version number which changes if 
74     any orphan rule changes. (It's unaffected by non-orphan rules.)
75
76   * We record usage info for any orphan module 'below' this one,
77     giving the orphan-rule version number.  We recompile if this 
78     changes. 
79
80 The net effect is that if an orphan rule changes, we recompile every
81 module above it.  That's very conservative, but it's devilishly hard
82 to know what it might affect, so we just have to be conservative.
83
84 Instance decls
85 ~~~~~~~~~~~~~~
86 In an iface file we have
87      module A where
88         instance Eq a => Eq [a]  =  dfun29
89         dfun29 :: ... 
90
91 We have a version number for dfun29, covering its unfolding
92 etc. Suppose we are compiling a module M that imports A only
93 indirectly.  If typechecking M uses this instance decl, we record the
94 dependency on A.dfun29 as if it were a free variable of the module
95 (via the tcg_inst_usages accumulator).  That means that A will appear
96 in M's usage list.  If the shape of the instance declaration changes,
97 then so will dfun29's version, triggering a recompilation.
98
99 Adding an instance declaration, or changing an instance decl that is
100 not currently used, is more tricky.  (This really only makes a
101 difference when we have overlapping instance decls, because then the
102 new instance decl might kick in to override the old one.)  We handle
103 this in a very similar way that we handle rules above.
104
105   * For non-orphan instance decls, identify one locally-defined tycon/class
106     mentioned in the decl.  Treat the instance decl as part of the defn of that
107     tycon/class, so that if the shape of the instance decl changes, so does the
108     tycon/class; that in turn will force recompilation of anything that uses
109     that tycon/class.
110
111   * For orphan instance decls, act the same way as for orphan rules.
112     Indeed, we use the same global orphan-rule version number.
113
114 mkUsageInfo
115 ~~~~~~~~~~~
116 mkUsageInfo figures out what the ``usage information'' for this
117 moudule is; that is, what it must record in its interface file as the
118 things it uses.  
119
120 We produce a line for every module B below the module, A, currently being
121 compiled:
122         import B <n> ;
123 to record the fact that A does import B indirectly.  This is used to decide
124 to look to look for B.hi rather than B.hi-boot when compiling a module that
125 imports A.  This line says that A imports B, but uses nothing in it.
126 So we'll get an early bale-out when compiling A if B's version changes.
127
128 The usage information records:
129
130 \begin{itemize}
131 \item   (a) anything reachable from its body code
132 \item   (b) any module exported with a @module Foo@
133 \item   (c) anything reachable from an exported item
134 \end{itemize}
135
136 Why (b)?  Because if @Foo@ changes then this module's export list
137 will change, so we must recompile this module at least as far as
138 making a new interface file --- but in practice that means complete
139 recompilation.
140
141 Why (c)?  Consider this:
142 \begin{verbatim}
143         module A( f, g ) where  |       module B( f ) where
144           import B( f )         |         f = h 3
145           g = ...               |         h = ...
146 \end{verbatim}
147
148 Here, @B.f@ isn't used in A.  Should we nevertheless record @B.f@ in
149 @A@'s usages?  Our idea is that we aren't going to touch A.hi if it is
150 *identical* to what it was before.  If anything about @B.f@ changes
151 than anyone who imports @A@ should be recompiled in case they use
152 @B.f@ (they'll get an early exit if they don't).  So, if anything
153 about @B.f@ changes we'd better make sure that something in A.hi
154 changes, and the convenient way to do that is to record the version
155 number @B.f@ in A.hi in the usage list.  If B.f changes that'll force a
156 complete recompiation of A, which is overkill but it's the only way to 
157 write a new, slightly different, A.hi.
158
159 But the example is tricker.  Even if @B.f@ doesn't change at all,
160 @B.h@ may do so, and this change may not be reflected in @f@'s version
161 number.  But with -O, a module that imports A must be recompiled if
162 @B.h@ changes!  So A must record a dependency on @B.h@.  So we treat
163 the occurrence of @B.f@ in the export list *just as if* it were in the
164 code of A, and thereby haul in all the stuff reachable from it.
165
166         *** Conclusion: if A mentions B.f in its export list,
167             behave just as if A mentioned B.f in its source code,
168             and slurp in B.f and all its transitive closure ***
169
170 [NB: If B was compiled with -O, but A isn't, we should really *still*
171 haul in all the unfoldings for B, in case the module that imports A *is*
172 compiled with -O.  I think this is the case.]
173
174
175 \begin{code}
176 #include "HsVersions.h"
177
178 import HsSyn
179 import Packages         ( isHomeModule, PackageIdH(..) )
180 import IfaceSyn         ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..),
181                           IfaceRule(..), IfaceInst(..), IfaceExtName(..), 
182                           eqIfDecl, eqIfRule, eqIfInst, IfaceEq(..), (&&&), bool, 
183                           eqMaybeBy, eqListBy, visibleIfConDecls,
184                           tyThingToIfaceDecl, instanceToIfaceInst, coreRuleToIfaceRule )
185 import LoadIface        ( readIface, loadInterface )
186 import BasicTypes       ( Version, initialVersion, bumpVersion )
187 import TcRnMonad
188 import HscTypes         ( ModIface(..), ModDetails(..), 
189                           ModGuts(..), IfaceExport,
190                           HscEnv(..), hscEPS, Dependencies(..), FixItem(..), 
191                           ModSummary(..), msHiFilePath, 
192                           mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
193                           typeEnvElts, 
194                           GenAvailInfo(..), availName, 
195                           ExternalPackageState(..),
196                           Usage(..), IsBootInterface,
197                           Deprecs(..), IfaceDeprecs, Deprecations,
198                           lookupIfaceByModule
199                         )
200
201
202 import Packages         ( HomeModules )
203 import DynFlags         ( GhcMode(..), DynFlags(..), DynFlag(..), dopt )
204 import StaticFlags      ( opt_HiVersion )
205 import Name             ( Name, nameModule, nameOccName, nameParent,
206                           isExternalName, isInternalName, nameParent_maybe, isWiredInName,
207                           isImplicitName, NamedThing(..) )
208 import NameEnv
209 import NameSet
210 import OccName          ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
211                           extendOccEnv_C,
212                           OccSet, emptyOccSet, elemOccSet, occSetElts, 
213                           extendOccSet, extendOccSetList,
214                           isEmptyOccSet, intersectOccSet, intersectsOccSet,
215                           occNameFS, isTcOcc )
216 import Module           ( Module, moduleFS,
217                           ModLocation(..), mkModuleFS, moduleString,
218                           ModuleEnv, emptyModuleEnv, lookupModuleEnv,
219                           extendModuleEnv_C
220                         )
221 import Outputable
222 import Util             ( createDirectoryHierarchy, directoryOf )
223 import Util             ( sortLe, seqList )
224 import Binary           ( getBinFileWithDict )
225 import BinIface         ( writeBinIface, v_IgnoreHiWay )
226 import Unique           ( Unique, Uniquable(..) )
227 import ErrUtils         ( dumpIfSet_dyn, showPass )
228 import Digraph          ( stronglyConnComp, SCC(..) )
229 import SrcLoc           ( SrcSpan )
230 import FiniteMap
231 import FastString
232
233 import DATA_IOREF       ( writeIORef )
234 import Monad            ( when )
235 import List             ( insert )
236 import Maybes           ( orElse, mapCatMaybes, isNothing, isJust, 
237                           expectJust, MaybeErr(..) )
238 \end{code}
239
240
241
242 %************************************************************************
243 %*                                                                      *
244 \subsection{Completing an interface}
245 %*                                                                      *
246 %************************************************************************
247
248 \begin{code}
249 mkIface :: HscEnv
250         -> Maybe ModIface       -- The old interface, if we have it
251         -> ModGuts              -- Usages, deprecations, etc
252         -> ModDetails           -- The trimmed, tidied interface
253         -> IO (ModIface,        -- The new one, complete with decls and versions
254                Bool)            -- True <=> there was an old Iface, and the new one
255                                 --          is identical, so no need to write it
256
257 mkIface hsc_env maybe_old_iface 
258         (ModGuts{     mg_module  = this_mod,
259                       mg_boot    = is_boot,
260                       mg_usages  = usages,
261                       mg_deps    = deps,
262                       mg_home_mods = home_mods,
263                       mg_rdr_env = rdr_env,
264                       mg_fix_env = fix_env,
265                       mg_deprecs = src_deprecs })
266         (ModDetails{  md_insts   = insts, 
267                       md_rules   = rules,
268                       md_types   = type_env,
269                       md_exports = exports })
270         
271 -- NB:  notice that mkIface does not look at the bindings
272 --      only at the TypeEnv.  The previous Tidy phase has
273 --      put exactly the info into the TypeEnv that we want
274 --      to expose in the interface
275
276   = do  { eps <- hscEPS hsc_env
277         ; let   { ext_nm_rhs = mkExtNameFn hsc_env home_mods eps this_mod
278                 ; ext_nm_lhs = mkLhsNameFn this_mod
279
280                 ; decls  = [ tyThingToIfaceDecl ext_nm_rhs thing 
281                            | thing <- typeEnvElts type_env, 
282                              not (isImplicitName (getName thing)) ]
283                         -- Don't put implicit Ids and class tycons in the interface file
284
285                 ; fixities    = [(occ,fix) | FixItem occ fix _ <- nameEnvElts fix_env]
286                 ; deprecs     = mkIfaceDeprec src_deprecs
287                 ; iface_rules = map (coreRuleToIfaceRule ext_nm_lhs ext_nm_rhs) rules
288                 ; iface_insts = map (instanceToIfaceInst ext_nm_lhs) insts
289
290                 ; intermediate_iface = ModIface { 
291                         mi_module   = this_mod,
292                         mi_package  = HomePackage,
293                         mi_boot     = is_boot,
294                         mi_deps     = deps,
295                         mi_usages   = usages,
296                         mi_exports  = mkIfaceExports exports,
297                         mi_insts    = sortLe le_inst iface_insts,
298                         mi_rules    = sortLe le_rule iface_rules,
299                         mi_fixities = fixities,
300                         mi_deprecs  = deprecs,
301                         mi_globals  = Just rdr_env,
302
303                         -- Left out deliberately: filled in by addVersionInfo
304                         mi_mod_vers  = initialVersion,
305                         mi_exp_vers  = initialVersion,
306                         mi_rule_vers = initialVersion,
307                         mi_orphan    = False,   -- Always set by addVersionInfo, but
308                                                 -- it's a strict field, so we can't omit it.
309                         mi_decls     = deliberatelyOmitted "decls",
310                         mi_ver_fn    = deliberatelyOmitted "ver_fn",
311
312                         -- And build the cached values
313                         mi_dep_fn = mkIfaceDepCache deprecs,
314                         mi_fix_fn = mkIfaceFixCache fixities }
315
316                 -- Add version information
317                 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs) 
318                         = _scc_ "versioninfo" 
319                          addVersionInfo maybe_old_iface intermediate_iface decls
320                 }
321
322                 -- Debug printing
323         ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags) 
324                (printDump (expectJust "mkIface" pp_orphs))
325         ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
326         ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE" 
327                         (pprModIface new_iface)
328
329         ; return (new_iface, no_change_at_all) }
330   where
331      r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
332      i1 `le_inst` i2 = ifDFun     i1 <= ifDFun     i2
333
334      dflags = hsc_dflags hsc_env
335      deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
336
337                                               
338 -----------------------------
339 writeIfaceFile :: ModLocation -> ModIface -> IO ()
340 writeIfaceFile location new_iface
341     = do createDirectoryHierarchy (directoryOf hi_file_path)
342          writeBinIface hi_file_path new_iface
343     where hi_file_path = ml_hi_file location
344
345
346 -----------------------------
347 mkExtNameFn :: HscEnv -> HomeModules -> ExternalPackageState -> Module -> Name -> IfaceExtName
348 mkExtNameFn hsc_env hmods eps this_mod
349   = ext_nm
350   where
351     hpt = hsc_HPT hsc_env
352     pit = eps_PIT eps
353
354     ext_nm name 
355       | mod == this_mod = case nameParent_maybe name of
356                                 Nothing  -> LocalTop occ
357                                 Just par -> LocalTopSub occ (nameOccName par)
358       | isWiredInName name       = ExtPkg  mod occ
359       | isHomeModule hmods mod   = HomePkg mod occ vers
360       | otherwise                = ExtPkg  mod occ
361       where
362         mod      = nameModule name
363         occ      = nameOccName name
364         par_occ  = nameOccName (nameParent name)
365                 -- The version of the *parent* is the one want
366         vers     = lookupVersion mod par_occ
367               
368     lookupVersion :: Module -> OccName -> Version
369         -- Even though we're looking up a home-package thing, in
370         -- one-shot mode the imported interfaces may be in the PIT
371     lookupVersion mod occ
372       = mi_ver_fn iface occ `orElse` 
373         pprPanic "lookupVers1" (ppr mod <+> ppr occ)
374       where
375         iface = lookupIfaceByModule hpt pit mod `orElse` 
376                 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
377
378
379 ---------------------
380 -- mkLhsNameFn ignores versioning info altogether
381 -- It is used for the LHS of instance decls and rules, where we 
382 -- there's no point in recording version info
383 mkLhsNameFn :: Module -> Name -> IfaceExtName
384 mkLhsNameFn this_mod name       
385   | isInternalName name = pprTrace "mkLhsNameFn: unexpected internal" (ppr name) $
386                           LocalTop occ  -- Should not happen
387   | mod == this_mod = LocalTop occ
388   | otherwise       = ExtPkg mod occ
389   where
390     mod = nameModule name
391     occ = nameOccName name
392
393
394 -----------------------------
395 -- Compute version numbers for local decls
396
397 addVersionInfo :: Maybe ModIface        -- The old interface, read from M.hi
398                -> ModIface              -- The new interface decls (lacking decls)
399                -> [IfaceDecl]           -- The new decls
400                -> (ModIface, 
401                    Bool,                -- True <=> no changes at all; no need to write new Iface
402                    SDoc,                -- Differences
403                    Maybe SDoc)          -- Warnings about orphans
404
405 addVersionInfo Nothing new_iface new_decls
406 -- No old interface, so definitely write a new one!
407   = (new_iface { mi_orphan = anyNothing ifInstOrph (mi_insts new_iface)
408                           || anyNothing ifRuleOrph (mi_rules new_iface),
409                  mi_decls  = [(initialVersion, decl) | decl <- new_decls],
410                  mi_ver_fn = \n -> Just initialVersion },
411      False, 
412      ptext SLIT("No old interface file"),
413      pprOrphans orph_insts orph_rules)
414   where
415     orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
416     orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
417
418 addVersionInfo (Just old_iface@(ModIface { mi_mod_vers  = old_mod_vers, 
419                                            mi_exp_vers  = old_exp_vers, 
420                                            mi_rule_vers = old_rule_vers, 
421                                            mi_decls     = old_decls,
422                                            mi_ver_fn    = old_decl_vers,
423                                            mi_fix_fn    = old_fixities }))
424                new_iface@(ModIface { mi_fix_fn = new_fixities })
425                new_decls
426
427   | no_change_at_all = (old_iface,   True,  ptext SLIT("Interface file unchanged"), pp_orphs)
428   | otherwise        = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
429                                                   nest 2 pp_diffs], pp_orphs)
430   where
431     final_iface = new_iface { mi_mod_vers  = bump_unless no_output_change old_mod_vers,
432                               mi_exp_vers  = bump_unless no_export_change old_exp_vers,
433                               mi_rule_vers = bump_unless no_rule_change   old_rule_vers,
434                               mi_orphan    = not (null new_orph_rules && null new_orph_insts),
435                               mi_decls     = decls_w_vers,
436                               mi_ver_fn    = mkIfaceVerCache decls_w_vers }
437
438     decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
439
440     -------------------
441     (old_non_orph_insts, old_orph_insts) = mkOrphMap ifInstOrph (mi_insts old_iface)
442     (new_non_orph_insts, new_orph_insts) = mkOrphMap ifInstOrph (mi_insts new_iface)
443     same_insts occ = eqMaybeBy  (eqListBy eqIfInst) 
444                                 (lookupOccEnv old_non_orph_insts occ)
445                                 (lookupOccEnv new_non_orph_insts occ)
446   
447     (old_non_orph_rules, old_orph_rules) = mkOrphMap ifRuleOrph (mi_rules old_iface)
448     (new_non_orph_rules, new_orph_rules) = mkOrphMap ifRuleOrph (mi_rules new_iface)
449     same_rules occ = eqMaybeBy  (eqListBy eqIfRule)
450                                 (lookupOccEnv old_non_orph_rules occ)
451                                 (lookupOccEnv new_non_orph_rules occ)
452     -------------------
453     -- Computing what changed
454     no_output_change = no_decl_change   && no_rule_change && 
455                        no_export_change && no_deprec_change
456     no_export_change = mi_exports new_iface == mi_exports old_iface     -- Kept sorted
457     no_decl_change   = isEmptyOccSet changed_occs
458     no_rule_change   = not (changedWrt changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
459                          || changedWrt changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
460     no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
461
462         -- If the usages havn't changed either, we don't need to write the interface file
463     no_other_changes = mi_usages new_iface == mi_usages old_iface && 
464                        mi_deps new_iface == mi_deps old_iface
465     no_change_at_all = no_output_change && no_other_changes
466  
467     pp_diffs = vcat [pp_change no_export_change "Export list" 
468                         (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
469                      pp_change no_rule_change "Rules"
470                         (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
471                      pp_change no_deprec_change "Deprecations" empty,
472                      pp_change no_other_changes  "Usages" empty,
473                      pp_decl_diffs]
474     pp_change True  what info = empty
475     pp_change False what info = text what <+> ptext SLIT("changed") <+> info
476
477     -------------------
478     old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
479     same_fixity n = bool (old_fixities n == new_fixities n)
480
481     -------------------
482     -- Adding version info
483     new_version     = bumpVersion old_mod_vers
484     add_vers decl | occ `elemOccSet` changed_occs = new_version
485                   | otherwise = expectJust "add_vers" (old_decl_vers occ)
486                                 -- If it's unchanged, there jolly well 
487                   where         -- should be an old version number
488                     occ = ifName decl
489
490     -------------------
491     changed_occs :: OccSet
492     changed_occs = computeChangedOccs eq_info
493
494     eq_info :: [(OccName, IfaceEq)]
495     eq_info = map check_eq new_decls
496     check_eq new_decl | Just old_decl <- lookupOccEnv old_decl_env occ 
497                       = (occ, new_decl `eqIfDecl` old_decl &&&
498                               eq_indirects new_decl)
499                       | otherwise {- No corresponding old decl -}      
500                       = (occ, NotEqual) 
501                       where
502                         occ = ifName new_decl
503
504     eq_indirects :: IfaceDecl -> IfaceEq
505                 -- When seeing if two decls are the same, remember to
506                 -- check whether any relevant fixity or rules have changed
507     eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
508     eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
509         = same_insts cls_occ &&& 
510           eq_ind_occs [op | IfaceClassOp op _ _ <- sigs] 
511     eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
512         = same_insts tc_occ &&& same_fixity tc_occ &&&  -- The TyCon can have a fixity too
513           eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
514     eq_indirects other = Equal  -- Synonyms and foreign declarations
515
516     eq_ind_occ :: OccName -> IfaceEq    -- For class ops and Ids; check fixity and rules
517     eq_ind_occ occ = same_fixity occ &&& same_rules occ
518     eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal 
519    
520     -------------------
521     -- Diffs
522     pp_decl_diffs :: SDoc       -- Nothing => no changes
523     pp_decl_diffs 
524         | isEmptyOccSet changed_occs = empty
525         | otherwise 
526         = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
527                 ptext SLIT("Version change for these decls:"),
528                 nest 2 (vcat (map show_change new_decls))]
529
530     eq_env = mkOccEnv eq_info
531     show_change new_decl
532         | not (occ `elemOccSet` changed_occs) = empty
533         | otherwise
534         = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version, 
535                 nest 2 why]
536         where
537           occ = ifName new_decl
538           why = case lookupOccEnv eq_env occ of
539                     Just (EqBut occs) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
540                                               nest 2 (braces (fsep (map ppr (occSetElts 
541                                                 (occs `intersectOccSet` changed_occs)))))]
542                     Just NotEqual  
543                         | Just old_decl <- lookupOccEnv old_decl_env occ 
544                         -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
545                          ptext SLIT("New:") <+> ppr new_decl]
546                         | otherwise 
547                         -> ppr occ <+> ptext SLIT("only in new interface")
548                     other -> pprPanic "MkIface.show_change" (ppr occ)
549         
550     pp_orphs = pprOrphans new_orph_insts new_orph_rules
551
552 pprOrphans insts rules
553   | null insts && null rules = Nothing
554   | otherwise
555   = Just $ vcat [
556         if null insts then empty else
557              hang (ptext SLIT("Warning: orphan instances:"))
558                 2 (vcat (map ppr insts)),
559         if null rules then empty else
560              hang (ptext SLIT("Warning: orphan rules:"))
561                 2 (vcat (map ppr rules))
562     ]
563
564 computeChangedOccs :: [(OccName, IfaceEq)] -> OccSet
565 computeChangedOccs eq_info
566   = foldl add_changes emptyOccSet (stronglyConnComp edges)
567   where
568     edges :: [((OccName,IfaceEq), Unique, [Unique])]
569     edges = [ (node, getUnique occ, map getUnique occs)
570             | node@(occ, iface_eq) <- eq_info
571             , let occs = case iface_eq of
572                            EqBut occ_set -> occSetElts occ_set
573                            other -> [] ]
574
575     -- Changes in declarations
576     add_changes :: OccSet -> SCC (OccName, IfaceEq) -> OccSet
577     add_changes so_far (AcyclicSCC (occ, iface_eq)) 
578         | changedWrt so_far iface_eq                            -- This one has changed
579         = extendOccSet so_far occ
580     add_changes so_far (CyclicSCC pairs)
581         | changedWrt so_far (foldr1 (&&&) (map snd pairs))      -- One of this group has changed
582         = extendOccSetList so_far (map fst pairs)
583     add_changes so_far other = so_far
584
585 changedWrt :: OccSet -> IfaceEq -> Bool
586 changedWrt so_far Equal        = False
587 changedWrt so_far NotEqual     = True
588 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
589
590 ----------------------
591 -- mkOrphMap partitions instance decls or rules into
592 --      (a) an OccEnv for ones that are not orphans, 
593 --          mapping the local OccName to a list of its decls
594 --      (b) a list of orphan decls
595 mkOrphMap :: (decl -> Maybe OccName)    -- (Just occ) for a non-orphan decl, keyed by occ
596                                         -- Nothing for an orphan decl
597           -> [decl]                     -- Sorted into canonical order
598           -> (OccEnv [decl],            -- Non-orphan decls associated with their key;
599                                         --      each sublist in canonical order
600               [decl])                   -- Orphan decls; in canonical order
601 mkOrphMap get_key decls
602   = foldl go (emptyOccEnv, []) decls
603   where
604     go (non_orphs, orphs) d
605         | Just occ <- get_key d
606         = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
607         | otherwise = (non_orphs, d:orphs)
608
609 anyNothing :: (a -> Maybe b) -> [a] -> Bool
610 anyNothing p []     = False
611 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
612
613 ----------------------
614 mkIfaceDeprec :: Deprecations -> IfaceDeprecs
615 mkIfaceDeprec NoDeprecs        = NoDeprecs
616 mkIfaceDeprec (DeprecAll t)    = DeprecAll t
617 mkIfaceDeprec (DeprecSome env) = DeprecSome (sortLe (<=) (nameEnvElts env))
618
619 ----------------------
620 bump_unless :: Bool -> Version -> Version
621 bump_unless True  v = v -- True <=> no change
622 bump_unless False v = bumpVersion v
623 \end{code}
624
625
626 %*********************************************************
627 %*                                                      *
628 \subsection{Keeping track of what we've slurped, and version numbers}
629 %*                                                      *
630 %*********************************************************
631
632
633 \begin{code}
634 mkUsageInfo :: HscEnv 
635             -> HomeModules
636             -> ModuleEnv (Module, Bool, SrcSpan)
637             -> [(Module, IsBootInterface)]
638             -> NameSet -> IO [Usage]
639 mkUsageInfo hsc_env hmods dir_imp_mods dep_mods used_names
640   = do  { eps <- hscEPS hsc_env
641         ; let usages = mk_usage_info (eps_PIT eps) hsc_env hmods
642                                      dir_imp_mods dep_mods used_names
643         ; usages `seqList`  return usages }
644          -- seq the list of Usages returned: occasionally these
645          -- don't get evaluated for a while and we can end up hanging on to
646          -- the entire collection of Ifaces.
647
648 mk_usage_info pit hsc_env hmods dir_imp_mods dep_mods proto_used_names
649   = mapCatMaybes mkUsage dep_mods
650         -- ToDo: do we need to sort into canonical order?
651   where
652     hpt = hsc_HPT hsc_env
653
654     used_names = mkNameSet $                    -- Eliminate duplicates
655                  [ nameParent n                 -- Just record usage on the 'main' names
656                  | n <- nameSetToList proto_used_names
657                  , not (isWiredInName n)        -- Don't record usages for wired-in names
658                  , isExternalName n             -- Ignore internal names
659                  ]
660
661     -- ent_map groups together all the things imported and used
662     -- from a particular module in this package
663     ent_map :: ModuleEnv [OccName]
664     ent_map  = foldNameSet add_mv emptyModuleEnv used_names
665     add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [occ]
666                    where
667                      occ = nameOccName name
668                      mod = nameModule name
669                      add_item occs _ = occ:occs
670     
671     depend_on_exports mod = case lookupModuleEnv dir_imp_mods mod of
672                                 Just (_,no_imp,_) -> not no_imp
673                                 Nothing           -> True
674     
675     -- We want to create a Usage for a home module if 
676     --  a) we used something from; has something in used_names
677     --  b) we imported all of it, even if we used nothing from it
678     --          (need to recompile if its export list changes: export_vers)
679     --  c) is a home-package orphan module (need to recompile if its
680     --          instance decls change: rules_vers)
681     mkUsage :: (Module, Bool) -> Maybe Usage
682     mkUsage (mod_name, _)
683       |  isNothing maybe_iface  -- We can't depend on it if we didn't
684       || not (isHomeModule hmods mod)   -- even open the interface!
685       || (null used_occs
686           && isNothing export_vers
687           && not orphan_mod)
688       = Nothing                 -- Record no usage info
689     
690       | otherwise       
691       = Just (Usage { usg_name     = mod,
692                       usg_mod      = mod_vers,
693                       usg_exports  = export_vers,
694                       usg_entities = ent_vers,
695                       usg_rules    = rules_vers })
696       where
697         maybe_iface  = lookupIfaceByModule hpt pit mod_name
698                 -- In one-shot mode, the interfaces for home-package 
699                 -- modules accumulate in the PIT not HPT.  Sigh.
700
701         Just iface   = maybe_iface
702         mod          = mi_module    iface
703         orphan_mod   = mi_orphan    iface
704         version_env  = mi_ver_fn    iface
705         mod_vers     = mi_mod_vers  iface
706         rules_vers   = mi_rule_vers iface
707         export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
708                     | otherwise             = Nothing
709     
710         -- The sort is to put them into canonical order
711         used_occs = lookupModuleEnv ent_map mod `orElse` []
712         ent_vers :: [(OccName,Version)]
713         ent_vers = [ (occ, version_env occ `orElse` initialVersion) 
714                    | occ <- sortLe (<=) used_occs]
715 \end{code}
716
717 \begin{code}
718 mkIfaceExports :: NameSet -> [(Module, [GenAvailInfo OccName])]
719   -- Group by module and sort by occurrence
720   -- This keeps the list in canonical order
721 mkIfaceExports exports 
722   = [ (mkModuleFS fs, eltsFM avails)
723     | (fs, avails) <- fmToList groupFM
724     ]
725   where
726     groupFM :: FiniteMap FastString (FiniteMap FastString (GenAvailInfo OccName))
727         -- Deliberately use the FastString so we
728         -- get a canonical ordering
729     groupFM = foldl add emptyFM (nameSetToList exports)
730
731     add env name = addToFM_C add_avail env mod_fs 
732                              (unitFM avail_fs avail)
733       where
734         occ    = nameOccName name
735         mod_fs = moduleFS (nameModule name)
736         avail | Just p <- nameParent_maybe name = AvailTC (nameOccName p) [occ]
737               | isTcOcc occ                     = AvailTC occ [occ]
738               | otherwise                       = Avail occ
739         avail_fs = occNameFS (availName avail)      
740         add_avail avail_fm _ = addToFM_C add_item avail_fm avail_fs avail
741
742         add_item (AvailTC p occs) _ = AvailTC p (List.insert occ occs)
743         add_item (Avail n)        _ = pprPanic "MkIface.addAvail" (ppr n <+> ppr name)
744 \end{code}
745
746
747 %************************************************************************
748 %*                                                                      *
749         Load the old interface file for this module (unless
750         we have it aleady), and check whether it is up to date
751         
752 %*                                                                      *
753 %************************************************************************
754
755 \begin{code}
756 checkOldIface :: HscEnv
757               -> ModSummary
758               -> Bool                   -- Source unchanged
759               -> Maybe ModIface         -- Old interface from compilation manager, if any
760               -> IO (RecompileRequired, Maybe ModIface)
761
762 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
763   = do  { showPass (hsc_dflags hsc_env) 
764                    ("Checking old interface for " ++ moduleString (ms_mod mod_summary)) ;
765
766         ; initIfaceCheck hsc_env $
767           check_old_iface mod_summary source_unchanged maybe_iface
768      }
769
770 check_old_iface mod_summary source_unchanged maybe_iface
771  =      -- CHECK WHETHER THE SOURCE HAS CHANGED
772     ifM (not source_unchanged)
773         (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
774                                                 `thenM_`
775
776      -- If the source has changed and we're in interactive mode, avoid reading
777      -- an interface; just return the one we might have been supplied with.
778     getGhcMode                                  `thenM` \ ghc_mode ->
779     if (ghc_mode == Interactive || ghc_mode == JustTypecheck) 
780         && not source_unchanged then
781          returnM (outOfDate, maybe_iface)
782     else
783
784     case maybe_iface of {
785        Just old_iface -> -- Use the one we already have
786                          checkVersions source_unchanged old_iface       `thenM` \ recomp ->
787                          returnM (recomp, Just old_iface)
788
789     ;  Nothing ->
790
791         -- Try and read the old interface for the current module
792         -- from the .hi file left from the last time we compiled it
793     let
794         iface_path = msHiFilePath mod_summary
795     in
796     readIface (ms_mod mod_summary) iface_path False     `thenM` \ read_result ->
797     case read_result of {
798        Failed err ->    -- Old interface file not found, or garbled; give up
799                    traceIf (text "FYI: cannot read old interface file:"
800                                  $$ nest 4 err)         `thenM_`
801                    returnM (outOfDate, Nothing)
802
803     ;  Succeeded iface ->       
804
805         -- We have got the old iface; check its versions
806     checkVersions source_unchanged iface        `thenM` \ recomp ->
807     returnM (recomp, Just iface)
808     }}
809 \end{code}
810
811 @recompileRequired@ is called from the HscMain.   It checks whether
812 a recompilation is required.  It needs access to the persistent state,
813 finder, etc, because it may have to load lots of interface files to
814 check their versions.
815
816 \begin{code}
817 type RecompileRequired = Bool
818 upToDate  = False       -- Recompile not required
819 outOfDate = True        -- Recompile required
820
821 checkVersions :: Bool           -- True <=> source unchanged
822               -> ModIface       -- Old interface
823               -> IfG RecompileRequired
824 checkVersions source_unchanged iface
825   | not source_unchanged
826   = returnM outOfDate
827   | otherwise
828   = do  { traceHiDiffs (text "Considering whether compilation is required for" <+> 
829                         ppr (mi_module iface) <> colon)
830
831         -- Source code unchanged and no errors yet... carry on 
832
833         -- First put the dependent-module info, read from the old interface, into the envt, 
834         -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
835         -- 
836         -- It's just temporary because either the usage check will succeed 
837         -- (in which case we are done with this module) or it'll fail (in which
838         -- case we'll compile the module from scratch anyhow).
839         --      
840         -- We do this regardless of compilation mode
841         ; updateEps_ $ \eps  -> eps { eps_is_boot = mod_deps }
842
843         ; checkList [checkModUsage u | u <- mi_usages iface]
844     }
845   where
846         -- This is a bit of a hack really
847     mod_deps :: ModuleEnv (Module, IsBootInterface)
848     mod_deps = mkModDeps (dep_mods (mi_deps iface))
849
850 checkModUsage :: Usage -> IfG RecompileRequired
851 -- Given the usage information extracted from the old
852 -- M.hi file for the module being compiled, figure out
853 -- whether M needs to be recompiled.
854
855 checkModUsage (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
856                        usg_rules = old_rule_vers,
857                        usg_exports = maybe_old_export_vers, 
858                        usg_entities = old_decl_vers })
859   =     -- Load the imported interface is possible
860     let
861         doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
862     in
863     traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
864
865     loadInterface doc_str mod_name ImportBySystem       `thenM` \ mb_iface ->
866         -- Load the interface, but don't complain on failure;
867         -- Instead, get an Either back which we can test
868
869     case mb_iface of {
870         Failed exn ->  (out_of_date (sep [ptext SLIT("Can't find version number for module"), 
871                                        ppr mod_name]));
872                 -- Couldn't find or parse a module mentioned in the
873                 -- old interface file.  Don't complain -- it might just be that
874                 -- the current module doesn't need that import and it's been deleted
875
876         Succeeded iface -> 
877     let
878         new_mod_vers    = mi_mod_vers  iface
879         new_decl_vers   = mi_ver_fn    iface
880         new_export_vers = mi_exp_vers  iface
881         new_rule_vers   = mi_rule_vers iface
882     in
883         -- CHECK MODULE
884     checkModuleVersion old_mod_vers new_mod_vers        `thenM` \ recompile ->
885     if not recompile then
886         returnM upToDate
887     else
888                                  
889         -- CHECK EXPORT LIST
890     if checkExportList maybe_old_export_vers new_export_vers then
891         out_of_date_vers (ptext SLIT("  Export list changed"))
892                          (expectJust "checkModUsage" maybe_old_export_vers) 
893                          new_export_vers
894     else
895
896         -- CHECK RULES
897     if old_rule_vers /= new_rule_vers then
898         out_of_date_vers (ptext SLIT("  Rules changed")) 
899                          old_rule_vers new_rule_vers
900     else
901
902         -- CHECK ITEMS ONE BY ONE
903     checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]   `thenM` \ recompile ->
904     if recompile then
905         returnM outOfDate       -- This one failed, so just bail out now
906     else
907         up_to_date (ptext SLIT("  Great!  The bits I use are up to date"))
908     }
909
910 ------------------------
911 checkModuleVersion old_mod_vers new_mod_vers
912   | new_mod_vers == old_mod_vers
913   = up_to_date (ptext SLIT("Module version unchanged"))
914
915   | otherwise
916   = out_of_date_vers (ptext SLIT("  Module version has changed"))
917                      old_mod_vers new_mod_vers
918
919 ------------------------
920 checkExportList Nothing  new_vers = upToDate
921 checkExportList (Just v) new_vers = v /= new_vers
922
923 ------------------------
924 checkEntityUsage new_vers (name,old_vers)
925   = case new_vers name of
926
927         Nothing       ->        -- We used it before, but it ain't there now
928                           out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
929
930         Just new_vers   -- It's there, but is it up to date?
931           | new_vers == old_vers -> traceHiDiffs (text "  Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
932                                     returnM upToDate
933           | otherwise            -> out_of_date_vers (ptext SLIT("  Out of date:") <+> ppr name)
934                                                      old_vers new_vers
935
936 up_to_date  msg = traceHiDiffs msg `thenM_` returnM upToDate
937 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
938 out_of_date_vers msg old_vers new_vers 
939   = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
940
941 ----------------------
942 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
943 -- This helper is used in two places
944 checkList []             = returnM upToDate
945 checkList (check:checks) = check        `thenM` \ recompile ->
946                            if recompile then 
947                                 returnM outOfDate
948                            else
949                                 checkList checks
950 \end{code}
951
952 %************************************************************************
953 %*                                                                      *
954                 Printing interfaces
955 %*                                                                      *
956 %************************************************************************
957
958 \begin{code}
959 showIface :: FilePath -> IO ()
960 -- Read binary interface, and print it out
961 showIface filename = do
962    -- skip the version check; we don't want to worry about profiled vs.
963    -- non-profiled interfaces, for example.
964    writeIORef v_IgnoreHiWay True
965    iface <- Binary.getBinFileWithDict filename
966    printDump (pprModIface iface)
967  where
968 \end{code}
969
970
971 \begin{code}
972 pprModIface :: ModIface -> SDoc
973 -- Show a ModIface
974 pprModIface iface
975  = vcat [ ptext SLIT("interface")
976                 <+> ppr_package (mi_package iface)
977                 <+> ppr (mi_module iface) <+> pp_boot 
978                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
979                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
980                 <+> int opt_HiVersion
981                 <+> ptext SLIT("where")
982         , vcat (map pprExport (mi_exports iface))
983         , pprDeps (mi_deps iface)
984         , vcat (map pprUsage (mi_usages iface))
985         , pprFixities (mi_fixities iface)
986         , vcat (map pprIfaceDecl (mi_decls iface))
987         , vcat (map ppr (mi_insts iface))
988         , vcat (map ppr (mi_rules iface))
989         , pprDeprecs (mi_deprecs iface)
990         ]
991   where
992     pp_boot | mi_boot iface = ptext SLIT("[boot]")
993             | otherwise     = empty
994     ppr_package HomePackage = empty
995     ppr_package (ExtPackage id) = doubleQuotes (ppr id)
996
997     exp_vers  = mi_exp_vers iface
998     rule_vers = mi_rule_vers iface
999
1000     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
1001                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
1002 \end{code}
1003
1004 When printing export lists, we print like this:
1005         Avail   f               f
1006         AvailTC C [C, x, y]     C(x,y)
1007         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
1008
1009 \begin{code}
1010 pprExport :: IfaceExport -> SDoc
1011 pprExport (mod, items)
1012  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
1013   where
1014     pp_avail :: GenAvailInfo OccName -> SDoc
1015     pp_avail (Avail occ)    = ppr occ
1016     pp_avail (AvailTC _ []) = empty
1017     pp_avail (AvailTC n (n':ns)) 
1018         | n==n'     = ppr n <> pp_export ns
1019         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
1020     
1021     pp_export []    = empty
1022     pp_export names = braces (hsep (map ppr names))
1023
1024 pprUsage :: Usage -> SDoc
1025 pprUsage usage
1026   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
1027           int (usg_mod usage), 
1028           pp_export_version (usg_exports usage),
1029           int (usg_rules usage),
1030           pp_versions (usg_entities usage) ]
1031   where
1032     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
1033     pp_export_version Nothing  = empty
1034     pp_export_version (Just v) = int v
1035
1036 pprDeps :: Dependencies -> SDoc
1037 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
1038   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
1039           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
1040           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
1041         ]
1042   where
1043     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
1044     ppr_boot True  = text "[boot]"
1045     ppr_boot False = empty
1046
1047 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
1048 pprIfaceDecl (ver, decl)
1049   = ppr_vers ver <+> ppr decl
1050   where
1051         -- Print the version for the decl
1052     ppr_vers v | v == initialVersion = empty
1053                | otherwise           = int v
1054
1055 pprFixities :: [(OccName, Fixity)] -> SDoc
1056 pprFixities []    = empty
1057 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
1058                   where
1059                     pprFix (occ,fix) = ppr fix <+> ppr occ 
1060
1061 pprDeprecs NoDeprecs        = empty
1062 pprDeprecs (DeprecAll txt)  = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
1063 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
1064                             where
1065                               pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
1066 \end{code}